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,
1272 btrfs_delalloc_helper,
1273 async_cow_start, async_cow_submit,
1276 nr_pages = DIV_ROUND_UP(cur_end - start, PAGE_SIZE);
1277 atomic_add(nr_pages, &fs_info->async_delalloc_pages);
1279 btrfs_queue_work(fs_info->delalloc_workers, &async_chunk[i].work);
1281 *nr_written += nr_pages;
1282 start = cur_end + 1;
1288 static noinline int csum_exist_in_range(struct btrfs_fs_info *fs_info,
1289 u64 bytenr, u64 num_bytes)
1292 struct btrfs_ordered_sum *sums;
1295 ret = btrfs_lookup_csums_range(fs_info->csum_root, bytenr,
1296 bytenr + num_bytes - 1, &list, 0);
1297 if (ret == 0 && list_empty(&list))
1300 while (!list_empty(&list)) {
1301 sums = list_entry(list.next, struct btrfs_ordered_sum, list);
1302 list_del(&sums->list);
1311 * when nowcow writeback call back. This checks for snapshots or COW copies
1312 * of the extents that exist in the file, and COWs the file as required.
1314 * If no cow copies or snapshots exist, we write directly to the existing
1317 static noinline int run_delalloc_nocow(struct inode *inode,
1318 struct page *locked_page,
1319 const u64 start, const u64 end,
1320 int *page_started, int force,
1321 unsigned long *nr_written)
1323 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1324 struct btrfs_root *root = BTRFS_I(inode)->root;
1325 struct btrfs_path *path;
1326 u64 cow_start = (u64)-1;
1327 u64 cur_offset = start;
1329 bool check_prev = true;
1330 const bool freespace_inode = btrfs_is_free_space_inode(BTRFS_I(inode));
1331 u64 ino = btrfs_ino(BTRFS_I(inode));
1333 u64 disk_bytenr = 0;
1335 path = btrfs_alloc_path();
1337 extent_clear_unlock_delalloc(inode, start, end, locked_page,
1338 EXTENT_LOCKED | EXTENT_DELALLOC |
1339 EXTENT_DO_ACCOUNTING |
1340 EXTENT_DEFRAG, PAGE_UNLOCK |
1342 PAGE_SET_WRITEBACK |
1343 PAGE_END_WRITEBACK);
1348 struct btrfs_key found_key;
1349 struct btrfs_file_extent_item *fi;
1350 struct extent_buffer *leaf;
1360 ret = btrfs_lookup_file_extent(NULL, root, path, ino,
1366 * If there is no extent for our range when doing the initial
1367 * search, then go back to the previous slot as it will be the
1368 * one containing the search offset
1370 if (ret > 0 && path->slots[0] > 0 && check_prev) {
1371 leaf = path->nodes[0];
1372 btrfs_item_key_to_cpu(leaf, &found_key,
1373 path->slots[0] - 1);
1374 if (found_key.objectid == ino &&
1375 found_key.type == BTRFS_EXTENT_DATA_KEY)
1380 /* Go to next leaf if we have exhausted the current one */
1381 leaf = path->nodes[0];
1382 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
1383 ret = btrfs_next_leaf(root, path);
1385 if (cow_start != (u64)-1)
1386 cur_offset = cow_start;
1391 leaf = path->nodes[0];
1394 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
1396 /* Didn't find anything for our INO */
1397 if (found_key.objectid > ino)
1400 * Keep searching until we find an EXTENT_ITEM or there are no
1401 * more extents for this inode
1403 if (WARN_ON_ONCE(found_key.objectid < ino) ||
1404 found_key.type < BTRFS_EXTENT_DATA_KEY) {
1409 /* Found key is not EXTENT_DATA_KEY or starts after req range */
1410 if (found_key.type > BTRFS_EXTENT_DATA_KEY ||
1411 found_key.offset > end)
1415 * If the found extent starts after requested offset, then
1416 * adjust extent_end to be right before this extent begins
1418 if (found_key.offset > cur_offset) {
1419 extent_end = found_key.offset;
1425 * Found extent which begins before our range and potentially
1428 fi = btrfs_item_ptr(leaf, path->slots[0],
1429 struct btrfs_file_extent_item);
1430 extent_type = btrfs_file_extent_type(leaf, fi);
1432 ram_bytes = btrfs_file_extent_ram_bytes(leaf, fi);
1433 if (extent_type == BTRFS_FILE_EXTENT_REG ||
1434 extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
1435 disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
1436 extent_offset = btrfs_file_extent_offset(leaf, fi);
1437 extent_end = found_key.offset +
1438 btrfs_file_extent_num_bytes(leaf, fi);
1440 btrfs_file_extent_disk_num_bytes(leaf, fi);
1442 * If extent we got ends before our range starts, skip
1445 if (extent_end <= start) {
1450 if (disk_bytenr == 0)
1452 /* Skip compressed/encrypted/encoded extents */
1453 if (btrfs_file_extent_compression(leaf, fi) ||
1454 btrfs_file_extent_encryption(leaf, fi) ||
1455 btrfs_file_extent_other_encoding(leaf, fi))
1458 * If extent is created before the last volume's snapshot
1459 * this implies the extent is shared, hence we can't do
1460 * nocow. This is the same check as in
1461 * btrfs_cross_ref_exist but without calling
1462 * btrfs_search_slot.
1464 if (!freespace_inode &&
1465 btrfs_file_extent_generation(leaf, fi) <=
1466 btrfs_root_last_snapshot(&root->root_item))
1468 if (extent_type == BTRFS_FILE_EXTENT_REG && !force)
1470 /* If extent is RO, we must COW it */
1471 if (btrfs_extent_readonly(fs_info, disk_bytenr))
1473 ret = btrfs_cross_ref_exist(root, ino,
1475 extent_offset, disk_bytenr);
1478 * ret could be -EIO if the above fails to read
1482 if (cow_start != (u64)-1)
1483 cur_offset = cow_start;
1487 WARN_ON_ONCE(freespace_inode);
1490 disk_bytenr += extent_offset;
1491 disk_bytenr += cur_offset - found_key.offset;
1492 num_bytes = min(end + 1, extent_end) - cur_offset;
1494 * If there are pending snapshots for this root, we
1495 * fall into common COW way
1497 if (!freespace_inode && atomic_read(&root->snapshot_force_cow))
1500 * force cow if csum exists in the range.
1501 * this ensure that csum for a given extent are
1502 * either valid or do not exist.
1504 ret = csum_exist_in_range(fs_info, disk_bytenr,
1508 * ret could be -EIO if the above fails to read
1512 if (cow_start != (u64)-1)
1513 cur_offset = cow_start;
1516 WARN_ON_ONCE(freespace_inode);
1519 if (!btrfs_inc_nocow_writers(fs_info, disk_bytenr))
1522 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
1523 extent_end = found_key.offset + ram_bytes;
1524 extent_end = ALIGN(extent_end, fs_info->sectorsize);
1525 /* Skip extents outside of our requested range */
1526 if (extent_end <= start) {
1531 /* If this triggers then we have a memory corruption */
1536 * If nocow is false then record the beginning of the range
1537 * that needs to be COWed
1540 if (cow_start == (u64)-1)
1541 cow_start = cur_offset;
1542 cur_offset = extent_end;
1543 if (cur_offset > end)
1549 btrfs_release_path(path);
1552 * COW range from cow_start to found_key.offset - 1. As the key
1553 * will contain the beginning of the first extent that can be
1554 * NOCOW, following one which needs to be COW'ed
1556 if (cow_start != (u64)-1) {
1557 ret = cow_file_range(inode, locked_page,
1558 cow_start, found_key.offset - 1,
1559 page_started, nr_written, 1);
1562 btrfs_dec_nocow_writers(fs_info,
1566 cow_start = (u64)-1;
1569 if (extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
1570 u64 orig_start = found_key.offset - extent_offset;
1571 struct extent_map *em;
1573 em = create_io_em(inode, cur_offset, num_bytes,
1575 disk_bytenr, /* block_start */
1576 num_bytes, /* block_len */
1577 disk_num_bytes, /* orig_block_len */
1578 ram_bytes, BTRFS_COMPRESS_NONE,
1579 BTRFS_ORDERED_PREALLOC);
1582 btrfs_dec_nocow_writers(fs_info,
1587 free_extent_map(em);
1588 ret = btrfs_add_ordered_extent(inode, cur_offset,
1589 disk_bytenr, num_bytes,
1591 BTRFS_ORDERED_PREALLOC);
1593 btrfs_drop_extent_cache(BTRFS_I(inode),
1595 cur_offset + num_bytes - 1,
1600 ret = btrfs_add_ordered_extent(inode, cur_offset,
1601 disk_bytenr, num_bytes,
1603 BTRFS_ORDERED_NOCOW);
1609 btrfs_dec_nocow_writers(fs_info, disk_bytenr);
1612 if (root->root_key.objectid ==
1613 BTRFS_DATA_RELOC_TREE_OBJECTID)
1615 * Error handled later, as we must prevent
1616 * extent_clear_unlock_delalloc() in error handler
1617 * from freeing metadata of created ordered extent.
1619 ret = btrfs_reloc_clone_csums(inode, cur_offset,
1622 extent_clear_unlock_delalloc(inode, cur_offset,
1623 cur_offset + num_bytes - 1,
1624 locked_page, EXTENT_LOCKED |
1626 EXTENT_CLEAR_DATA_RESV,
1627 PAGE_UNLOCK | PAGE_SET_PRIVATE2);
1629 cur_offset = extent_end;
1632 * btrfs_reloc_clone_csums() error, now we're OK to call error
1633 * handler, as metadata for created ordered extent will only
1634 * be freed by btrfs_finish_ordered_io().
1638 if (cur_offset > end)
1641 btrfs_release_path(path);
1643 if (cur_offset <= end && cow_start == (u64)-1)
1644 cow_start = cur_offset;
1646 if (cow_start != (u64)-1) {
1648 ret = cow_file_range(inode, locked_page, cow_start, end,
1649 page_started, nr_written, 1);
1656 btrfs_dec_nocow_writers(fs_info, disk_bytenr);
1658 if (ret && cur_offset < end)
1659 extent_clear_unlock_delalloc(inode, cur_offset, end,
1660 locked_page, EXTENT_LOCKED |
1661 EXTENT_DELALLOC | EXTENT_DEFRAG |
1662 EXTENT_DO_ACCOUNTING, PAGE_UNLOCK |
1664 PAGE_SET_WRITEBACK |
1665 PAGE_END_WRITEBACK);
1666 btrfs_free_path(path);
1670 static inline int need_force_cow(struct inode *inode, u64 start, u64 end)
1673 if (!(BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW) &&
1674 !(BTRFS_I(inode)->flags & BTRFS_INODE_PREALLOC))
1678 * @defrag_bytes is a hint value, no spinlock held here,
1679 * if is not zero, it means the file is defragging.
1680 * Force cow if given extent needs to be defragged.
1682 if (BTRFS_I(inode)->defrag_bytes &&
1683 test_range_bit(&BTRFS_I(inode)->io_tree, start, end,
1684 EXTENT_DEFRAG, 0, NULL))
1691 * Function to process delayed allocation (create CoW) for ranges which are
1692 * being touched for the first time.
1694 int btrfs_run_delalloc_range(struct inode *inode, struct page *locked_page,
1695 u64 start, u64 end, int *page_started, unsigned long *nr_written,
1696 struct writeback_control *wbc)
1699 int force_cow = need_force_cow(inode, start, end);
1700 unsigned int write_flags = wbc_to_write_flags(wbc);
1702 if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW && !force_cow) {
1703 ret = run_delalloc_nocow(inode, locked_page, start, end,
1704 page_started, 1, nr_written);
1705 } else if (BTRFS_I(inode)->flags & BTRFS_INODE_PREALLOC && !force_cow) {
1706 ret = run_delalloc_nocow(inode, locked_page, start, end,
1707 page_started, 0, nr_written);
1708 } else if (!inode_can_compress(inode) ||
1709 !inode_need_compress(inode, start, end)) {
1710 ret = cow_file_range(inode, locked_page, start, end,
1711 page_started, nr_written, 1);
1713 set_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
1714 &BTRFS_I(inode)->runtime_flags);
1715 ret = cow_file_range_async(inode, locked_page, start, end,
1716 page_started, nr_written,
1720 btrfs_cleanup_ordered_extents(inode, locked_page, start,
1725 void btrfs_split_delalloc_extent(struct inode *inode,
1726 struct extent_state *orig, u64 split)
1730 /* not delalloc, ignore it */
1731 if (!(orig->state & EXTENT_DELALLOC))
1734 size = orig->end - orig->start + 1;
1735 if (size > BTRFS_MAX_EXTENT_SIZE) {
1740 * See the explanation in btrfs_merge_delalloc_extent, the same
1741 * applies here, just in reverse.
1743 new_size = orig->end - split + 1;
1744 num_extents = count_max_extents(new_size);
1745 new_size = split - orig->start;
1746 num_extents += count_max_extents(new_size);
1747 if (count_max_extents(size) >= num_extents)
1751 spin_lock(&BTRFS_I(inode)->lock);
1752 btrfs_mod_outstanding_extents(BTRFS_I(inode), 1);
1753 spin_unlock(&BTRFS_I(inode)->lock);
1757 * Handle merged delayed allocation extents so we can keep track of new extents
1758 * that are just merged onto old extents, such as when we are doing sequential
1759 * writes, so we can properly account for the metadata space we'll need.
1761 void btrfs_merge_delalloc_extent(struct inode *inode, struct extent_state *new,
1762 struct extent_state *other)
1764 u64 new_size, old_size;
1767 /* not delalloc, ignore it */
1768 if (!(other->state & EXTENT_DELALLOC))
1771 if (new->start > other->start)
1772 new_size = new->end - other->start + 1;
1774 new_size = other->end - new->start + 1;
1776 /* we're not bigger than the max, unreserve the space and go */
1777 if (new_size <= BTRFS_MAX_EXTENT_SIZE) {
1778 spin_lock(&BTRFS_I(inode)->lock);
1779 btrfs_mod_outstanding_extents(BTRFS_I(inode), -1);
1780 spin_unlock(&BTRFS_I(inode)->lock);
1785 * We have to add up either side to figure out how many extents were
1786 * accounted for before we merged into one big extent. If the number of
1787 * extents we accounted for is <= the amount we need for the new range
1788 * then we can return, otherwise drop. Think of it like this
1792 * So we've grown the extent by a MAX_SIZE extent, this would mean we
1793 * need 2 outstanding extents, on one side we have 1 and the other side
1794 * we have 1 so they are == and we can return. But in this case
1796 * [MAX_SIZE+4k][MAX_SIZE+4k]
1798 * Each range on their own accounts for 2 extents, but merged together
1799 * they are only 3 extents worth of accounting, so we need to drop in
1802 old_size = other->end - other->start + 1;
1803 num_extents = count_max_extents(old_size);
1804 old_size = new->end - new->start + 1;
1805 num_extents += count_max_extents(old_size);
1806 if (count_max_extents(new_size) >= num_extents)
1809 spin_lock(&BTRFS_I(inode)->lock);
1810 btrfs_mod_outstanding_extents(BTRFS_I(inode), -1);
1811 spin_unlock(&BTRFS_I(inode)->lock);
1814 static void btrfs_add_delalloc_inodes(struct btrfs_root *root,
1815 struct inode *inode)
1817 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1819 spin_lock(&root->delalloc_lock);
1820 if (list_empty(&BTRFS_I(inode)->delalloc_inodes)) {
1821 list_add_tail(&BTRFS_I(inode)->delalloc_inodes,
1822 &root->delalloc_inodes);
1823 set_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1824 &BTRFS_I(inode)->runtime_flags);
1825 root->nr_delalloc_inodes++;
1826 if (root->nr_delalloc_inodes == 1) {
1827 spin_lock(&fs_info->delalloc_root_lock);
1828 BUG_ON(!list_empty(&root->delalloc_root));
1829 list_add_tail(&root->delalloc_root,
1830 &fs_info->delalloc_roots);
1831 spin_unlock(&fs_info->delalloc_root_lock);
1834 spin_unlock(&root->delalloc_lock);
1838 void __btrfs_del_delalloc_inode(struct btrfs_root *root,
1839 struct btrfs_inode *inode)
1841 struct btrfs_fs_info *fs_info = root->fs_info;
1843 if (!list_empty(&inode->delalloc_inodes)) {
1844 list_del_init(&inode->delalloc_inodes);
1845 clear_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1846 &inode->runtime_flags);
1847 root->nr_delalloc_inodes--;
1848 if (!root->nr_delalloc_inodes) {
1849 ASSERT(list_empty(&root->delalloc_inodes));
1850 spin_lock(&fs_info->delalloc_root_lock);
1851 BUG_ON(list_empty(&root->delalloc_root));
1852 list_del_init(&root->delalloc_root);
1853 spin_unlock(&fs_info->delalloc_root_lock);
1858 static void btrfs_del_delalloc_inode(struct btrfs_root *root,
1859 struct btrfs_inode *inode)
1861 spin_lock(&root->delalloc_lock);
1862 __btrfs_del_delalloc_inode(root, inode);
1863 spin_unlock(&root->delalloc_lock);
1867 * Properly track delayed allocation bytes in the inode and to maintain the
1868 * list of inodes that have pending delalloc work to be done.
1870 void btrfs_set_delalloc_extent(struct inode *inode, struct extent_state *state,
1873 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1875 if ((*bits & EXTENT_DEFRAG) && !(*bits & EXTENT_DELALLOC))
1878 * set_bit and clear bit hooks normally require _irqsave/restore
1879 * but in this case, we are only testing for the DELALLOC
1880 * bit, which is only set or cleared with irqs on
1882 if (!(state->state & EXTENT_DELALLOC) && (*bits & EXTENT_DELALLOC)) {
1883 struct btrfs_root *root = BTRFS_I(inode)->root;
1884 u64 len = state->end + 1 - state->start;
1885 u32 num_extents = count_max_extents(len);
1886 bool do_list = !btrfs_is_free_space_inode(BTRFS_I(inode));
1888 spin_lock(&BTRFS_I(inode)->lock);
1889 btrfs_mod_outstanding_extents(BTRFS_I(inode), num_extents);
1890 spin_unlock(&BTRFS_I(inode)->lock);
1892 /* For sanity tests */
1893 if (btrfs_is_testing(fs_info))
1896 percpu_counter_add_batch(&fs_info->delalloc_bytes, len,
1897 fs_info->delalloc_batch);
1898 spin_lock(&BTRFS_I(inode)->lock);
1899 BTRFS_I(inode)->delalloc_bytes += len;
1900 if (*bits & EXTENT_DEFRAG)
1901 BTRFS_I(inode)->defrag_bytes += len;
1902 if (do_list && !test_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1903 &BTRFS_I(inode)->runtime_flags))
1904 btrfs_add_delalloc_inodes(root, inode);
1905 spin_unlock(&BTRFS_I(inode)->lock);
1908 if (!(state->state & EXTENT_DELALLOC_NEW) &&
1909 (*bits & EXTENT_DELALLOC_NEW)) {
1910 spin_lock(&BTRFS_I(inode)->lock);
1911 BTRFS_I(inode)->new_delalloc_bytes += state->end + 1 -
1913 spin_unlock(&BTRFS_I(inode)->lock);
1918 * Once a range is no longer delalloc this function ensures that proper
1919 * accounting happens.
1921 void btrfs_clear_delalloc_extent(struct inode *vfs_inode,
1922 struct extent_state *state, unsigned *bits)
1924 struct btrfs_inode *inode = BTRFS_I(vfs_inode);
1925 struct btrfs_fs_info *fs_info = btrfs_sb(vfs_inode->i_sb);
1926 u64 len = state->end + 1 - state->start;
1927 u32 num_extents = count_max_extents(len);
1929 if ((state->state & EXTENT_DEFRAG) && (*bits & EXTENT_DEFRAG)) {
1930 spin_lock(&inode->lock);
1931 inode->defrag_bytes -= len;
1932 spin_unlock(&inode->lock);
1936 * set_bit and clear bit hooks normally require _irqsave/restore
1937 * but in this case, we are only testing for the DELALLOC
1938 * bit, which is only set or cleared with irqs on
1940 if ((state->state & EXTENT_DELALLOC) && (*bits & EXTENT_DELALLOC)) {
1941 struct btrfs_root *root = inode->root;
1942 bool do_list = !btrfs_is_free_space_inode(inode);
1944 spin_lock(&inode->lock);
1945 btrfs_mod_outstanding_extents(inode, -num_extents);
1946 spin_unlock(&inode->lock);
1949 * We don't reserve metadata space for space cache inodes so we
1950 * don't need to call delalloc_release_metadata if there is an
1953 if (*bits & EXTENT_CLEAR_META_RESV &&
1954 root != fs_info->tree_root)
1955 btrfs_delalloc_release_metadata(inode, len, false);
1957 /* For sanity tests. */
1958 if (btrfs_is_testing(fs_info))
1961 if (root->root_key.objectid != BTRFS_DATA_RELOC_TREE_OBJECTID &&
1962 do_list && !(state->state & EXTENT_NORESERVE) &&
1963 (*bits & EXTENT_CLEAR_DATA_RESV))
1964 btrfs_free_reserved_data_space_noquota(
1968 percpu_counter_add_batch(&fs_info->delalloc_bytes, -len,
1969 fs_info->delalloc_batch);
1970 spin_lock(&inode->lock);
1971 inode->delalloc_bytes -= len;
1972 if (do_list && inode->delalloc_bytes == 0 &&
1973 test_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1974 &inode->runtime_flags))
1975 btrfs_del_delalloc_inode(root, inode);
1976 spin_unlock(&inode->lock);
1979 if ((state->state & EXTENT_DELALLOC_NEW) &&
1980 (*bits & EXTENT_DELALLOC_NEW)) {
1981 spin_lock(&inode->lock);
1982 ASSERT(inode->new_delalloc_bytes >= len);
1983 inode->new_delalloc_bytes -= len;
1984 spin_unlock(&inode->lock);
1989 * btrfs_bio_fits_in_stripe - Checks whether the size of the given bio will fit
1990 * in a chunk's stripe. This function ensures that bios do not span a
1993 * @page - The page we are about to add to the bio
1994 * @size - size we want to add to the bio
1995 * @bio - bio we want to ensure is smaller than a stripe
1996 * @bio_flags - flags of the bio
1998 * return 1 if page cannot be added to the bio
1999 * return 0 if page can be added to the bio
2000 * return error otherwise
2002 int btrfs_bio_fits_in_stripe(struct page *page, size_t size, struct bio *bio,
2003 unsigned long bio_flags)
2005 struct inode *inode = page->mapping->host;
2006 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2007 u64 logical = (u64)bio->bi_iter.bi_sector << 9;
2011 struct btrfs_io_geometry geom;
2013 if (bio_flags & EXTENT_BIO_COMPRESSED)
2016 length = bio->bi_iter.bi_size;
2017 map_length = length;
2018 ret = btrfs_get_io_geometry(fs_info, btrfs_op(bio), logical, map_length,
2023 if (geom.len < length + size)
2029 * in order to insert checksums into the metadata in large chunks,
2030 * we wait until bio submission time. All the pages in the bio are
2031 * checksummed and sums are attached onto the ordered extent record.
2033 * At IO completion time the cums attached on the ordered extent record
2034 * are inserted into the btree
2036 static blk_status_t btrfs_submit_bio_start(void *private_data, struct bio *bio,
2039 struct inode *inode = private_data;
2040 blk_status_t ret = 0;
2042 ret = btrfs_csum_one_bio(inode, bio, 0, 0);
2043 BUG_ON(ret); /* -ENOMEM */
2048 * extent_io.c submission hook. This does the right thing for csum calculation
2049 * on write, or reading the csums from the tree before a read.
2051 * Rules about async/sync submit,
2052 * a) read: sync submit
2054 * b) write without checksum: sync submit
2056 * c) write with checksum:
2057 * c-1) if bio is issued by fsync: sync submit
2058 * (sync_writers != 0)
2060 * c-2) if root is reloc root: sync submit
2061 * (only in case of buffered IO)
2063 * c-3) otherwise: async submit
2065 static blk_status_t btrfs_submit_bio_hook(struct inode *inode, struct bio *bio,
2067 unsigned long bio_flags)
2070 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2071 struct btrfs_root *root = BTRFS_I(inode)->root;
2072 enum btrfs_wq_endio_type metadata = BTRFS_WQ_ENDIO_DATA;
2073 blk_status_t ret = 0;
2075 int async = !atomic_read(&BTRFS_I(inode)->sync_writers);
2077 skip_sum = BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM;
2079 if (btrfs_is_free_space_inode(BTRFS_I(inode)))
2080 metadata = BTRFS_WQ_ENDIO_FREE_SPACE;
2082 if (bio_op(bio) != REQ_OP_WRITE) {
2083 ret = btrfs_bio_wq_end_io(fs_info, bio, metadata);
2087 if (bio_flags & EXTENT_BIO_COMPRESSED) {
2088 ret = btrfs_submit_compressed_read(inode, bio,
2092 } else if (!skip_sum) {
2093 ret = btrfs_lookup_bio_sums(inode, bio, NULL);
2098 } else if (async && !skip_sum) {
2099 /* csum items have already been cloned */
2100 if (root->root_key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID)
2102 /* we're doing a write, do the async checksumming */
2103 ret = btrfs_wq_submit_bio(fs_info, bio, mirror_num, bio_flags,
2104 0, inode, btrfs_submit_bio_start);
2106 } else if (!skip_sum) {
2107 ret = btrfs_csum_one_bio(inode, bio, 0, 0);
2113 ret = btrfs_map_bio(fs_info, bio, mirror_num, 0);
2117 bio->bi_status = ret;
2124 * given a list of ordered sums record them in the inode. This happens
2125 * at IO completion time based on sums calculated at bio submission time.
2127 static noinline int add_pending_csums(struct btrfs_trans_handle *trans,
2128 struct inode *inode, struct list_head *list)
2130 struct btrfs_ordered_sum *sum;
2133 list_for_each_entry(sum, list, list) {
2134 trans->adding_csums = true;
2135 ret = btrfs_csum_file_blocks(trans,
2136 BTRFS_I(inode)->root->fs_info->csum_root, sum);
2137 trans->adding_csums = false;
2144 int btrfs_set_extent_delalloc(struct inode *inode, u64 start, u64 end,
2145 unsigned int extra_bits,
2146 struct extent_state **cached_state)
2148 WARN_ON(PAGE_ALIGNED(end));
2149 return set_extent_delalloc(&BTRFS_I(inode)->io_tree, start, end,
2150 extra_bits, cached_state);
2153 /* see btrfs_writepage_start_hook for details on why this is required */
2154 struct btrfs_writepage_fixup {
2156 struct btrfs_work work;
2159 static void btrfs_writepage_fixup_worker(struct btrfs_work *work)
2161 struct btrfs_writepage_fixup *fixup;
2162 struct btrfs_ordered_extent *ordered;
2163 struct extent_state *cached_state = NULL;
2164 struct extent_changeset *data_reserved = NULL;
2166 struct inode *inode;
2171 fixup = container_of(work, struct btrfs_writepage_fixup, work);
2175 if (!page->mapping || !PageDirty(page) || !PageChecked(page)) {
2176 ClearPageChecked(page);
2180 inode = page->mapping->host;
2181 page_start = page_offset(page);
2182 page_end = page_offset(page) + PAGE_SIZE - 1;
2184 lock_extent_bits(&BTRFS_I(inode)->io_tree, page_start, page_end,
2187 /* already ordered? We're done */
2188 if (PagePrivate2(page))
2191 ordered = btrfs_lookup_ordered_range(BTRFS_I(inode), page_start,
2194 unlock_extent_cached(&BTRFS_I(inode)->io_tree, page_start,
2195 page_end, &cached_state);
2197 btrfs_start_ordered_extent(inode, ordered, 1);
2198 btrfs_put_ordered_extent(ordered);
2202 ret = btrfs_delalloc_reserve_space(inode, &data_reserved, page_start,
2205 mapping_set_error(page->mapping, ret);
2206 end_extent_writepage(page, ret, page_start, page_end);
2207 ClearPageChecked(page);
2211 ret = btrfs_set_extent_delalloc(inode, page_start, page_end, 0,
2214 mapping_set_error(page->mapping, ret);
2215 end_extent_writepage(page, ret, page_start, page_end);
2216 ClearPageChecked(page);
2220 ClearPageChecked(page);
2221 set_page_dirty(page);
2222 btrfs_delalloc_release_extents(BTRFS_I(inode), PAGE_SIZE);
2224 unlock_extent_cached(&BTRFS_I(inode)->io_tree, page_start, page_end,
2230 extent_changeset_free(data_reserved);
2234 * There are a few paths in the higher layers of the kernel that directly
2235 * set the page dirty bit without asking the filesystem if it is a
2236 * good idea. This causes problems because we want to make sure COW
2237 * properly happens and the data=ordered rules are followed.
2239 * In our case any range that doesn't have the ORDERED bit set
2240 * hasn't been properly setup for IO. We kick off an async process
2241 * to fix it up. The async helper will wait for ordered extents, set
2242 * the delalloc bit and make it safe to write the page.
2244 int btrfs_writepage_cow_fixup(struct page *page, u64 start, u64 end)
2246 struct inode *inode = page->mapping->host;
2247 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2248 struct btrfs_writepage_fixup *fixup;
2250 /* this page is properly in the ordered list */
2251 if (TestClearPagePrivate2(page))
2254 if (PageChecked(page))
2257 fixup = kzalloc(sizeof(*fixup), GFP_NOFS);
2261 SetPageChecked(page);
2263 btrfs_init_work(&fixup->work, btrfs_fixup_helper,
2264 btrfs_writepage_fixup_worker, NULL, NULL);
2266 btrfs_queue_work(fs_info->fixup_workers, &fixup->work);
2270 static int insert_reserved_file_extent(struct btrfs_trans_handle *trans,
2271 struct inode *inode, u64 file_pos,
2272 u64 disk_bytenr, u64 disk_num_bytes,
2273 u64 num_bytes, u64 ram_bytes,
2274 u8 compression, u8 encryption,
2275 u16 other_encoding, int extent_type)
2277 struct btrfs_root *root = BTRFS_I(inode)->root;
2278 struct btrfs_file_extent_item *fi;
2279 struct btrfs_path *path;
2280 struct extent_buffer *leaf;
2281 struct btrfs_key ins;
2283 int extent_inserted = 0;
2286 path = btrfs_alloc_path();
2291 * we may be replacing one extent in the tree with another.
2292 * The new extent is pinned in the extent map, and we don't want
2293 * to drop it from the cache until it is completely in the btree.
2295 * So, tell btrfs_drop_extents to leave this extent in the cache.
2296 * the caller is expected to unpin it and allow it to be merged
2299 ret = __btrfs_drop_extents(trans, root, inode, path, file_pos,
2300 file_pos + num_bytes, NULL, 0,
2301 1, sizeof(*fi), &extent_inserted);
2305 if (!extent_inserted) {
2306 ins.objectid = btrfs_ino(BTRFS_I(inode));
2307 ins.offset = file_pos;
2308 ins.type = BTRFS_EXTENT_DATA_KEY;
2310 path->leave_spinning = 1;
2311 ret = btrfs_insert_empty_item(trans, root, path, &ins,
2316 leaf = path->nodes[0];
2317 fi = btrfs_item_ptr(leaf, path->slots[0],
2318 struct btrfs_file_extent_item);
2319 btrfs_set_file_extent_generation(leaf, fi, trans->transid);
2320 btrfs_set_file_extent_type(leaf, fi, extent_type);
2321 btrfs_set_file_extent_disk_bytenr(leaf, fi, disk_bytenr);
2322 btrfs_set_file_extent_disk_num_bytes(leaf, fi, disk_num_bytes);
2323 btrfs_set_file_extent_offset(leaf, fi, 0);
2324 btrfs_set_file_extent_num_bytes(leaf, fi, num_bytes);
2325 btrfs_set_file_extent_ram_bytes(leaf, fi, ram_bytes);
2326 btrfs_set_file_extent_compression(leaf, fi, compression);
2327 btrfs_set_file_extent_encryption(leaf, fi, encryption);
2328 btrfs_set_file_extent_other_encoding(leaf, fi, other_encoding);
2330 btrfs_mark_buffer_dirty(leaf);
2331 btrfs_release_path(path);
2333 inode_add_bytes(inode, num_bytes);
2335 ins.objectid = disk_bytenr;
2336 ins.offset = disk_num_bytes;
2337 ins.type = BTRFS_EXTENT_ITEM_KEY;
2340 * Release the reserved range from inode dirty range map, as it is
2341 * already moved into delayed_ref_head
2343 ret = btrfs_qgroup_release_data(inode, file_pos, ram_bytes);
2347 ret = btrfs_alloc_reserved_file_extent(trans, root,
2348 btrfs_ino(BTRFS_I(inode)),
2349 file_pos, qg_released, &ins);
2351 btrfs_free_path(path);
2356 /* snapshot-aware defrag */
2357 struct sa_defrag_extent_backref {
2358 struct rb_node node;
2359 struct old_sa_defrag_extent *old;
2368 struct old_sa_defrag_extent {
2369 struct list_head list;
2370 struct new_sa_defrag_extent *new;
2379 struct new_sa_defrag_extent {
2380 struct rb_root root;
2381 struct list_head head;
2382 struct btrfs_path *path;
2383 struct inode *inode;
2391 static int backref_comp(struct sa_defrag_extent_backref *b1,
2392 struct sa_defrag_extent_backref *b2)
2394 if (b1->root_id < b2->root_id)
2396 else if (b1->root_id > b2->root_id)
2399 if (b1->inum < b2->inum)
2401 else if (b1->inum > b2->inum)
2404 if (b1->file_pos < b2->file_pos)
2406 else if (b1->file_pos > b2->file_pos)
2410 * [------------------------------] ===> (a range of space)
2411 * |<--->| |<---->| =============> (fs/file tree A)
2412 * |<---------------------------->| ===> (fs/file tree B)
2414 * A range of space can refer to two file extents in one tree while
2415 * refer to only one file extent in another tree.
2417 * So we may process a disk offset more than one time(two extents in A)
2418 * and locate at the same extent(one extent in B), then insert two same
2419 * backrefs(both refer to the extent in B).
2424 static void backref_insert(struct rb_root *root,
2425 struct sa_defrag_extent_backref *backref)
2427 struct rb_node **p = &root->rb_node;
2428 struct rb_node *parent = NULL;
2429 struct sa_defrag_extent_backref *entry;
2434 entry = rb_entry(parent, struct sa_defrag_extent_backref, node);
2436 ret = backref_comp(backref, entry);
2440 p = &(*p)->rb_right;
2443 rb_link_node(&backref->node, parent, p);
2444 rb_insert_color(&backref->node, root);
2448 * Note the backref might has changed, and in this case we just return 0.
2450 static noinline int record_one_backref(u64 inum, u64 offset, u64 root_id,
2453 struct btrfs_file_extent_item *extent;
2454 struct old_sa_defrag_extent *old = ctx;
2455 struct new_sa_defrag_extent *new = old->new;
2456 struct btrfs_path *path = new->path;
2457 struct btrfs_key key;
2458 struct btrfs_root *root;
2459 struct sa_defrag_extent_backref *backref;
2460 struct extent_buffer *leaf;
2461 struct inode *inode = new->inode;
2462 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2468 if (BTRFS_I(inode)->root->root_key.objectid == root_id &&
2469 inum == btrfs_ino(BTRFS_I(inode)))
2472 key.objectid = root_id;
2473 key.type = BTRFS_ROOT_ITEM_KEY;
2474 key.offset = (u64)-1;
2476 root = btrfs_read_fs_root_no_name(fs_info, &key);
2478 if (PTR_ERR(root) == -ENOENT)
2481 btrfs_debug(fs_info, "inum=%llu, offset=%llu, root_id=%llu",
2482 inum, offset, root_id);
2483 return PTR_ERR(root);
2486 key.objectid = inum;
2487 key.type = BTRFS_EXTENT_DATA_KEY;
2488 if (offset > (u64)-1 << 32)
2491 key.offset = offset;
2493 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2494 if (WARN_ON(ret < 0))
2501 leaf = path->nodes[0];
2502 slot = path->slots[0];
2504 if (slot >= btrfs_header_nritems(leaf)) {
2505 ret = btrfs_next_leaf(root, path);
2508 } else if (ret > 0) {
2517 btrfs_item_key_to_cpu(leaf, &key, slot);
2519 if (key.objectid > inum)
2522 if (key.objectid < inum || key.type != BTRFS_EXTENT_DATA_KEY)
2525 extent = btrfs_item_ptr(leaf, slot,
2526 struct btrfs_file_extent_item);
2528 if (btrfs_file_extent_disk_bytenr(leaf, extent) != old->bytenr)
2532 * 'offset' refers to the exact key.offset,
2533 * NOT the 'offset' field in btrfs_extent_data_ref, ie.
2534 * (key.offset - extent_offset).
2536 if (key.offset != offset)
2539 extent_offset = btrfs_file_extent_offset(leaf, extent);
2540 num_bytes = btrfs_file_extent_num_bytes(leaf, extent);
2542 if (extent_offset >= old->extent_offset + old->offset +
2543 old->len || extent_offset + num_bytes <=
2544 old->extent_offset + old->offset)
2549 backref = kmalloc(sizeof(*backref), GFP_NOFS);
2555 backref->root_id = root_id;
2556 backref->inum = inum;
2557 backref->file_pos = offset;
2558 backref->num_bytes = num_bytes;
2559 backref->extent_offset = extent_offset;
2560 backref->generation = btrfs_file_extent_generation(leaf, extent);
2562 backref_insert(&new->root, backref);
2565 btrfs_release_path(path);
2570 static noinline bool record_extent_backrefs(struct btrfs_path *path,
2571 struct new_sa_defrag_extent *new)
2573 struct btrfs_fs_info *fs_info = btrfs_sb(new->inode->i_sb);
2574 struct old_sa_defrag_extent *old, *tmp;
2579 list_for_each_entry_safe(old, tmp, &new->head, list) {
2580 ret = iterate_inodes_from_logical(old->bytenr +
2581 old->extent_offset, fs_info,
2582 path, record_one_backref,
2584 if (ret < 0 && ret != -ENOENT)
2587 /* no backref to be processed for this extent */
2589 list_del(&old->list);
2594 if (list_empty(&new->head))
2600 static int relink_is_mergable(struct extent_buffer *leaf,
2601 struct btrfs_file_extent_item *fi,
2602 struct new_sa_defrag_extent *new)
2604 if (btrfs_file_extent_disk_bytenr(leaf, fi) != new->bytenr)
2607 if (btrfs_file_extent_type(leaf, fi) != BTRFS_FILE_EXTENT_REG)
2610 if (btrfs_file_extent_compression(leaf, fi) != new->compress_type)
2613 if (btrfs_file_extent_encryption(leaf, fi) ||
2614 btrfs_file_extent_other_encoding(leaf, fi))
2621 * Note the backref might has changed, and in this case we just return 0.
2623 static noinline int relink_extent_backref(struct btrfs_path *path,
2624 struct sa_defrag_extent_backref *prev,
2625 struct sa_defrag_extent_backref *backref)
2627 struct btrfs_file_extent_item *extent;
2628 struct btrfs_file_extent_item *item;
2629 struct btrfs_ordered_extent *ordered;
2630 struct btrfs_trans_handle *trans;
2631 struct btrfs_ref ref = { 0 };
2632 struct btrfs_root *root;
2633 struct btrfs_key key;
2634 struct extent_buffer *leaf;
2635 struct old_sa_defrag_extent *old = backref->old;
2636 struct new_sa_defrag_extent *new = old->new;
2637 struct btrfs_fs_info *fs_info = btrfs_sb(new->inode->i_sb);
2638 struct inode *inode;
2639 struct extent_state *cached = NULL;
2648 if (prev && prev->root_id == backref->root_id &&
2649 prev->inum == backref->inum &&
2650 prev->file_pos + prev->num_bytes == backref->file_pos)
2653 /* step 1: get root */
2654 key.objectid = backref->root_id;
2655 key.type = BTRFS_ROOT_ITEM_KEY;
2656 key.offset = (u64)-1;
2658 index = srcu_read_lock(&fs_info->subvol_srcu);
2660 root = btrfs_read_fs_root_no_name(fs_info, &key);
2662 srcu_read_unlock(&fs_info->subvol_srcu, index);
2663 if (PTR_ERR(root) == -ENOENT)
2665 return PTR_ERR(root);
2668 if (btrfs_root_readonly(root)) {
2669 srcu_read_unlock(&fs_info->subvol_srcu, index);
2673 /* step 2: get inode */
2674 key.objectid = backref->inum;
2675 key.type = BTRFS_INODE_ITEM_KEY;
2678 inode = btrfs_iget(fs_info->sb, &key, root, NULL);
2679 if (IS_ERR(inode)) {
2680 srcu_read_unlock(&fs_info->subvol_srcu, index);
2684 srcu_read_unlock(&fs_info->subvol_srcu, index);
2686 /* step 3: relink backref */
2687 lock_start = backref->file_pos;
2688 lock_end = backref->file_pos + backref->num_bytes - 1;
2689 lock_extent_bits(&BTRFS_I(inode)->io_tree, lock_start, lock_end,
2692 ordered = btrfs_lookup_first_ordered_extent(inode, lock_end);
2694 btrfs_put_ordered_extent(ordered);
2698 trans = btrfs_join_transaction(root);
2699 if (IS_ERR(trans)) {
2700 ret = PTR_ERR(trans);
2704 key.objectid = backref->inum;
2705 key.type = BTRFS_EXTENT_DATA_KEY;
2706 key.offset = backref->file_pos;
2708 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2711 } else if (ret > 0) {
2716 extent = btrfs_item_ptr(path->nodes[0], path->slots[0],
2717 struct btrfs_file_extent_item);
2719 if (btrfs_file_extent_generation(path->nodes[0], extent) !=
2720 backref->generation)
2723 btrfs_release_path(path);
2725 start = backref->file_pos;
2726 if (backref->extent_offset < old->extent_offset + old->offset)
2727 start += old->extent_offset + old->offset -
2728 backref->extent_offset;
2730 len = min(backref->extent_offset + backref->num_bytes,
2731 old->extent_offset + old->offset + old->len);
2732 len -= max(backref->extent_offset, old->extent_offset + old->offset);
2734 ret = btrfs_drop_extents(trans, root, inode, start,
2739 key.objectid = btrfs_ino(BTRFS_I(inode));
2740 key.type = BTRFS_EXTENT_DATA_KEY;
2743 path->leave_spinning = 1;
2745 struct btrfs_file_extent_item *fi;
2747 struct btrfs_key found_key;
2749 ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
2754 leaf = path->nodes[0];
2755 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
2757 fi = btrfs_item_ptr(leaf, path->slots[0],
2758 struct btrfs_file_extent_item);
2759 extent_len = btrfs_file_extent_num_bytes(leaf, fi);
2761 if (extent_len + found_key.offset == start &&
2762 relink_is_mergable(leaf, fi, new)) {
2763 btrfs_set_file_extent_num_bytes(leaf, fi,
2765 btrfs_mark_buffer_dirty(leaf);
2766 inode_add_bytes(inode, len);
2772 btrfs_release_path(path);
2777 ret = btrfs_insert_empty_item(trans, root, path, &key,
2780 btrfs_abort_transaction(trans, ret);
2784 leaf = path->nodes[0];
2785 item = btrfs_item_ptr(leaf, path->slots[0],
2786 struct btrfs_file_extent_item);
2787 btrfs_set_file_extent_disk_bytenr(leaf, item, new->bytenr);
2788 btrfs_set_file_extent_disk_num_bytes(leaf, item, new->disk_len);
2789 btrfs_set_file_extent_offset(leaf, item, start - new->file_pos);
2790 btrfs_set_file_extent_num_bytes(leaf, item, len);
2791 btrfs_set_file_extent_ram_bytes(leaf, item, new->len);
2792 btrfs_set_file_extent_generation(leaf, item, trans->transid);
2793 btrfs_set_file_extent_type(leaf, item, BTRFS_FILE_EXTENT_REG);
2794 btrfs_set_file_extent_compression(leaf, item, new->compress_type);
2795 btrfs_set_file_extent_encryption(leaf, item, 0);
2796 btrfs_set_file_extent_other_encoding(leaf, item, 0);
2798 btrfs_mark_buffer_dirty(leaf);
2799 inode_add_bytes(inode, len);
2800 btrfs_release_path(path);
2802 btrfs_init_generic_ref(&ref, BTRFS_ADD_DELAYED_REF, new->bytenr,
2804 btrfs_init_data_ref(&ref, backref->root_id, backref->inum,
2805 new->file_pos); /* start - extent_offset */
2806 ret = btrfs_inc_extent_ref(trans, &ref);
2808 btrfs_abort_transaction(trans, ret);
2814 btrfs_release_path(path);
2815 path->leave_spinning = 0;
2816 btrfs_end_transaction(trans);
2818 unlock_extent_cached(&BTRFS_I(inode)->io_tree, lock_start, lock_end,
2824 static void free_sa_defrag_extent(struct new_sa_defrag_extent *new)
2826 struct old_sa_defrag_extent *old, *tmp;
2831 list_for_each_entry_safe(old, tmp, &new->head, list) {
2837 static void relink_file_extents(struct new_sa_defrag_extent *new)
2839 struct btrfs_fs_info *fs_info = btrfs_sb(new->inode->i_sb);
2840 struct btrfs_path *path;
2841 struct sa_defrag_extent_backref *backref;
2842 struct sa_defrag_extent_backref *prev = NULL;
2843 struct rb_node *node;
2846 path = btrfs_alloc_path();
2850 if (!record_extent_backrefs(path, new)) {
2851 btrfs_free_path(path);
2854 btrfs_release_path(path);
2857 node = rb_first(&new->root);
2860 rb_erase(node, &new->root);
2862 backref = rb_entry(node, struct sa_defrag_extent_backref, node);
2864 ret = relink_extent_backref(path, prev, backref);
2877 btrfs_free_path(path);
2879 free_sa_defrag_extent(new);
2881 atomic_dec(&fs_info->defrag_running);
2882 wake_up(&fs_info->transaction_wait);
2885 static struct new_sa_defrag_extent *
2886 record_old_file_extents(struct inode *inode,
2887 struct btrfs_ordered_extent *ordered)
2889 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2890 struct btrfs_root *root = BTRFS_I(inode)->root;
2891 struct btrfs_path *path;
2892 struct btrfs_key key;
2893 struct old_sa_defrag_extent *old;
2894 struct new_sa_defrag_extent *new;
2897 new = kmalloc(sizeof(*new), GFP_NOFS);
2902 new->file_pos = ordered->file_offset;
2903 new->len = ordered->len;
2904 new->bytenr = ordered->start;
2905 new->disk_len = ordered->disk_len;
2906 new->compress_type = ordered->compress_type;
2907 new->root = RB_ROOT;
2908 INIT_LIST_HEAD(&new->head);
2910 path = btrfs_alloc_path();
2914 key.objectid = btrfs_ino(BTRFS_I(inode));
2915 key.type = BTRFS_EXTENT_DATA_KEY;
2916 key.offset = new->file_pos;
2918 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2921 if (ret > 0 && path->slots[0] > 0)
2924 /* find out all the old extents for the file range */
2926 struct btrfs_file_extent_item *extent;
2927 struct extent_buffer *l;
2936 slot = path->slots[0];
2938 if (slot >= btrfs_header_nritems(l)) {
2939 ret = btrfs_next_leaf(root, path);
2947 btrfs_item_key_to_cpu(l, &key, slot);
2949 if (key.objectid != btrfs_ino(BTRFS_I(inode)))
2951 if (key.type != BTRFS_EXTENT_DATA_KEY)
2953 if (key.offset >= new->file_pos + new->len)
2956 extent = btrfs_item_ptr(l, slot, struct btrfs_file_extent_item);
2958 num_bytes = btrfs_file_extent_num_bytes(l, extent);
2959 if (key.offset + num_bytes < new->file_pos)
2962 disk_bytenr = btrfs_file_extent_disk_bytenr(l, extent);
2966 extent_offset = btrfs_file_extent_offset(l, extent);
2968 old = kmalloc(sizeof(*old), GFP_NOFS);
2972 offset = max(new->file_pos, key.offset);
2973 end = min(new->file_pos + new->len, key.offset + num_bytes);
2975 old->bytenr = disk_bytenr;
2976 old->extent_offset = extent_offset;
2977 old->offset = offset - key.offset;
2978 old->len = end - offset;
2981 list_add_tail(&old->list, &new->head);
2987 btrfs_free_path(path);
2988 atomic_inc(&fs_info->defrag_running);
2993 btrfs_free_path(path);
2995 free_sa_defrag_extent(new);
2999 static void btrfs_release_delalloc_bytes(struct btrfs_fs_info *fs_info,
3002 struct btrfs_block_group_cache *cache;
3004 cache = btrfs_lookup_block_group(fs_info, start);
3007 spin_lock(&cache->lock);
3008 cache->delalloc_bytes -= len;
3009 spin_unlock(&cache->lock);
3011 btrfs_put_block_group(cache);
3014 /* as ordered data IO finishes, this gets called so we can finish
3015 * an ordered extent if the range of bytes in the file it covers are
3018 static int btrfs_finish_ordered_io(struct btrfs_ordered_extent *ordered_extent)
3020 struct inode *inode = ordered_extent->inode;
3021 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
3022 struct btrfs_root *root = BTRFS_I(inode)->root;
3023 struct btrfs_trans_handle *trans = NULL;
3024 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
3025 struct extent_state *cached_state = NULL;
3026 struct new_sa_defrag_extent *new = NULL;
3027 int compress_type = 0;
3029 u64 logical_len = ordered_extent->len;
3031 bool truncated = false;
3032 bool range_locked = false;
3033 bool clear_new_delalloc_bytes = false;
3034 bool clear_reserved_extent = true;
3036 if (!test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags) &&
3037 !test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags) &&
3038 !test_bit(BTRFS_ORDERED_DIRECT, &ordered_extent->flags))
3039 clear_new_delalloc_bytes = true;
3041 nolock = btrfs_is_free_space_inode(BTRFS_I(inode));
3043 if (test_bit(BTRFS_ORDERED_IOERR, &ordered_extent->flags)) {
3048 btrfs_free_io_failure_record(BTRFS_I(inode),
3049 ordered_extent->file_offset,
3050 ordered_extent->file_offset +
3051 ordered_extent->len - 1);
3053 if (test_bit(BTRFS_ORDERED_TRUNCATED, &ordered_extent->flags)) {
3055 logical_len = ordered_extent->truncated_len;
3056 /* Truncated the entire extent, don't bother adding */
3061 if (test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags)) {
3062 BUG_ON(!list_empty(&ordered_extent->list)); /* Logic error */
3065 * For mwrite(mmap + memset to write) case, we still reserve
3066 * space for NOCOW range.
3067 * As NOCOW won't cause a new delayed ref, just free the space
3069 btrfs_qgroup_free_data(inode, NULL, ordered_extent->file_offset,
3070 ordered_extent->len);
3071 btrfs_ordered_update_i_size(inode, 0, ordered_extent);
3073 trans = btrfs_join_transaction_nolock(root);
3075 trans = btrfs_join_transaction(root);
3076 if (IS_ERR(trans)) {
3077 ret = PTR_ERR(trans);
3081 trans->block_rsv = &BTRFS_I(inode)->block_rsv;
3082 ret = btrfs_update_inode_fallback(trans, root, inode);
3083 if (ret) /* -ENOMEM or corruption */
3084 btrfs_abort_transaction(trans, ret);
3088 range_locked = true;
3089 lock_extent_bits(io_tree, ordered_extent->file_offset,
3090 ordered_extent->file_offset + ordered_extent->len - 1,
3093 ret = test_range_bit(io_tree, ordered_extent->file_offset,
3094 ordered_extent->file_offset + ordered_extent->len - 1,
3095 EXTENT_DEFRAG, 0, cached_state);
3097 u64 last_snapshot = btrfs_root_last_snapshot(&root->root_item);
3098 if (0 && last_snapshot >= BTRFS_I(inode)->generation)
3099 /* the inode is shared */
3100 new = record_old_file_extents(inode, ordered_extent);
3102 clear_extent_bit(io_tree, ordered_extent->file_offset,
3103 ordered_extent->file_offset + ordered_extent->len - 1,
3104 EXTENT_DEFRAG, 0, 0, &cached_state);
3108 trans = btrfs_join_transaction_nolock(root);
3110 trans = btrfs_join_transaction(root);
3111 if (IS_ERR(trans)) {
3112 ret = PTR_ERR(trans);
3117 trans->block_rsv = &BTRFS_I(inode)->block_rsv;
3119 if (test_bit(BTRFS_ORDERED_COMPRESSED, &ordered_extent->flags))
3120 compress_type = ordered_extent->compress_type;
3121 if (test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags)) {
3122 BUG_ON(compress_type);
3123 btrfs_qgroup_free_data(inode, NULL, ordered_extent->file_offset,
3124 ordered_extent->len);
3125 ret = btrfs_mark_extent_written(trans, BTRFS_I(inode),
3126 ordered_extent->file_offset,
3127 ordered_extent->file_offset +
3130 BUG_ON(root == fs_info->tree_root);
3131 ret = insert_reserved_file_extent(trans, inode,
3132 ordered_extent->file_offset,
3133 ordered_extent->start,
3134 ordered_extent->disk_len,
3135 logical_len, logical_len,
3136 compress_type, 0, 0,
3137 BTRFS_FILE_EXTENT_REG);
3139 clear_reserved_extent = false;
3140 btrfs_release_delalloc_bytes(fs_info,
3141 ordered_extent->start,
3142 ordered_extent->disk_len);
3145 unpin_extent_cache(&BTRFS_I(inode)->extent_tree,
3146 ordered_extent->file_offset, ordered_extent->len,
3149 btrfs_abort_transaction(trans, ret);
3153 ret = add_pending_csums(trans, inode, &ordered_extent->list);
3155 btrfs_abort_transaction(trans, ret);
3159 btrfs_ordered_update_i_size(inode, 0, ordered_extent);
3160 ret = btrfs_update_inode_fallback(trans, root, inode);
3161 if (ret) { /* -ENOMEM or corruption */
3162 btrfs_abort_transaction(trans, ret);
3167 if (range_locked || clear_new_delalloc_bytes) {
3168 unsigned int clear_bits = 0;
3171 clear_bits |= EXTENT_LOCKED;
3172 if (clear_new_delalloc_bytes)
3173 clear_bits |= EXTENT_DELALLOC_NEW;
3174 clear_extent_bit(&BTRFS_I(inode)->io_tree,
3175 ordered_extent->file_offset,
3176 ordered_extent->file_offset +
3177 ordered_extent->len - 1,
3179 (clear_bits & EXTENT_LOCKED) ? 1 : 0,
3184 btrfs_end_transaction(trans);
3186 if (ret || truncated) {
3190 start = ordered_extent->file_offset + logical_len;
3192 start = ordered_extent->file_offset;
3193 end = ordered_extent->file_offset + ordered_extent->len - 1;
3194 clear_extent_uptodate(io_tree, start, end, NULL);
3196 /* Drop the cache for the part of the extent we didn't write. */
3197 btrfs_drop_extent_cache(BTRFS_I(inode), start, end, 0);
3200 * If the ordered extent had an IOERR or something else went
3201 * wrong we need to return the space for this ordered extent
3202 * back to the allocator. We only free the extent in the
3203 * truncated case if we didn't write out the extent at all.
3205 * If we made it past insert_reserved_file_extent before we
3206 * errored out then we don't need to do this as the accounting
3207 * has already been done.
3209 if ((ret || !logical_len) &&
3210 clear_reserved_extent &&
3211 !test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags) &&
3212 !test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags))
3213 btrfs_free_reserved_extent(fs_info,
3214 ordered_extent->start,
3215 ordered_extent->disk_len, 1);
3220 * This needs to be done to make sure anybody waiting knows we are done
3221 * updating everything for this ordered extent.
3223 btrfs_remove_ordered_extent(inode, ordered_extent);
3225 /* for snapshot-aware defrag */
3228 free_sa_defrag_extent(new);
3229 atomic_dec(&fs_info->defrag_running);
3231 relink_file_extents(new);
3236 btrfs_put_ordered_extent(ordered_extent);
3237 /* once for the tree */
3238 btrfs_put_ordered_extent(ordered_extent);
3243 static void finish_ordered_fn(struct btrfs_work *work)
3245 struct btrfs_ordered_extent *ordered_extent;
3246 ordered_extent = container_of(work, struct btrfs_ordered_extent, work);
3247 btrfs_finish_ordered_io(ordered_extent);
3250 void btrfs_writepage_endio_finish_ordered(struct page *page, u64 start,
3251 u64 end, int uptodate)
3253 struct inode *inode = page->mapping->host;
3254 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
3255 struct btrfs_ordered_extent *ordered_extent = NULL;
3256 struct btrfs_workqueue *wq;
3257 btrfs_work_func_t func;
3259 trace_btrfs_writepage_end_io_hook(page, start, end, uptodate);
3261 ClearPagePrivate2(page);
3262 if (!btrfs_dec_test_ordered_pending(inode, &ordered_extent, start,
3263 end - start + 1, uptodate))
3266 if (btrfs_is_free_space_inode(BTRFS_I(inode))) {
3267 wq = fs_info->endio_freespace_worker;
3268 func = btrfs_freespace_write_helper;
3270 wq = fs_info->endio_write_workers;
3271 func = btrfs_endio_write_helper;
3274 btrfs_init_work(&ordered_extent->work, func, finish_ordered_fn, NULL,
3276 btrfs_queue_work(wq, &ordered_extent->work);
3279 static int __readpage_endio_check(struct inode *inode,
3280 struct btrfs_io_bio *io_bio,
3281 int icsum, struct page *page,
3282 int pgoff, u64 start, size_t len)
3284 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
3285 SHASH_DESC_ON_STACK(shash, fs_info->csum_shash);
3287 u16 csum_size = btrfs_super_csum_size(fs_info->super_copy);
3289 u8 csum[BTRFS_CSUM_SIZE];
3291 csum_expected = ((u8 *)io_bio->csum) + icsum * csum_size;
3293 kaddr = kmap_atomic(page);
3294 shash->tfm = fs_info->csum_shash;
3296 crypto_shash_init(shash);
3297 crypto_shash_update(shash, kaddr + pgoff, len);
3298 crypto_shash_final(shash, csum);
3300 if (memcmp(csum, csum_expected, csum_size))
3303 kunmap_atomic(kaddr);
3306 btrfs_print_data_csum_error(BTRFS_I(inode), start, csum, csum_expected,
3307 io_bio->mirror_num);
3308 memset(kaddr + pgoff, 1, len);
3309 flush_dcache_page(page);
3310 kunmap_atomic(kaddr);
3315 * when reads are done, we need to check csums to verify the data is correct
3316 * if there's a match, we allow the bio to finish. If not, the code in
3317 * extent_io.c will try to find good copies for us.
3319 static int btrfs_readpage_end_io_hook(struct btrfs_io_bio *io_bio,
3320 u64 phy_offset, struct page *page,
3321 u64 start, u64 end, int mirror)
3323 size_t offset = start - page_offset(page);
3324 struct inode *inode = page->mapping->host;
3325 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
3326 struct btrfs_root *root = BTRFS_I(inode)->root;
3328 if (PageChecked(page)) {
3329 ClearPageChecked(page);
3333 if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)
3336 if (root->root_key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID &&
3337 test_range_bit(io_tree, start, end, EXTENT_NODATASUM, 1, NULL)) {
3338 clear_extent_bits(io_tree, start, end, EXTENT_NODATASUM);
3342 phy_offset >>= inode->i_sb->s_blocksize_bits;
3343 return __readpage_endio_check(inode, io_bio, phy_offset, page, offset,
3344 start, (size_t)(end - start + 1));
3348 * btrfs_add_delayed_iput - perform a delayed iput on @inode
3350 * @inode: The inode we want to perform iput on
3352 * This function uses the generic vfs_inode::i_count to track whether we should
3353 * just decrement it (in case it's > 1) or if this is the last iput then link
3354 * the inode to the delayed iput machinery. Delayed iputs are processed at
3355 * transaction commit time/superblock commit/cleaner kthread.
3357 void btrfs_add_delayed_iput(struct inode *inode)
3359 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
3360 struct btrfs_inode *binode = BTRFS_I(inode);
3362 if (atomic_add_unless(&inode->i_count, -1, 1))
3365 atomic_inc(&fs_info->nr_delayed_iputs);
3366 spin_lock(&fs_info->delayed_iput_lock);
3367 ASSERT(list_empty(&binode->delayed_iput));
3368 list_add_tail(&binode->delayed_iput, &fs_info->delayed_iputs);
3369 spin_unlock(&fs_info->delayed_iput_lock);
3370 if (!test_bit(BTRFS_FS_CLEANER_RUNNING, &fs_info->flags))
3371 wake_up_process(fs_info->cleaner_kthread);
3374 static void run_delayed_iput_locked(struct btrfs_fs_info *fs_info,
3375 struct btrfs_inode *inode)
3377 list_del_init(&inode->delayed_iput);
3378 spin_unlock(&fs_info->delayed_iput_lock);
3379 iput(&inode->vfs_inode);
3380 if (atomic_dec_and_test(&fs_info->nr_delayed_iputs))
3381 wake_up(&fs_info->delayed_iputs_wait);
3382 spin_lock(&fs_info->delayed_iput_lock);
3385 static void btrfs_run_delayed_iput(struct btrfs_fs_info *fs_info,
3386 struct btrfs_inode *inode)
3388 if (!list_empty(&inode->delayed_iput)) {
3389 spin_lock(&fs_info->delayed_iput_lock);
3390 if (!list_empty(&inode->delayed_iput))
3391 run_delayed_iput_locked(fs_info, inode);
3392 spin_unlock(&fs_info->delayed_iput_lock);
3396 void btrfs_run_delayed_iputs(struct btrfs_fs_info *fs_info)
3399 spin_lock(&fs_info->delayed_iput_lock);
3400 while (!list_empty(&fs_info->delayed_iputs)) {
3401 struct btrfs_inode *inode;
3403 inode = list_first_entry(&fs_info->delayed_iputs,
3404 struct btrfs_inode, delayed_iput);
3405 run_delayed_iput_locked(fs_info, inode);
3407 spin_unlock(&fs_info->delayed_iput_lock);
3411 * btrfs_wait_on_delayed_iputs - wait on the delayed iputs to be done running
3412 * @fs_info - the fs_info for this fs
3413 * @return - EINTR if we were killed, 0 if nothing's pending
3415 * This will wait on any delayed iputs that are currently running with KILLABLE
3416 * set. Once they are all done running we will return, unless we are killed in
3417 * which case we return EINTR. This helps in user operations like fallocate etc
3418 * that might get blocked on the iputs.
3420 int btrfs_wait_on_delayed_iputs(struct btrfs_fs_info *fs_info)
3422 int ret = wait_event_killable(fs_info->delayed_iputs_wait,
3423 atomic_read(&fs_info->nr_delayed_iputs) == 0);
3430 * This creates an orphan entry for the given inode in case something goes wrong
3431 * in the middle of an unlink.
3433 int btrfs_orphan_add(struct btrfs_trans_handle *trans,
3434 struct btrfs_inode *inode)
3438 ret = btrfs_insert_orphan_item(trans, inode->root, btrfs_ino(inode));
3439 if (ret && ret != -EEXIST) {
3440 btrfs_abort_transaction(trans, ret);
3448 * We have done the delete so we can go ahead and remove the orphan item for
3449 * this particular inode.
3451 static int btrfs_orphan_del(struct btrfs_trans_handle *trans,
3452 struct btrfs_inode *inode)
3454 return btrfs_del_orphan_item(trans, inode->root, btrfs_ino(inode));
3458 * this cleans up any orphans that may be left on the list from the last use
3461 int btrfs_orphan_cleanup(struct btrfs_root *root)
3463 struct btrfs_fs_info *fs_info = root->fs_info;
3464 struct btrfs_path *path;
3465 struct extent_buffer *leaf;
3466 struct btrfs_key key, found_key;
3467 struct btrfs_trans_handle *trans;
3468 struct inode *inode;
3469 u64 last_objectid = 0;
3470 int ret = 0, nr_unlink = 0;
3472 if (cmpxchg(&root->orphan_cleanup_state, 0, ORPHAN_CLEANUP_STARTED))
3475 path = btrfs_alloc_path();
3480 path->reada = READA_BACK;
3482 key.objectid = BTRFS_ORPHAN_OBJECTID;
3483 key.type = BTRFS_ORPHAN_ITEM_KEY;
3484 key.offset = (u64)-1;
3487 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
3492 * if ret == 0 means we found what we were searching for, which
3493 * is weird, but possible, so only screw with path if we didn't
3494 * find the key and see if we have stuff that matches
3498 if (path->slots[0] == 0)
3503 /* pull out the item */
3504 leaf = path->nodes[0];
3505 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
3507 /* make sure the item matches what we want */
3508 if (found_key.objectid != BTRFS_ORPHAN_OBJECTID)
3510 if (found_key.type != BTRFS_ORPHAN_ITEM_KEY)
3513 /* release the path since we're done with it */
3514 btrfs_release_path(path);
3517 * this is where we are basically btrfs_lookup, without the
3518 * crossing root thing. we store the inode number in the
3519 * offset of the orphan item.
3522 if (found_key.offset == last_objectid) {
3524 "Error removing orphan entry, stopping orphan cleanup");
3529 last_objectid = found_key.offset;
3531 found_key.objectid = found_key.offset;
3532 found_key.type = BTRFS_INODE_ITEM_KEY;
3533 found_key.offset = 0;
3534 inode = btrfs_iget(fs_info->sb, &found_key, root, NULL);
3535 ret = PTR_ERR_OR_ZERO(inode);
3536 if (ret && ret != -ENOENT)
3539 if (ret == -ENOENT && root == fs_info->tree_root) {
3540 struct btrfs_root *dead_root;
3541 struct btrfs_fs_info *fs_info = root->fs_info;
3542 int is_dead_root = 0;
3545 * this is an orphan in the tree root. Currently these
3546 * could come from 2 sources:
3547 * a) a snapshot deletion in progress
3548 * b) a free space cache inode
3549 * We need to distinguish those two, as the snapshot
3550 * orphan must not get deleted.
3551 * find_dead_roots already ran before us, so if this
3552 * is a snapshot deletion, we should find the root
3553 * in the dead_roots list
3555 spin_lock(&fs_info->trans_lock);
3556 list_for_each_entry(dead_root, &fs_info->dead_roots,
3558 if (dead_root->root_key.objectid ==
3559 found_key.objectid) {
3564 spin_unlock(&fs_info->trans_lock);
3566 /* prevent this orphan from being found again */
3567 key.offset = found_key.objectid - 1;
3574 * If we have an inode with links, there are a couple of
3575 * possibilities. Old kernels (before v3.12) used to create an
3576 * orphan item for truncate indicating that there were possibly
3577 * extent items past i_size that needed to be deleted. In v3.12,
3578 * truncate was changed to update i_size in sync with the extent
3579 * items, but the (useless) orphan item was still created. Since
3580 * v4.18, we don't create the orphan item for truncate at all.
3582 * So, this item could mean that we need to do a truncate, but
3583 * only if this filesystem was last used on a pre-v3.12 kernel
3584 * and was not cleanly unmounted. The odds of that are quite
3585 * slim, and it's a pain to do the truncate now, so just delete
3588 * It's also possible that this orphan item was supposed to be
3589 * deleted but wasn't. The inode number may have been reused,
3590 * but either way, we can delete the orphan item.
3592 if (ret == -ENOENT || inode->i_nlink) {
3595 trans = btrfs_start_transaction(root, 1);
3596 if (IS_ERR(trans)) {
3597 ret = PTR_ERR(trans);
3600 btrfs_debug(fs_info, "auto deleting %Lu",
3601 found_key.objectid);
3602 ret = btrfs_del_orphan_item(trans, root,
3603 found_key.objectid);
3604 btrfs_end_transaction(trans);
3612 /* this will do delete_inode and everything for us */
3615 /* release the path since we're done with it */
3616 btrfs_release_path(path);
3618 root->orphan_cleanup_state = ORPHAN_CLEANUP_DONE;
3620 if (test_bit(BTRFS_ROOT_ORPHAN_ITEM_INSERTED, &root->state)) {
3621 trans = btrfs_join_transaction(root);
3623 btrfs_end_transaction(trans);
3627 btrfs_debug(fs_info, "unlinked %d orphans", nr_unlink);
3631 btrfs_err(fs_info, "could not do orphan cleanup %d", ret);
3632 btrfs_free_path(path);
3637 * very simple check to peek ahead in the leaf looking for xattrs. If we
3638 * don't find any xattrs, we know there can't be any acls.
3640 * slot is the slot the inode is in, objectid is the objectid of the inode
3642 static noinline int acls_after_inode_item(struct extent_buffer *leaf,
3643 int slot, u64 objectid,
3644 int *first_xattr_slot)
3646 u32 nritems = btrfs_header_nritems(leaf);
3647 struct btrfs_key found_key;
3648 static u64 xattr_access = 0;
3649 static u64 xattr_default = 0;
3652 if (!xattr_access) {
3653 xattr_access = btrfs_name_hash(XATTR_NAME_POSIX_ACL_ACCESS,
3654 strlen(XATTR_NAME_POSIX_ACL_ACCESS));
3655 xattr_default = btrfs_name_hash(XATTR_NAME_POSIX_ACL_DEFAULT,
3656 strlen(XATTR_NAME_POSIX_ACL_DEFAULT));
3660 *first_xattr_slot = -1;
3661 while (slot < nritems) {
3662 btrfs_item_key_to_cpu(leaf, &found_key, slot);
3664 /* we found a different objectid, there must not be acls */
3665 if (found_key.objectid != objectid)
3668 /* we found an xattr, assume we've got an acl */
3669 if (found_key.type == BTRFS_XATTR_ITEM_KEY) {
3670 if (*first_xattr_slot == -1)
3671 *first_xattr_slot = slot;
3672 if (found_key.offset == xattr_access ||
3673 found_key.offset == xattr_default)
3678 * we found a key greater than an xattr key, there can't
3679 * be any acls later on
3681 if (found_key.type > BTRFS_XATTR_ITEM_KEY)
3688 * it goes inode, inode backrefs, xattrs, extents,
3689 * so if there are a ton of hard links to an inode there can
3690 * be a lot of backrefs. Don't waste time searching too hard,
3691 * this is just an optimization
3696 /* we hit the end of the leaf before we found an xattr or
3697 * something larger than an xattr. We have to assume the inode
3700 if (*first_xattr_slot == -1)
3701 *first_xattr_slot = slot;
3706 * read an inode from the btree into the in-memory inode
3708 static int btrfs_read_locked_inode(struct inode *inode,
3709 struct btrfs_path *in_path)
3711 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
3712 struct btrfs_path *path = in_path;
3713 struct extent_buffer *leaf;
3714 struct btrfs_inode_item *inode_item;
3715 struct btrfs_root *root = BTRFS_I(inode)->root;
3716 struct btrfs_key location;
3721 bool filled = false;
3722 int first_xattr_slot;
3724 ret = btrfs_fill_inode(inode, &rdev);
3729 path = btrfs_alloc_path();
3734 memcpy(&location, &BTRFS_I(inode)->location, sizeof(location));
3736 ret = btrfs_lookup_inode(NULL, root, path, &location, 0);
3738 if (path != in_path)
3739 btrfs_free_path(path);
3743 leaf = path->nodes[0];
3748 inode_item = btrfs_item_ptr(leaf, path->slots[0],
3749 struct btrfs_inode_item);
3750 inode->i_mode = btrfs_inode_mode(leaf, inode_item);
3751 set_nlink(inode, btrfs_inode_nlink(leaf, inode_item));
3752 i_uid_write(inode, btrfs_inode_uid(leaf, inode_item));
3753 i_gid_write(inode, btrfs_inode_gid(leaf, inode_item));
3754 btrfs_i_size_write(BTRFS_I(inode), btrfs_inode_size(leaf, inode_item));
3756 inode->i_atime.tv_sec = btrfs_timespec_sec(leaf, &inode_item->atime);
3757 inode->i_atime.tv_nsec = btrfs_timespec_nsec(leaf, &inode_item->atime);
3759 inode->i_mtime.tv_sec = btrfs_timespec_sec(leaf, &inode_item->mtime);
3760 inode->i_mtime.tv_nsec = btrfs_timespec_nsec(leaf, &inode_item->mtime);
3762 inode->i_ctime.tv_sec = btrfs_timespec_sec(leaf, &inode_item->ctime);
3763 inode->i_ctime.tv_nsec = btrfs_timespec_nsec(leaf, &inode_item->ctime);
3765 BTRFS_I(inode)->i_otime.tv_sec =
3766 btrfs_timespec_sec(leaf, &inode_item->otime);
3767 BTRFS_I(inode)->i_otime.tv_nsec =
3768 btrfs_timespec_nsec(leaf, &inode_item->otime);
3770 inode_set_bytes(inode, btrfs_inode_nbytes(leaf, inode_item));
3771 BTRFS_I(inode)->generation = btrfs_inode_generation(leaf, inode_item);
3772 BTRFS_I(inode)->last_trans = btrfs_inode_transid(leaf, inode_item);
3774 inode_set_iversion_queried(inode,
3775 btrfs_inode_sequence(leaf, inode_item));
3776 inode->i_generation = BTRFS_I(inode)->generation;
3778 rdev = btrfs_inode_rdev(leaf, inode_item);
3780 BTRFS_I(inode)->index_cnt = (u64)-1;
3781 BTRFS_I(inode)->flags = btrfs_inode_flags(leaf, inode_item);
3785 * If we were modified in the current generation and evicted from memory
3786 * and then re-read we need to do a full sync since we don't have any
3787 * idea about which extents were modified before we were evicted from
3790 * This is required for both inode re-read from disk and delayed inode
3791 * in delayed_nodes_tree.
3793 if (BTRFS_I(inode)->last_trans == fs_info->generation)
3794 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
3795 &BTRFS_I(inode)->runtime_flags);
3798 * We don't persist the id of the transaction where an unlink operation
3799 * against the inode was last made. So here we assume the inode might
3800 * have been evicted, and therefore the exact value of last_unlink_trans
3801 * lost, and set it to last_trans to avoid metadata inconsistencies
3802 * between the inode and its parent if the inode is fsync'ed and the log
3803 * replayed. For example, in the scenario:
3806 * ln mydir/foo mydir/bar
3809 * echo 2 > /proc/sys/vm/drop_caches # evicts inode
3810 * xfs_io -c fsync mydir/foo
3812 * mount fs, triggers fsync log replay
3814 * We must make sure that when we fsync our inode foo we also log its
3815 * parent inode, otherwise after log replay the parent still has the
3816 * dentry with the "bar" name but our inode foo has a link count of 1
3817 * and doesn't have an inode ref with the name "bar" anymore.
3819 * Setting last_unlink_trans to last_trans is a pessimistic approach,
3820 * but it guarantees correctness at the expense of occasional full
3821 * transaction commits on fsync if our inode is a directory, or if our
3822 * inode is not a directory, logging its parent unnecessarily.
3824 BTRFS_I(inode)->last_unlink_trans = BTRFS_I(inode)->last_trans;
3827 if (inode->i_nlink != 1 ||
3828 path->slots[0] >= btrfs_header_nritems(leaf))
3831 btrfs_item_key_to_cpu(leaf, &location, path->slots[0]);
3832 if (location.objectid != btrfs_ino(BTRFS_I(inode)))
3835 ptr = btrfs_item_ptr_offset(leaf, path->slots[0]);
3836 if (location.type == BTRFS_INODE_REF_KEY) {
3837 struct btrfs_inode_ref *ref;
3839 ref = (struct btrfs_inode_ref *)ptr;
3840 BTRFS_I(inode)->dir_index = btrfs_inode_ref_index(leaf, ref);
3841 } else if (location.type == BTRFS_INODE_EXTREF_KEY) {
3842 struct btrfs_inode_extref *extref;
3844 extref = (struct btrfs_inode_extref *)ptr;
3845 BTRFS_I(inode)->dir_index = btrfs_inode_extref_index(leaf,
3850 * try to precache a NULL acl entry for files that don't have
3851 * any xattrs or acls
3853 maybe_acls = acls_after_inode_item(leaf, path->slots[0],
3854 btrfs_ino(BTRFS_I(inode)), &first_xattr_slot);
3855 if (first_xattr_slot != -1) {
3856 path->slots[0] = first_xattr_slot;
3857 ret = btrfs_load_inode_props(inode, path);
3860 "error loading props for ino %llu (root %llu): %d",
3861 btrfs_ino(BTRFS_I(inode)),
3862 root->root_key.objectid, ret);
3864 if (path != in_path)
3865 btrfs_free_path(path);
3868 cache_no_acl(inode);
3870 switch (inode->i_mode & S_IFMT) {
3872 inode->i_mapping->a_ops = &btrfs_aops;
3873 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
3874 inode->i_fop = &btrfs_file_operations;
3875 inode->i_op = &btrfs_file_inode_operations;
3878 inode->i_fop = &btrfs_dir_file_operations;
3879 inode->i_op = &btrfs_dir_inode_operations;
3882 inode->i_op = &btrfs_symlink_inode_operations;
3883 inode_nohighmem(inode);
3884 inode->i_mapping->a_ops = &btrfs_aops;
3887 inode->i_op = &btrfs_special_inode_operations;
3888 init_special_inode(inode, inode->i_mode, rdev);
3892 btrfs_sync_inode_flags_to_i_flags(inode);
3897 * given a leaf and an inode, copy the inode fields into the leaf
3899 static void fill_inode_item(struct btrfs_trans_handle *trans,
3900 struct extent_buffer *leaf,
3901 struct btrfs_inode_item *item,
3902 struct inode *inode)
3904 struct btrfs_map_token token;
3906 btrfs_init_map_token(&token, leaf);
3908 btrfs_set_token_inode_uid(leaf, item, i_uid_read(inode), &token);
3909 btrfs_set_token_inode_gid(leaf, item, i_gid_read(inode), &token);
3910 btrfs_set_token_inode_size(leaf, item, BTRFS_I(inode)->disk_i_size,
3912 btrfs_set_token_inode_mode(leaf, item, inode->i_mode, &token);
3913 btrfs_set_token_inode_nlink(leaf, item, inode->i_nlink, &token);
3915 btrfs_set_token_timespec_sec(leaf, &item->atime,
3916 inode->i_atime.tv_sec, &token);
3917 btrfs_set_token_timespec_nsec(leaf, &item->atime,
3918 inode->i_atime.tv_nsec, &token);
3920 btrfs_set_token_timespec_sec(leaf, &item->mtime,
3921 inode->i_mtime.tv_sec, &token);
3922 btrfs_set_token_timespec_nsec(leaf, &item->mtime,
3923 inode->i_mtime.tv_nsec, &token);
3925 btrfs_set_token_timespec_sec(leaf, &item->ctime,
3926 inode->i_ctime.tv_sec, &token);
3927 btrfs_set_token_timespec_nsec(leaf, &item->ctime,
3928 inode->i_ctime.tv_nsec, &token);
3930 btrfs_set_token_timespec_sec(leaf, &item->otime,
3931 BTRFS_I(inode)->i_otime.tv_sec, &token);
3932 btrfs_set_token_timespec_nsec(leaf, &item->otime,
3933 BTRFS_I(inode)->i_otime.tv_nsec, &token);
3935 btrfs_set_token_inode_nbytes(leaf, item, inode_get_bytes(inode),
3937 btrfs_set_token_inode_generation(leaf, item, BTRFS_I(inode)->generation,
3939 btrfs_set_token_inode_sequence(leaf, item, inode_peek_iversion(inode),
3941 btrfs_set_token_inode_transid(leaf, item, trans->transid, &token);
3942 btrfs_set_token_inode_rdev(leaf, item, inode->i_rdev, &token);
3943 btrfs_set_token_inode_flags(leaf, item, BTRFS_I(inode)->flags, &token);
3944 btrfs_set_token_inode_block_group(leaf, item, 0, &token);
3948 * copy everything in the in-memory inode into the btree.
3950 static noinline int btrfs_update_inode_item(struct btrfs_trans_handle *trans,
3951 struct btrfs_root *root, struct inode *inode)
3953 struct btrfs_inode_item *inode_item;
3954 struct btrfs_path *path;
3955 struct extent_buffer *leaf;
3958 path = btrfs_alloc_path();
3962 path->leave_spinning = 1;
3963 ret = btrfs_lookup_inode(trans, root, path, &BTRFS_I(inode)->location,
3971 leaf = path->nodes[0];
3972 inode_item = btrfs_item_ptr(leaf, path->slots[0],
3973 struct btrfs_inode_item);
3975 fill_inode_item(trans, leaf, inode_item, inode);
3976 btrfs_mark_buffer_dirty(leaf);
3977 btrfs_set_inode_last_trans(trans, inode);
3980 btrfs_free_path(path);
3985 * copy everything in the in-memory inode into the btree.
3987 noinline int btrfs_update_inode(struct btrfs_trans_handle *trans,
3988 struct btrfs_root *root, struct inode *inode)
3990 struct btrfs_fs_info *fs_info = root->fs_info;
3994 * If the inode is a free space inode, we can deadlock during commit
3995 * if we put it into the delayed code.
3997 * The data relocation inode should also be directly updated
4000 if (!btrfs_is_free_space_inode(BTRFS_I(inode))
4001 && root->root_key.objectid != BTRFS_DATA_RELOC_TREE_OBJECTID
4002 && !test_bit(BTRFS_FS_LOG_RECOVERING, &fs_info->flags)) {
4003 btrfs_update_root_times(trans, root);
4005 ret = btrfs_delayed_update_inode(trans, root, inode);
4007 btrfs_set_inode_last_trans(trans, inode);
4011 return btrfs_update_inode_item(trans, root, inode);
4014 noinline int btrfs_update_inode_fallback(struct btrfs_trans_handle *trans,
4015 struct btrfs_root *root,
4016 struct inode *inode)
4020 ret = btrfs_update_inode(trans, root, inode);
4022 return btrfs_update_inode_item(trans, root, inode);
4027 * unlink helper that gets used here in inode.c and in the tree logging
4028 * recovery code. It remove a link in a directory with a given name, and
4029 * also drops the back refs in the inode to the directory
4031 static int __btrfs_unlink_inode(struct btrfs_trans_handle *trans,
4032 struct btrfs_root *root,
4033 struct btrfs_inode *dir,
4034 struct btrfs_inode *inode,
4035 const char *name, int name_len)
4037 struct btrfs_fs_info *fs_info = root->fs_info;
4038 struct btrfs_path *path;
4040 struct btrfs_dir_item *di;
4042 u64 ino = btrfs_ino(inode);
4043 u64 dir_ino = btrfs_ino(dir);
4045 path = btrfs_alloc_path();
4051 path->leave_spinning = 1;
4052 di = btrfs_lookup_dir_item(trans, root, path, dir_ino,
4053 name, name_len, -1);
4054 if (IS_ERR_OR_NULL(di)) {
4055 ret = di ? PTR_ERR(di) : -ENOENT;
4058 ret = btrfs_delete_one_dir_name(trans, root, path, di);
4061 btrfs_release_path(path);
4064 * If we don't have dir index, we have to get it by looking up
4065 * the inode ref, since we get the inode ref, remove it directly,
4066 * it is unnecessary to do delayed deletion.
4068 * But if we have dir index, needn't search inode ref to get it.
4069 * Since the inode ref is close to the inode item, it is better
4070 * that we delay to delete it, and just do this deletion when
4071 * we update the inode item.
4073 if (inode->dir_index) {
4074 ret = btrfs_delayed_delete_inode_ref(inode);
4076 index = inode->dir_index;
4081 ret = btrfs_del_inode_ref(trans, root, name, name_len, ino,
4085 "failed to delete reference to %.*s, inode %llu parent %llu",
4086 name_len, name, ino, dir_ino);
4087 btrfs_abort_transaction(trans, ret);
4091 ret = btrfs_delete_delayed_dir_index(trans, dir, index);
4093 btrfs_abort_transaction(trans, ret);
4097 ret = btrfs_del_inode_ref_in_log(trans, root, name, name_len, inode,
4099 if (ret != 0 && ret != -ENOENT) {
4100 btrfs_abort_transaction(trans, ret);
4104 ret = btrfs_del_dir_entries_in_log(trans, root, name, name_len, dir,
4109 btrfs_abort_transaction(trans, ret);
4112 * If we have a pending delayed iput we could end up with the final iput
4113 * being run in btrfs-cleaner context. If we have enough of these built
4114 * up we can end up burning a lot of time in btrfs-cleaner without any
4115 * way to throttle the unlinks. Since we're currently holding a ref on
4116 * the inode we can run the delayed iput here without any issues as the
4117 * final iput won't be done until after we drop the ref we're currently
4120 btrfs_run_delayed_iput(fs_info, inode);
4122 btrfs_free_path(path);
4126 btrfs_i_size_write(dir, dir->vfs_inode.i_size - name_len * 2);
4127 inode_inc_iversion(&inode->vfs_inode);
4128 inode_inc_iversion(&dir->vfs_inode);
4129 inode->vfs_inode.i_ctime = dir->vfs_inode.i_mtime =
4130 dir->vfs_inode.i_ctime = current_time(&inode->vfs_inode);
4131 ret = btrfs_update_inode(trans, root, &dir->vfs_inode);
4136 int btrfs_unlink_inode(struct btrfs_trans_handle *trans,
4137 struct btrfs_root *root,
4138 struct btrfs_inode *dir, struct btrfs_inode *inode,
4139 const char *name, int name_len)
4142 ret = __btrfs_unlink_inode(trans, root, dir, inode, name, name_len);
4144 drop_nlink(&inode->vfs_inode);
4145 ret = btrfs_update_inode(trans, root, &inode->vfs_inode);
4151 * helper to start transaction for unlink and rmdir.
4153 * unlink and rmdir are special in btrfs, they do not always free space, so
4154 * if we cannot make our reservations the normal way try and see if there is
4155 * plenty of slack room in the global reserve to migrate, otherwise we cannot
4156 * allow the unlink to occur.
4158 static struct btrfs_trans_handle *__unlink_start_trans(struct inode *dir)
4160 struct btrfs_root *root = BTRFS_I(dir)->root;
4163 * 1 for the possible orphan item
4164 * 1 for the dir item
4165 * 1 for the dir index
4166 * 1 for the inode ref
4169 return btrfs_start_transaction_fallback_global_rsv(root, 5, 5);
4172 static int btrfs_unlink(struct inode *dir, struct dentry *dentry)
4174 struct btrfs_root *root = BTRFS_I(dir)->root;
4175 struct btrfs_trans_handle *trans;
4176 struct inode *inode = d_inode(dentry);
4179 trans = __unlink_start_trans(dir);
4181 return PTR_ERR(trans);
4183 btrfs_record_unlink_dir(trans, BTRFS_I(dir), BTRFS_I(d_inode(dentry)),
4186 ret = btrfs_unlink_inode(trans, root, BTRFS_I(dir),
4187 BTRFS_I(d_inode(dentry)), dentry->d_name.name,
4188 dentry->d_name.len);
4192 if (inode->i_nlink == 0) {
4193 ret = btrfs_orphan_add(trans, BTRFS_I(inode));
4199 btrfs_end_transaction(trans);
4200 btrfs_btree_balance_dirty(root->fs_info);
4204 static int btrfs_unlink_subvol(struct btrfs_trans_handle *trans,
4205 struct inode *dir, u64 objectid,
4206 const char *name, int name_len)
4208 struct btrfs_root *root = BTRFS_I(dir)->root;
4209 struct btrfs_path *path;
4210 struct extent_buffer *leaf;
4211 struct btrfs_dir_item *di;
4212 struct btrfs_key key;
4215 u64 dir_ino = btrfs_ino(BTRFS_I(dir));
4217 path = btrfs_alloc_path();
4221 di = btrfs_lookup_dir_item(trans, root, path, dir_ino,
4222 name, name_len, -1);
4223 if (IS_ERR_OR_NULL(di)) {
4224 ret = di ? PTR_ERR(di) : -ENOENT;
4228 leaf = path->nodes[0];
4229 btrfs_dir_item_key_to_cpu(leaf, di, &key);
4230 WARN_ON(key.type != BTRFS_ROOT_ITEM_KEY || key.objectid != objectid);
4231 ret = btrfs_delete_one_dir_name(trans, root, path, di);
4233 btrfs_abort_transaction(trans, ret);
4236 btrfs_release_path(path);
4238 ret = btrfs_del_root_ref(trans, objectid, root->root_key.objectid,
4239 dir_ino, &index, name, name_len);
4241 if (ret != -ENOENT) {
4242 btrfs_abort_transaction(trans, ret);
4245 di = btrfs_search_dir_index_item(root, path, dir_ino,
4247 if (IS_ERR_OR_NULL(di)) {
4252 btrfs_abort_transaction(trans, ret);
4256 leaf = path->nodes[0];
4257 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
4260 btrfs_release_path(path);
4262 ret = btrfs_delete_delayed_dir_index(trans, BTRFS_I(dir), index);
4264 btrfs_abort_transaction(trans, ret);
4268 btrfs_i_size_write(BTRFS_I(dir), dir->i_size - name_len * 2);
4269 inode_inc_iversion(dir);
4270 dir->i_mtime = dir->i_ctime = current_time(dir);
4271 ret = btrfs_update_inode_fallback(trans, root, dir);
4273 btrfs_abort_transaction(trans, ret);
4275 btrfs_free_path(path);
4280 * Helper to check if the subvolume references other subvolumes or if it's
4283 static noinline int may_destroy_subvol(struct btrfs_root *root)
4285 struct btrfs_fs_info *fs_info = root->fs_info;
4286 struct btrfs_path *path;
4287 struct btrfs_dir_item *di;
4288 struct btrfs_key key;
4292 path = btrfs_alloc_path();
4296 /* Make sure this root isn't set as the default subvol */
4297 dir_id = btrfs_super_root_dir(fs_info->super_copy);
4298 di = btrfs_lookup_dir_item(NULL, fs_info->tree_root, path,
4299 dir_id, "default", 7, 0);
4300 if (di && !IS_ERR(di)) {
4301 btrfs_dir_item_key_to_cpu(path->nodes[0], di, &key);
4302 if (key.objectid == root->root_key.objectid) {
4305 "deleting default subvolume %llu is not allowed",
4309 btrfs_release_path(path);
4312 key.objectid = root->root_key.objectid;
4313 key.type = BTRFS_ROOT_REF_KEY;
4314 key.offset = (u64)-1;
4316 ret = btrfs_search_slot(NULL, fs_info->tree_root, &key, path, 0, 0);
4322 if (path->slots[0] > 0) {
4324 btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
4325 if (key.objectid == root->root_key.objectid &&
4326 key.type == BTRFS_ROOT_REF_KEY)
4330 btrfs_free_path(path);
4334 /* Delete all dentries for inodes belonging to the root */
4335 static void btrfs_prune_dentries(struct btrfs_root *root)
4337 struct btrfs_fs_info *fs_info = root->fs_info;
4338 struct rb_node *node;
4339 struct rb_node *prev;
4340 struct btrfs_inode *entry;
4341 struct inode *inode;
4344 if (!test_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state))
4345 WARN_ON(btrfs_root_refs(&root->root_item) != 0);
4347 spin_lock(&root->inode_lock);
4349 node = root->inode_tree.rb_node;
4353 entry = rb_entry(node, struct btrfs_inode, rb_node);
4355 if (objectid < btrfs_ino(entry))
4356 node = node->rb_left;
4357 else if (objectid > btrfs_ino(entry))
4358 node = node->rb_right;
4364 entry = rb_entry(prev, struct btrfs_inode, rb_node);
4365 if (objectid <= btrfs_ino(entry)) {
4369 prev = rb_next(prev);
4373 entry = rb_entry(node, struct btrfs_inode, rb_node);
4374 objectid = btrfs_ino(entry) + 1;
4375 inode = igrab(&entry->vfs_inode);
4377 spin_unlock(&root->inode_lock);
4378 if (atomic_read(&inode->i_count) > 1)
4379 d_prune_aliases(inode);
4381 * btrfs_drop_inode will have it removed from the inode
4382 * cache when its usage count hits zero.
4386 spin_lock(&root->inode_lock);
4390 if (cond_resched_lock(&root->inode_lock))
4393 node = rb_next(node);
4395 spin_unlock(&root->inode_lock);
4398 int btrfs_delete_subvolume(struct inode *dir, struct dentry *dentry)
4400 struct btrfs_fs_info *fs_info = btrfs_sb(dentry->d_sb);
4401 struct btrfs_root *root = BTRFS_I(dir)->root;
4402 struct inode *inode = d_inode(dentry);
4403 struct btrfs_root *dest = BTRFS_I(inode)->root;
4404 struct btrfs_trans_handle *trans;
4405 struct btrfs_block_rsv block_rsv;
4411 * Don't allow to delete a subvolume with send in progress. This is
4412 * inside the inode lock so the error handling that has to drop the bit
4413 * again is not run concurrently.
4415 spin_lock(&dest->root_item_lock);
4416 if (dest->send_in_progress) {
4417 spin_unlock(&dest->root_item_lock);
4419 "attempt to delete subvolume %llu during send",
4420 dest->root_key.objectid);
4423 root_flags = btrfs_root_flags(&dest->root_item);
4424 btrfs_set_root_flags(&dest->root_item,
4425 root_flags | BTRFS_ROOT_SUBVOL_DEAD);
4426 spin_unlock(&dest->root_item_lock);
4428 down_write(&fs_info->subvol_sem);
4430 err = may_destroy_subvol(dest);
4434 btrfs_init_block_rsv(&block_rsv, BTRFS_BLOCK_RSV_TEMP);
4436 * One for dir inode,
4437 * two for dir entries,
4438 * two for root ref/backref.
4440 err = btrfs_subvolume_reserve_metadata(root, &block_rsv, 5, true);
4444 trans = btrfs_start_transaction(root, 0);
4445 if (IS_ERR(trans)) {
4446 err = PTR_ERR(trans);
4449 trans->block_rsv = &block_rsv;
4450 trans->bytes_reserved = block_rsv.size;
4452 btrfs_record_snapshot_destroy(trans, BTRFS_I(dir));
4454 ret = btrfs_unlink_subvol(trans, dir, dest->root_key.objectid,
4455 dentry->d_name.name, dentry->d_name.len);
4458 btrfs_abort_transaction(trans, ret);
4462 btrfs_record_root_in_trans(trans, dest);
4464 memset(&dest->root_item.drop_progress, 0,
4465 sizeof(dest->root_item.drop_progress));
4466 dest->root_item.drop_level = 0;
4467 btrfs_set_root_refs(&dest->root_item, 0);
4469 if (!test_and_set_bit(BTRFS_ROOT_ORPHAN_ITEM_INSERTED, &dest->state)) {
4470 ret = btrfs_insert_orphan_item(trans,
4472 dest->root_key.objectid);
4474 btrfs_abort_transaction(trans, ret);
4480 ret = btrfs_uuid_tree_remove(trans, dest->root_item.uuid,
4481 BTRFS_UUID_KEY_SUBVOL,
4482 dest->root_key.objectid);
4483 if (ret && ret != -ENOENT) {
4484 btrfs_abort_transaction(trans, ret);
4488 if (!btrfs_is_empty_uuid(dest->root_item.received_uuid)) {
4489 ret = btrfs_uuid_tree_remove(trans,
4490 dest->root_item.received_uuid,
4491 BTRFS_UUID_KEY_RECEIVED_SUBVOL,
4492 dest->root_key.objectid);
4493 if (ret && ret != -ENOENT) {
4494 btrfs_abort_transaction(trans, ret);
4501 trans->block_rsv = NULL;
4502 trans->bytes_reserved = 0;
4503 ret = btrfs_end_transaction(trans);
4506 inode->i_flags |= S_DEAD;
4508 btrfs_subvolume_release_metadata(fs_info, &block_rsv);
4510 up_write(&fs_info->subvol_sem);
4512 spin_lock(&dest->root_item_lock);
4513 root_flags = btrfs_root_flags(&dest->root_item);
4514 btrfs_set_root_flags(&dest->root_item,
4515 root_flags & ~BTRFS_ROOT_SUBVOL_DEAD);
4516 spin_unlock(&dest->root_item_lock);
4518 d_invalidate(dentry);
4519 btrfs_prune_dentries(dest);
4520 ASSERT(dest->send_in_progress == 0);
4523 if (dest->ino_cache_inode) {
4524 iput(dest->ino_cache_inode);
4525 dest->ino_cache_inode = NULL;
4532 static int btrfs_rmdir(struct inode *dir, struct dentry *dentry)
4534 struct inode *inode = d_inode(dentry);
4536 struct btrfs_root *root = BTRFS_I(dir)->root;
4537 struct btrfs_trans_handle *trans;
4538 u64 last_unlink_trans;
4540 if (inode->i_size > BTRFS_EMPTY_DIR_SIZE)
4542 if (btrfs_ino(BTRFS_I(inode)) == BTRFS_FIRST_FREE_OBJECTID)
4543 return btrfs_delete_subvolume(dir, dentry);
4545 trans = __unlink_start_trans(dir);
4547 return PTR_ERR(trans);
4549 if (unlikely(btrfs_ino(BTRFS_I(inode)) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)) {
4550 err = btrfs_unlink_subvol(trans, dir,
4551 BTRFS_I(inode)->location.objectid,
4552 dentry->d_name.name,
4553 dentry->d_name.len);
4557 err = btrfs_orphan_add(trans, BTRFS_I(inode));
4561 last_unlink_trans = BTRFS_I(inode)->last_unlink_trans;
4563 /* now the directory is empty */
4564 err = btrfs_unlink_inode(trans, root, BTRFS_I(dir),
4565 BTRFS_I(d_inode(dentry)), dentry->d_name.name,
4566 dentry->d_name.len);
4568 btrfs_i_size_write(BTRFS_I(inode), 0);
4570 * Propagate the last_unlink_trans value of the deleted dir to
4571 * its parent directory. This is to prevent an unrecoverable
4572 * log tree in the case we do something like this:
4574 * 2) create snapshot under dir foo
4575 * 3) delete the snapshot
4578 * 6) fsync foo or some file inside foo
4580 if (last_unlink_trans >= trans->transid)
4581 BTRFS_I(dir)->last_unlink_trans = last_unlink_trans;
4584 btrfs_end_transaction(trans);
4585 btrfs_btree_balance_dirty(root->fs_info);
4591 * Return this if we need to call truncate_block for the last bit of the
4594 #define NEED_TRUNCATE_BLOCK 1
4597 * this can truncate away extent items, csum items and directory items.
4598 * It starts at a high offset and removes keys until it can't find
4599 * any higher than new_size
4601 * csum items that cross the new i_size are truncated to the new size
4604 * min_type is the minimum key type to truncate down to. If set to 0, this
4605 * will kill all the items on this inode, including the INODE_ITEM_KEY.
4607 int btrfs_truncate_inode_items(struct btrfs_trans_handle *trans,
4608 struct btrfs_root *root,
4609 struct inode *inode,
4610 u64 new_size, u32 min_type)
4612 struct btrfs_fs_info *fs_info = root->fs_info;
4613 struct btrfs_path *path;
4614 struct extent_buffer *leaf;
4615 struct btrfs_file_extent_item *fi;
4616 struct btrfs_key key;
4617 struct btrfs_key found_key;
4618 u64 extent_start = 0;
4619 u64 extent_num_bytes = 0;
4620 u64 extent_offset = 0;
4622 u64 last_size = new_size;
4623 u32 found_type = (u8)-1;
4626 int pending_del_nr = 0;
4627 int pending_del_slot = 0;
4628 int extent_type = -1;
4630 u64 ino = btrfs_ino(BTRFS_I(inode));
4631 u64 bytes_deleted = 0;
4632 bool be_nice = false;
4633 bool should_throttle = false;
4635 BUG_ON(new_size > 0 && min_type != BTRFS_EXTENT_DATA_KEY);
4638 * for non-free space inodes and ref cows, we want to back off from
4641 if (!btrfs_is_free_space_inode(BTRFS_I(inode)) &&
4642 test_bit(BTRFS_ROOT_REF_COWS, &root->state))
4645 path = btrfs_alloc_path();
4648 path->reada = READA_BACK;
4651 * We want to drop from the next block forward in case this new size is
4652 * not block aligned since we will be keeping the last block of the
4653 * extent just the way it is.
4655 if (test_bit(BTRFS_ROOT_REF_COWS, &root->state) ||
4656 root == fs_info->tree_root)
4657 btrfs_drop_extent_cache(BTRFS_I(inode), ALIGN(new_size,
4658 fs_info->sectorsize),
4662 * This function is also used to drop the items in the log tree before
4663 * we relog the inode, so if root != BTRFS_I(inode)->root, it means
4664 * it is used to drop the logged items. So we shouldn't kill the delayed
4667 if (min_type == 0 && root == BTRFS_I(inode)->root)
4668 btrfs_kill_delayed_inode_items(BTRFS_I(inode));
4671 key.offset = (u64)-1;
4676 * with a 16K leaf size and 128MB extents, you can actually queue
4677 * up a huge file in a single leaf. Most of the time that
4678 * bytes_deleted is > 0, it will be huge by the time we get here
4680 if (be_nice && bytes_deleted > SZ_32M &&
4681 btrfs_should_end_transaction(trans)) {
4686 path->leave_spinning = 1;
4687 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
4693 /* there are no items in the tree for us to truncate, we're
4696 if (path->slots[0] == 0)
4703 leaf = path->nodes[0];
4704 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
4705 found_type = found_key.type;
4707 if (found_key.objectid != ino)
4710 if (found_type < min_type)
4713 item_end = found_key.offset;
4714 if (found_type == BTRFS_EXTENT_DATA_KEY) {
4715 fi = btrfs_item_ptr(leaf, path->slots[0],
4716 struct btrfs_file_extent_item);
4717 extent_type = btrfs_file_extent_type(leaf, fi);
4718 if (extent_type != BTRFS_FILE_EXTENT_INLINE) {
4720 btrfs_file_extent_num_bytes(leaf, fi);
4722 trace_btrfs_truncate_show_fi_regular(
4723 BTRFS_I(inode), leaf, fi,
4725 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
4726 item_end += btrfs_file_extent_ram_bytes(leaf,
4729 trace_btrfs_truncate_show_fi_inline(
4730 BTRFS_I(inode), leaf, fi, path->slots[0],
4735 if (found_type > min_type) {
4738 if (item_end < new_size)
4740 if (found_key.offset >= new_size)
4746 /* FIXME, shrink the extent if the ref count is only 1 */
4747 if (found_type != BTRFS_EXTENT_DATA_KEY)
4750 if (extent_type != BTRFS_FILE_EXTENT_INLINE) {
4752 extent_start = btrfs_file_extent_disk_bytenr(leaf, fi);
4754 u64 orig_num_bytes =
4755 btrfs_file_extent_num_bytes(leaf, fi);
4756 extent_num_bytes = ALIGN(new_size -
4758 fs_info->sectorsize);
4759 btrfs_set_file_extent_num_bytes(leaf, fi,
4761 num_dec = (orig_num_bytes -
4763 if (test_bit(BTRFS_ROOT_REF_COWS,
4766 inode_sub_bytes(inode, num_dec);
4767 btrfs_mark_buffer_dirty(leaf);
4770 btrfs_file_extent_disk_num_bytes(leaf,
4772 extent_offset = found_key.offset -
4773 btrfs_file_extent_offset(leaf, fi);
4775 /* FIXME blocksize != 4096 */
4776 num_dec = btrfs_file_extent_num_bytes(leaf, fi);
4777 if (extent_start != 0) {
4779 if (test_bit(BTRFS_ROOT_REF_COWS,
4781 inode_sub_bytes(inode, num_dec);
4784 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
4786 * we can't truncate inline items that have had
4790 btrfs_file_extent_encryption(leaf, fi) == 0 &&
4791 btrfs_file_extent_other_encoding(leaf, fi) == 0 &&
4792 btrfs_file_extent_compression(leaf, fi) == 0) {
4793 u32 size = (u32)(new_size - found_key.offset);
4795 btrfs_set_file_extent_ram_bytes(leaf, fi, size);
4796 size = btrfs_file_extent_calc_inline_size(size);
4797 btrfs_truncate_item(path, size, 1);
4798 } else if (!del_item) {
4800 * We have to bail so the last_size is set to
4801 * just before this extent.
4803 ret = NEED_TRUNCATE_BLOCK;
4807 if (test_bit(BTRFS_ROOT_REF_COWS, &root->state))
4808 inode_sub_bytes(inode, item_end + 1 - new_size);
4812 last_size = found_key.offset;
4814 last_size = new_size;
4816 if (!pending_del_nr) {
4817 /* no pending yet, add ourselves */
4818 pending_del_slot = path->slots[0];
4820 } else if (pending_del_nr &&
4821 path->slots[0] + 1 == pending_del_slot) {
4822 /* hop on the pending chunk */
4824 pending_del_slot = path->slots[0];
4831 should_throttle = false;
4834 (test_bit(BTRFS_ROOT_REF_COWS, &root->state) ||
4835 root == fs_info->tree_root)) {
4836 struct btrfs_ref ref = { 0 };
4838 btrfs_set_path_blocking(path);
4839 bytes_deleted += extent_num_bytes;
4841 btrfs_init_generic_ref(&ref, BTRFS_DROP_DELAYED_REF,
4842 extent_start, extent_num_bytes, 0);
4843 ref.real_root = root->root_key.objectid;
4844 btrfs_init_data_ref(&ref, btrfs_header_owner(leaf),
4845 ino, extent_offset);
4846 ret = btrfs_free_extent(trans, &ref);
4848 btrfs_abort_transaction(trans, ret);
4852 if (btrfs_should_throttle_delayed_refs(trans))
4853 should_throttle = true;
4857 if (found_type == BTRFS_INODE_ITEM_KEY)
4860 if (path->slots[0] == 0 ||
4861 path->slots[0] != pending_del_slot ||
4863 if (pending_del_nr) {
4864 ret = btrfs_del_items(trans, root, path,
4868 btrfs_abort_transaction(trans, ret);
4873 btrfs_release_path(path);
4876 * We can generate a lot of delayed refs, so we need to
4877 * throttle every once and a while and make sure we're
4878 * adding enough space to keep up with the work we are
4879 * generating. Since we hold a transaction here we
4880 * can't flush, and we don't want to FLUSH_LIMIT because
4881 * we could have generated too many delayed refs to
4882 * actually allocate, so just bail if we're short and
4883 * let the normal reservation dance happen higher up.
4885 if (should_throttle) {
4886 ret = btrfs_delayed_refs_rsv_refill(fs_info,
4887 BTRFS_RESERVE_NO_FLUSH);
4899 if (ret >= 0 && pending_del_nr) {
4902 err = btrfs_del_items(trans, root, path, pending_del_slot,
4905 btrfs_abort_transaction(trans, err);
4909 if (root->root_key.objectid != BTRFS_TREE_LOG_OBJECTID) {
4910 ASSERT(last_size >= new_size);
4911 if (!ret && last_size > new_size)
4912 last_size = new_size;
4913 btrfs_ordered_update_i_size(inode, last_size, NULL);
4916 btrfs_free_path(path);
4921 * btrfs_truncate_block - read, zero a chunk and write a block
4922 * @inode - inode that we're zeroing
4923 * @from - the offset to start zeroing
4924 * @len - the length to zero, 0 to zero the entire range respective to the
4926 * @front - zero up to the offset instead of from the offset on
4928 * This will find the block for the "from" offset and cow the block and zero the
4929 * part we want to zero. This is used with truncate and hole punching.
4931 int btrfs_truncate_block(struct inode *inode, loff_t from, loff_t len,
4934 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
4935 struct address_space *mapping = inode->i_mapping;
4936 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
4937 struct btrfs_ordered_extent *ordered;
4938 struct extent_state *cached_state = NULL;
4939 struct extent_changeset *data_reserved = NULL;
4941 u32 blocksize = fs_info->sectorsize;
4942 pgoff_t index = from >> PAGE_SHIFT;
4943 unsigned offset = from & (blocksize - 1);
4945 gfp_t mask = btrfs_alloc_write_mask(mapping);
4950 if (IS_ALIGNED(offset, blocksize) &&
4951 (!len || IS_ALIGNED(len, blocksize)))
4954 block_start = round_down(from, blocksize);
4955 block_end = block_start + blocksize - 1;
4957 ret = btrfs_delalloc_reserve_space(inode, &data_reserved,
4958 block_start, blocksize);
4963 page = find_or_create_page(mapping, index, mask);
4965 btrfs_delalloc_release_space(inode, data_reserved,
4966 block_start, blocksize, true);
4967 btrfs_delalloc_release_extents(BTRFS_I(inode), blocksize);
4972 if (!PageUptodate(page)) {
4973 ret = btrfs_readpage(NULL, page);
4975 if (page->mapping != mapping) {
4980 if (!PageUptodate(page)) {
4985 wait_on_page_writeback(page);
4987 lock_extent_bits(io_tree, block_start, block_end, &cached_state);
4988 set_page_extent_mapped(page);
4990 ordered = btrfs_lookup_ordered_extent(inode, block_start);
4992 unlock_extent_cached(io_tree, block_start, block_end,
4996 btrfs_start_ordered_extent(inode, ordered, 1);
4997 btrfs_put_ordered_extent(ordered);
5001 clear_extent_bit(&BTRFS_I(inode)->io_tree, block_start, block_end,
5002 EXTENT_DELALLOC | EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG,
5003 0, 0, &cached_state);
5005 ret = btrfs_set_extent_delalloc(inode, block_start, block_end, 0,
5008 unlock_extent_cached(io_tree, block_start, block_end,
5013 if (offset != blocksize) {
5015 len = blocksize - offset;
5018 memset(kaddr + (block_start - page_offset(page)),
5021 memset(kaddr + (block_start - page_offset(page)) + offset,
5023 flush_dcache_page(page);
5026 ClearPageChecked(page);
5027 set_page_dirty(page);
5028 unlock_extent_cached(io_tree, block_start, block_end, &cached_state);
5032 btrfs_delalloc_release_space(inode, data_reserved, block_start,
5034 btrfs_delalloc_release_extents(BTRFS_I(inode), blocksize);
5038 extent_changeset_free(data_reserved);
5042 static int maybe_insert_hole(struct btrfs_root *root, struct inode *inode,
5043 u64 offset, u64 len)
5045 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
5046 struct btrfs_trans_handle *trans;
5050 * Still need to make sure the inode looks like it's been updated so
5051 * that any holes get logged if we fsync.
5053 if (btrfs_fs_incompat(fs_info, NO_HOLES)) {
5054 BTRFS_I(inode)->last_trans = fs_info->generation;
5055 BTRFS_I(inode)->last_sub_trans = root->log_transid;
5056 BTRFS_I(inode)->last_log_commit = root->last_log_commit;
5061 * 1 - for the one we're dropping
5062 * 1 - for the one we're adding
5063 * 1 - for updating the inode.
5065 trans = btrfs_start_transaction(root, 3);
5067 return PTR_ERR(trans);
5069 ret = btrfs_drop_extents(trans, root, inode, offset, offset + len, 1);
5071 btrfs_abort_transaction(trans, ret);
5072 btrfs_end_transaction(trans);
5076 ret = btrfs_insert_file_extent(trans, root, btrfs_ino(BTRFS_I(inode)),
5077 offset, 0, 0, len, 0, len, 0, 0, 0);
5079 btrfs_abort_transaction(trans, ret);
5081 btrfs_update_inode(trans, root, inode);
5082 btrfs_end_transaction(trans);
5087 * This function puts in dummy file extents for the area we're creating a hole
5088 * for. So if we are truncating this file to a larger size we need to insert
5089 * these file extents so that btrfs_get_extent will return a EXTENT_MAP_HOLE for
5090 * the range between oldsize and size
5092 int btrfs_cont_expand(struct inode *inode, loff_t oldsize, loff_t size)
5094 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
5095 struct btrfs_root *root = BTRFS_I(inode)->root;
5096 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
5097 struct extent_map *em = NULL;
5098 struct extent_state *cached_state = NULL;
5099 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
5100 u64 hole_start = ALIGN(oldsize, fs_info->sectorsize);
5101 u64 block_end = ALIGN(size, fs_info->sectorsize);
5108 * If our size started in the middle of a block we need to zero out the
5109 * rest of the block before we expand the i_size, otherwise we could
5110 * expose stale data.
5112 err = btrfs_truncate_block(inode, oldsize, 0, 0);
5116 if (size <= hole_start)
5119 btrfs_lock_and_flush_ordered_range(io_tree, BTRFS_I(inode), hole_start,
5120 block_end - 1, &cached_state);
5121 cur_offset = hole_start;
5123 em = btrfs_get_extent(BTRFS_I(inode), NULL, 0, cur_offset,
5124 block_end - cur_offset, 0);
5130 last_byte = min(extent_map_end(em), block_end);
5131 last_byte = ALIGN(last_byte, fs_info->sectorsize);
5132 if (!test_bit(EXTENT_FLAG_PREALLOC, &em->flags)) {
5133 struct extent_map *hole_em;
5134 hole_size = last_byte - cur_offset;
5136 err = maybe_insert_hole(root, inode, cur_offset,
5140 btrfs_drop_extent_cache(BTRFS_I(inode), cur_offset,
5141 cur_offset + hole_size - 1, 0);
5142 hole_em = alloc_extent_map();
5144 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
5145 &BTRFS_I(inode)->runtime_flags);
5148 hole_em->start = cur_offset;
5149 hole_em->len = hole_size;
5150 hole_em->orig_start = cur_offset;
5152 hole_em->block_start = EXTENT_MAP_HOLE;
5153 hole_em->block_len = 0;
5154 hole_em->orig_block_len = 0;
5155 hole_em->ram_bytes = hole_size;
5156 hole_em->bdev = fs_info->fs_devices->latest_bdev;
5157 hole_em->compress_type = BTRFS_COMPRESS_NONE;
5158 hole_em->generation = fs_info->generation;
5161 write_lock(&em_tree->lock);
5162 err = add_extent_mapping(em_tree, hole_em, 1);
5163 write_unlock(&em_tree->lock);
5166 btrfs_drop_extent_cache(BTRFS_I(inode),
5171 free_extent_map(hole_em);
5174 free_extent_map(em);
5176 cur_offset = last_byte;
5177 if (cur_offset >= block_end)
5180 free_extent_map(em);
5181 unlock_extent_cached(io_tree, hole_start, block_end - 1, &cached_state);
5185 static int btrfs_setsize(struct inode *inode, struct iattr *attr)
5187 struct btrfs_root *root = BTRFS_I(inode)->root;
5188 struct btrfs_trans_handle *trans;
5189 loff_t oldsize = i_size_read(inode);
5190 loff_t newsize = attr->ia_size;
5191 int mask = attr->ia_valid;
5195 * The regular truncate() case without ATTR_CTIME and ATTR_MTIME is a
5196 * special case where we need to update the times despite not having
5197 * these flags set. For all other operations the VFS set these flags
5198 * explicitly if it wants a timestamp update.
5200 if (newsize != oldsize) {
5201 inode_inc_iversion(inode);
5202 if (!(mask & (ATTR_CTIME | ATTR_MTIME)))
5203 inode->i_ctime = inode->i_mtime =
5204 current_time(inode);
5207 if (newsize > oldsize) {
5209 * Don't do an expanding truncate while snapshotting is ongoing.
5210 * This is to ensure the snapshot captures a fully consistent
5211 * state of this file - if the snapshot captures this expanding
5212 * truncation, it must capture all writes that happened before
5215 btrfs_wait_for_snapshot_creation(root);
5216 ret = btrfs_cont_expand(inode, oldsize, newsize);
5218 btrfs_end_write_no_snapshotting(root);
5222 trans = btrfs_start_transaction(root, 1);
5223 if (IS_ERR(trans)) {
5224 btrfs_end_write_no_snapshotting(root);
5225 return PTR_ERR(trans);
5228 i_size_write(inode, newsize);
5229 btrfs_ordered_update_i_size(inode, i_size_read(inode), NULL);
5230 pagecache_isize_extended(inode, oldsize, newsize);
5231 ret = btrfs_update_inode(trans, root, inode);
5232 btrfs_end_write_no_snapshotting(root);
5233 btrfs_end_transaction(trans);
5237 * We're truncating a file that used to have good data down to
5238 * zero. Make sure it gets into the ordered flush list so that
5239 * any new writes get down to disk quickly.
5242 set_bit(BTRFS_INODE_ORDERED_DATA_CLOSE,
5243 &BTRFS_I(inode)->runtime_flags);
5245 truncate_setsize(inode, newsize);
5247 /* Disable nonlocked read DIO to avoid the endless truncate */
5248 btrfs_inode_block_unlocked_dio(BTRFS_I(inode));
5249 inode_dio_wait(inode);
5250 btrfs_inode_resume_unlocked_dio(BTRFS_I(inode));
5252 ret = btrfs_truncate(inode, newsize == oldsize);
5253 if (ret && inode->i_nlink) {
5257 * Truncate failed, so fix up the in-memory size. We
5258 * adjusted disk_i_size down as we removed extents, so
5259 * wait for disk_i_size to be stable and then update the
5260 * in-memory size to match.
5262 err = btrfs_wait_ordered_range(inode, 0, (u64)-1);
5265 i_size_write(inode, BTRFS_I(inode)->disk_i_size);
5272 static int btrfs_setattr(struct dentry *dentry, struct iattr *attr)
5274 struct inode *inode = d_inode(dentry);
5275 struct btrfs_root *root = BTRFS_I(inode)->root;
5278 if (btrfs_root_readonly(root))
5281 err = setattr_prepare(dentry, attr);
5285 if (S_ISREG(inode->i_mode) && (attr->ia_valid & ATTR_SIZE)) {
5286 err = btrfs_setsize(inode, attr);
5291 if (attr->ia_valid) {
5292 setattr_copy(inode, attr);
5293 inode_inc_iversion(inode);
5294 err = btrfs_dirty_inode(inode);
5296 if (!err && attr->ia_valid & ATTR_MODE)
5297 err = posix_acl_chmod(inode, inode->i_mode);
5304 * While truncating the inode pages during eviction, we get the VFS calling
5305 * btrfs_invalidatepage() against each page of the inode. This is slow because
5306 * the calls to btrfs_invalidatepage() result in a huge amount of calls to
5307 * lock_extent_bits() and clear_extent_bit(), which keep merging and splitting
5308 * extent_state structures over and over, wasting lots of time.
5310 * Therefore if the inode is being evicted, let btrfs_invalidatepage() skip all
5311 * those expensive operations on a per page basis and do only the ordered io
5312 * finishing, while we release here the extent_map and extent_state structures,
5313 * without the excessive merging and splitting.
5315 static void evict_inode_truncate_pages(struct inode *inode)
5317 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
5318 struct extent_map_tree *map_tree = &BTRFS_I(inode)->extent_tree;
5319 struct rb_node *node;
5321 ASSERT(inode->i_state & I_FREEING);
5322 truncate_inode_pages_final(&inode->i_data);
5324 write_lock(&map_tree->lock);
5325 while (!RB_EMPTY_ROOT(&map_tree->map.rb_root)) {
5326 struct extent_map *em;
5328 node = rb_first_cached(&map_tree->map);
5329 em = rb_entry(node, struct extent_map, rb_node);
5330 clear_bit(EXTENT_FLAG_PINNED, &em->flags);
5331 clear_bit(EXTENT_FLAG_LOGGING, &em->flags);
5332 remove_extent_mapping(map_tree, em);
5333 free_extent_map(em);
5334 if (need_resched()) {
5335 write_unlock(&map_tree->lock);
5337 write_lock(&map_tree->lock);
5340 write_unlock(&map_tree->lock);
5343 * Keep looping until we have no more ranges in the io tree.
5344 * We can have ongoing bios started by readpages (called from readahead)
5345 * that have their endio callback (extent_io.c:end_bio_extent_readpage)
5346 * still in progress (unlocked the pages in the bio but did not yet
5347 * unlocked the ranges in the io tree). Therefore this means some
5348 * ranges can still be locked and eviction started because before
5349 * submitting those bios, which are executed by a separate task (work
5350 * queue kthread), inode references (inode->i_count) were not taken
5351 * (which would be dropped in the end io callback of each bio).
5352 * Therefore here we effectively end up waiting for those bios and
5353 * anyone else holding locked ranges without having bumped the inode's
5354 * reference count - if we don't do it, when they access the inode's
5355 * io_tree to unlock a range it may be too late, leading to an
5356 * use-after-free issue.
5358 spin_lock(&io_tree->lock);
5359 while (!RB_EMPTY_ROOT(&io_tree->state)) {
5360 struct extent_state *state;
5361 struct extent_state *cached_state = NULL;
5364 unsigned state_flags;
5366 node = rb_first(&io_tree->state);
5367 state = rb_entry(node, struct extent_state, rb_node);
5368 start = state->start;
5370 state_flags = state->state;
5371 spin_unlock(&io_tree->lock);
5373 lock_extent_bits(io_tree, start, end, &cached_state);
5376 * If still has DELALLOC flag, the extent didn't reach disk,
5377 * and its reserved space won't be freed by delayed_ref.
5378 * So we need to free its reserved space here.
5379 * (Refer to comment in btrfs_invalidatepage, case 2)
5381 * Note, end is the bytenr of last byte, so we need + 1 here.
5383 if (state_flags & EXTENT_DELALLOC)
5384 btrfs_qgroup_free_data(inode, NULL, start, end - start + 1);
5386 clear_extent_bit(io_tree, start, end,
5387 EXTENT_LOCKED | EXTENT_DELALLOC |
5388 EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG, 1, 1,
5392 spin_lock(&io_tree->lock);
5394 spin_unlock(&io_tree->lock);
5397 static struct btrfs_trans_handle *evict_refill_and_join(struct btrfs_root *root,
5398 struct btrfs_block_rsv *rsv)
5400 struct btrfs_fs_info *fs_info = root->fs_info;
5401 struct btrfs_block_rsv *global_rsv = &fs_info->global_block_rsv;
5402 struct btrfs_trans_handle *trans;
5403 u64 delayed_refs_extra = btrfs_calc_insert_metadata_size(fs_info, 1);
5407 * Eviction should be taking place at some place safe because of our
5408 * delayed iputs. However the normal flushing code will run delayed
5409 * iputs, so we cannot use FLUSH_ALL otherwise we'll deadlock.
5411 * We reserve the delayed_refs_extra here again because we can't use
5412 * btrfs_start_transaction(root, 0) for the same deadlocky reason as
5413 * above. We reserve our extra bit here because we generate a ton of
5414 * delayed refs activity by truncating.
5416 * If we cannot make our reservation we'll attempt to steal from the
5417 * global reserve, because we really want to be able to free up space.
5419 ret = btrfs_block_rsv_refill(root, rsv, rsv->size + delayed_refs_extra,
5420 BTRFS_RESERVE_FLUSH_EVICT);
5423 * Try to steal from the global reserve if there is space for
5426 if (btrfs_check_space_for_delayed_refs(fs_info) ||
5427 btrfs_block_rsv_migrate(global_rsv, rsv, rsv->size, 0)) {
5429 "could not allocate space for delete; will truncate on mount");
5430 return ERR_PTR(-ENOSPC);
5432 delayed_refs_extra = 0;
5435 trans = btrfs_join_transaction(root);
5439 if (delayed_refs_extra) {
5440 trans->block_rsv = &fs_info->trans_block_rsv;
5441 trans->bytes_reserved = delayed_refs_extra;
5442 btrfs_block_rsv_migrate(rsv, trans->block_rsv,
5443 delayed_refs_extra, 1);
5448 void btrfs_evict_inode(struct inode *inode)
5450 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
5451 struct btrfs_trans_handle *trans;
5452 struct btrfs_root *root = BTRFS_I(inode)->root;
5453 struct btrfs_block_rsv *rsv;
5456 trace_btrfs_inode_evict(inode);
5463 evict_inode_truncate_pages(inode);
5465 if (inode->i_nlink &&
5466 ((btrfs_root_refs(&root->root_item) != 0 &&
5467 root->root_key.objectid != BTRFS_ROOT_TREE_OBJECTID) ||
5468 btrfs_is_free_space_inode(BTRFS_I(inode))))
5471 if (is_bad_inode(inode))
5474 btrfs_free_io_failure_record(BTRFS_I(inode), 0, (u64)-1);
5476 if (test_bit(BTRFS_FS_LOG_RECOVERING, &fs_info->flags))
5479 if (inode->i_nlink > 0) {
5480 BUG_ON(btrfs_root_refs(&root->root_item) != 0 &&
5481 root->root_key.objectid != BTRFS_ROOT_TREE_OBJECTID);
5485 ret = btrfs_commit_inode_delayed_inode(BTRFS_I(inode));
5489 rsv = btrfs_alloc_block_rsv(fs_info, BTRFS_BLOCK_RSV_TEMP);
5492 rsv->size = btrfs_calc_metadata_size(fs_info, 1);
5495 btrfs_i_size_write(BTRFS_I(inode), 0);
5498 trans = evict_refill_and_join(root, rsv);
5502 trans->block_rsv = rsv;
5504 ret = btrfs_truncate_inode_items(trans, root, inode, 0, 0);
5505 trans->block_rsv = &fs_info->trans_block_rsv;
5506 btrfs_end_transaction(trans);
5507 btrfs_btree_balance_dirty(fs_info);
5508 if (ret && ret != -ENOSPC && ret != -EAGAIN)
5515 * Errors here aren't a big deal, it just means we leave orphan items in
5516 * the tree. They will be cleaned up on the next mount. If the inode
5517 * number gets reused, cleanup deletes the orphan item without doing
5518 * anything, and unlink reuses the existing orphan item.
5520 * If it turns out that we are dropping too many of these, we might want
5521 * to add a mechanism for retrying these after a commit.
5523 trans = evict_refill_and_join(root, rsv);
5524 if (!IS_ERR(trans)) {
5525 trans->block_rsv = rsv;
5526 btrfs_orphan_del(trans, BTRFS_I(inode));
5527 trans->block_rsv = &fs_info->trans_block_rsv;
5528 btrfs_end_transaction(trans);
5531 if (!(root == fs_info->tree_root ||
5532 root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID))
5533 btrfs_return_ino(root, btrfs_ino(BTRFS_I(inode)));
5536 btrfs_free_block_rsv(fs_info, rsv);
5539 * If we didn't successfully delete, the orphan item will still be in
5540 * the tree and we'll retry on the next mount. Again, we might also want
5541 * to retry these periodically in the future.
5543 btrfs_remove_delayed_node(BTRFS_I(inode));
5548 * Return the key found in the dir entry in the location pointer, fill @type
5549 * with BTRFS_FT_*, and return 0.
5551 * If no dir entries were found, returns -ENOENT.
5552 * If found a corrupted location in dir entry, returns -EUCLEAN.
5554 static int btrfs_inode_by_name(struct inode *dir, struct dentry *dentry,
5555 struct btrfs_key *location, u8 *type)
5557 const char *name = dentry->d_name.name;
5558 int namelen = dentry->d_name.len;
5559 struct btrfs_dir_item *di;
5560 struct btrfs_path *path;
5561 struct btrfs_root *root = BTRFS_I(dir)->root;
5564 path = btrfs_alloc_path();
5568 di = btrfs_lookup_dir_item(NULL, root, path, btrfs_ino(BTRFS_I(dir)),
5570 if (IS_ERR_OR_NULL(di)) {
5571 ret = di ? PTR_ERR(di) : -ENOENT;
5575 btrfs_dir_item_key_to_cpu(path->nodes[0], di, location);
5576 if (location->type != BTRFS_INODE_ITEM_KEY &&
5577 location->type != BTRFS_ROOT_ITEM_KEY) {
5579 btrfs_warn(root->fs_info,
5580 "%s gets something invalid in DIR_ITEM (name %s, directory ino %llu, location(%llu %u %llu))",
5581 __func__, name, btrfs_ino(BTRFS_I(dir)),
5582 location->objectid, location->type, location->offset);
5585 *type = btrfs_dir_type(path->nodes[0], di);
5587 btrfs_free_path(path);
5592 * when we hit a tree root in a directory, the btrfs part of the inode
5593 * needs to be changed to reflect the root directory of the tree root. This
5594 * is kind of like crossing a mount point.
5596 static int fixup_tree_root_location(struct btrfs_fs_info *fs_info,
5598 struct dentry *dentry,
5599 struct btrfs_key *location,
5600 struct btrfs_root **sub_root)
5602 struct btrfs_path *path;
5603 struct btrfs_root *new_root;
5604 struct btrfs_root_ref *ref;
5605 struct extent_buffer *leaf;
5606 struct btrfs_key key;
5610 path = btrfs_alloc_path();
5617 key.objectid = BTRFS_I(dir)->root->root_key.objectid;
5618 key.type = BTRFS_ROOT_REF_KEY;
5619 key.offset = location->objectid;
5621 ret = btrfs_search_slot(NULL, fs_info->tree_root, &key, path, 0, 0);
5628 leaf = path->nodes[0];
5629 ref = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_root_ref);
5630 if (btrfs_root_ref_dirid(leaf, ref) != btrfs_ino(BTRFS_I(dir)) ||
5631 btrfs_root_ref_name_len(leaf, ref) != dentry->d_name.len)
5634 ret = memcmp_extent_buffer(leaf, dentry->d_name.name,
5635 (unsigned long)(ref + 1),
5636 dentry->d_name.len);
5640 btrfs_release_path(path);
5642 new_root = btrfs_read_fs_root_no_name(fs_info, location);
5643 if (IS_ERR(new_root)) {
5644 err = PTR_ERR(new_root);
5648 *sub_root = new_root;
5649 location->objectid = btrfs_root_dirid(&new_root->root_item);
5650 location->type = BTRFS_INODE_ITEM_KEY;
5651 location->offset = 0;
5654 btrfs_free_path(path);
5658 static void inode_tree_add(struct inode *inode)
5660 struct btrfs_root *root = BTRFS_I(inode)->root;
5661 struct btrfs_inode *entry;
5663 struct rb_node *parent;
5664 struct rb_node *new = &BTRFS_I(inode)->rb_node;
5665 u64 ino = btrfs_ino(BTRFS_I(inode));
5667 if (inode_unhashed(inode))
5670 spin_lock(&root->inode_lock);
5671 p = &root->inode_tree.rb_node;
5674 entry = rb_entry(parent, struct btrfs_inode, rb_node);
5676 if (ino < btrfs_ino(entry))
5677 p = &parent->rb_left;
5678 else if (ino > btrfs_ino(entry))
5679 p = &parent->rb_right;
5681 WARN_ON(!(entry->vfs_inode.i_state &
5682 (I_WILL_FREE | I_FREEING)));
5683 rb_replace_node(parent, new, &root->inode_tree);
5684 RB_CLEAR_NODE(parent);
5685 spin_unlock(&root->inode_lock);
5689 rb_link_node(new, parent, p);
5690 rb_insert_color(new, &root->inode_tree);
5691 spin_unlock(&root->inode_lock);
5694 static void inode_tree_del(struct inode *inode)
5696 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
5697 struct btrfs_root *root = BTRFS_I(inode)->root;
5700 spin_lock(&root->inode_lock);
5701 if (!RB_EMPTY_NODE(&BTRFS_I(inode)->rb_node)) {
5702 rb_erase(&BTRFS_I(inode)->rb_node, &root->inode_tree);
5703 RB_CLEAR_NODE(&BTRFS_I(inode)->rb_node);
5704 empty = RB_EMPTY_ROOT(&root->inode_tree);
5706 spin_unlock(&root->inode_lock);
5708 if (empty && btrfs_root_refs(&root->root_item) == 0) {
5709 synchronize_srcu(&fs_info->subvol_srcu);
5710 spin_lock(&root->inode_lock);
5711 empty = RB_EMPTY_ROOT(&root->inode_tree);
5712 spin_unlock(&root->inode_lock);
5714 btrfs_add_dead_root(root);
5719 static int btrfs_init_locked_inode(struct inode *inode, void *p)
5721 struct btrfs_iget_args *args = p;
5722 inode->i_ino = args->location->objectid;
5723 memcpy(&BTRFS_I(inode)->location, args->location,
5724 sizeof(*args->location));
5725 BTRFS_I(inode)->root = args->root;
5729 static int btrfs_find_actor(struct inode *inode, void *opaque)
5731 struct btrfs_iget_args *args = opaque;
5732 return args->location->objectid == BTRFS_I(inode)->location.objectid &&
5733 args->root == BTRFS_I(inode)->root;
5736 static struct inode *btrfs_iget_locked(struct super_block *s,
5737 struct btrfs_key *location,
5738 struct btrfs_root *root)
5740 struct inode *inode;
5741 struct btrfs_iget_args args;
5742 unsigned long hashval = btrfs_inode_hash(location->objectid, root);
5744 args.location = location;
5747 inode = iget5_locked(s, hashval, btrfs_find_actor,
5748 btrfs_init_locked_inode,
5753 /* Get an inode object given its location and corresponding root.
5754 * Returns in *is_new if the inode was read from disk
5756 struct inode *btrfs_iget_path(struct super_block *s, struct btrfs_key *location,
5757 struct btrfs_root *root, int *new,
5758 struct btrfs_path *path)
5760 struct inode *inode;
5762 inode = btrfs_iget_locked(s, location, root);
5764 return ERR_PTR(-ENOMEM);
5766 if (inode->i_state & I_NEW) {
5769 ret = btrfs_read_locked_inode(inode, path);
5771 inode_tree_add(inode);
5772 unlock_new_inode(inode);
5778 * ret > 0 can come from btrfs_search_slot called by
5779 * btrfs_read_locked_inode, this means the inode item
5784 inode = ERR_PTR(ret);
5791 struct inode *btrfs_iget(struct super_block *s, struct btrfs_key *location,
5792 struct btrfs_root *root, int *new)
5794 return btrfs_iget_path(s, location, root, new, NULL);
5797 static struct inode *new_simple_dir(struct super_block *s,
5798 struct btrfs_key *key,
5799 struct btrfs_root *root)
5801 struct inode *inode = new_inode(s);
5804 return ERR_PTR(-ENOMEM);
5806 BTRFS_I(inode)->root = root;
5807 memcpy(&BTRFS_I(inode)->location, key, sizeof(*key));
5808 set_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags);
5810 inode->i_ino = BTRFS_EMPTY_SUBVOL_DIR_OBJECTID;
5811 inode->i_op = &btrfs_dir_ro_inode_operations;
5812 inode->i_opflags &= ~IOP_XATTR;
5813 inode->i_fop = &simple_dir_operations;
5814 inode->i_mode = S_IFDIR | S_IRUGO | S_IWUSR | S_IXUGO;
5815 inode->i_mtime = current_time(inode);
5816 inode->i_atime = inode->i_mtime;
5817 inode->i_ctime = inode->i_mtime;
5818 BTRFS_I(inode)->i_otime = inode->i_mtime;
5823 static inline u8 btrfs_inode_type(struct inode *inode)
5826 * Compile-time asserts that generic FT_* types still match
5829 BUILD_BUG_ON(BTRFS_FT_UNKNOWN != FT_UNKNOWN);
5830 BUILD_BUG_ON(BTRFS_FT_REG_FILE != FT_REG_FILE);
5831 BUILD_BUG_ON(BTRFS_FT_DIR != FT_DIR);
5832 BUILD_BUG_ON(BTRFS_FT_CHRDEV != FT_CHRDEV);
5833 BUILD_BUG_ON(BTRFS_FT_BLKDEV != FT_BLKDEV);
5834 BUILD_BUG_ON(BTRFS_FT_FIFO != FT_FIFO);
5835 BUILD_BUG_ON(BTRFS_FT_SOCK != FT_SOCK);
5836 BUILD_BUG_ON(BTRFS_FT_SYMLINK != FT_SYMLINK);
5838 return fs_umode_to_ftype(inode->i_mode);
5841 struct inode *btrfs_lookup_dentry(struct inode *dir, struct dentry *dentry)
5843 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
5844 struct inode *inode;
5845 struct btrfs_root *root = BTRFS_I(dir)->root;
5846 struct btrfs_root *sub_root = root;
5847 struct btrfs_key location;
5852 if (dentry->d_name.len > BTRFS_NAME_LEN)
5853 return ERR_PTR(-ENAMETOOLONG);
5855 ret = btrfs_inode_by_name(dir, dentry, &location, &di_type);
5857 return ERR_PTR(ret);
5859 if (location.type == BTRFS_INODE_ITEM_KEY) {
5860 inode = btrfs_iget(dir->i_sb, &location, root, NULL);
5864 /* Do extra check against inode mode with di_type */
5865 if (btrfs_inode_type(inode) != di_type) {
5867 "inode mode mismatch with dir: inode mode=0%o btrfs type=%u dir type=%u",
5868 inode->i_mode, btrfs_inode_type(inode),
5871 return ERR_PTR(-EUCLEAN);
5876 index = srcu_read_lock(&fs_info->subvol_srcu);
5877 ret = fixup_tree_root_location(fs_info, dir, dentry,
5878 &location, &sub_root);
5881 inode = ERR_PTR(ret);
5883 inode = new_simple_dir(dir->i_sb, &location, sub_root);
5885 inode = btrfs_iget(dir->i_sb, &location, sub_root, NULL);
5887 srcu_read_unlock(&fs_info->subvol_srcu, index);
5889 if (!IS_ERR(inode) && root != sub_root) {
5890 down_read(&fs_info->cleanup_work_sem);
5891 if (!sb_rdonly(inode->i_sb))
5892 ret = btrfs_orphan_cleanup(sub_root);
5893 up_read(&fs_info->cleanup_work_sem);
5896 inode = ERR_PTR(ret);
5903 static int btrfs_dentry_delete(const struct dentry *dentry)
5905 struct btrfs_root *root;
5906 struct inode *inode = d_inode(dentry);
5908 if (!inode && !IS_ROOT(dentry))
5909 inode = d_inode(dentry->d_parent);
5912 root = BTRFS_I(inode)->root;
5913 if (btrfs_root_refs(&root->root_item) == 0)
5916 if (btrfs_ino(BTRFS_I(inode)) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)
5922 static struct dentry *btrfs_lookup(struct inode *dir, struct dentry *dentry,
5925 struct inode *inode = btrfs_lookup_dentry(dir, dentry);
5927 if (inode == ERR_PTR(-ENOENT))
5929 return d_splice_alias(inode, dentry);
5933 * All this infrastructure exists because dir_emit can fault, and we are holding
5934 * the tree lock when doing readdir. For now just allocate a buffer and copy
5935 * our information into that, and then dir_emit from the buffer. This is
5936 * similar to what NFS does, only we don't keep the buffer around in pagecache
5937 * because I'm afraid I'll mess that up. Long term we need to make filldir do
5938 * copy_to_user_inatomic so we don't have to worry about page faulting under the
5941 static int btrfs_opendir(struct inode *inode, struct file *file)
5943 struct btrfs_file_private *private;
5945 private = kzalloc(sizeof(struct btrfs_file_private), GFP_KERNEL);
5948 private->filldir_buf = kzalloc(PAGE_SIZE, GFP_KERNEL);
5949 if (!private->filldir_buf) {
5953 file->private_data = private;
5964 static int btrfs_filldir(void *addr, int entries, struct dir_context *ctx)
5967 struct dir_entry *entry = addr;
5968 char *name = (char *)(entry + 1);
5970 ctx->pos = get_unaligned(&entry->offset);
5971 if (!dir_emit(ctx, name, get_unaligned(&entry->name_len),
5972 get_unaligned(&entry->ino),
5973 get_unaligned(&entry->type)))
5975 addr += sizeof(struct dir_entry) +
5976 get_unaligned(&entry->name_len);
5982 static int btrfs_real_readdir(struct file *file, struct dir_context *ctx)
5984 struct inode *inode = file_inode(file);
5985 struct btrfs_root *root = BTRFS_I(inode)->root;
5986 struct btrfs_file_private *private = file->private_data;
5987 struct btrfs_dir_item *di;
5988 struct btrfs_key key;
5989 struct btrfs_key found_key;
5990 struct btrfs_path *path;
5992 struct list_head ins_list;
5993 struct list_head del_list;
5995 struct extent_buffer *leaf;
6002 struct btrfs_key location;
6004 if (!dir_emit_dots(file, ctx))
6007 path = btrfs_alloc_path();
6011 addr = private->filldir_buf;
6012 path->reada = READA_FORWARD;
6014 INIT_LIST_HEAD(&ins_list);
6015 INIT_LIST_HEAD(&del_list);
6016 put = btrfs_readdir_get_delayed_items(inode, &ins_list, &del_list);
6019 key.type = BTRFS_DIR_INDEX_KEY;
6020 key.offset = ctx->pos;
6021 key.objectid = btrfs_ino(BTRFS_I(inode));
6023 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
6028 struct dir_entry *entry;
6030 leaf = path->nodes[0];
6031 slot = path->slots[0];
6032 if (slot >= btrfs_header_nritems(leaf)) {
6033 ret = btrfs_next_leaf(root, path);
6041 btrfs_item_key_to_cpu(leaf, &found_key, slot);
6043 if (found_key.objectid != key.objectid)
6045 if (found_key.type != BTRFS_DIR_INDEX_KEY)
6047 if (found_key.offset < ctx->pos)
6049 if (btrfs_should_delete_dir_index(&del_list, found_key.offset))
6051 di = btrfs_item_ptr(leaf, slot, struct btrfs_dir_item);
6052 name_len = btrfs_dir_name_len(leaf, di);
6053 if ((total_len + sizeof(struct dir_entry) + name_len) >=
6055 btrfs_release_path(path);
6056 ret = btrfs_filldir(private->filldir_buf, entries, ctx);
6059 addr = private->filldir_buf;
6066 put_unaligned(name_len, &entry->name_len);
6067 name_ptr = (char *)(entry + 1);
6068 read_extent_buffer(leaf, name_ptr, (unsigned long)(di + 1),
6070 put_unaligned(fs_ftype_to_dtype(btrfs_dir_type(leaf, di)),
6072 btrfs_dir_item_key_to_cpu(leaf, di, &location);
6073 put_unaligned(location.objectid, &entry->ino);
6074 put_unaligned(found_key.offset, &entry->offset);
6076 addr += sizeof(struct dir_entry) + name_len;
6077 total_len += sizeof(struct dir_entry) + name_len;
6081 btrfs_release_path(path);
6083 ret = btrfs_filldir(private->filldir_buf, entries, ctx);
6087 ret = btrfs_readdir_delayed_dir_index(ctx, &ins_list);
6092 * Stop new entries from being returned after we return the last
6095 * New directory entries are assigned a strictly increasing
6096 * offset. This means that new entries created during readdir
6097 * are *guaranteed* to be seen in the future by that readdir.
6098 * This has broken buggy programs which operate on names as
6099 * they're returned by readdir. Until we re-use freed offsets
6100 * we have this hack to stop new entries from being returned
6101 * under the assumption that they'll never reach this huge
6104 * This is being careful not to overflow 32bit loff_t unless the
6105 * last entry requires it because doing so has broken 32bit apps
6108 if (ctx->pos >= INT_MAX)
6109 ctx->pos = LLONG_MAX;
6116 btrfs_readdir_put_delayed_items(inode, &ins_list, &del_list);
6117 btrfs_free_path(path);
6122 * This is somewhat expensive, updating the tree every time the
6123 * inode changes. But, it is most likely to find the inode in cache.
6124 * FIXME, needs more benchmarking...there are no reasons other than performance
6125 * to keep or drop this code.
6127 static int btrfs_dirty_inode(struct inode *inode)
6129 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
6130 struct btrfs_root *root = BTRFS_I(inode)->root;
6131 struct btrfs_trans_handle *trans;
6134 if (test_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags))
6137 trans = btrfs_join_transaction(root);
6139 return PTR_ERR(trans);
6141 ret = btrfs_update_inode(trans, root, inode);
6142 if (ret && ret == -ENOSPC) {
6143 /* whoops, lets try again with the full transaction */
6144 btrfs_end_transaction(trans);
6145 trans = btrfs_start_transaction(root, 1);
6147 return PTR_ERR(trans);
6149 ret = btrfs_update_inode(trans, root, inode);
6151 btrfs_end_transaction(trans);
6152 if (BTRFS_I(inode)->delayed_node)
6153 btrfs_balance_delayed_items(fs_info);
6159 * This is a copy of file_update_time. We need this so we can return error on
6160 * ENOSPC for updating the inode in the case of file write and mmap writes.
6162 static int btrfs_update_time(struct inode *inode, struct timespec64 *now,
6165 struct btrfs_root *root = BTRFS_I(inode)->root;
6166 bool dirty = flags & ~S_VERSION;
6168 if (btrfs_root_readonly(root))
6171 if (flags & S_VERSION)
6172 dirty |= inode_maybe_inc_iversion(inode, dirty);
6173 if (flags & S_CTIME)
6174 inode->i_ctime = *now;
6175 if (flags & S_MTIME)
6176 inode->i_mtime = *now;
6177 if (flags & S_ATIME)
6178 inode->i_atime = *now;
6179 return dirty ? btrfs_dirty_inode(inode) : 0;
6183 * find the highest existing sequence number in a directory
6184 * and then set the in-memory index_cnt variable to reflect
6185 * free sequence numbers
6187 static int btrfs_set_inode_index_count(struct btrfs_inode *inode)
6189 struct btrfs_root *root = inode->root;
6190 struct btrfs_key key, found_key;
6191 struct btrfs_path *path;
6192 struct extent_buffer *leaf;
6195 key.objectid = btrfs_ino(inode);
6196 key.type = BTRFS_DIR_INDEX_KEY;
6197 key.offset = (u64)-1;
6199 path = btrfs_alloc_path();
6203 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
6206 /* FIXME: we should be able to handle this */
6212 * MAGIC NUMBER EXPLANATION:
6213 * since we search a directory based on f_pos we have to start at 2
6214 * since '.' and '..' have f_pos of 0 and 1 respectively, so everybody
6215 * else has to start at 2
6217 if (path->slots[0] == 0) {
6218 inode->index_cnt = 2;
6224 leaf = path->nodes[0];
6225 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
6227 if (found_key.objectid != btrfs_ino(inode) ||
6228 found_key.type != BTRFS_DIR_INDEX_KEY) {
6229 inode->index_cnt = 2;
6233 inode->index_cnt = found_key.offset + 1;
6235 btrfs_free_path(path);
6240 * helper to find a free sequence number in a given directory. This current
6241 * code is very simple, later versions will do smarter things in the btree
6243 int btrfs_set_inode_index(struct btrfs_inode *dir, u64 *index)
6247 if (dir->index_cnt == (u64)-1) {
6248 ret = btrfs_inode_delayed_dir_index_count(dir);
6250 ret = btrfs_set_inode_index_count(dir);
6256 *index = dir->index_cnt;
6262 static int btrfs_insert_inode_locked(struct inode *inode)
6264 struct btrfs_iget_args args;
6265 args.location = &BTRFS_I(inode)->location;
6266 args.root = BTRFS_I(inode)->root;
6268 return insert_inode_locked4(inode,
6269 btrfs_inode_hash(inode->i_ino, BTRFS_I(inode)->root),
6270 btrfs_find_actor, &args);
6274 * Inherit flags from the parent inode.
6276 * Currently only the compression flags and the cow flags are inherited.
6278 static void btrfs_inherit_iflags(struct inode *inode, struct inode *dir)
6285 flags = BTRFS_I(dir)->flags;
6287 if (flags & BTRFS_INODE_NOCOMPRESS) {
6288 BTRFS_I(inode)->flags &= ~BTRFS_INODE_COMPRESS;
6289 BTRFS_I(inode)->flags |= BTRFS_INODE_NOCOMPRESS;
6290 } else if (flags & BTRFS_INODE_COMPRESS) {
6291 BTRFS_I(inode)->flags &= ~BTRFS_INODE_NOCOMPRESS;
6292 BTRFS_I(inode)->flags |= BTRFS_INODE_COMPRESS;
6295 if (flags & BTRFS_INODE_NODATACOW) {
6296 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATACOW;
6297 if (S_ISREG(inode->i_mode))
6298 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATASUM;
6301 btrfs_sync_inode_flags_to_i_flags(inode);
6304 static struct inode *btrfs_new_inode(struct btrfs_trans_handle *trans,
6305 struct btrfs_root *root,
6307 const char *name, int name_len,
6308 u64 ref_objectid, u64 objectid,
6309 umode_t mode, u64 *index)
6311 struct btrfs_fs_info *fs_info = root->fs_info;
6312 struct inode *inode;
6313 struct btrfs_inode_item *inode_item;
6314 struct btrfs_key *location;
6315 struct btrfs_path *path;
6316 struct btrfs_inode_ref *ref;
6317 struct btrfs_key key[2];
6319 int nitems = name ? 2 : 1;
6321 unsigned int nofs_flag;
6324 path = btrfs_alloc_path();
6326 return ERR_PTR(-ENOMEM);
6328 nofs_flag = memalloc_nofs_save();
6329 inode = new_inode(fs_info->sb);
6330 memalloc_nofs_restore(nofs_flag);
6332 btrfs_free_path(path);
6333 return ERR_PTR(-ENOMEM);
6337 * O_TMPFILE, set link count to 0, so that after this point,
6338 * we fill in an inode item with the correct link count.
6341 set_nlink(inode, 0);
6344 * we have to initialize this early, so we can reclaim the inode
6345 * number if we fail afterwards in this function.
6347 inode->i_ino = objectid;
6350 trace_btrfs_inode_request(dir);
6352 ret = btrfs_set_inode_index(BTRFS_I(dir), index);
6354 btrfs_free_path(path);
6356 return ERR_PTR(ret);
6362 * index_cnt is ignored for everything but a dir,
6363 * btrfs_set_inode_index_count has an explanation for the magic
6366 BTRFS_I(inode)->index_cnt = 2;
6367 BTRFS_I(inode)->dir_index = *index;
6368 BTRFS_I(inode)->root = root;
6369 BTRFS_I(inode)->generation = trans->transid;
6370 inode->i_generation = BTRFS_I(inode)->generation;
6373 * We could have gotten an inode number from somebody who was fsynced
6374 * and then removed in this same transaction, so let's just set full
6375 * sync since it will be a full sync anyway and this will blow away the
6376 * old info in the log.
6378 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &BTRFS_I(inode)->runtime_flags);
6380 key[0].objectid = objectid;
6381 key[0].type = BTRFS_INODE_ITEM_KEY;
6384 sizes[0] = sizeof(struct btrfs_inode_item);
6388 * Start new inodes with an inode_ref. This is slightly more
6389 * efficient for small numbers of hard links since they will
6390 * be packed into one item. Extended refs will kick in if we
6391 * add more hard links than can fit in the ref item.
6393 key[1].objectid = objectid;
6394 key[1].type = BTRFS_INODE_REF_KEY;
6395 key[1].offset = ref_objectid;
6397 sizes[1] = name_len + sizeof(*ref);
6400 location = &BTRFS_I(inode)->location;
6401 location->objectid = objectid;
6402 location->offset = 0;
6403 location->type = BTRFS_INODE_ITEM_KEY;
6405 ret = btrfs_insert_inode_locked(inode);
6411 path->leave_spinning = 1;
6412 ret = btrfs_insert_empty_items(trans, root, path, key, sizes, nitems);
6416 inode_init_owner(inode, dir, mode);
6417 inode_set_bytes(inode, 0);
6419 inode->i_mtime = current_time(inode);
6420 inode->i_atime = inode->i_mtime;
6421 inode->i_ctime = inode->i_mtime;
6422 BTRFS_I(inode)->i_otime = inode->i_mtime;
6424 inode_item = btrfs_item_ptr(path->nodes[0], path->slots[0],
6425 struct btrfs_inode_item);
6426 memzero_extent_buffer(path->nodes[0], (unsigned long)inode_item,
6427 sizeof(*inode_item));
6428 fill_inode_item(trans, path->nodes[0], inode_item, inode);
6431 ref = btrfs_item_ptr(path->nodes[0], path->slots[0] + 1,
6432 struct btrfs_inode_ref);
6433 btrfs_set_inode_ref_name_len(path->nodes[0], ref, name_len);
6434 btrfs_set_inode_ref_index(path->nodes[0], ref, *index);
6435 ptr = (unsigned long)(ref + 1);
6436 write_extent_buffer(path->nodes[0], name, ptr, name_len);
6439 btrfs_mark_buffer_dirty(path->nodes[0]);
6440 btrfs_free_path(path);
6442 btrfs_inherit_iflags(inode, dir);
6444 if (S_ISREG(mode)) {
6445 if (btrfs_test_opt(fs_info, NODATASUM))
6446 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATASUM;
6447 if (btrfs_test_opt(fs_info, NODATACOW))
6448 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATACOW |
6449 BTRFS_INODE_NODATASUM;
6452 inode_tree_add(inode);
6454 trace_btrfs_inode_new(inode);
6455 btrfs_set_inode_last_trans(trans, inode);
6457 btrfs_update_root_times(trans, root);
6459 ret = btrfs_inode_inherit_props(trans, inode, dir);
6462 "error inheriting props for ino %llu (root %llu): %d",
6463 btrfs_ino(BTRFS_I(inode)), root->root_key.objectid, ret);
6468 discard_new_inode(inode);
6471 BTRFS_I(dir)->index_cnt--;
6472 btrfs_free_path(path);
6473 return ERR_PTR(ret);
6477 * utility function to add 'inode' into 'parent_inode' with
6478 * a give name and a given sequence number.
6479 * if 'add_backref' is true, also insert a backref from the
6480 * inode to the parent directory.
6482 int btrfs_add_link(struct btrfs_trans_handle *trans,
6483 struct btrfs_inode *parent_inode, struct btrfs_inode *inode,
6484 const char *name, int name_len, int add_backref, u64 index)
6487 struct btrfs_key key;
6488 struct btrfs_root *root = parent_inode->root;
6489 u64 ino = btrfs_ino(inode);
6490 u64 parent_ino = btrfs_ino(parent_inode);
6492 if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
6493 memcpy(&key, &inode->root->root_key, sizeof(key));
6496 key.type = BTRFS_INODE_ITEM_KEY;
6500 if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
6501 ret = btrfs_add_root_ref(trans, key.objectid,
6502 root->root_key.objectid, parent_ino,
6503 index, name, name_len);
6504 } else if (add_backref) {
6505 ret = btrfs_insert_inode_ref(trans, root, name, name_len, ino,
6509 /* Nothing to clean up yet */
6513 ret = btrfs_insert_dir_item(trans, name, name_len, parent_inode, &key,
6514 btrfs_inode_type(&inode->vfs_inode), index);
6515 if (ret == -EEXIST || ret == -EOVERFLOW)
6518 btrfs_abort_transaction(trans, ret);
6522 btrfs_i_size_write(parent_inode, parent_inode->vfs_inode.i_size +
6524 inode_inc_iversion(&parent_inode->vfs_inode);
6526 * If we are replaying a log tree, we do not want to update the mtime
6527 * and ctime of the parent directory with the current time, since the
6528 * log replay procedure is responsible for setting them to their correct
6529 * values (the ones it had when the fsync was done).
6531 if (!test_bit(BTRFS_FS_LOG_RECOVERING, &root->fs_info->flags)) {
6532 struct timespec64 now = current_time(&parent_inode->vfs_inode);
6534 parent_inode->vfs_inode.i_mtime = now;
6535 parent_inode->vfs_inode.i_ctime = now;
6537 ret = btrfs_update_inode(trans, root, &parent_inode->vfs_inode);
6539 btrfs_abort_transaction(trans, ret);
6543 if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
6546 err = btrfs_del_root_ref(trans, key.objectid,
6547 root->root_key.objectid, parent_ino,
6548 &local_index, name, name_len);
6550 btrfs_abort_transaction(trans, err);
6551 } else if (add_backref) {
6555 err = btrfs_del_inode_ref(trans, root, name, name_len,
6556 ino, parent_ino, &local_index);
6558 btrfs_abort_transaction(trans, err);
6561 /* Return the original error code */
6565 static int btrfs_add_nondir(struct btrfs_trans_handle *trans,
6566 struct btrfs_inode *dir, struct dentry *dentry,
6567 struct btrfs_inode *inode, int backref, u64 index)
6569 int err = btrfs_add_link(trans, dir, inode,
6570 dentry->d_name.name, dentry->d_name.len,
6577 static int btrfs_mknod(struct inode *dir, struct dentry *dentry,
6578 umode_t mode, dev_t rdev)
6580 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
6581 struct btrfs_trans_handle *trans;
6582 struct btrfs_root *root = BTRFS_I(dir)->root;
6583 struct inode *inode = NULL;
6589 * 2 for inode item and ref
6591 * 1 for xattr if selinux is on
6593 trans = btrfs_start_transaction(root, 5);
6595 return PTR_ERR(trans);
6597 err = btrfs_find_free_ino(root, &objectid);
6601 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
6602 dentry->d_name.len, btrfs_ino(BTRFS_I(dir)), objectid,
6604 if (IS_ERR(inode)) {
6605 err = PTR_ERR(inode);
6611 * If the active LSM wants to access the inode during
6612 * d_instantiate it needs these. Smack checks to see
6613 * if the filesystem supports xattrs by looking at the
6616 inode->i_op = &btrfs_special_inode_operations;
6617 init_special_inode(inode, inode->i_mode, rdev);
6619 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
6623 err = btrfs_add_nondir(trans, BTRFS_I(dir), dentry, BTRFS_I(inode),
6628 btrfs_update_inode(trans, root, inode);
6629 d_instantiate_new(dentry, inode);
6632 btrfs_end_transaction(trans);
6633 btrfs_btree_balance_dirty(fs_info);
6635 inode_dec_link_count(inode);
6636 discard_new_inode(inode);
6641 static int btrfs_create(struct inode *dir, struct dentry *dentry,
6642 umode_t mode, bool excl)
6644 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
6645 struct btrfs_trans_handle *trans;
6646 struct btrfs_root *root = BTRFS_I(dir)->root;
6647 struct inode *inode = NULL;
6653 * 2 for inode item and ref
6655 * 1 for xattr if selinux is on
6657 trans = btrfs_start_transaction(root, 5);
6659 return PTR_ERR(trans);
6661 err = btrfs_find_free_ino(root, &objectid);
6665 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
6666 dentry->d_name.len, btrfs_ino(BTRFS_I(dir)), objectid,
6668 if (IS_ERR(inode)) {
6669 err = PTR_ERR(inode);
6674 * If the active LSM wants to access the inode during
6675 * d_instantiate it needs these. Smack checks to see
6676 * if the filesystem supports xattrs by looking at the
6679 inode->i_fop = &btrfs_file_operations;
6680 inode->i_op = &btrfs_file_inode_operations;
6681 inode->i_mapping->a_ops = &btrfs_aops;
6683 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
6687 err = btrfs_update_inode(trans, root, inode);
6691 err = btrfs_add_nondir(trans, BTRFS_I(dir), dentry, BTRFS_I(inode),
6696 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
6697 d_instantiate_new(dentry, inode);
6700 btrfs_end_transaction(trans);
6702 inode_dec_link_count(inode);
6703 discard_new_inode(inode);
6705 btrfs_btree_balance_dirty(fs_info);
6709 static int btrfs_link(struct dentry *old_dentry, struct inode *dir,
6710 struct dentry *dentry)
6712 struct btrfs_trans_handle *trans = NULL;
6713 struct btrfs_root *root = BTRFS_I(dir)->root;
6714 struct inode *inode = d_inode(old_dentry);
6715 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
6720 /* do not allow sys_link's with other subvols of the same device */
6721 if (root->root_key.objectid != BTRFS_I(inode)->root->root_key.objectid)
6724 if (inode->i_nlink >= BTRFS_LINK_MAX)
6727 err = btrfs_set_inode_index(BTRFS_I(dir), &index);
6732 * 2 items for inode and inode ref
6733 * 2 items for dir items
6734 * 1 item for parent inode
6735 * 1 item for orphan item deletion if O_TMPFILE
6737 trans = btrfs_start_transaction(root, inode->i_nlink ? 5 : 6);
6738 if (IS_ERR(trans)) {
6739 err = PTR_ERR(trans);
6744 /* There are several dir indexes for this inode, clear the cache. */
6745 BTRFS_I(inode)->dir_index = 0ULL;
6747 inode_inc_iversion(inode);
6748 inode->i_ctime = current_time(inode);
6750 set_bit(BTRFS_INODE_COPY_EVERYTHING, &BTRFS_I(inode)->runtime_flags);
6752 err = btrfs_add_nondir(trans, BTRFS_I(dir), dentry, BTRFS_I(inode),
6758 struct dentry *parent = dentry->d_parent;
6761 err = btrfs_update_inode(trans, root, inode);
6764 if (inode->i_nlink == 1) {
6766 * If new hard link count is 1, it's a file created
6767 * with open(2) O_TMPFILE flag.
6769 err = btrfs_orphan_del(trans, BTRFS_I(inode));
6773 d_instantiate(dentry, inode);
6774 ret = btrfs_log_new_name(trans, BTRFS_I(inode), NULL, parent,
6776 if (ret == BTRFS_NEED_TRANS_COMMIT) {
6777 err = btrfs_commit_transaction(trans);
6784 btrfs_end_transaction(trans);
6786 inode_dec_link_count(inode);
6789 btrfs_btree_balance_dirty(fs_info);
6793 static int btrfs_mkdir(struct inode *dir, struct dentry *dentry, umode_t mode)
6795 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
6796 struct inode *inode = NULL;
6797 struct btrfs_trans_handle *trans;
6798 struct btrfs_root *root = BTRFS_I(dir)->root;
6804 * 2 items for inode and ref
6805 * 2 items for dir items
6806 * 1 for xattr if selinux is on
6808 trans = btrfs_start_transaction(root, 5);
6810 return PTR_ERR(trans);
6812 err = btrfs_find_free_ino(root, &objectid);
6816 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
6817 dentry->d_name.len, btrfs_ino(BTRFS_I(dir)), objectid,
6818 S_IFDIR | mode, &index);
6819 if (IS_ERR(inode)) {
6820 err = PTR_ERR(inode);
6825 /* these must be set before we unlock the inode */
6826 inode->i_op = &btrfs_dir_inode_operations;
6827 inode->i_fop = &btrfs_dir_file_operations;
6829 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
6833 btrfs_i_size_write(BTRFS_I(inode), 0);
6834 err = btrfs_update_inode(trans, root, inode);
6838 err = btrfs_add_link(trans, BTRFS_I(dir), BTRFS_I(inode),
6839 dentry->d_name.name,
6840 dentry->d_name.len, 0, index);
6844 d_instantiate_new(dentry, inode);
6847 btrfs_end_transaction(trans);
6849 inode_dec_link_count(inode);
6850 discard_new_inode(inode);
6852 btrfs_btree_balance_dirty(fs_info);
6856 static noinline int uncompress_inline(struct btrfs_path *path,
6858 size_t pg_offset, u64 extent_offset,
6859 struct btrfs_file_extent_item *item)
6862 struct extent_buffer *leaf = path->nodes[0];
6865 unsigned long inline_size;
6869 WARN_ON(pg_offset != 0);
6870 compress_type = btrfs_file_extent_compression(leaf, item);
6871 max_size = btrfs_file_extent_ram_bytes(leaf, item);
6872 inline_size = btrfs_file_extent_inline_item_len(leaf,
6873 btrfs_item_nr(path->slots[0]));
6874 tmp = kmalloc(inline_size, GFP_NOFS);
6877 ptr = btrfs_file_extent_inline_start(item);
6879 read_extent_buffer(leaf, tmp, ptr, inline_size);
6881 max_size = min_t(unsigned long, PAGE_SIZE, max_size);
6882 ret = btrfs_decompress(compress_type, tmp, page,
6883 extent_offset, inline_size, max_size);
6886 * decompression code contains a memset to fill in any space between the end
6887 * of the uncompressed data and the end of max_size in case the decompressed
6888 * data ends up shorter than ram_bytes. That doesn't cover the hole between
6889 * the end of an inline extent and the beginning of the next block, so we
6890 * cover that region here.
6893 if (max_size + pg_offset < PAGE_SIZE) {
6894 char *map = kmap(page);
6895 memset(map + pg_offset + max_size, 0, PAGE_SIZE - max_size - pg_offset);
6903 * a bit scary, this does extent mapping from logical file offset to the disk.
6904 * the ugly parts come from merging extents from the disk with the in-ram
6905 * representation. This gets more complex because of the data=ordered code,
6906 * where the in-ram extents might be locked pending data=ordered completion.
6908 * This also copies inline extents directly into the page.
6910 struct extent_map *btrfs_get_extent(struct btrfs_inode *inode,
6912 size_t pg_offset, u64 start, u64 len,
6915 struct btrfs_fs_info *fs_info = inode->root->fs_info;
6918 u64 extent_start = 0;
6920 u64 objectid = btrfs_ino(inode);
6921 int extent_type = -1;
6922 struct btrfs_path *path = NULL;
6923 struct btrfs_root *root = inode->root;
6924 struct btrfs_file_extent_item *item;
6925 struct extent_buffer *leaf;
6926 struct btrfs_key found_key;
6927 struct extent_map *em = NULL;
6928 struct extent_map_tree *em_tree = &inode->extent_tree;
6929 struct extent_io_tree *io_tree = &inode->io_tree;
6930 const bool new_inline = !page || create;
6932 read_lock(&em_tree->lock);
6933 em = lookup_extent_mapping(em_tree, start, len);
6935 em->bdev = fs_info->fs_devices->latest_bdev;
6936 read_unlock(&em_tree->lock);
6939 if (em->start > start || em->start + em->len <= start)
6940 free_extent_map(em);
6941 else if (em->block_start == EXTENT_MAP_INLINE && page)
6942 free_extent_map(em);
6946 em = alloc_extent_map();
6951 em->bdev = fs_info->fs_devices->latest_bdev;
6952 em->start = EXTENT_MAP_HOLE;
6953 em->orig_start = EXTENT_MAP_HOLE;
6955 em->block_len = (u64)-1;
6957 path = btrfs_alloc_path();
6963 /* Chances are we'll be called again, so go ahead and do readahead */
6964 path->reada = READA_FORWARD;
6967 * Unless we're going to uncompress the inline extent, no sleep would
6970 path->leave_spinning = 1;
6972 ret = btrfs_lookup_file_extent(NULL, root, path, objectid, start, 0);
6976 } else if (ret > 0) {
6977 if (path->slots[0] == 0)
6982 leaf = path->nodes[0];
6983 item = btrfs_item_ptr(leaf, path->slots[0],
6984 struct btrfs_file_extent_item);
6985 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
6986 if (found_key.objectid != objectid ||
6987 found_key.type != BTRFS_EXTENT_DATA_KEY) {
6989 * If we backup past the first extent we want to move forward
6990 * and see if there is an extent in front of us, otherwise we'll
6991 * say there is a hole for our whole search range which can
6998 extent_type = btrfs_file_extent_type(leaf, item);
6999 extent_start = found_key.offset;
7000 if (extent_type == BTRFS_FILE_EXTENT_REG ||
7001 extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
7002 /* Only regular file could have regular/prealloc extent */
7003 if (!S_ISREG(inode->vfs_inode.i_mode)) {
7006 "regular/prealloc extent found for non-regular inode %llu",
7010 extent_end = extent_start +
7011 btrfs_file_extent_num_bytes(leaf, item);
7013 trace_btrfs_get_extent_show_fi_regular(inode, leaf, item,
7015 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
7018 size = btrfs_file_extent_ram_bytes(leaf, item);
7019 extent_end = ALIGN(extent_start + size,
7020 fs_info->sectorsize);
7022 trace_btrfs_get_extent_show_fi_inline(inode, leaf, item,
7027 if (start >= extent_end) {
7029 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
7030 ret = btrfs_next_leaf(root, path);
7034 } else if (ret > 0) {
7037 leaf = path->nodes[0];
7039 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
7040 if (found_key.objectid != objectid ||
7041 found_key.type != BTRFS_EXTENT_DATA_KEY)
7043 if (start + len <= found_key.offset)
7045 if (start > found_key.offset)
7048 /* New extent overlaps with existing one */
7050 em->orig_start = start;
7051 em->len = found_key.offset - start;
7052 em->block_start = EXTENT_MAP_HOLE;
7056 btrfs_extent_item_to_extent_map(inode, path, item,
7059 if (extent_type == BTRFS_FILE_EXTENT_REG ||
7060 extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
7062 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
7066 size_t extent_offset;
7072 size = btrfs_file_extent_ram_bytes(leaf, item);
7073 extent_offset = page_offset(page) + pg_offset - extent_start;
7074 copy_size = min_t(u64, PAGE_SIZE - pg_offset,
7075 size - extent_offset);
7076 em->start = extent_start + extent_offset;
7077 em->len = ALIGN(copy_size, fs_info->sectorsize);
7078 em->orig_block_len = em->len;
7079 em->orig_start = em->start;
7080 ptr = btrfs_file_extent_inline_start(item) + extent_offset;
7082 btrfs_set_path_blocking(path);
7083 if (!PageUptodate(page)) {
7084 if (btrfs_file_extent_compression(leaf, item) !=
7085 BTRFS_COMPRESS_NONE) {
7086 ret = uncompress_inline(path, page, pg_offset,
7087 extent_offset, item);
7094 read_extent_buffer(leaf, map + pg_offset, ptr,
7096 if (pg_offset + copy_size < PAGE_SIZE) {
7097 memset(map + pg_offset + copy_size, 0,
7098 PAGE_SIZE - pg_offset -
7103 flush_dcache_page(page);
7105 set_extent_uptodate(io_tree, em->start,
7106 extent_map_end(em) - 1, NULL, GFP_NOFS);
7111 em->orig_start = start;
7113 em->block_start = EXTENT_MAP_HOLE;
7115 btrfs_release_path(path);
7116 if (em->start > start || extent_map_end(em) <= start) {
7118 "bad extent! em: [%llu %llu] passed [%llu %llu]",
7119 em->start, em->len, start, len);
7125 write_lock(&em_tree->lock);
7126 err = btrfs_add_extent_mapping(fs_info, em_tree, &em, start, len);
7127 write_unlock(&em_tree->lock);
7129 btrfs_free_path(path);
7131 trace_btrfs_get_extent(root, inode, em);
7134 free_extent_map(em);
7135 return ERR_PTR(err);
7137 BUG_ON(!em); /* Error is always set */
7141 struct extent_map *btrfs_get_extent_fiemap(struct btrfs_inode *inode,
7144 struct extent_map *em;
7145 struct extent_map *hole_em = NULL;
7146 u64 delalloc_start = start;
7152 em = btrfs_get_extent(inode, NULL, 0, start, len, 0);
7156 * If our em maps to:
7158 * - a pre-alloc extent,
7159 * there might actually be delalloc bytes behind it.
7161 if (em->block_start != EXTENT_MAP_HOLE &&
7162 !test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
7167 /* check to see if we've wrapped (len == -1 or similar) */
7176 /* ok, we didn't find anything, lets look for delalloc */
7177 delalloc_len = count_range_bits(&inode->io_tree, &delalloc_start,
7178 end, len, EXTENT_DELALLOC, 1);
7179 delalloc_end = delalloc_start + delalloc_len;
7180 if (delalloc_end < delalloc_start)
7181 delalloc_end = (u64)-1;
7184 * We didn't find anything useful, return the original results from
7187 if (delalloc_start > end || delalloc_end <= start) {
7194 * Adjust the delalloc_start to make sure it doesn't go backwards from
7195 * the start they passed in
7197 delalloc_start = max(start, delalloc_start);
7198 delalloc_len = delalloc_end - delalloc_start;
7200 if (delalloc_len > 0) {
7203 const u64 hole_end = extent_map_end(hole_em);
7205 em = alloc_extent_map();
7214 * When btrfs_get_extent can't find anything it returns one
7217 * Make sure what it found really fits our range, and adjust to
7218 * make sure it is based on the start from the caller
7220 if (hole_end <= start || hole_em->start > end) {
7221 free_extent_map(hole_em);
7224 hole_start = max(hole_em->start, start);
7225 hole_len = hole_end - hole_start;
7228 if (hole_em && delalloc_start > hole_start) {
7230 * Our hole starts before our delalloc, so we have to
7231 * return just the parts of the hole that go until the
7234 em->len = min(hole_len, delalloc_start - hole_start);
7235 em->start = hole_start;
7236 em->orig_start = hole_start;
7238 * Don't adjust block start at all, it is fixed at
7241 em->block_start = hole_em->block_start;
7242 em->block_len = hole_len;
7243 if (test_bit(EXTENT_FLAG_PREALLOC, &hole_em->flags))
7244 set_bit(EXTENT_FLAG_PREALLOC, &em->flags);
7247 * Hole is out of passed range or it starts after
7250 em->start = delalloc_start;
7251 em->len = delalloc_len;
7252 em->orig_start = delalloc_start;
7253 em->block_start = EXTENT_MAP_DELALLOC;
7254 em->block_len = delalloc_len;
7261 free_extent_map(hole_em);
7263 free_extent_map(em);
7264 return ERR_PTR(err);
7269 static struct extent_map *btrfs_create_dio_extent(struct inode *inode,
7272 const u64 orig_start,
7273 const u64 block_start,
7274 const u64 block_len,
7275 const u64 orig_block_len,
7276 const u64 ram_bytes,
7279 struct extent_map *em = NULL;
7282 if (type != BTRFS_ORDERED_NOCOW) {
7283 em = create_io_em(inode, start, len, orig_start,
7284 block_start, block_len, orig_block_len,
7286 BTRFS_COMPRESS_NONE, /* compress_type */
7291 ret = btrfs_add_ordered_extent_dio(inode, start, block_start,
7292 len, block_len, type);
7295 free_extent_map(em);
7296 btrfs_drop_extent_cache(BTRFS_I(inode), start,
7297 start + len - 1, 0);
7306 static struct extent_map *btrfs_new_extent_direct(struct inode *inode,
7309 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7310 struct btrfs_root *root = BTRFS_I(inode)->root;
7311 struct extent_map *em;
7312 struct btrfs_key ins;
7316 alloc_hint = get_extent_allocation_hint(inode, start, len);
7317 ret = btrfs_reserve_extent(root, len, len, fs_info->sectorsize,
7318 0, alloc_hint, &ins, 1, 1);
7320 return ERR_PTR(ret);
7322 em = btrfs_create_dio_extent(inode, start, ins.offset, start,
7323 ins.objectid, ins.offset, ins.offset,
7324 ins.offset, BTRFS_ORDERED_REGULAR);
7325 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
7327 btrfs_free_reserved_extent(fs_info, ins.objectid,
7334 * returns 1 when the nocow is safe, < 1 on error, 0 if the
7335 * block must be cow'd
7337 noinline int can_nocow_extent(struct inode *inode, u64 offset, u64 *len,
7338 u64 *orig_start, u64 *orig_block_len,
7341 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7342 struct btrfs_path *path;
7344 struct extent_buffer *leaf;
7345 struct btrfs_root *root = BTRFS_I(inode)->root;
7346 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
7347 struct btrfs_file_extent_item *fi;
7348 struct btrfs_key key;
7355 bool nocow = (BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW);
7357 path = btrfs_alloc_path();
7361 ret = btrfs_lookup_file_extent(NULL, root, path,
7362 btrfs_ino(BTRFS_I(inode)), offset, 0);
7366 slot = path->slots[0];
7369 /* can't find the item, must cow */
7376 leaf = path->nodes[0];
7377 btrfs_item_key_to_cpu(leaf, &key, slot);
7378 if (key.objectid != btrfs_ino(BTRFS_I(inode)) ||
7379 key.type != BTRFS_EXTENT_DATA_KEY) {
7380 /* not our file or wrong item type, must cow */
7384 if (key.offset > offset) {
7385 /* Wrong offset, must cow */
7389 fi = btrfs_item_ptr(leaf, slot, struct btrfs_file_extent_item);
7390 found_type = btrfs_file_extent_type(leaf, fi);
7391 if (found_type != BTRFS_FILE_EXTENT_REG &&
7392 found_type != BTRFS_FILE_EXTENT_PREALLOC) {
7393 /* not a regular extent, must cow */
7397 if (!nocow && found_type == BTRFS_FILE_EXTENT_REG)
7400 extent_end = key.offset + btrfs_file_extent_num_bytes(leaf, fi);
7401 if (extent_end <= offset)
7404 disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
7405 if (disk_bytenr == 0)
7408 if (btrfs_file_extent_compression(leaf, fi) ||
7409 btrfs_file_extent_encryption(leaf, fi) ||
7410 btrfs_file_extent_other_encoding(leaf, fi))
7414 * Do the same check as in btrfs_cross_ref_exist but without the
7415 * unnecessary search.
7417 if (btrfs_file_extent_generation(leaf, fi) <=
7418 btrfs_root_last_snapshot(&root->root_item))
7421 backref_offset = btrfs_file_extent_offset(leaf, fi);
7424 *orig_start = key.offset - backref_offset;
7425 *orig_block_len = btrfs_file_extent_disk_num_bytes(leaf, fi);
7426 *ram_bytes = btrfs_file_extent_ram_bytes(leaf, fi);
7429 if (btrfs_extent_readonly(fs_info, disk_bytenr))
7432 num_bytes = min(offset + *len, extent_end) - offset;
7433 if (!nocow && found_type == BTRFS_FILE_EXTENT_PREALLOC) {
7436 range_end = round_up(offset + num_bytes,
7437 root->fs_info->sectorsize) - 1;
7438 ret = test_range_bit(io_tree, offset, range_end,
7439 EXTENT_DELALLOC, 0, NULL);
7446 btrfs_release_path(path);
7449 * look for other files referencing this extent, if we
7450 * find any we must cow
7453 ret = btrfs_cross_ref_exist(root, btrfs_ino(BTRFS_I(inode)),
7454 key.offset - backref_offset, disk_bytenr);
7461 * adjust disk_bytenr and num_bytes to cover just the bytes
7462 * in this extent we are about to write. If there
7463 * are any csums in that range we have to cow in order
7464 * to keep the csums correct
7466 disk_bytenr += backref_offset;
7467 disk_bytenr += offset - key.offset;
7468 if (csum_exist_in_range(fs_info, disk_bytenr, num_bytes))
7471 * all of the above have passed, it is safe to overwrite this extent
7477 btrfs_free_path(path);
7481 static int lock_extent_direct(struct inode *inode, u64 lockstart, u64 lockend,
7482 struct extent_state **cached_state, int writing)
7484 struct btrfs_ordered_extent *ordered;
7488 lock_extent_bits(&BTRFS_I(inode)->io_tree, lockstart, lockend,
7491 * We're concerned with the entire range that we're going to be
7492 * doing DIO to, so we need to make sure there's no ordered
7493 * extents in this range.
7495 ordered = btrfs_lookup_ordered_range(BTRFS_I(inode), lockstart,
7496 lockend - lockstart + 1);
7499 * We need to make sure there are no buffered pages in this
7500 * range either, we could have raced between the invalidate in
7501 * generic_file_direct_write and locking the extent. The
7502 * invalidate needs to happen so that reads after a write do not
7506 (!writing || !filemap_range_has_page(inode->i_mapping,
7507 lockstart, lockend)))
7510 unlock_extent_cached(&BTRFS_I(inode)->io_tree, lockstart, lockend,
7515 * If we are doing a DIO read and the ordered extent we
7516 * found is for a buffered write, we can not wait for it
7517 * to complete and retry, because if we do so we can
7518 * deadlock with concurrent buffered writes on page
7519 * locks. This happens only if our DIO read covers more
7520 * than one extent map, if at this point has already
7521 * created an ordered extent for a previous extent map
7522 * and locked its range in the inode's io tree, and a
7523 * concurrent write against that previous extent map's
7524 * range and this range started (we unlock the ranges
7525 * in the io tree only when the bios complete and
7526 * buffered writes always lock pages before attempting
7527 * to lock range in the io tree).
7530 test_bit(BTRFS_ORDERED_DIRECT, &ordered->flags))
7531 btrfs_start_ordered_extent(inode, ordered, 1);
7534 btrfs_put_ordered_extent(ordered);
7537 * We could trigger writeback for this range (and wait
7538 * for it to complete) and then invalidate the pages for
7539 * this range (through invalidate_inode_pages2_range()),
7540 * but that can lead us to a deadlock with a concurrent
7541 * call to readpages() (a buffered read or a defrag call
7542 * triggered a readahead) on a page lock due to an
7543 * ordered dio extent we created before but did not have
7544 * yet a corresponding bio submitted (whence it can not
7545 * complete), which makes readpages() wait for that
7546 * ordered extent to complete while holding a lock on
7561 /* The callers of this must take lock_extent() */
7562 static struct extent_map *create_io_em(struct inode *inode, u64 start, u64 len,
7563 u64 orig_start, u64 block_start,
7564 u64 block_len, u64 orig_block_len,
7565 u64 ram_bytes, int compress_type,
7568 struct extent_map_tree *em_tree;
7569 struct extent_map *em;
7570 struct btrfs_root *root = BTRFS_I(inode)->root;
7573 ASSERT(type == BTRFS_ORDERED_PREALLOC ||
7574 type == BTRFS_ORDERED_COMPRESSED ||
7575 type == BTRFS_ORDERED_NOCOW ||
7576 type == BTRFS_ORDERED_REGULAR);
7578 em_tree = &BTRFS_I(inode)->extent_tree;
7579 em = alloc_extent_map();
7581 return ERR_PTR(-ENOMEM);
7584 em->orig_start = orig_start;
7586 em->block_len = block_len;
7587 em->block_start = block_start;
7588 em->bdev = root->fs_info->fs_devices->latest_bdev;
7589 em->orig_block_len = orig_block_len;
7590 em->ram_bytes = ram_bytes;
7591 em->generation = -1;
7592 set_bit(EXTENT_FLAG_PINNED, &em->flags);
7593 if (type == BTRFS_ORDERED_PREALLOC) {
7594 set_bit(EXTENT_FLAG_FILLING, &em->flags);
7595 } else if (type == BTRFS_ORDERED_COMPRESSED) {
7596 set_bit(EXTENT_FLAG_COMPRESSED, &em->flags);
7597 em->compress_type = compress_type;
7601 btrfs_drop_extent_cache(BTRFS_I(inode), em->start,
7602 em->start + em->len - 1, 0);
7603 write_lock(&em_tree->lock);
7604 ret = add_extent_mapping(em_tree, em, 1);
7605 write_unlock(&em_tree->lock);
7607 * The caller has taken lock_extent(), who could race with us
7610 } while (ret == -EEXIST);
7613 free_extent_map(em);
7614 return ERR_PTR(ret);
7617 /* em got 2 refs now, callers needs to do free_extent_map once. */
7622 static int btrfs_get_blocks_direct_read(struct extent_map *em,
7623 struct buffer_head *bh_result,
7624 struct inode *inode,
7627 if (em->block_start == EXTENT_MAP_HOLE ||
7628 test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
7631 len = min(len, em->len - (start - em->start));
7633 bh_result->b_blocknr = (em->block_start + (start - em->start)) >>
7635 bh_result->b_size = len;
7636 bh_result->b_bdev = em->bdev;
7637 set_buffer_mapped(bh_result);
7642 static int btrfs_get_blocks_direct_write(struct extent_map **map,
7643 struct buffer_head *bh_result,
7644 struct inode *inode,
7645 struct btrfs_dio_data *dio_data,
7648 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7649 struct extent_map *em = *map;
7653 * We don't allocate a new extent in the following cases
7655 * 1) The inode is marked as NODATACOW. In this case we'll just use the
7657 * 2) The extent is marked as PREALLOC. We're good to go here and can
7658 * just use the extent.
7661 if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags) ||
7662 ((BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW) &&
7663 em->block_start != EXTENT_MAP_HOLE)) {
7665 u64 block_start, orig_start, orig_block_len, ram_bytes;
7667 if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
7668 type = BTRFS_ORDERED_PREALLOC;
7670 type = BTRFS_ORDERED_NOCOW;
7671 len = min(len, em->len - (start - em->start));
7672 block_start = em->block_start + (start - em->start);
7674 if (can_nocow_extent(inode, start, &len, &orig_start,
7675 &orig_block_len, &ram_bytes) == 1 &&
7676 btrfs_inc_nocow_writers(fs_info, block_start)) {
7677 struct extent_map *em2;
7679 em2 = btrfs_create_dio_extent(inode, start, len,
7680 orig_start, block_start,
7681 len, orig_block_len,
7683 btrfs_dec_nocow_writers(fs_info, block_start);
7684 if (type == BTRFS_ORDERED_PREALLOC) {
7685 free_extent_map(em);
7689 if (em2 && IS_ERR(em2)) {
7694 * For inode marked NODATACOW or extent marked PREALLOC,
7695 * use the existing or preallocated extent, so does not
7696 * need to adjust btrfs_space_info's bytes_may_use.
7698 btrfs_free_reserved_data_space_noquota(inode, start,
7704 /* this will cow the extent */
7705 len = bh_result->b_size;
7706 free_extent_map(em);
7707 *map = em = btrfs_new_extent_direct(inode, start, len);
7713 len = min(len, em->len - (start - em->start));
7716 bh_result->b_blocknr = (em->block_start + (start - em->start)) >>
7718 bh_result->b_size = len;
7719 bh_result->b_bdev = em->bdev;
7720 set_buffer_mapped(bh_result);
7722 if (!test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
7723 set_buffer_new(bh_result);
7726 * Need to update the i_size under the extent lock so buffered
7727 * readers will get the updated i_size when we unlock.
7729 if (!dio_data->overwrite && start + len > i_size_read(inode))
7730 i_size_write(inode, start + len);
7732 WARN_ON(dio_data->reserve < len);
7733 dio_data->reserve -= len;
7734 dio_data->unsubmitted_oe_range_end = start + len;
7735 current->journal_info = dio_data;
7740 static int btrfs_get_blocks_direct(struct inode *inode, sector_t iblock,
7741 struct buffer_head *bh_result, int create)
7743 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7744 struct extent_map *em;
7745 struct extent_state *cached_state = NULL;
7746 struct btrfs_dio_data *dio_data = NULL;
7747 u64 start = iblock << inode->i_blkbits;
7748 u64 lockstart, lockend;
7749 u64 len = bh_result->b_size;
7753 len = min_t(u64, len, fs_info->sectorsize);
7756 lockend = start + len - 1;
7758 if (current->journal_info) {
7760 * Need to pull our outstanding extents and set journal_info to NULL so
7761 * that anything that needs to check if there's a transaction doesn't get
7764 dio_data = current->journal_info;
7765 current->journal_info = NULL;
7769 * If this errors out it's because we couldn't invalidate pagecache for
7770 * this range and we need to fallback to buffered.
7772 if (lock_extent_direct(inode, lockstart, lockend, &cached_state,
7778 em = btrfs_get_extent(BTRFS_I(inode), NULL, 0, start, len, 0);
7785 * Ok for INLINE and COMPRESSED extents we need to fallback on buffered
7786 * io. INLINE is special, and we could probably kludge it in here, but
7787 * it's still buffered so for safety lets just fall back to the generic
7790 * For COMPRESSED we _have_ to read the entire extent in so we can
7791 * decompress it, so there will be buffering required no matter what we
7792 * do, so go ahead and fallback to buffered.
7794 * We return -ENOTBLK because that's what makes DIO go ahead and go back
7795 * to buffered IO. Don't blame me, this is the price we pay for using
7798 if (test_bit(EXTENT_FLAG_COMPRESSED, &em->flags) ||
7799 em->block_start == EXTENT_MAP_INLINE) {
7800 free_extent_map(em);
7806 ret = btrfs_get_blocks_direct_write(&em, bh_result, inode,
7807 dio_data, start, len);
7811 unlock_extent_cached(&BTRFS_I(inode)->io_tree, lockstart,
7812 lockend, &cached_state);
7814 ret = btrfs_get_blocks_direct_read(em, bh_result, inode,
7816 /* Can be negative only if we read from a hole */
7819 free_extent_map(em);
7823 * We need to unlock only the end area that we aren't using.
7824 * The rest is going to be unlocked by the endio routine.
7826 lockstart = start + bh_result->b_size;
7827 if (lockstart < lockend) {
7828 unlock_extent_cached(&BTRFS_I(inode)->io_tree,
7829 lockstart, lockend, &cached_state);
7831 free_extent_state(cached_state);
7835 free_extent_map(em);
7840 unlock_extent_cached(&BTRFS_I(inode)->io_tree, lockstart, lockend,
7844 current->journal_info = dio_data;
7848 static inline blk_status_t submit_dio_repair_bio(struct inode *inode,
7852 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7855 BUG_ON(bio_op(bio) == REQ_OP_WRITE);
7857 ret = btrfs_bio_wq_end_io(fs_info, bio, BTRFS_WQ_ENDIO_DIO_REPAIR);
7861 ret = btrfs_map_bio(fs_info, bio, mirror_num, 0);
7866 static int btrfs_check_dio_repairable(struct inode *inode,
7867 struct bio *failed_bio,
7868 struct io_failure_record *failrec,
7871 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7874 num_copies = btrfs_num_copies(fs_info, failrec->logical, failrec->len);
7875 if (num_copies == 1) {
7877 * we only have a single copy of the data, so don't bother with
7878 * all the retry and error correction code that follows. no
7879 * matter what the error is, it is very likely to persist.
7881 btrfs_debug(fs_info,
7882 "Check DIO Repairable: cannot repair, num_copies=%d, next_mirror %d, failed_mirror %d",
7883 num_copies, failrec->this_mirror, failed_mirror);
7887 failrec->failed_mirror = failed_mirror;
7888 failrec->this_mirror++;
7889 if (failrec->this_mirror == failed_mirror)
7890 failrec->this_mirror++;
7892 if (failrec->this_mirror > num_copies) {
7893 btrfs_debug(fs_info,
7894 "Check DIO Repairable: (fail) num_copies=%d, next_mirror %d, failed_mirror %d",
7895 num_copies, failrec->this_mirror, failed_mirror);
7902 static blk_status_t dio_read_error(struct inode *inode, struct bio *failed_bio,
7903 struct page *page, unsigned int pgoff,
7904 u64 start, u64 end, int failed_mirror,
7905 bio_end_io_t *repair_endio, void *repair_arg)
7907 struct io_failure_record *failrec;
7908 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
7909 struct extent_io_tree *failure_tree = &BTRFS_I(inode)->io_failure_tree;
7912 unsigned int read_mode = 0;
7915 blk_status_t status;
7916 struct bio_vec bvec;
7918 BUG_ON(bio_op(failed_bio) == REQ_OP_WRITE);
7920 ret = btrfs_get_io_failure_record(inode, start, end, &failrec);
7922 return errno_to_blk_status(ret);
7924 ret = btrfs_check_dio_repairable(inode, failed_bio, failrec,
7927 free_io_failure(failure_tree, io_tree, failrec);
7928 return BLK_STS_IOERR;
7931 segs = bio_segments(failed_bio);
7932 bio_get_first_bvec(failed_bio, &bvec);
7934 (bvec.bv_len > btrfs_inode_sectorsize(inode)))
7935 read_mode |= REQ_FAILFAST_DEV;
7937 isector = start - btrfs_io_bio(failed_bio)->logical;
7938 isector >>= inode->i_sb->s_blocksize_bits;
7939 bio = btrfs_create_repair_bio(inode, failed_bio, failrec, page,
7940 pgoff, isector, repair_endio, repair_arg);
7941 bio->bi_opf = REQ_OP_READ | read_mode;
7943 btrfs_debug(BTRFS_I(inode)->root->fs_info,
7944 "repair DIO read error: submitting new dio read[%#x] to this_mirror=%d, in_validation=%d",
7945 read_mode, failrec->this_mirror, failrec->in_validation);
7947 status = submit_dio_repair_bio(inode, bio, failrec->this_mirror);
7949 free_io_failure(failure_tree, io_tree, failrec);
7956 struct btrfs_retry_complete {
7957 struct completion done;
7958 struct inode *inode;
7963 static void btrfs_retry_endio_nocsum(struct bio *bio)
7965 struct btrfs_retry_complete *done = bio->bi_private;
7966 struct inode *inode = done->inode;
7967 struct bio_vec *bvec;
7968 struct extent_io_tree *io_tree, *failure_tree;
7969 struct bvec_iter_all iter_all;
7974 ASSERT(bio->bi_vcnt == 1);
7975 io_tree = &BTRFS_I(inode)->io_tree;
7976 failure_tree = &BTRFS_I(inode)->io_failure_tree;
7977 ASSERT(bio_first_bvec_all(bio)->bv_len == btrfs_inode_sectorsize(inode));
7980 ASSERT(!bio_flagged(bio, BIO_CLONED));
7981 bio_for_each_segment_all(bvec, bio, iter_all)
7982 clean_io_failure(BTRFS_I(inode)->root->fs_info, failure_tree,
7983 io_tree, done->start, bvec->bv_page,
7984 btrfs_ino(BTRFS_I(inode)), 0);
7986 complete(&done->done);
7990 static blk_status_t __btrfs_correct_data_nocsum(struct inode *inode,
7991 struct btrfs_io_bio *io_bio)
7993 struct btrfs_fs_info *fs_info;
7994 struct bio_vec bvec;
7995 struct bvec_iter iter;
7996 struct btrfs_retry_complete done;
8002 blk_status_t err = BLK_STS_OK;
8004 fs_info = BTRFS_I(inode)->root->fs_info;
8005 sectorsize = fs_info->sectorsize;
8007 start = io_bio->logical;
8009 io_bio->bio.bi_iter = io_bio->iter;
8011 bio_for_each_segment(bvec, &io_bio->bio, iter) {
8012 nr_sectors = BTRFS_BYTES_TO_BLKS(fs_info, bvec.bv_len);
8013 pgoff = bvec.bv_offset;
8015 next_block_or_try_again:
8018 init_completion(&done.done);
8020 ret = dio_read_error(inode, &io_bio->bio, bvec.bv_page,
8021 pgoff, start, start + sectorsize - 1,
8023 btrfs_retry_endio_nocsum, &done);
8029 wait_for_completion_io(&done.done);
8031 if (!done.uptodate) {
8032 /* We might have another mirror, so try again */
8033 goto next_block_or_try_again;
8037 start += sectorsize;
8041 pgoff += sectorsize;
8042 ASSERT(pgoff < PAGE_SIZE);
8043 goto next_block_or_try_again;
8050 static void btrfs_retry_endio(struct bio *bio)
8052 struct btrfs_retry_complete *done = bio->bi_private;
8053 struct btrfs_io_bio *io_bio = btrfs_io_bio(bio);
8054 struct extent_io_tree *io_tree, *failure_tree;
8055 struct inode *inode = done->inode;
8056 struct bio_vec *bvec;
8060 struct bvec_iter_all iter_all;
8067 ASSERT(bio->bi_vcnt == 1);
8068 ASSERT(bio_first_bvec_all(bio)->bv_len == btrfs_inode_sectorsize(done->inode));
8070 io_tree = &BTRFS_I(inode)->io_tree;
8071 failure_tree = &BTRFS_I(inode)->io_failure_tree;
8073 ASSERT(!bio_flagged(bio, BIO_CLONED));
8074 bio_for_each_segment_all(bvec, bio, iter_all) {
8075 ret = __readpage_endio_check(inode, io_bio, i, bvec->bv_page,
8076 bvec->bv_offset, done->start,
8079 clean_io_failure(BTRFS_I(inode)->root->fs_info,
8080 failure_tree, io_tree, done->start,
8082 btrfs_ino(BTRFS_I(inode)),
8089 done->uptodate = uptodate;
8091 complete(&done->done);
8095 static blk_status_t __btrfs_subio_endio_read(struct inode *inode,
8096 struct btrfs_io_bio *io_bio, blk_status_t err)
8098 struct btrfs_fs_info *fs_info;
8099 struct bio_vec bvec;
8100 struct bvec_iter iter;
8101 struct btrfs_retry_complete done;
8108 bool uptodate = (err == 0);
8110 blk_status_t status;
8112 fs_info = BTRFS_I(inode)->root->fs_info;
8113 sectorsize = fs_info->sectorsize;
8116 start = io_bio->logical;
8118 io_bio->bio.bi_iter = io_bio->iter;
8120 bio_for_each_segment(bvec, &io_bio->bio, iter) {
8121 nr_sectors = BTRFS_BYTES_TO_BLKS(fs_info, bvec.bv_len);
8123 pgoff = bvec.bv_offset;
8126 csum_pos = BTRFS_BYTES_TO_BLKS(fs_info, offset);
8127 ret = __readpage_endio_check(inode, io_bio, csum_pos,
8128 bvec.bv_page, pgoff, start, sectorsize);
8135 init_completion(&done.done);
8137 status = dio_read_error(inode, &io_bio->bio, bvec.bv_page,
8138 pgoff, start, start + sectorsize - 1,
8139 io_bio->mirror_num, btrfs_retry_endio,
8146 wait_for_completion_io(&done.done);
8148 if (!done.uptodate) {
8149 /* We might have another mirror, so try again */
8153 offset += sectorsize;
8154 start += sectorsize;
8160 pgoff += sectorsize;
8161 ASSERT(pgoff < PAGE_SIZE);
8169 static blk_status_t btrfs_subio_endio_read(struct inode *inode,
8170 struct btrfs_io_bio *io_bio, blk_status_t err)
8172 bool skip_csum = BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM;
8176 return __btrfs_correct_data_nocsum(inode, io_bio);
8180 return __btrfs_subio_endio_read(inode, io_bio, err);
8184 static void btrfs_endio_direct_read(struct bio *bio)
8186 struct btrfs_dio_private *dip = bio->bi_private;
8187 struct inode *inode = dip->inode;
8188 struct bio *dio_bio;
8189 struct btrfs_io_bio *io_bio = btrfs_io_bio(bio);
8190 blk_status_t err = bio->bi_status;
8192 if (dip->flags & BTRFS_DIO_ORIG_BIO_SUBMITTED)
8193 err = btrfs_subio_endio_read(inode, io_bio, err);
8195 unlock_extent(&BTRFS_I(inode)->io_tree, dip->logical_offset,
8196 dip->logical_offset + dip->bytes - 1);
8197 dio_bio = dip->dio_bio;
8201 dio_bio->bi_status = err;
8202 dio_end_io(dio_bio);
8203 btrfs_io_bio_free_csum(io_bio);
8207 static void __endio_write_update_ordered(struct inode *inode,
8208 const u64 offset, const u64 bytes,
8209 const bool uptodate)
8211 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
8212 struct btrfs_ordered_extent *ordered = NULL;
8213 struct btrfs_workqueue *wq;
8214 btrfs_work_func_t func;
8215 u64 ordered_offset = offset;
8216 u64 ordered_bytes = bytes;
8219 if (btrfs_is_free_space_inode(BTRFS_I(inode))) {
8220 wq = fs_info->endio_freespace_worker;
8221 func = btrfs_freespace_write_helper;
8223 wq = fs_info->endio_write_workers;
8224 func = btrfs_endio_write_helper;
8227 while (ordered_offset < offset + bytes) {
8228 last_offset = ordered_offset;
8229 if (btrfs_dec_test_first_ordered_pending(inode, &ordered,
8233 btrfs_init_work(&ordered->work, func,
8236 btrfs_queue_work(wq, &ordered->work);
8239 * If btrfs_dec_test_ordered_pending does not find any ordered
8240 * extent in the range, we can exit.
8242 if (ordered_offset == last_offset)
8245 * Our bio might span multiple ordered extents. In this case
8246 * we keep going until we have accounted the whole dio.
8248 if (ordered_offset < offset + bytes) {
8249 ordered_bytes = offset + bytes - ordered_offset;
8255 static void btrfs_endio_direct_write(struct bio *bio)
8257 struct btrfs_dio_private *dip = bio->bi_private;
8258 struct bio *dio_bio = dip->dio_bio;
8260 __endio_write_update_ordered(dip->inode, dip->logical_offset,
8261 dip->bytes, !bio->bi_status);
8265 dio_bio->bi_status = bio->bi_status;
8266 dio_end_io(dio_bio);
8270 static blk_status_t btrfs_submit_bio_start_direct_io(void *private_data,
8271 struct bio *bio, u64 offset)
8273 struct inode *inode = private_data;
8275 ret = btrfs_csum_one_bio(inode, bio, offset, 1);
8276 BUG_ON(ret); /* -ENOMEM */
8280 static void btrfs_end_dio_bio(struct bio *bio)
8282 struct btrfs_dio_private *dip = bio->bi_private;
8283 blk_status_t err = bio->bi_status;
8286 btrfs_warn(BTRFS_I(dip->inode)->root->fs_info,
8287 "direct IO failed ino %llu rw %d,%u sector %#Lx len %u err no %d",
8288 btrfs_ino(BTRFS_I(dip->inode)), bio_op(bio),
8290 (unsigned long long)bio->bi_iter.bi_sector,
8291 bio->bi_iter.bi_size, err);
8293 if (dip->subio_endio)
8294 err = dip->subio_endio(dip->inode, btrfs_io_bio(bio), err);
8298 * We want to perceive the errors flag being set before
8299 * decrementing the reference count. We don't need a barrier
8300 * since atomic operations with a return value are fully
8301 * ordered as per atomic_t.txt
8306 /* if there are more bios still pending for this dio, just exit */
8307 if (!atomic_dec_and_test(&dip->pending_bios))
8311 bio_io_error(dip->orig_bio);
8313 dip->dio_bio->bi_status = BLK_STS_OK;
8314 bio_endio(dip->orig_bio);
8320 static inline blk_status_t btrfs_lookup_and_bind_dio_csum(struct inode *inode,
8321 struct btrfs_dio_private *dip,
8325 struct btrfs_io_bio *io_bio = btrfs_io_bio(bio);
8326 struct btrfs_io_bio *orig_io_bio = btrfs_io_bio(dip->orig_bio);
8330 * We load all the csum data we need when we submit
8331 * the first bio to reduce the csum tree search and
8334 if (dip->logical_offset == file_offset) {
8335 ret = btrfs_lookup_bio_sums_dio(inode, dip->orig_bio,
8341 if (bio == dip->orig_bio)
8344 file_offset -= dip->logical_offset;
8345 file_offset >>= inode->i_sb->s_blocksize_bits;
8346 io_bio->csum = (u8 *)(((u32 *)orig_io_bio->csum) + file_offset);
8351 static inline blk_status_t btrfs_submit_dio_bio(struct bio *bio,
8352 struct inode *inode, u64 file_offset, int async_submit)
8354 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
8355 struct btrfs_dio_private *dip = bio->bi_private;
8356 bool write = bio_op(bio) == REQ_OP_WRITE;
8359 /* Check btrfs_submit_bio_hook() for rules about async submit. */
8361 async_submit = !atomic_read(&BTRFS_I(inode)->sync_writers);
8364 ret = btrfs_bio_wq_end_io(fs_info, bio, BTRFS_WQ_ENDIO_DATA);
8369 if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)
8372 if (write && async_submit) {
8373 ret = btrfs_wq_submit_bio(fs_info, bio, 0, 0,
8375 btrfs_submit_bio_start_direct_io);
8379 * If we aren't doing async submit, calculate the csum of the
8382 ret = btrfs_csum_one_bio(inode, bio, file_offset, 1);
8386 ret = btrfs_lookup_and_bind_dio_csum(inode, dip, bio,
8392 ret = btrfs_map_bio(fs_info, bio, 0, 0);
8397 static int btrfs_submit_direct_hook(struct btrfs_dio_private *dip)
8399 struct inode *inode = dip->inode;
8400 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
8402 struct bio *orig_bio = dip->orig_bio;
8403 u64 start_sector = orig_bio->bi_iter.bi_sector;
8404 u64 file_offset = dip->logical_offset;
8405 int async_submit = 0;
8407 int clone_offset = 0;
8410 blk_status_t status;
8411 struct btrfs_io_geometry geom;
8413 submit_len = orig_bio->bi_iter.bi_size;
8414 ret = btrfs_get_io_geometry(fs_info, btrfs_op(orig_bio),
8415 start_sector << 9, submit_len, &geom);
8419 if (geom.len >= submit_len) {
8421 dip->flags |= BTRFS_DIO_ORIG_BIO_SUBMITTED;
8425 /* async crcs make it difficult to collect full stripe writes. */
8426 if (btrfs_data_alloc_profile(fs_info) & BTRFS_BLOCK_GROUP_RAID56_MASK)
8432 ASSERT(geom.len <= INT_MAX);
8433 atomic_inc(&dip->pending_bios);
8435 clone_len = min_t(int, submit_len, geom.len);
8438 * This will never fail as it's passing GPF_NOFS and
8439 * the allocation is backed by btrfs_bioset.
8441 bio = btrfs_bio_clone_partial(orig_bio, clone_offset,
8443 bio->bi_private = dip;
8444 bio->bi_end_io = btrfs_end_dio_bio;
8445 btrfs_io_bio(bio)->logical = file_offset;
8447 ASSERT(submit_len >= clone_len);
8448 submit_len -= clone_len;
8449 if (submit_len == 0)
8453 * Increase the count before we submit the bio so we know
8454 * the end IO handler won't happen before we increase the
8455 * count. Otherwise, the dip might get freed before we're
8456 * done setting it up.
8458 atomic_inc(&dip->pending_bios);
8460 status = btrfs_submit_dio_bio(bio, inode, file_offset,
8464 atomic_dec(&dip->pending_bios);
8468 clone_offset += clone_len;
8469 start_sector += clone_len >> 9;
8470 file_offset += clone_len;
8472 ret = btrfs_get_io_geometry(fs_info, btrfs_op(orig_bio),
8473 start_sector << 9, submit_len, &geom);
8476 } while (submit_len > 0);
8479 status = btrfs_submit_dio_bio(bio, inode, file_offset, async_submit);
8487 * Before atomic variable goto zero, we must make sure dip->errors is
8488 * perceived to be set. This ordering is ensured by the fact that an
8489 * atomic operations with a return value are fully ordered as per
8492 if (atomic_dec_and_test(&dip->pending_bios))
8493 bio_io_error(dip->orig_bio);
8495 /* bio_end_io() will handle error, so we needn't return it */
8499 static void btrfs_submit_direct(struct bio *dio_bio, struct inode *inode,
8502 struct btrfs_dio_private *dip = NULL;
8503 struct bio *bio = NULL;
8504 struct btrfs_io_bio *io_bio;
8505 bool write = (bio_op(dio_bio) == REQ_OP_WRITE);
8508 bio = btrfs_bio_clone(dio_bio);
8510 dip = kzalloc(sizeof(*dip), GFP_NOFS);
8516 dip->private = dio_bio->bi_private;
8518 dip->logical_offset = file_offset;
8519 dip->bytes = dio_bio->bi_iter.bi_size;
8520 dip->disk_bytenr = (u64)dio_bio->bi_iter.bi_sector << 9;
8521 bio->bi_private = dip;
8522 dip->orig_bio = bio;
8523 dip->dio_bio = dio_bio;
8524 atomic_set(&dip->pending_bios, 0);
8525 io_bio = btrfs_io_bio(bio);
8526 io_bio->logical = file_offset;
8529 bio->bi_end_io = btrfs_endio_direct_write;
8531 bio->bi_end_io = btrfs_endio_direct_read;
8532 dip->subio_endio = btrfs_subio_endio_read;
8536 * Reset the range for unsubmitted ordered extents (to a 0 length range)
8537 * even if we fail to submit a bio, because in such case we do the
8538 * corresponding error handling below and it must not be done a second
8539 * time by btrfs_direct_IO().
8542 struct btrfs_dio_data *dio_data = current->journal_info;
8544 dio_data->unsubmitted_oe_range_end = dip->logical_offset +
8546 dio_data->unsubmitted_oe_range_start =
8547 dio_data->unsubmitted_oe_range_end;
8550 ret = btrfs_submit_direct_hook(dip);
8554 btrfs_io_bio_free_csum(io_bio);
8558 * If we arrived here it means either we failed to submit the dip
8559 * or we either failed to clone the dio_bio or failed to allocate the
8560 * dip. If we cloned the dio_bio and allocated the dip, we can just
8561 * call bio_endio against our io_bio so that we get proper resource
8562 * cleanup if we fail to submit the dip, otherwise, we must do the
8563 * same as btrfs_endio_direct_[write|read] because we can't call these
8564 * callbacks - they require an allocated dip and a clone of dio_bio.
8569 * The end io callbacks free our dip, do the final put on bio
8570 * and all the cleanup and final put for dio_bio (through
8577 __endio_write_update_ordered(inode,
8579 dio_bio->bi_iter.bi_size,
8582 unlock_extent(&BTRFS_I(inode)->io_tree, file_offset,
8583 file_offset + dio_bio->bi_iter.bi_size - 1);
8585 dio_bio->bi_status = BLK_STS_IOERR;
8587 * Releases and cleans up our dio_bio, no need to bio_put()
8588 * nor bio_endio()/bio_io_error() against dio_bio.
8590 dio_end_io(dio_bio);
8597 static ssize_t check_direct_IO(struct btrfs_fs_info *fs_info,
8598 const struct iov_iter *iter, loff_t offset)
8602 unsigned int blocksize_mask = fs_info->sectorsize - 1;
8603 ssize_t retval = -EINVAL;
8605 if (offset & blocksize_mask)
8608 if (iov_iter_alignment(iter) & blocksize_mask)
8611 /* If this is a write we don't need to check anymore */
8612 if (iov_iter_rw(iter) != READ || !iter_is_iovec(iter))
8615 * Check to make sure we don't have duplicate iov_base's in this
8616 * iovec, if so return EINVAL, otherwise we'll get csum errors
8617 * when reading back.
8619 for (seg = 0; seg < iter->nr_segs; seg++) {
8620 for (i = seg + 1; i < iter->nr_segs; i++) {
8621 if (iter->iov[seg].iov_base == iter->iov[i].iov_base)
8630 static ssize_t btrfs_direct_IO(struct kiocb *iocb, struct iov_iter *iter)
8632 struct file *file = iocb->ki_filp;
8633 struct inode *inode = file->f_mapping->host;
8634 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
8635 struct btrfs_dio_data dio_data = { 0 };
8636 struct extent_changeset *data_reserved = NULL;
8637 loff_t offset = iocb->ki_pos;
8641 bool relock = false;
8644 if (check_direct_IO(fs_info, iter, offset))
8647 inode_dio_begin(inode);
8650 * The generic stuff only does filemap_write_and_wait_range, which
8651 * isn't enough if we've written compressed pages to this area, so
8652 * we need to flush the dirty pages again to make absolutely sure
8653 * that any outstanding dirty pages are on disk.
8655 count = iov_iter_count(iter);
8656 if (test_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
8657 &BTRFS_I(inode)->runtime_flags))
8658 filemap_fdatawrite_range(inode->i_mapping, offset,
8659 offset + count - 1);
8661 if (iov_iter_rw(iter) == WRITE) {
8663 * If the write DIO is beyond the EOF, we need update
8664 * the isize, but it is protected by i_mutex. So we can
8665 * not unlock the i_mutex at this case.
8667 if (offset + count <= inode->i_size) {
8668 dio_data.overwrite = 1;
8669 inode_unlock(inode);
8671 } else if (iocb->ki_flags & IOCB_NOWAIT) {
8675 ret = btrfs_delalloc_reserve_space(inode, &data_reserved,
8681 * We need to know how many extents we reserved so that we can
8682 * do the accounting properly if we go over the number we
8683 * originally calculated. Abuse current->journal_info for this.
8685 dio_data.reserve = round_up(count,
8686 fs_info->sectorsize);
8687 dio_data.unsubmitted_oe_range_start = (u64)offset;
8688 dio_data.unsubmitted_oe_range_end = (u64)offset;
8689 current->journal_info = &dio_data;
8690 down_read(&BTRFS_I(inode)->dio_sem);
8691 } else if (test_bit(BTRFS_INODE_READDIO_NEED_LOCK,
8692 &BTRFS_I(inode)->runtime_flags)) {
8693 inode_dio_end(inode);
8694 flags = DIO_LOCKING | DIO_SKIP_HOLES;
8698 ret = __blockdev_direct_IO(iocb, inode,
8699 fs_info->fs_devices->latest_bdev,
8700 iter, btrfs_get_blocks_direct, NULL,
8701 btrfs_submit_direct, flags);
8702 if (iov_iter_rw(iter) == WRITE) {
8703 up_read(&BTRFS_I(inode)->dio_sem);
8704 current->journal_info = NULL;
8705 if (ret < 0 && ret != -EIOCBQUEUED) {
8706 if (dio_data.reserve)
8707 btrfs_delalloc_release_space(inode, data_reserved,
8708 offset, dio_data.reserve, true);
8710 * On error we might have left some ordered extents
8711 * without submitting corresponding bios for them, so
8712 * cleanup them up to avoid other tasks getting them
8713 * and waiting for them to complete forever.
8715 if (dio_data.unsubmitted_oe_range_start <
8716 dio_data.unsubmitted_oe_range_end)
8717 __endio_write_update_ordered(inode,
8718 dio_data.unsubmitted_oe_range_start,
8719 dio_data.unsubmitted_oe_range_end -
8720 dio_data.unsubmitted_oe_range_start,
8722 } else if (ret >= 0 && (size_t)ret < count)
8723 btrfs_delalloc_release_space(inode, data_reserved,
8724 offset, count - (size_t)ret, true);
8725 btrfs_delalloc_release_extents(BTRFS_I(inode), count);
8729 inode_dio_end(inode);
8733 extent_changeset_free(data_reserved);
8737 #define BTRFS_FIEMAP_FLAGS (FIEMAP_FLAG_SYNC)
8739 static int btrfs_fiemap(struct inode *inode, struct fiemap_extent_info *fieinfo,
8740 __u64 start, __u64 len)
8744 ret = fiemap_check_flags(fieinfo, BTRFS_FIEMAP_FLAGS);
8748 return extent_fiemap(inode, fieinfo, start, len);
8751 int btrfs_readpage(struct file *file, struct page *page)
8753 struct extent_io_tree *tree;
8754 tree = &BTRFS_I(page->mapping->host)->io_tree;
8755 return extent_read_full_page(tree, page, btrfs_get_extent, 0);
8758 static int btrfs_writepage(struct page *page, struct writeback_control *wbc)
8760 struct inode *inode = page->mapping->host;
8763 if (current->flags & PF_MEMALLOC) {
8764 redirty_page_for_writepage(wbc, page);
8770 * If we are under memory pressure we will call this directly from the
8771 * VM, we need to make sure we have the inode referenced for the ordered
8772 * extent. If not just return like we didn't do anything.
8774 if (!igrab(inode)) {
8775 redirty_page_for_writepage(wbc, page);
8776 return AOP_WRITEPAGE_ACTIVATE;
8778 ret = extent_write_full_page(page, wbc);
8779 btrfs_add_delayed_iput(inode);
8783 static int btrfs_writepages(struct address_space *mapping,
8784 struct writeback_control *wbc)
8786 return extent_writepages(mapping, wbc);
8790 btrfs_readpages(struct file *file, struct address_space *mapping,
8791 struct list_head *pages, unsigned nr_pages)
8793 return extent_readpages(mapping, pages, nr_pages);
8796 static int __btrfs_releasepage(struct page *page, gfp_t gfp_flags)
8798 int ret = try_release_extent_mapping(page, gfp_flags);
8800 ClearPagePrivate(page);
8801 set_page_private(page, 0);
8807 static int btrfs_releasepage(struct page *page, gfp_t gfp_flags)
8809 if (PageWriteback(page) || PageDirty(page))
8811 return __btrfs_releasepage(page, gfp_flags);
8814 static void btrfs_invalidatepage(struct page *page, unsigned int offset,
8815 unsigned int length)
8817 struct inode *inode = page->mapping->host;
8818 struct extent_io_tree *tree;
8819 struct btrfs_ordered_extent *ordered;
8820 struct extent_state *cached_state = NULL;
8821 u64 page_start = page_offset(page);
8822 u64 page_end = page_start + PAGE_SIZE - 1;
8825 int inode_evicting = inode->i_state & I_FREEING;
8828 * we have the page locked, so new writeback can't start,
8829 * and the dirty bit won't be cleared while we are here.
8831 * Wait for IO on this page so that we can safely clear
8832 * the PagePrivate2 bit and do ordered accounting
8834 wait_on_page_writeback(page);
8836 tree = &BTRFS_I(inode)->io_tree;
8838 btrfs_releasepage(page, GFP_NOFS);
8842 if (!inode_evicting)
8843 lock_extent_bits(tree, page_start, page_end, &cached_state);
8846 ordered = btrfs_lookup_ordered_range(BTRFS_I(inode), start,
8847 page_end - start + 1);
8849 end = min(page_end, ordered->file_offset + ordered->len - 1);
8851 * IO on this page will never be started, so we need
8852 * to account for any ordered extents now
8854 if (!inode_evicting)
8855 clear_extent_bit(tree, start, end,
8856 EXTENT_DELALLOC | EXTENT_DELALLOC_NEW |
8857 EXTENT_LOCKED | EXTENT_DO_ACCOUNTING |
8858 EXTENT_DEFRAG, 1, 0, &cached_state);
8860 * whoever cleared the private bit is responsible
8861 * for the finish_ordered_io
8863 if (TestClearPagePrivate2(page)) {
8864 struct btrfs_ordered_inode_tree *tree;
8867 tree = &BTRFS_I(inode)->ordered_tree;
8869 spin_lock_irq(&tree->lock);
8870 set_bit(BTRFS_ORDERED_TRUNCATED, &ordered->flags);
8871 new_len = start - ordered->file_offset;
8872 if (new_len < ordered->truncated_len)
8873 ordered->truncated_len = new_len;
8874 spin_unlock_irq(&tree->lock);
8876 if (btrfs_dec_test_ordered_pending(inode, &ordered,
8878 end - start + 1, 1))
8879 btrfs_finish_ordered_io(ordered);
8881 btrfs_put_ordered_extent(ordered);
8882 if (!inode_evicting) {
8883 cached_state = NULL;
8884 lock_extent_bits(tree, start, end,
8889 if (start < page_end)
8894 * Qgroup reserved space handler
8895 * Page here will be either
8896 * 1) Already written to disk
8897 * In this case, its reserved space is released from data rsv map
8898 * and will be freed by delayed_ref handler finally.
8899 * So even we call qgroup_free_data(), it won't decrease reserved
8901 * 2) Not written to disk
8902 * This means the reserved space should be freed here. However,
8903 * if a truncate invalidates the page (by clearing PageDirty)
8904 * and the page is accounted for while allocating extent
8905 * in btrfs_check_data_free_space() we let delayed_ref to
8906 * free the entire extent.
8908 if (PageDirty(page))
8909 btrfs_qgroup_free_data(inode, NULL, page_start, PAGE_SIZE);
8910 if (!inode_evicting) {
8911 clear_extent_bit(tree, page_start, page_end, EXTENT_LOCKED |
8912 EXTENT_DELALLOC | EXTENT_DELALLOC_NEW |
8913 EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG, 1, 1,
8916 __btrfs_releasepage(page, GFP_NOFS);
8919 ClearPageChecked(page);
8920 if (PagePrivate(page)) {
8921 ClearPagePrivate(page);
8922 set_page_private(page, 0);
8928 * btrfs_page_mkwrite() is not allowed to change the file size as it gets
8929 * called from a page fault handler when a page is first dirtied. Hence we must
8930 * be careful to check for EOF conditions here. We set the page up correctly
8931 * for a written page which means we get ENOSPC checking when writing into
8932 * holes and correct delalloc and unwritten extent mapping on filesystems that
8933 * support these features.
8935 * We are not allowed to take the i_mutex here so we have to play games to
8936 * protect against truncate races as the page could now be beyond EOF. Because
8937 * truncate_setsize() writes the inode size before removing pages, once we have
8938 * the page lock we can determine safely if the page is beyond EOF. If it is not
8939 * beyond EOF, then the page is guaranteed safe against truncation until we
8942 vm_fault_t btrfs_page_mkwrite(struct vm_fault *vmf)
8944 struct page *page = vmf->page;
8945 struct inode *inode = file_inode(vmf->vma->vm_file);
8946 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
8947 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
8948 struct btrfs_ordered_extent *ordered;
8949 struct extent_state *cached_state = NULL;
8950 struct extent_changeset *data_reserved = NULL;
8952 unsigned long zero_start;
8962 reserved_space = PAGE_SIZE;
8964 sb_start_pagefault(inode->i_sb);
8965 page_start = page_offset(page);
8966 page_end = page_start + PAGE_SIZE - 1;
8970 * Reserving delalloc space after obtaining the page lock can lead to
8971 * deadlock. For example, if a dirty page is locked by this function
8972 * and the call to btrfs_delalloc_reserve_space() ends up triggering
8973 * dirty page write out, then the btrfs_writepage() function could
8974 * end up waiting indefinitely to get a lock on the page currently
8975 * being processed by btrfs_page_mkwrite() function.
8977 ret2 = btrfs_delalloc_reserve_space(inode, &data_reserved, page_start,
8980 ret2 = file_update_time(vmf->vma->vm_file);
8984 ret = vmf_error(ret2);
8990 ret = VM_FAULT_NOPAGE; /* make the VM retry the fault */
8993 size = i_size_read(inode);
8995 if ((page->mapping != inode->i_mapping) ||
8996 (page_start >= size)) {
8997 /* page got truncated out from underneath us */
9000 wait_on_page_writeback(page);
9002 lock_extent_bits(io_tree, page_start, page_end, &cached_state);
9003 set_page_extent_mapped(page);
9006 * we can't set the delalloc bits if there are pending ordered
9007 * extents. Drop our locks and wait for them to finish
9009 ordered = btrfs_lookup_ordered_range(BTRFS_I(inode), page_start,
9012 unlock_extent_cached(io_tree, page_start, page_end,
9015 btrfs_start_ordered_extent(inode, ordered, 1);
9016 btrfs_put_ordered_extent(ordered);
9020 if (page->index == ((size - 1) >> PAGE_SHIFT)) {
9021 reserved_space = round_up(size - page_start,
9022 fs_info->sectorsize);
9023 if (reserved_space < PAGE_SIZE) {
9024 end = page_start + reserved_space - 1;
9025 btrfs_delalloc_release_space(inode, data_reserved,
9026 page_start, PAGE_SIZE - reserved_space,
9032 * page_mkwrite gets called when the page is firstly dirtied after it's
9033 * faulted in, but write(2) could also dirty a page and set delalloc
9034 * bits, thus in this case for space account reason, we still need to
9035 * clear any delalloc bits within this page range since we have to
9036 * reserve data&meta space before lock_page() (see above comments).
9038 clear_extent_bit(&BTRFS_I(inode)->io_tree, page_start, end,
9039 EXTENT_DELALLOC | EXTENT_DO_ACCOUNTING |
9040 EXTENT_DEFRAG, 0, 0, &cached_state);
9042 ret2 = btrfs_set_extent_delalloc(inode, page_start, end, 0,
9045 unlock_extent_cached(io_tree, page_start, page_end,
9047 ret = VM_FAULT_SIGBUS;
9052 /* page is wholly or partially inside EOF */
9053 if (page_start + PAGE_SIZE > size)
9054 zero_start = offset_in_page(size);
9056 zero_start = PAGE_SIZE;
9058 if (zero_start != PAGE_SIZE) {
9060 memset(kaddr + zero_start, 0, PAGE_SIZE - zero_start);
9061 flush_dcache_page(page);
9064 ClearPageChecked(page);
9065 set_page_dirty(page);
9066 SetPageUptodate(page);
9068 BTRFS_I(inode)->last_trans = fs_info->generation;
9069 BTRFS_I(inode)->last_sub_trans = BTRFS_I(inode)->root->log_transid;
9070 BTRFS_I(inode)->last_log_commit = BTRFS_I(inode)->root->last_log_commit;
9072 unlock_extent_cached(io_tree, page_start, page_end, &cached_state);
9075 btrfs_delalloc_release_extents(BTRFS_I(inode), PAGE_SIZE);
9076 sb_end_pagefault(inode->i_sb);
9077 extent_changeset_free(data_reserved);
9078 return VM_FAULT_LOCKED;
9084 btrfs_delalloc_release_extents(BTRFS_I(inode), PAGE_SIZE);
9085 btrfs_delalloc_release_space(inode, data_reserved, page_start,
9086 reserved_space, (ret != 0));
9088 sb_end_pagefault(inode->i_sb);
9089 extent_changeset_free(data_reserved);
9093 static int btrfs_truncate(struct inode *inode, bool skip_writeback)
9095 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
9096 struct btrfs_root *root = BTRFS_I(inode)->root;
9097 struct btrfs_block_rsv *rsv;
9099 struct btrfs_trans_handle *trans;
9100 u64 mask = fs_info->sectorsize - 1;
9101 u64 min_size = btrfs_calc_metadata_size(fs_info, 1);
9103 if (!skip_writeback) {
9104 ret = btrfs_wait_ordered_range(inode, inode->i_size & (~mask),
9111 * Yes ladies and gentlemen, this is indeed ugly. We have a couple of
9112 * things going on here:
9114 * 1) We need to reserve space to update our inode.
9116 * 2) We need to have something to cache all the space that is going to
9117 * be free'd up by the truncate operation, but also have some slack
9118 * space reserved in case it uses space during the truncate (thank you
9119 * very much snapshotting).
9121 * And we need these to be separate. The fact is we can use a lot of
9122 * space doing the truncate, and we have no earthly idea how much space
9123 * we will use, so we need the truncate reservation to be separate so it
9124 * doesn't end up using space reserved for updating the inode. We also
9125 * need to be able to stop the transaction and start a new one, which
9126 * means we need to be able to update the inode several times, and we
9127 * have no idea of knowing how many times that will be, so we can't just
9128 * reserve 1 item for the entirety of the operation, so that has to be
9129 * done separately as well.
9131 * So that leaves us with
9133 * 1) rsv - for the truncate reservation, which we will steal from the
9134 * transaction reservation.
9135 * 2) fs_info->trans_block_rsv - this will have 1 items worth left for
9136 * updating the inode.
9138 rsv = btrfs_alloc_block_rsv(fs_info, BTRFS_BLOCK_RSV_TEMP);
9141 rsv->size = min_size;
9145 * 1 for the truncate slack space
9146 * 1 for updating the inode.
9148 trans = btrfs_start_transaction(root, 2);
9149 if (IS_ERR(trans)) {
9150 ret = PTR_ERR(trans);
9154 /* Migrate the slack space for the truncate to our reserve */
9155 ret = btrfs_block_rsv_migrate(&fs_info->trans_block_rsv, rsv,
9160 * So if we truncate and then write and fsync we normally would just
9161 * write the extents that changed, which is a problem if we need to
9162 * first truncate that entire inode. So set this flag so we write out
9163 * all of the extents in the inode to the sync log so we're completely
9166 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &BTRFS_I(inode)->runtime_flags);
9167 trans->block_rsv = rsv;
9170 ret = btrfs_truncate_inode_items(trans, root, inode,
9172 BTRFS_EXTENT_DATA_KEY);
9173 trans->block_rsv = &fs_info->trans_block_rsv;
9174 if (ret != -ENOSPC && ret != -EAGAIN)
9177 ret = btrfs_update_inode(trans, root, inode);
9181 btrfs_end_transaction(trans);
9182 btrfs_btree_balance_dirty(fs_info);
9184 trans = btrfs_start_transaction(root, 2);
9185 if (IS_ERR(trans)) {
9186 ret = PTR_ERR(trans);
9191 btrfs_block_rsv_release(fs_info, rsv, -1);
9192 ret = btrfs_block_rsv_migrate(&fs_info->trans_block_rsv,
9193 rsv, min_size, false);
9194 BUG_ON(ret); /* shouldn't happen */
9195 trans->block_rsv = rsv;
9199 * We can't call btrfs_truncate_block inside a trans handle as we could
9200 * deadlock with freeze, if we got NEED_TRUNCATE_BLOCK then we know
9201 * we've truncated everything except the last little bit, and can do
9202 * btrfs_truncate_block and then update the disk_i_size.
9204 if (ret == NEED_TRUNCATE_BLOCK) {
9205 btrfs_end_transaction(trans);
9206 btrfs_btree_balance_dirty(fs_info);
9208 ret = btrfs_truncate_block(inode, inode->i_size, 0, 0);
9211 trans = btrfs_start_transaction(root, 1);
9212 if (IS_ERR(trans)) {
9213 ret = PTR_ERR(trans);
9216 btrfs_ordered_update_i_size(inode, inode->i_size, NULL);
9222 trans->block_rsv = &fs_info->trans_block_rsv;
9223 ret2 = btrfs_update_inode(trans, root, inode);
9227 ret2 = btrfs_end_transaction(trans);
9230 btrfs_btree_balance_dirty(fs_info);
9233 btrfs_free_block_rsv(fs_info, rsv);
9239 * create a new subvolume directory/inode (helper for the ioctl).
9241 int btrfs_create_subvol_root(struct btrfs_trans_handle *trans,
9242 struct btrfs_root *new_root,
9243 struct btrfs_root *parent_root,
9246 struct inode *inode;
9250 inode = btrfs_new_inode(trans, new_root, NULL, "..", 2,
9251 new_dirid, new_dirid,
9252 S_IFDIR | (~current_umask() & S_IRWXUGO),
9255 return PTR_ERR(inode);
9256 inode->i_op = &btrfs_dir_inode_operations;
9257 inode->i_fop = &btrfs_dir_file_operations;
9259 set_nlink(inode, 1);
9260 btrfs_i_size_write(BTRFS_I(inode), 0);
9261 unlock_new_inode(inode);
9263 err = btrfs_subvol_inherit_props(trans, new_root, parent_root);
9265 btrfs_err(new_root->fs_info,
9266 "error inheriting subvolume %llu properties: %d",
9267 new_root->root_key.objectid, err);
9269 err = btrfs_update_inode(trans, new_root, inode);
9275 struct inode *btrfs_alloc_inode(struct super_block *sb)
9277 struct btrfs_fs_info *fs_info = btrfs_sb(sb);
9278 struct btrfs_inode *ei;
9279 struct inode *inode;
9281 ei = kmem_cache_alloc(btrfs_inode_cachep, GFP_KERNEL);
9288 ei->last_sub_trans = 0;
9289 ei->logged_trans = 0;
9290 ei->delalloc_bytes = 0;
9291 ei->new_delalloc_bytes = 0;
9292 ei->defrag_bytes = 0;
9293 ei->disk_i_size = 0;
9296 ei->index_cnt = (u64)-1;
9298 ei->last_unlink_trans = 0;
9299 ei->last_log_commit = 0;
9301 spin_lock_init(&ei->lock);
9302 ei->outstanding_extents = 0;
9303 if (sb->s_magic != BTRFS_TEST_MAGIC)
9304 btrfs_init_metadata_block_rsv(fs_info, &ei->block_rsv,
9305 BTRFS_BLOCK_RSV_DELALLOC);
9306 ei->runtime_flags = 0;
9307 ei->prop_compress = BTRFS_COMPRESS_NONE;
9308 ei->defrag_compress = BTRFS_COMPRESS_NONE;
9310 ei->delayed_node = NULL;
9312 ei->i_otime.tv_sec = 0;
9313 ei->i_otime.tv_nsec = 0;
9315 inode = &ei->vfs_inode;
9316 extent_map_tree_init(&ei->extent_tree);
9317 extent_io_tree_init(fs_info, &ei->io_tree, IO_TREE_INODE_IO, inode);
9318 extent_io_tree_init(fs_info, &ei->io_failure_tree,
9319 IO_TREE_INODE_IO_FAILURE, inode);
9320 ei->io_tree.track_uptodate = true;
9321 ei->io_failure_tree.track_uptodate = true;
9322 atomic_set(&ei->sync_writers, 0);
9323 mutex_init(&ei->log_mutex);
9324 mutex_init(&ei->delalloc_mutex);
9325 btrfs_ordered_inode_tree_init(&ei->ordered_tree);
9326 INIT_LIST_HEAD(&ei->delalloc_inodes);
9327 INIT_LIST_HEAD(&ei->delayed_iput);
9328 RB_CLEAR_NODE(&ei->rb_node);
9329 init_rwsem(&ei->dio_sem);
9334 #ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
9335 void btrfs_test_destroy_inode(struct inode *inode)
9337 btrfs_drop_extent_cache(BTRFS_I(inode), 0, (u64)-1, 0);
9338 kmem_cache_free(btrfs_inode_cachep, BTRFS_I(inode));
9342 void btrfs_free_inode(struct inode *inode)
9344 kmem_cache_free(btrfs_inode_cachep, BTRFS_I(inode));
9347 void btrfs_destroy_inode(struct inode *inode)
9349 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
9350 struct btrfs_ordered_extent *ordered;
9351 struct btrfs_root *root = BTRFS_I(inode)->root;
9353 WARN_ON(!hlist_empty(&inode->i_dentry));
9354 WARN_ON(inode->i_data.nrpages);
9355 WARN_ON(BTRFS_I(inode)->block_rsv.reserved);
9356 WARN_ON(BTRFS_I(inode)->block_rsv.size);
9357 WARN_ON(BTRFS_I(inode)->outstanding_extents);
9358 WARN_ON(BTRFS_I(inode)->delalloc_bytes);
9359 WARN_ON(BTRFS_I(inode)->new_delalloc_bytes);
9360 WARN_ON(BTRFS_I(inode)->csum_bytes);
9361 WARN_ON(BTRFS_I(inode)->defrag_bytes);
9364 * This can happen where we create an inode, but somebody else also
9365 * created the same inode and we need to destroy the one we already
9372 ordered = btrfs_lookup_first_ordered_extent(inode, (u64)-1);
9377 "found ordered extent %llu %llu on inode cleanup",
9378 ordered->file_offset, ordered->len);
9379 btrfs_remove_ordered_extent(inode, ordered);
9380 btrfs_put_ordered_extent(ordered);
9381 btrfs_put_ordered_extent(ordered);
9384 btrfs_qgroup_check_reserved_leak(inode);
9385 inode_tree_del(inode);
9386 btrfs_drop_extent_cache(BTRFS_I(inode), 0, (u64)-1, 0);
9389 int btrfs_drop_inode(struct inode *inode)
9391 struct btrfs_root *root = BTRFS_I(inode)->root;
9396 /* the snap/subvol tree is on deleting */
9397 if (btrfs_root_refs(&root->root_item) == 0)
9400 return generic_drop_inode(inode);
9403 static void init_once(void *foo)
9405 struct btrfs_inode *ei = (struct btrfs_inode *) foo;
9407 inode_init_once(&ei->vfs_inode);
9410 void __cold btrfs_destroy_cachep(void)
9413 * Make sure all delayed rcu free inodes are flushed before we
9417 kmem_cache_destroy(btrfs_inode_cachep);
9418 kmem_cache_destroy(btrfs_trans_handle_cachep);
9419 kmem_cache_destroy(btrfs_path_cachep);
9420 kmem_cache_destroy(btrfs_free_space_cachep);
9421 kmem_cache_destroy(btrfs_free_space_bitmap_cachep);
9424 int __init btrfs_init_cachep(void)
9426 btrfs_inode_cachep = kmem_cache_create("btrfs_inode",
9427 sizeof(struct btrfs_inode), 0,
9428 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD | SLAB_ACCOUNT,
9430 if (!btrfs_inode_cachep)
9433 btrfs_trans_handle_cachep = kmem_cache_create("btrfs_trans_handle",
9434 sizeof(struct btrfs_trans_handle), 0,
9435 SLAB_TEMPORARY | SLAB_MEM_SPREAD, NULL);
9436 if (!btrfs_trans_handle_cachep)
9439 btrfs_path_cachep = kmem_cache_create("btrfs_path",
9440 sizeof(struct btrfs_path), 0,
9441 SLAB_MEM_SPREAD, NULL);
9442 if (!btrfs_path_cachep)
9445 btrfs_free_space_cachep = kmem_cache_create("btrfs_free_space",
9446 sizeof(struct btrfs_free_space), 0,
9447 SLAB_MEM_SPREAD, NULL);
9448 if (!btrfs_free_space_cachep)
9451 btrfs_free_space_bitmap_cachep = kmem_cache_create("btrfs_free_space_bitmap",
9452 PAGE_SIZE, PAGE_SIZE,
9453 SLAB_RED_ZONE, NULL);
9454 if (!btrfs_free_space_bitmap_cachep)
9459 btrfs_destroy_cachep();
9463 static int btrfs_getattr(const struct path *path, struct kstat *stat,
9464 u32 request_mask, unsigned int flags)
9467 struct inode *inode = d_inode(path->dentry);
9468 u32 blocksize = inode->i_sb->s_blocksize;
9469 u32 bi_flags = BTRFS_I(inode)->flags;
9471 stat->result_mask |= STATX_BTIME;
9472 stat->btime.tv_sec = BTRFS_I(inode)->i_otime.tv_sec;
9473 stat->btime.tv_nsec = BTRFS_I(inode)->i_otime.tv_nsec;
9474 if (bi_flags & BTRFS_INODE_APPEND)
9475 stat->attributes |= STATX_ATTR_APPEND;
9476 if (bi_flags & BTRFS_INODE_COMPRESS)
9477 stat->attributes |= STATX_ATTR_COMPRESSED;
9478 if (bi_flags & BTRFS_INODE_IMMUTABLE)
9479 stat->attributes |= STATX_ATTR_IMMUTABLE;
9480 if (bi_flags & BTRFS_INODE_NODUMP)
9481 stat->attributes |= STATX_ATTR_NODUMP;
9483 stat->attributes_mask |= (STATX_ATTR_APPEND |
9484 STATX_ATTR_COMPRESSED |
9485 STATX_ATTR_IMMUTABLE |
9488 generic_fillattr(inode, stat);
9489 stat->dev = BTRFS_I(inode)->root->anon_dev;
9491 spin_lock(&BTRFS_I(inode)->lock);
9492 delalloc_bytes = BTRFS_I(inode)->new_delalloc_bytes;
9493 spin_unlock(&BTRFS_I(inode)->lock);
9494 stat->blocks = (ALIGN(inode_get_bytes(inode), blocksize) +
9495 ALIGN(delalloc_bytes, blocksize)) >> 9;
9499 static int btrfs_rename_exchange(struct inode *old_dir,
9500 struct dentry *old_dentry,
9501 struct inode *new_dir,
9502 struct dentry *new_dentry)
9504 struct btrfs_fs_info *fs_info = btrfs_sb(old_dir->i_sb);
9505 struct btrfs_trans_handle *trans;
9506 struct btrfs_root *root = BTRFS_I(old_dir)->root;
9507 struct btrfs_root *dest = BTRFS_I(new_dir)->root;
9508 struct inode *new_inode = new_dentry->d_inode;
9509 struct inode *old_inode = old_dentry->d_inode;
9510 struct timespec64 ctime = current_time(old_inode);
9511 struct dentry *parent;
9512 u64 old_ino = btrfs_ino(BTRFS_I(old_inode));
9513 u64 new_ino = btrfs_ino(BTRFS_I(new_inode));
9518 bool root_log_pinned = false;
9519 bool dest_log_pinned = false;
9520 struct btrfs_log_ctx ctx_root;
9521 struct btrfs_log_ctx ctx_dest;
9522 bool sync_log_root = false;
9523 bool sync_log_dest = false;
9524 bool commit_transaction = false;
9526 /* we only allow rename subvolume link between subvolumes */
9527 if (old_ino != BTRFS_FIRST_FREE_OBJECTID && root != dest)
9530 btrfs_init_log_ctx(&ctx_root, old_inode);
9531 btrfs_init_log_ctx(&ctx_dest, new_inode);
9533 /* close the race window with snapshot create/destroy ioctl */
9534 if (old_ino == BTRFS_FIRST_FREE_OBJECTID)
9535 down_read(&fs_info->subvol_sem);
9536 if (new_ino == BTRFS_FIRST_FREE_OBJECTID)
9537 down_read(&fs_info->subvol_sem);
9540 * We want to reserve the absolute worst case amount of items. So if
9541 * both inodes are subvols and we need to unlink them then that would
9542 * require 4 item modifications, but if they are both normal inodes it
9543 * would require 5 item modifications, so we'll assume their normal
9544 * inodes. So 5 * 2 is 10, plus 2 for the new links, so 12 total items
9545 * should cover the worst case number of items we'll modify.
9547 trans = btrfs_start_transaction(root, 12);
9548 if (IS_ERR(trans)) {
9549 ret = PTR_ERR(trans);
9554 * We need to find a free sequence number both in the source and
9555 * in the destination directory for the exchange.
9557 ret = btrfs_set_inode_index(BTRFS_I(new_dir), &old_idx);
9560 ret = btrfs_set_inode_index(BTRFS_I(old_dir), &new_idx);
9564 BTRFS_I(old_inode)->dir_index = 0ULL;
9565 BTRFS_I(new_inode)->dir_index = 0ULL;
9567 /* Reference for the source. */
9568 if (old_ino == BTRFS_FIRST_FREE_OBJECTID) {
9569 /* force full log commit if subvolume involved. */
9570 btrfs_set_log_full_commit(trans);
9572 btrfs_pin_log_trans(root);
9573 root_log_pinned = true;
9574 ret = btrfs_insert_inode_ref(trans, dest,
9575 new_dentry->d_name.name,
9576 new_dentry->d_name.len,
9578 btrfs_ino(BTRFS_I(new_dir)),
9584 /* And now for the dest. */
9585 if (new_ino == BTRFS_FIRST_FREE_OBJECTID) {
9586 /* force full log commit if subvolume involved. */
9587 btrfs_set_log_full_commit(trans);
9589 btrfs_pin_log_trans(dest);
9590 dest_log_pinned = true;
9591 ret = btrfs_insert_inode_ref(trans, root,
9592 old_dentry->d_name.name,
9593 old_dentry->d_name.len,
9595 btrfs_ino(BTRFS_I(old_dir)),
9601 /* Update inode version and ctime/mtime. */
9602 inode_inc_iversion(old_dir);
9603 inode_inc_iversion(new_dir);
9604 inode_inc_iversion(old_inode);
9605 inode_inc_iversion(new_inode);
9606 old_dir->i_ctime = old_dir->i_mtime = ctime;
9607 new_dir->i_ctime = new_dir->i_mtime = ctime;
9608 old_inode->i_ctime = ctime;
9609 new_inode->i_ctime = ctime;
9611 if (old_dentry->d_parent != new_dentry->d_parent) {
9612 btrfs_record_unlink_dir(trans, BTRFS_I(old_dir),
9613 BTRFS_I(old_inode), 1);
9614 btrfs_record_unlink_dir(trans, BTRFS_I(new_dir),
9615 BTRFS_I(new_inode), 1);
9618 /* src is a subvolume */
9619 if (old_ino == BTRFS_FIRST_FREE_OBJECTID) {
9620 root_objectid = BTRFS_I(old_inode)->root->root_key.objectid;
9621 ret = btrfs_unlink_subvol(trans, old_dir, root_objectid,
9622 old_dentry->d_name.name,
9623 old_dentry->d_name.len);
9624 } else { /* src is an inode */
9625 ret = __btrfs_unlink_inode(trans, root, BTRFS_I(old_dir),
9626 BTRFS_I(old_dentry->d_inode),
9627 old_dentry->d_name.name,
9628 old_dentry->d_name.len);
9630 ret = btrfs_update_inode(trans, root, old_inode);
9633 btrfs_abort_transaction(trans, ret);
9637 /* dest is a subvolume */
9638 if (new_ino == BTRFS_FIRST_FREE_OBJECTID) {
9639 root_objectid = BTRFS_I(new_inode)->root->root_key.objectid;
9640 ret = btrfs_unlink_subvol(trans, new_dir, root_objectid,
9641 new_dentry->d_name.name,
9642 new_dentry->d_name.len);
9643 } else { /* dest is an inode */
9644 ret = __btrfs_unlink_inode(trans, dest, BTRFS_I(new_dir),
9645 BTRFS_I(new_dentry->d_inode),
9646 new_dentry->d_name.name,
9647 new_dentry->d_name.len);
9649 ret = btrfs_update_inode(trans, dest, new_inode);
9652 btrfs_abort_transaction(trans, ret);
9656 ret = btrfs_add_link(trans, BTRFS_I(new_dir), BTRFS_I(old_inode),
9657 new_dentry->d_name.name,
9658 new_dentry->d_name.len, 0, old_idx);
9660 btrfs_abort_transaction(trans, ret);
9664 ret = btrfs_add_link(trans, BTRFS_I(old_dir), BTRFS_I(new_inode),
9665 old_dentry->d_name.name,
9666 old_dentry->d_name.len, 0, new_idx);
9668 btrfs_abort_transaction(trans, ret);
9672 if (old_inode->i_nlink == 1)
9673 BTRFS_I(old_inode)->dir_index = old_idx;
9674 if (new_inode->i_nlink == 1)
9675 BTRFS_I(new_inode)->dir_index = new_idx;
9677 if (root_log_pinned) {
9678 parent = new_dentry->d_parent;
9679 ret = btrfs_log_new_name(trans, BTRFS_I(old_inode),
9680 BTRFS_I(old_dir), parent,
9682 if (ret == BTRFS_NEED_LOG_SYNC)
9683 sync_log_root = true;
9684 else if (ret == BTRFS_NEED_TRANS_COMMIT)
9685 commit_transaction = true;
9687 btrfs_end_log_trans(root);
9688 root_log_pinned = false;
9690 if (dest_log_pinned) {
9691 if (!commit_transaction) {
9692 parent = old_dentry->d_parent;
9693 ret = btrfs_log_new_name(trans, BTRFS_I(new_inode),
9694 BTRFS_I(new_dir), parent,
9696 if (ret == BTRFS_NEED_LOG_SYNC)
9697 sync_log_dest = true;
9698 else if (ret == BTRFS_NEED_TRANS_COMMIT)
9699 commit_transaction = true;
9702 btrfs_end_log_trans(dest);
9703 dest_log_pinned = false;
9707 * If we have pinned a log and an error happened, we unpin tasks
9708 * trying to sync the log and force them to fallback to a transaction
9709 * commit if the log currently contains any of the inodes involved in
9710 * this rename operation (to ensure we do not persist a log with an
9711 * inconsistent state for any of these inodes or leading to any
9712 * inconsistencies when replayed). If the transaction was aborted, the
9713 * abortion reason is propagated to userspace when attempting to commit
9714 * the transaction. If the log does not contain any of these inodes, we
9715 * allow the tasks to sync it.
9717 if (ret && (root_log_pinned || dest_log_pinned)) {
9718 if (btrfs_inode_in_log(BTRFS_I(old_dir), fs_info->generation) ||
9719 btrfs_inode_in_log(BTRFS_I(new_dir), fs_info->generation) ||
9720 btrfs_inode_in_log(BTRFS_I(old_inode), fs_info->generation) ||
9722 btrfs_inode_in_log(BTRFS_I(new_inode), fs_info->generation)))
9723 btrfs_set_log_full_commit(trans);
9725 if (root_log_pinned) {
9726 btrfs_end_log_trans(root);
9727 root_log_pinned = false;
9729 if (dest_log_pinned) {
9730 btrfs_end_log_trans(dest);
9731 dest_log_pinned = false;
9734 if (!ret && sync_log_root && !commit_transaction) {
9735 ret = btrfs_sync_log(trans, BTRFS_I(old_inode)->root,
9738 commit_transaction = true;
9740 if (!ret && sync_log_dest && !commit_transaction) {
9741 ret = btrfs_sync_log(trans, BTRFS_I(new_inode)->root,
9744 commit_transaction = true;
9746 if (commit_transaction) {
9747 ret = btrfs_commit_transaction(trans);
9751 ret2 = btrfs_end_transaction(trans);
9752 ret = ret ? ret : ret2;
9755 if (new_ino == BTRFS_FIRST_FREE_OBJECTID)
9756 up_read(&fs_info->subvol_sem);
9757 if (old_ino == BTRFS_FIRST_FREE_OBJECTID)
9758 up_read(&fs_info->subvol_sem);
9763 static int btrfs_whiteout_for_rename(struct btrfs_trans_handle *trans,
9764 struct btrfs_root *root,
9766 struct dentry *dentry)
9769 struct inode *inode;
9773 ret = btrfs_find_free_ino(root, &objectid);
9777 inode = btrfs_new_inode(trans, root, dir,
9778 dentry->d_name.name,
9780 btrfs_ino(BTRFS_I(dir)),
9782 S_IFCHR | WHITEOUT_MODE,
9785 if (IS_ERR(inode)) {
9786 ret = PTR_ERR(inode);
9790 inode->i_op = &btrfs_special_inode_operations;
9791 init_special_inode(inode, inode->i_mode,
9794 ret = btrfs_init_inode_security(trans, inode, dir,
9799 ret = btrfs_add_nondir(trans, BTRFS_I(dir), dentry,
9800 BTRFS_I(inode), 0, index);
9804 ret = btrfs_update_inode(trans, root, inode);
9806 unlock_new_inode(inode);
9808 inode_dec_link_count(inode);
9814 static int btrfs_rename(struct inode *old_dir, struct dentry *old_dentry,
9815 struct inode *new_dir, struct dentry *new_dentry,
9818 struct btrfs_fs_info *fs_info = btrfs_sb(old_dir->i_sb);
9819 struct btrfs_trans_handle *trans;
9820 unsigned int trans_num_items;
9821 struct btrfs_root *root = BTRFS_I(old_dir)->root;
9822 struct btrfs_root *dest = BTRFS_I(new_dir)->root;
9823 struct inode *new_inode = d_inode(new_dentry);
9824 struct inode *old_inode = d_inode(old_dentry);
9828 u64 old_ino = btrfs_ino(BTRFS_I(old_inode));
9829 bool log_pinned = false;
9830 struct btrfs_log_ctx ctx;
9831 bool sync_log = false;
9832 bool commit_transaction = false;
9834 if (btrfs_ino(BTRFS_I(new_dir)) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)
9837 /* we only allow rename subvolume link between subvolumes */
9838 if (old_ino != BTRFS_FIRST_FREE_OBJECTID && root != dest)
9841 if (old_ino == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID ||
9842 (new_inode && btrfs_ino(BTRFS_I(new_inode)) == BTRFS_FIRST_FREE_OBJECTID))
9845 if (S_ISDIR(old_inode->i_mode) && new_inode &&
9846 new_inode->i_size > BTRFS_EMPTY_DIR_SIZE)
9850 /* check for collisions, even if the name isn't there */
9851 ret = btrfs_check_dir_item_collision(dest, new_dir->i_ino,
9852 new_dentry->d_name.name,
9853 new_dentry->d_name.len);
9856 if (ret == -EEXIST) {
9858 * eexist without a new_inode */
9859 if (WARN_ON(!new_inode)) {
9863 /* maybe -EOVERFLOW */
9870 * we're using rename to replace one file with another. Start IO on it
9871 * now so we don't add too much work to the end of the transaction
9873 if (new_inode && S_ISREG(old_inode->i_mode) && new_inode->i_size)
9874 filemap_flush(old_inode->i_mapping);
9876 /* close the racy window with snapshot create/destroy ioctl */
9877 if (old_ino == BTRFS_FIRST_FREE_OBJECTID)
9878 down_read(&fs_info->subvol_sem);
9880 * We want to reserve the absolute worst case amount of items. So if
9881 * both inodes are subvols and we need to unlink them then that would
9882 * require 4 item modifications, but if they are both normal inodes it
9883 * would require 5 item modifications, so we'll assume they are normal
9884 * inodes. So 5 * 2 is 10, plus 1 for the new link, so 11 total items
9885 * should cover the worst case number of items we'll modify.
9886 * If our rename has the whiteout flag, we need more 5 units for the
9887 * new inode (1 inode item, 1 inode ref, 2 dir items and 1 xattr item
9888 * when selinux is enabled).
9890 trans_num_items = 11;
9891 if (flags & RENAME_WHITEOUT)
9892 trans_num_items += 5;
9893 trans = btrfs_start_transaction(root, trans_num_items);
9894 if (IS_ERR(trans)) {
9895 ret = PTR_ERR(trans);
9900 btrfs_record_root_in_trans(trans, dest);
9902 ret = btrfs_set_inode_index(BTRFS_I(new_dir), &index);
9906 BTRFS_I(old_inode)->dir_index = 0ULL;
9907 if (unlikely(old_ino == BTRFS_FIRST_FREE_OBJECTID)) {
9908 /* force full log commit if subvolume involved. */
9909 btrfs_set_log_full_commit(trans);
9911 btrfs_pin_log_trans(root);
9913 ret = btrfs_insert_inode_ref(trans, dest,
9914 new_dentry->d_name.name,
9915 new_dentry->d_name.len,
9917 btrfs_ino(BTRFS_I(new_dir)), index);
9922 inode_inc_iversion(old_dir);
9923 inode_inc_iversion(new_dir);
9924 inode_inc_iversion(old_inode);
9925 old_dir->i_ctime = old_dir->i_mtime =
9926 new_dir->i_ctime = new_dir->i_mtime =
9927 old_inode->i_ctime = current_time(old_dir);
9929 if (old_dentry->d_parent != new_dentry->d_parent)
9930 btrfs_record_unlink_dir(trans, BTRFS_I(old_dir),
9931 BTRFS_I(old_inode), 1);
9933 if (unlikely(old_ino == BTRFS_FIRST_FREE_OBJECTID)) {
9934 root_objectid = BTRFS_I(old_inode)->root->root_key.objectid;
9935 ret = btrfs_unlink_subvol(trans, old_dir, root_objectid,
9936 old_dentry->d_name.name,
9937 old_dentry->d_name.len);
9939 ret = __btrfs_unlink_inode(trans, root, BTRFS_I(old_dir),
9940 BTRFS_I(d_inode(old_dentry)),
9941 old_dentry->d_name.name,
9942 old_dentry->d_name.len);
9944 ret = btrfs_update_inode(trans, root, old_inode);
9947 btrfs_abort_transaction(trans, ret);
9952 inode_inc_iversion(new_inode);
9953 new_inode->i_ctime = current_time(new_inode);
9954 if (unlikely(btrfs_ino(BTRFS_I(new_inode)) ==
9955 BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)) {
9956 root_objectid = BTRFS_I(new_inode)->location.objectid;
9957 ret = btrfs_unlink_subvol(trans, new_dir, root_objectid,
9958 new_dentry->d_name.name,
9959 new_dentry->d_name.len);
9960 BUG_ON(new_inode->i_nlink == 0);
9962 ret = btrfs_unlink_inode(trans, dest, BTRFS_I(new_dir),
9963 BTRFS_I(d_inode(new_dentry)),
9964 new_dentry->d_name.name,
9965 new_dentry->d_name.len);
9967 if (!ret && new_inode->i_nlink == 0)
9968 ret = btrfs_orphan_add(trans,
9969 BTRFS_I(d_inode(new_dentry)));
9971 btrfs_abort_transaction(trans, ret);
9976 ret = btrfs_add_link(trans, BTRFS_I(new_dir), BTRFS_I(old_inode),
9977 new_dentry->d_name.name,
9978 new_dentry->d_name.len, 0, index);
9980 btrfs_abort_transaction(trans, ret);
9984 if (old_inode->i_nlink == 1)
9985 BTRFS_I(old_inode)->dir_index = index;
9988 struct dentry *parent = new_dentry->d_parent;
9990 btrfs_init_log_ctx(&ctx, old_inode);
9991 ret = btrfs_log_new_name(trans, BTRFS_I(old_inode),
9992 BTRFS_I(old_dir), parent,
9994 if (ret == BTRFS_NEED_LOG_SYNC)
9996 else if (ret == BTRFS_NEED_TRANS_COMMIT)
9997 commit_transaction = true;
9999 btrfs_end_log_trans(root);
10000 log_pinned = false;
10003 if (flags & RENAME_WHITEOUT) {
10004 ret = btrfs_whiteout_for_rename(trans, root, old_dir,
10008 btrfs_abort_transaction(trans, ret);
10014 * If we have pinned the log and an error happened, we unpin tasks
10015 * trying to sync the log and force them to fallback to a transaction
10016 * commit if the log currently contains any of the inodes involved in
10017 * this rename operation (to ensure we do not persist a log with an
10018 * inconsistent state for any of these inodes or leading to any
10019 * inconsistencies when replayed). If the transaction was aborted, the
10020 * abortion reason is propagated to userspace when attempting to commit
10021 * the transaction. If the log does not contain any of these inodes, we
10022 * allow the tasks to sync it.
10024 if (ret && log_pinned) {
10025 if (btrfs_inode_in_log(BTRFS_I(old_dir), fs_info->generation) ||
10026 btrfs_inode_in_log(BTRFS_I(new_dir), fs_info->generation) ||
10027 btrfs_inode_in_log(BTRFS_I(old_inode), fs_info->generation) ||
10029 btrfs_inode_in_log(BTRFS_I(new_inode), fs_info->generation)))
10030 btrfs_set_log_full_commit(trans);
10032 btrfs_end_log_trans(root);
10033 log_pinned = false;
10035 if (!ret && sync_log) {
10036 ret = btrfs_sync_log(trans, BTRFS_I(old_inode)->root, &ctx);
10038 commit_transaction = true;
10040 if (commit_transaction) {
10041 ret = btrfs_commit_transaction(trans);
10045 ret2 = btrfs_end_transaction(trans);
10046 ret = ret ? ret : ret2;
10049 if (old_ino == BTRFS_FIRST_FREE_OBJECTID)
10050 up_read(&fs_info->subvol_sem);
10055 static int btrfs_rename2(struct inode *old_dir, struct dentry *old_dentry,
10056 struct inode *new_dir, struct dentry *new_dentry,
10057 unsigned int flags)
10059 if (flags & ~(RENAME_NOREPLACE | RENAME_EXCHANGE | RENAME_WHITEOUT))
10062 if (flags & RENAME_EXCHANGE)
10063 return btrfs_rename_exchange(old_dir, old_dentry, new_dir,
10066 return btrfs_rename(old_dir, old_dentry, new_dir, new_dentry, flags);
10069 struct btrfs_delalloc_work {
10070 struct inode *inode;
10071 struct completion completion;
10072 struct list_head list;
10073 struct btrfs_work work;
10076 static void btrfs_run_delalloc_work(struct btrfs_work *work)
10078 struct btrfs_delalloc_work *delalloc_work;
10079 struct inode *inode;
10081 delalloc_work = container_of(work, struct btrfs_delalloc_work,
10083 inode = delalloc_work->inode;
10084 filemap_flush(inode->i_mapping);
10085 if (test_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
10086 &BTRFS_I(inode)->runtime_flags))
10087 filemap_flush(inode->i_mapping);
10090 complete(&delalloc_work->completion);
10093 static struct btrfs_delalloc_work *btrfs_alloc_delalloc_work(struct inode *inode)
10095 struct btrfs_delalloc_work *work;
10097 work = kmalloc(sizeof(*work), GFP_NOFS);
10101 init_completion(&work->completion);
10102 INIT_LIST_HEAD(&work->list);
10103 work->inode = inode;
10104 btrfs_init_work(&work->work, btrfs_flush_delalloc_helper,
10105 btrfs_run_delalloc_work, NULL, NULL);
10111 * some fairly slow code that needs optimization. This walks the list
10112 * of all the inodes with pending delalloc and forces them to disk.
10114 static int start_delalloc_inodes(struct btrfs_root *root, int nr, bool snapshot)
10116 struct btrfs_inode *binode;
10117 struct inode *inode;
10118 struct btrfs_delalloc_work *work, *next;
10119 struct list_head works;
10120 struct list_head splice;
10123 INIT_LIST_HEAD(&works);
10124 INIT_LIST_HEAD(&splice);
10126 mutex_lock(&root->delalloc_mutex);
10127 spin_lock(&root->delalloc_lock);
10128 list_splice_init(&root->delalloc_inodes, &splice);
10129 while (!list_empty(&splice)) {
10130 binode = list_entry(splice.next, struct btrfs_inode,
10133 list_move_tail(&binode->delalloc_inodes,
10134 &root->delalloc_inodes);
10135 inode = igrab(&binode->vfs_inode);
10137 cond_resched_lock(&root->delalloc_lock);
10140 spin_unlock(&root->delalloc_lock);
10143 set_bit(BTRFS_INODE_SNAPSHOT_FLUSH,
10144 &binode->runtime_flags);
10145 work = btrfs_alloc_delalloc_work(inode);
10151 list_add_tail(&work->list, &works);
10152 btrfs_queue_work(root->fs_info->flush_workers,
10155 if (nr != -1 && ret >= nr)
10158 spin_lock(&root->delalloc_lock);
10160 spin_unlock(&root->delalloc_lock);
10163 list_for_each_entry_safe(work, next, &works, list) {
10164 list_del_init(&work->list);
10165 wait_for_completion(&work->completion);
10169 if (!list_empty(&splice)) {
10170 spin_lock(&root->delalloc_lock);
10171 list_splice_tail(&splice, &root->delalloc_inodes);
10172 spin_unlock(&root->delalloc_lock);
10174 mutex_unlock(&root->delalloc_mutex);
10178 int btrfs_start_delalloc_snapshot(struct btrfs_root *root)
10180 struct btrfs_fs_info *fs_info = root->fs_info;
10183 if (test_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state))
10186 ret = start_delalloc_inodes(root, -1, true);
10192 int btrfs_start_delalloc_roots(struct btrfs_fs_info *fs_info, int nr)
10194 struct btrfs_root *root;
10195 struct list_head splice;
10198 if (test_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state))
10201 INIT_LIST_HEAD(&splice);
10203 mutex_lock(&fs_info->delalloc_root_mutex);
10204 spin_lock(&fs_info->delalloc_root_lock);
10205 list_splice_init(&fs_info->delalloc_roots, &splice);
10206 while (!list_empty(&splice) && nr) {
10207 root = list_first_entry(&splice, struct btrfs_root,
10209 root = btrfs_grab_fs_root(root);
10211 list_move_tail(&root->delalloc_root,
10212 &fs_info->delalloc_roots);
10213 spin_unlock(&fs_info->delalloc_root_lock);
10215 ret = start_delalloc_inodes(root, nr, false);
10216 btrfs_put_fs_root(root);
10224 spin_lock(&fs_info->delalloc_root_lock);
10226 spin_unlock(&fs_info->delalloc_root_lock);
10230 if (!list_empty(&splice)) {
10231 spin_lock(&fs_info->delalloc_root_lock);
10232 list_splice_tail(&splice, &fs_info->delalloc_roots);
10233 spin_unlock(&fs_info->delalloc_root_lock);
10235 mutex_unlock(&fs_info->delalloc_root_mutex);
10239 static int btrfs_symlink(struct inode *dir, struct dentry *dentry,
10240 const char *symname)
10242 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
10243 struct btrfs_trans_handle *trans;
10244 struct btrfs_root *root = BTRFS_I(dir)->root;
10245 struct btrfs_path *path;
10246 struct btrfs_key key;
10247 struct inode *inode = NULL;
10254 struct btrfs_file_extent_item *ei;
10255 struct extent_buffer *leaf;
10257 name_len = strlen(symname);
10258 if (name_len > BTRFS_MAX_INLINE_DATA_SIZE(fs_info))
10259 return -ENAMETOOLONG;
10262 * 2 items for inode item and ref
10263 * 2 items for dir items
10264 * 1 item for updating parent inode item
10265 * 1 item for the inline extent item
10266 * 1 item for xattr if selinux is on
10268 trans = btrfs_start_transaction(root, 7);
10270 return PTR_ERR(trans);
10272 err = btrfs_find_free_ino(root, &objectid);
10276 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
10277 dentry->d_name.len, btrfs_ino(BTRFS_I(dir)),
10278 objectid, S_IFLNK|S_IRWXUGO, &index);
10279 if (IS_ERR(inode)) {
10280 err = PTR_ERR(inode);
10286 * If the active LSM wants to access the inode during
10287 * d_instantiate it needs these. Smack checks to see
10288 * if the filesystem supports xattrs by looking at the
10291 inode->i_fop = &btrfs_file_operations;
10292 inode->i_op = &btrfs_file_inode_operations;
10293 inode->i_mapping->a_ops = &btrfs_aops;
10294 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
10296 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
10300 path = btrfs_alloc_path();
10305 key.objectid = btrfs_ino(BTRFS_I(inode));
10307 key.type = BTRFS_EXTENT_DATA_KEY;
10308 datasize = btrfs_file_extent_calc_inline_size(name_len);
10309 err = btrfs_insert_empty_item(trans, root, path, &key,
10312 btrfs_free_path(path);
10315 leaf = path->nodes[0];
10316 ei = btrfs_item_ptr(leaf, path->slots[0],
10317 struct btrfs_file_extent_item);
10318 btrfs_set_file_extent_generation(leaf, ei, trans->transid);
10319 btrfs_set_file_extent_type(leaf, ei,
10320 BTRFS_FILE_EXTENT_INLINE);
10321 btrfs_set_file_extent_encryption(leaf, ei, 0);
10322 btrfs_set_file_extent_compression(leaf, ei, 0);
10323 btrfs_set_file_extent_other_encoding(leaf, ei, 0);
10324 btrfs_set_file_extent_ram_bytes(leaf, ei, name_len);
10326 ptr = btrfs_file_extent_inline_start(ei);
10327 write_extent_buffer(leaf, symname, ptr, name_len);
10328 btrfs_mark_buffer_dirty(leaf);
10329 btrfs_free_path(path);
10331 inode->i_op = &btrfs_symlink_inode_operations;
10332 inode_nohighmem(inode);
10333 inode_set_bytes(inode, name_len);
10334 btrfs_i_size_write(BTRFS_I(inode), name_len);
10335 err = btrfs_update_inode(trans, root, inode);
10337 * Last step, add directory indexes for our symlink inode. This is the
10338 * last step to avoid extra cleanup of these indexes if an error happens
10342 err = btrfs_add_nondir(trans, BTRFS_I(dir), dentry,
10343 BTRFS_I(inode), 0, index);
10347 d_instantiate_new(dentry, inode);
10350 btrfs_end_transaction(trans);
10351 if (err && inode) {
10352 inode_dec_link_count(inode);
10353 discard_new_inode(inode);
10355 btrfs_btree_balance_dirty(fs_info);
10359 static int __btrfs_prealloc_file_range(struct inode *inode, int mode,
10360 u64 start, u64 num_bytes, u64 min_size,
10361 loff_t actual_len, u64 *alloc_hint,
10362 struct btrfs_trans_handle *trans)
10364 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
10365 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
10366 struct extent_map *em;
10367 struct btrfs_root *root = BTRFS_I(inode)->root;
10368 struct btrfs_key ins;
10369 u64 cur_offset = start;
10372 u64 last_alloc = (u64)-1;
10374 bool own_trans = true;
10375 u64 end = start + num_bytes - 1;
10379 while (num_bytes > 0) {
10381 trans = btrfs_start_transaction(root, 3);
10382 if (IS_ERR(trans)) {
10383 ret = PTR_ERR(trans);
10388 cur_bytes = min_t(u64, num_bytes, SZ_256M);
10389 cur_bytes = max(cur_bytes, min_size);
10391 * If we are severely fragmented we could end up with really
10392 * small allocations, so if the allocator is returning small
10393 * chunks lets make its job easier by only searching for those
10396 cur_bytes = min(cur_bytes, last_alloc);
10397 ret = btrfs_reserve_extent(root, cur_bytes, cur_bytes,
10398 min_size, 0, *alloc_hint, &ins, 1, 0);
10401 btrfs_end_transaction(trans);
10404 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
10406 last_alloc = ins.offset;
10407 ret = insert_reserved_file_extent(trans, inode,
10408 cur_offset, ins.objectid,
10409 ins.offset, ins.offset,
10410 ins.offset, 0, 0, 0,
10411 BTRFS_FILE_EXTENT_PREALLOC);
10413 btrfs_free_reserved_extent(fs_info, ins.objectid,
10415 btrfs_abort_transaction(trans, ret);
10417 btrfs_end_transaction(trans);
10421 btrfs_drop_extent_cache(BTRFS_I(inode), cur_offset,
10422 cur_offset + ins.offset -1, 0);
10424 em = alloc_extent_map();
10426 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
10427 &BTRFS_I(inode)->runtime_flags);
10431 em->start = cur_offset;
10432 em->orig_start = cur_offset;
10433 em->len = ins.offset;
10434 em->block_start = ins.objectid;
10435 em->block_len = ins.offset;
10436 em->orig_block_len = ins.offset;
10437 em->ram_bytes = ins.offset;
10438 em->bdev = fs_info->fs_devices->latest_bdev;
10439 set_bit(EXTENT_FLAG_PREALLOC, &em->flags);
10440 em->generation = trans->transid;
10443 write_lock(&em_tree->lock);
10444 ret = add_extent_mapping(em_tree, em, 1);
10445 write_unlock(&em_tree->lock);
10446 if (ret != -EEXIST)
10448 btrfs_drop_extent_cache(BTRFS_I(inode), cur_offset,
10449 cur_offset + ins.offset - 1,
10452 free_extent_map(em);
10454 num_bytes -= ins.offset;
10455 cur_offset += ins.offset;
10456 *alloc_hint = ins.objectid + ins.offset;
10458 inode_inc_iversion(inode);
10459 inode->i_ctime = current_time(inode);
10460 BTRFS_I(inode)->flags |= BTRFS_INODE_PREALLOC;
10461 if (!(mode & FALLOC_FL_KEEP_SIZE) &&
10462 (actual_len > inode->i_size) &&
10463 (cur_offset > inode->i_size)) {
10464 if (cur_offset > actual_len)
10465 i_size = actual_len;
10467 i_size = cur_offset;
10468 i_size_write(inode, i_size);
10469 btrfs_ordered_update_i_size(inode, i_size, NULL);
10472 ret = btrfs_update_inode(trans, root, inode);
10475 btrfs_abort_transaction(trans, ret);
10477 btrfs_end_transaction(trans);
10482 btrfs_end_transaction(trans);
10484 if (cur_offset < end)
10485 btrfs_free_reserved_data_space(inode, NULL, cur_offset,
10486 end - cur_offset + 1);
10490 int btrfs_prealloc_file_range(struct inode *inode, int mode,
10491 u64 start, u64 num_bytes, u64 min_size,
10492 loff_t actual_len, u64 *alloc_hint)
10494 return __btrfs_prealloc_file_range(inode, mode, start, num_bytes,
10495 min_size, actual_len, alloc_hint,
10499 int btrfs_prealloc_file_range_trans(struct inode *inode,
10500 struct btrfs_trans_handle *trans, int mode,
10501 u64 start, u64 num_bytes, u64 min_size,
10502 loff_t actual_len, u64 *alloc_hint)
10504 return __btrfs_prealloc_file_range(inode, mode, start, num_bytes,
10505 min_size, actual_len, alloc_hint, trans);
10508 static int btrfs_set_page_dirty(struct page *page)
10510 return __set_page_dirty_nobuffers(page);
10513 static int btrfs_permission(struct inode *inode, int mask)
10515 struct btrfs_root *root = BTRFS_I(inode)->root;
10516 umode_t mode = inode->i_mode;
10518 if (mask & MAY_WRITE &&
10519 (S_ISREG(mode) || S_ISDIR(mode) || S_ISLNK(mode))) {
10520 if (btrfs_root_readonly(root))
10522 if (BTRFS_I(inode)->flags & BTRFS_INODE_READONLY)
10525 return generic_permission(inode, mask);
10528 static int btrfs_tmpfile(struct inode *dir, struct dentry *dentry, umode_t mode)
10530 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
10531 struct btrfs_trans_handle *trans;
10532 struct btrfs_root *root = BTRFS_I(dir)->root;
10533 struct inode *inode = NULL;
10539 * 5 units required for adding orphan entry
10541 trans = btrfs_start_transaction(root, 5);
10543 return PTR_ERR(trans);
10545 ret = btrfs_find_free_ino(root, &objectid);
10549 inode = btrfs_new_inode(trans, root, dir, NULL, 0,
10550 btrfs_ino(BTRFS_I(dir)), objectid, mode, &index);
10551 if (IS_ERR(inode)) {
10552 ret = PTR_ERR(inode);
10557 inode->i_fop = &btrfs_file_operations;
10558 inode->i_op = &btrfs_file_inode_operations;
10560 inode->i_mapping->a_ops = &btrfs_aops;
10561 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
10563 ret = btrfs_init_inode_security(trans, inode, dir, NULL);
10567 ret = btrfs_update_inode(trans, root, inode);
10570 ret = btrfs_orphan_add(trans, BTRFS_I(inode));
10575 * We set number of links to 0 in btrfs_new_inode(), and here we set
10576 * it to 1 because d_tmpfile() will issue a warning if the count is 0,
10579 * d_tmpfile() -> inode_dec_link_count() -> drop_nlink()
10581 set_nlink(inode, 1);
10582 d_tmpfile(dentry, inode);
10583 unlock_new_inode(inode);
10584 mark_inode_dirty(inode);
10586 btrfs_end_transaction(trans);
10588 discard_new_inode(inode);
10589 btrfs_btree_balance_dirty(fs_info);
10593 void btrfs_set_range_writeback(struct extent_io_tree *tree, u64 start, u64 end)
10595 struct inode *inode = tree->private_data;
10596 unsigned long index = start >> PAGE_SHIFT;
10597 unsigned long end_index = end >> PAGE_SHIFT;
10600 while (index <= end_index) {
10601 page = find_get_page(inode->i_mapping, index);
10602 ASSERT(page); /* Pages should be in the extent_io_tree */
10603 set_page_writeback(page);
10611 * Add an entry indicating a block group or device which is pinned by a
10612 * swapfile. Returns 0 on success, 1 if there is already an entry for it, or a
10613 * negative errno on failure.
10615 static int btrfs_add_swapfile_pin(struct inode *inode, void *ptr,
10616 bool is_block_group)
10618 struct btrfs_fs_info *fs_info = BTRFS_I(inode)->root->fs_info;
10619 struct btrfs_swapfile_pin *sp, *entry;
10620 struct rb_node **p;
10621 struct rb_node *parent = NULL;
10623 sp = kmalloc(sizeof(*sp), GFP_NOFS);
10628 sp->is_block_group = is_block_group;
10630 spin_lock(&fs_info->swapfile_pins_lock);
10631 p = &fs_info->swapfile_pins.rb_node;
10634 entry = rb_entry(parent, struct btrfs_swapfile_pin, node);
10635 if (sp->ptr < entry->ptr ||
10636 (sp->ptr == entry->ptr && sp->inode < entry->inode)) {
10637 p = &(*p)->rb_left;
10638 } else if (sp->ptr > entry->ptr ||
10639 (sp->ptr == entry->ptr && sp->inode > entry->inode)) {
10640 p = &(*p)->rb_right;
10642 spin_unlock(&fs_info->swapfile_pins_lock);
10647 rb_link_node(&sp->node, parent, p);
10648 rb_insert_color(&sp->node, &fs_info->swapfile_pins);
10649 spin_unlock(&fs_info->swapfile_pins_lock);
10653 /* Free all of the entries pinned by this swapfile. */
10654 static void btrfs_free_swapfile_pins(struct inode *inode)
10656 struct btrfs_fs_info *fs_info = BTRFS_I(inode)->root->fs_info;
10657 struct btrfs_swapfile_pin *sp;
10658 struct rb_node *node, *next;
10660 spin_lock(&fs_info->swapfile_pins_lock);
10661 node = rb_first(&fs_info->swapfile_pins);
10663 next = rb_next(node);
10664 sp = rb_entry(node, struct btrfs_swapfile_pin, node);
10665 if (sp->inode == inode) {
10666 rb_erase(&sp->node, &fs_info->swapfile_pins);
10667 if (sp->is_block_group)
10668 btrfs_put_block_group(sp->ptr);
10673 spin_unlock(&fs_info->swapfile_pins_lock);
10676 struct btrfs_swap_info {
10682 unsigned long nr_pages;
10686 static int btrfs_add_swap_extent(struct swap_info_struct *sis,
10687 struct btrfs_swap_info *bsi)
10689 unsigned long nr_pages;
10690 u64 first_ppage, first_ppage_reported, next_ppage;
10693 first_ppage = ALIGN(bsi->block_start, PAGE_SIZE) >> PAGE_SHIFT;
10694 next_ppage = ALIGN_DOWN(bsi->block_start + bsi->block_len,
10695 PAGE_SIZE) >> PAGE_SHIFT;
10697 if (first_ppage >= next_ppage)
10699 nr_pages = next_ppage - first_ppage;
10701 first_ppage_reported = first_ppage;
10702 if (bsi->start == 0)
10703 first_ppage_reported++;
10704 if (bsi->lowest_ppage > first_ppage_reported)
10705 bsi->lowest_ppage = first_ppage_reported;
10706 if (bsi->highest_ppage < (next_ppage - 1))
10707 bsi->highest_ppage = next_ppage - 1;
10709 ret = add_swap_extent(sis, bsi->nr_pages, nr_pages, first_ppage);
10712 bsi->nr_extents += ret;
10713 bsi->nr_pages += nr_pages;
10717 static void btrfs_swap_deactivate(struct file *file)
10719 struct inode *inode = file_inode(file);
10721 btrfs_free_swapfile_pins(inode);
10722 atomic_dec(&BTRFS_I(inode)->root->nr_swapfiles);
10725 static int btrfs_swap_activate(struct swap_info_struct *sis, struct file *file,
10728 struct inode *inode = file_inode(file);
10729 struct btrfs_fs_info *fs_info = BTRFS_I(inode)->root->fs_info;
10730 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
10731 struct extent_state *cached_state = NULL;
10732 struct extent_map *em = NULL;
10733 struct btrfs_device *device = NULL;
10734 struct btrfs_swap_info bsi = {
10735 .lowest_ppage = (sector_t)-1ULL,
10742 * If the swap file was just created, make sure delalloc is done. If the
10743 * file changes again after this, the user is doing something stupid and
10744 * we don't really care.
10746 ret = btrfs_wait_ordered_range(inode, 0, (u64)-1);
10751 * The inode is locked, so these flags won't change after we check them.
10753 if (BTRFS_I(inode)->flags & BTRFS_INODE_COMPRESS) {
10754 btrfs_warn(fs_info, "swapfile must not be compressed");
10757 if (!(BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW)) {
10758 btrfs_warn(fs_info, "swapfile must not be copy-on-write");
10761 if (!(BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)) {
10762 btrfs_warn(fs_info, "swapfile must not be checksummed");
10767 * Balance or device remove/replace/resize can move stuff around from
10768 * under us. The EXCL_OP flag makes sure they aren't running/won't run
10769 * concurrently while we are mapping the swap extents, and
10770 * fs_info->swapfile_pins prevents them from running while the swap file
10771 * is active and moving the extents. Note that this also prevents a
10772 * concurrent device add which isn't actually necessary, but it's not
10773 * really worth the trouble to allow it.
10775 if (test_and_set_bit(BTRFS_FS_EXCL_OP, &fs_info->flags)) {
10776 btrfs_warn(fs_info,
10777 "cannot activate swapfile while exclusive operation is running");
10781 * Snapshots can create extents which require COW even if NODATACOW is
10782 * set. We use this counter to prevent snapshots. We must increment it
10783 * before walking the extents because we don't want a concurrent
10784 * snapshot to run after we've already checked the extents.
10786 atomic_inc(&BTRFS_I(inode)->root->nr_swapfiles);
10788 isize = ALIGN_DOWN(inode->i_size, fs_info->sectorsize);
10790 lock_extent_bits(io_tree, 0, isize - 1, &cached_state);
10792 while (start < isize) {
10793 u64 logical_block_start, physical_block_start;
10794 struct btrfs_block_group_cache *bg;
10795 u64 len = isize - start;
10797 em = btrfs_get_extent(BTRFS_I(inode), NULL, 0, start, len, 0);
10803 if (em->block_start == EXTENT_MAP_HOLE) {
10804 btrfs_warn(fs_info, "swapfile must not have holes");
10808 if (em->block_start == EXTENT_MAP_INLINE) {
10810 * It's unlikely we'll ever actually find ourselves
10811 * here, as a file small enough to fit inline won't be
10812 * big enough to store more than the swap header, but in
10813 * case something changes in the future, let's catch it
10814 * here rather than later.
10816 btrfs_warn(fs_info, "swapfile must not be inline");
10820 if (test_bit(EXTENT_FLAG_COMPRESSED, &em->flags)) {
10821 btrfs_warn(fs_info, "swapfile must not be compressed");
10826 logical_block_start = em->block_start + (start - em->start);
10827 len = min(len, em->len - (start - em->start));
10828 free_extent_map(em);
10831 ret = can_nocow_extent(inode, start, &len, NULL, NULL, NULL);
10837 btrfs_warn(fs_info,
10838 "swapfile must not be copy-on-write");
10843 em = btrfs_get_chunk_map(fs_info, logical_block_start, len);
10849 if (em->map_lookup->type & BTRFS_BLOCK_GROUP_PROFILE_MASK) {
10850 btrfs_warn(fs_info,
10851 "swapfile must have single data profile");
10856 if (device == NULL) {
10857 device = em->map_lookup->stripes[0].dev;
10858 ret = btrfs_add_swapfile_pin(inode, device, false);
10863 } else if (device != em->map_lookup->stripes[0].dev) {
10864 btrfs_warn(fs_info, "swapfile must be on one device");
10869 physical_block_start = (em->map_lookup->stripes[0].physical +
10870 (logical_block_start - em->start));
10871 len = min(len, em->len - (logical_block_start - em->start));
10872 free_extent_map(em);
10875 bg = btrfs_lookup_block_group(fs_info, logical_block_start);
10877 btrfs_warn(fs_info,
10878 "could not find block group containing swapfile");
10883 ret = btrfs_add_swapfile_pin(inode, bg, true);
10885 btrfs_put_block_group(bg);
10892 if (bsi.block_len &&
10893 bsi.block_start + bsi.block_len == physical_block_start) {
10894 bsi.block_len += len;
10896 if (bsi.block_len) {
10897 ret = btrfs_add_swap_extent(sis, &bsi);
10902 bsi.block_start = physical_block_start;
10903 bsi.block_len = len;
10910 ret = btrfs_add_swap_extent(sis, &bsi);
10913 if (!IS_ERR_OR_NULL(em))
10914 free_extent_map(em);
10916 unlock_extent_cached(io_tree, 0, isize - 1, &cached_state);
10919 btrfs_swap_deactivate(file);
10921 clear_bit(BTRFS_FS_EXCL_OP, &fs_info->flags);
10927 sis->bdev = device->bdev;
10928 *span = bsi.highest_ppage - bsi.lowest_ppage + 1;
10929 sis->max = bsi.nr_pages;
10930 sis->pages = bsi.nr_pages - 1;
10931 sis->highest_bit = bsi.nr_pages - 1;
10932 return bsi.nr_extents;
10935 static void btrfs_swap_deactivate(struct file *file)
10939 static int btrfs_swap_activate(struct swap_info_struct *sis, struct file *file,
10942 return -EOPNOTSUPP;
10946 static const struct inode_operations btrfs_dir_inode_operations = {
10947 .getattr = btrfs_getattr,
10948 .lookup = btrfs_lookup,
10949 .create = btrfs_create,
10950 .unlink = btrfs_unlink,
10951 .link = btrfs_link,
10952 .mkdir = btrfs_mkdir,
10953 .rmdir = btrfs_rmdir,
10954 .rename = btrfs_rename2,
10955 .symlink = btrfs_symlink,
10956 .setattr = btrfs_setattr,
10957 .mknod = btrfs_mknod,
10958 .listxattr = btrfs_listxattr,
10959 .permission = btrfs_permission,
10960 .get_acl = btrfs_get_acl,
10961 .set_acl = btrfs_set_acl,
10962 .update_time = btrfs_update_time,
10963 .tmpfile = btrfs_tmpfile,
10965 static const struct inode_operations btrfs_dir_ro_inode_operations = {
10966 .lookup = btrfs_lookup,
10967 .permission = btrfs_permission,
10968 .update_time = btrfs_update_time,
10971 static const struct file_operations btrfs_dir_file_operations = {
10972 .llseek = generic_file_llseek,
10973 .read = generic_read_dir,
10974 .iterate_shared = btrfs_real_readdir,
10975 .open = btrfs_opendir,
10976 .unlocked_ioctl = btrfs_ioctl,
10977 #ifdef CONFIG_COMPAT
10978 .compat_ioctl = btrfs_compat_ioctl,
10980 .release = btrfs_release_file,
10981 .fsync = btrfs_sync_file,
10984 static const struct extent_io_ops btrfs_extent_io_ops = {
10985 /* mandatory callbacks */
10986 .submit_bio_hook = btrfs_submit_bio_hook,
10987 .readpage_end_io_hook = btrfs_readpage_end_io_hook,
10991 * btrfs doesn't support the bmap operation because swapfiles
10992 * use bmap to make a mapping of extents in the file. They assume
10993 * these extents won't change over the life of the file and they
10994 * use the bmap result to do IO directly to the drive.
10996 * the btrfs bmap call would return logical addresses that aren't
10997 * suitable for IO and they also will change frequently as COW
10998 * operations happen. So, swapfile + btrfs == corruption.
11000 * For now we're avoiding this by dropping bmap.
11002 static const struct address_space_operations btrfs_aops = {
11003 .readpage = btrfs_readpage,
11004 .writepage = btrfs_writepage,
11005 .writepages = btrfs_writepages,
11006 .readpages = btrfs_readpages,
11007 .direct_IO = btrfs_direct_IO,
11008 .invalidatepage = btrfs_invalidatepage,
11009 .releasepage = btrfs_releasepage,
11010 .set_page_dirty = btrfs_set_page_dirty,
11011 .error_remove_page = generic_error_remove_page,
11012 .swap_activate = btrfs_swap_activate,
11013 .swap_deactivate = btrfs_swap_deactivate,
11016 static const struct inode_operations btrfs_file_inode_operations = {
11017 .getattr = btrfs_getattr,
11018 .setattr = btrfs_setattr,
11019 .listxattr = btrfs_listxattr,
11020 .permission = btrfs_permission,
11021 .fiemap = btrfs_fiemap,
11022 .get_acl = btrfs_get_acl,
11023 .set_acl = btrfs_set_acl,
11024 .update_time = btrfs_update_time,
11026 static const struct inode_operations btrfs_special_inode_operations = {
11027 .getattr = btrfs_getattr,
11028 .setattr = btrfs_setattr,
11029 .permission = btrfs_permission,
11030 .listxattr = btrfs_listxattr,
11031 .get_acl = btrfs_get_acl,
11032 .set_acl = btrfs_set_acl,
11033 .update_time = btrfs_update_time,
11035 static const struct inode_operations btrfs_symlink_inode_operations = {
11036 .get_link = page_get_link,
11037 .getattr = btrfs_getattr,
11038 .setattr = btrfs_setattr,
11039 .permission = btrfs_permission,
11040 .listxattr = btrfs_listxattr,
11041 .update_time = btrfs_update_time,
11044 const struct dentry_operations btrfs_dentry_operations = {
11045 .d_delete = btrfs_dentry_delete,