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 (async_chunk->locked_page &&
716 (page_offset(async_chunk->locked_page) >= start &&
717 page_offset(async_chunk->locked_page)) <= end) {
718 __set_page_dirty_nobuffers(async_chunk->locked_page);
719 /* unlocked later on in the async handlers */
723 extent_range_redirty_for_io(inode, start, end);
724 add_async_extent(async_chunk, start, end - start + 1, 0, NULL, 0,
725 BTRFS_COMPRESS_NONE);
726 compressed_extents++;
728 return compressed_extents;
731 static void free_async_extent_pages(struct async_extent *async_extent)
735 if (!async_extent->pages)
738 for (i = 0; i < async_extent->nr_pages; i++) {
739 WARN_ON(async_extent->pages[i]->mapping);
740 put_page(async_extent->pages[i]);
742 kfree(async_extent->pages);
743 async_extent->nr_pages = 0;
744 async_extent->pages = NULL;
748 * phase two of compressed writeback. This is the ordered portion
749 * of the code, which only gets called in the order the work was
750 * queued. We walk all the async extents created by compress_file_range
751 * and send them down to the disk.
753 static noinline void submit_compressed_extents(struct async_chunk *async_chunk)
755 struct inode *inode = async_chunk->inode;
756 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
757 struct async_extent *async_extent;
759 struct btrfs_key ins;
760 struct extent_map *em;
761 struct btrfs_root *root = BTRFS_I(inode)->root;
762 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
766 while (!list_empty(&async_chunk->extents)) {
767 async_extent = list_entry(async_chunk->extents.next,
768 struct async_extent, list);
769 list_del(&async_extent->list);
772 lock_extent(io_tree, async_extent->start,
773 async_extent->start + async_extent->ram_size - 1);
774 /* did the compression code fall back to uncompressed IO? */
775 if (!async_extent->pages) {
776 int page_started = 0;
777 unsigned long nr_written = 0;
779 /* allocate blocks */
780 ret = cow_file_range(inode, async_chunk->locked_page,
782 async_extent->start +
783 async_extent->ram_size - 1,
784 &page_started, &nr_written, 0);
789 * if page_started, cow_file_range inserted an
790 * inline extent and took care of all the unlocking
791 * and IO for us. Otherwise, we need to submit
792 * all those pages down to the drive.
794 if (!page_started && !ret)
795 extent_write_locked_range(inode,
797 async_extent->start +
798 async_extent->ram_size - 1,
800 else if (ret && async_chunk->locked_page)
801 unlock_page(async_chunk->locked_page);
807 ret = btrfs_reserve_extent(root, async_extent->ram_size,
808 async_extent->compressed_size,
809 async_extent->compressed_size,
810 0, alloc_hint, &ins, 1, 1);
812 free_async_extent_pages(async_extent);
814 if (ret == -ENOSPC) {
815 unlock_extent(io_tree, async_extent->start,
816 async_extent->start +
817 async_extent->ram_size - 1);
820 * we need to redirty the pages if we decide to
821 * fallback to uncompressed IO, otherwise we
822 * will not submit these pages down to lower
825 extent_range_redirty_for_io(inode,
827 async_extent->start +
828 async_extent->ram_size - 1);
835 * here we're doing allocation and writeback of the
838 em = create_io_em(inode, async_extent->start,
839 async_extent->ram_size, /* len */
840 async_extent->start, /* orig_start */
841 ins.objectid, /* block_start */
842 ins.offset, /* block_len */
843 ins.offset, /* orig_block_len */
844 async_extent->ram_size, /* ram_bytes */
845 async_extent->compress_type,
846 BTRFS_ORDERED_COMPRESSED);
848 /* ret value is not necessary due to void function */
849 goto out_free_reserve;
852 ret = btrfs_add_ordered_extent_compress(inode,
855 async_extent->ram_size,
857 BTRFS_ORDERED_COMPRESSED,
858 async_extent->compress_type);
860 btrfs_drop_extent_cache(BTRFS_I(inode),
862 async_extent->start +
863 async_extent->ram_size - 1, 0);
864 goto out_free_reserve;
866 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
869 * clear dirty, set writeback and unlock the pages.
871 extent_clear_unlock_delalloc(inode, async_extent->start,
872 async_extent->start +
873 async_extent->ram_size - 1,
874 NULL, EXTENT_LOCKED | EXTENT_DELALLOC,
875 PAGE_UNLOCK | PAGE_CLEAR_DIRTY |
877 if (btrfs_submit_compressed_write(inode,
879 async_extent->ram_size,
881 ins.offset, async_extent->pages,
882 async_extent->nr_pages,
883 async_chunk->write_flags)) {
884 struct page *p = async_extent->pages[0];
885 const u64 start = async_extent->start;
886 const u64 end = start + async_extent->ram_size - 1;
888 p->mapping = inode->i_mapping;
889 btrfs_writepage_endio_finish_ordered(p, start, end, 0);
892 extent_clear_unlock_delalloc(inode, start, end,
896 free_async_extent_pages(async_extent);
898 alloc_hint = ins.objectid + ins.offset;
904 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
905 btrfs_free_reserved_extent(fs_info, ins.objectid, ins.offset, 1);
907 extent_clear_unlock_delalloc(inode, async_extent->start,
908 async_extent->start +
909 async_extent->ram_size - 1,
910 NULL, EXTENT_LOCKED | EXTENT_DELALLOC |
911 EXTENT_DELALLOC_NEW |
912 EXTENT_DEFRAG | EXTENT_DO_ACCOUNTING,
913 PAGE_UNLOCK | PAGE_CLEAR_DIRTY |
914 PAGE_SET_WRITEBACK | PAGE_END_WRITEBACK |
916 free_async_extent_pages(async_extent);
921 static u64 get_extent_allocation_hint(struct inode *inode, u64 start,
924 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
925 struct extent_map *em;
928 read_lock(&em_tree->lock);
929 em = search_extent_mapping(em_tree, start, num_bytes);
932 * if block start isn't an actual block number then find the
933 * first block in this inode and use that as a hint. If that
934 * block is also bogus then just don't worry about it.
936 if (em->block_start >= EXTENT_MAP_LAST_BYTE) {
938 em = search_extent_mapping(em_tree, 0, 0);
939 if (em && em->block_start < EXTENT_MAP_LAST_BYTE)
940 alloc_hint = em->block_start;
944 alloc_hint = em->block_start;
948 read_unlock(&em_tree->lock);
954 * when extent_io.c finds a delayed allocation range in the file,
955 * the call backs end up in this code. The basic idea is to
956 * allocate extents on disk for the range, and create ordered data structs
957 * in ram to track those extents.
959 * locked_page is the page that writepage had locked already. We use
960 * it to make sure we don't do extra locks or unlocks.
962 * *page_started is set to one if we unlock locked_page and do everything
963 * required to start IO on it. It may be clean and already done with
966 static noinline int cow_file_range(struct inode *inode,
967 struct page *locked_page,
968 u64 start, u64 end, int *page_started,
969 unsigned long *nr_written, int unlock)
971 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
972 struct btrfs_root *root = BTRFS_I(inode)->root;
975 unsigned long ram_size;
976 u64 cur_alloc_size = 0;
977 u64 blocksize = fs_info->sectorsize;
978 struct btrfs_key ins;
979 struct extent_map *em;
981 unsigned long page_ops;
982 bool extent_reserved = false;
985 if (btrfs_is_free_space_inode(BTRFS_I(inode))) {
991 num_bytes = ALIGN(end - start + 1, blocksize);
992 num_bytes = max(blocksize, num_bytes);
993 ASSERT(num_bytes <= btrfs_super_total_bytes(fs_info->super_copy));
995 inode_should_defrag(BTRFS_I(inode), start, end, num_bytes, SZ_64K);
998 /* lets try to make an inline extent */
999 ret = cow_file_range_inline(inode, start, end, 0,
1000 BTRFS_COMPRESS_NONE, NULL);
1003 * We use DO_ACCOUNTING here because we need the
1004 * delalloc_release_metadata to be run _after_ we drop
1005 * our outstanding extent for clearing delalloc for this
1008 extent_clear_unlock_delalloc(inode, start, end, NULL,
1009 EXTENT_LOCKED | EXTENT_DELALLOC |
1010 EXTENT_DELALLOC_NEW | EXTENT_DEFRAG |
1011 EXTENT_DO_ACCOUNTING, PAGE_UNLOCK |
1012 PAGE_CLEAR_DIRTY | PAGE_SET_WRITEBACK |
1013 PAGE_END_WRITEBACK);
1014 *nr_written = *nr_written +
1015 (end - start + PAGE_SIZE) / PAGE_SIZE;
1018 } else if (ret < 0) {
1023 alloc_hint = get_extent_allocation_hint(inode, start, num_bytes);
1024 btrfs_drop_extent_cache(BTRFS_I(inode), start,
1025 start + num_bytes - 1, 0);
1027 while (num_bytes > 0) {
1028 cur_alloc_size = num_bytes;
1029 ret = btrfs_reserve_extent(root, cur_alloc_size, cur_alloc_size,
1030 fs_info->sectorsize, 0, alloc_hint,
1034 cur_alloc_size = ins.offset;
1035 extent_reserved = true;
1037 ram_size = ins.offset;
1038 em = create_io_em(inode, start, ins.offset, /* len */
1039 start, /* orig_start */
1040 ins.objectid, /* block_start */
1041 ins.offset, /* block_len */
1042 ins.offset, /* orig_block_len */
1043 ram_size, /* ram_bytes */
1044 BTRFS_COMPRESS_NONE, /* compress_type */
1045 BTRFS_ORDERED_REGULAR /* type */);
1050 free_extent_map(em);
1052 ret = btrfs_add_ordered_extent(inode, start, ins.objectid,
1053 ram_size, cur_alloc_size, 0);
1055 goto out_drop_extent_cache;
1057 if (root->root_key.objectid ==
1058 BTRFS_DATA_RELOC_TREE_OBJECTID) {
1059 ret = btrfs_reloc_clone_csums(inode, start,
1062 * Only drop cache here, and process as normal.
1064 * We must not allow extent_clear_unlock_delalloc()
1065 * at out_unlock label to free meta of this ordered
1066 * extent, as its meta should be freed by
1067 * btrfs_finish_ordered_io().
1069 * So we must continue until @start is increased to
1070 * skip current ordered extent.
1073 btrfs_drop_extent_cache(BTRFS_I(inode), start,
1074 start + ram_size - 1, 0);
1077 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
1079 /* we're not doing compressed IO, don't unlock the first
1080 * page (which the caller expects to stay locked), don't
1081 * clear any dirty bits and don't set any writeback bits
1083 * Do set the Private2 bit so we know this page was properly
1084 * setup for writepage
1086 page_ops = unlock ? PAGE_UNLOCK : 0;
1087 page_ops |= PAGE_SET_PRIVATE2;
1089 extent_clear_unlock_delalloc(inode, start,
1090 start + ram_size - 1,
1092 EXTENT_LOCKED | EXTENT_DELALLOC,
1094 if (num_bytes < cur_alloc_size)
1097 num_bytes -= cur_alloc_size;
1098 alloc_hint = ins.objectid + ins.offset;
1099 start += cur_alloc_size;
1100 extent_reserved = false;
1103 * btrfs_reloc_clone_csums() error, since start is increased
1104 * extent_clear_unlock_delalloc() at out_unlock label won't
1105 * free metadata of current ordered extent, we're OK to exit.
1113 out_drop_extent_cache:
1114 btrfs_drop_extent_cache(BTRFS_I(inode), start, start + ram_size - 1, 0);
1116 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
1117 btrfs_free_reserved_extent(fs_info, ins.objectid, ins.offset, 1);
1119 clear_bits = EXTENT_LOCKED | EXTENT_DELALLOC | EXTENT_DELALLOC_NEW |
1120 EXTENT_DEFRAG | EXTENT_CLEAR_META_RESV;
1121 page_ops = PAGE_UNLOCK | PAGE_CLEAR_DIRTY | PAGE_SET_WRITEBACK |
1124 * If we reserved an extent for our delalloc range (or a subrange) and
1125 * failed to create the respective ordered extent, then it means that
1126 * when we reserved the extent we decremented the extent's size from
1127 * the data space_info's bytes_may_use counter and incremented the
1128 * space_info's bytes_reserved counter by the same amount. We must make
1129 * sure extent_clear_unlock_delalloc() does not try to decrement again
1130 * the data space_info's bytes_may_use counter, therefore we do not pass
1131 * it the flag EXTENT_CLEAR_DATA_RESV.
1133 if (extent_reserved) {
1134 extent_clear_unlock_delalloc(inode, start,
1135 start + cur_alloc_size,
1139 start += cur_alloc_size;
1143 extent_clear_unlock_delalloc(inode, start, end, locked_page,
1144 clear_bits | EXTENT_CLEAR_DATA_RESV,
1150 * work queue call back to started compression on a file and pages
1152 static noinline void async_cow_start(struct btrfs_work *work)
1154 struct async_chunk *async_chunk;
1155 int compressed_extents;
1157 async_chunk = container_of(work, struct async_chunk, work);
1159 compressed_extents = compress_file_range(async_chunk);
1160 if (compressed_extents == 0) {
1161 btrfs_add_delayed_iput(async_chunk->inode);
1162 async_chunk->inode = NULL;
1167 * work queue call back to submit previously compressed pages
1169 static noinline void async_cow_submit(struct btrfs_work *work)
1171 struct async_chunk *async_chunk = container_of(work, struct async_chunk,
1173 struct btrfs_fs_info *fs_info = btrfs_work_owner(work);
1174 unsigned long nr_pages;
1176 nr_pages = (async_chunk->end - async_chunk->start + PAGE_SIZE) >>
1179 /* atomic_sub_return implies a barrier */
1180 if (atomic_sub_return(nr_pages, &fs_info->async_delalloc_pages) <
1182 cond_wake_up_nomb(&fs_info->async_submit_wait);
1185 * ->inode could be NULL if async_chunk_start has failed to compress,
1186 * in which case we don't have anything to submit, yet we need to
1187 * always adjust ->async_delalloc_pages as its paired with the init
1188 * happening in cow_file_range_async
1190 if (async_chunk->inode)
1191 submit_compressed_extents(async_chunk);
1194 static noinline void async_cow_free(struct btrfs_work *work)
1196 struct async_chunk *async_chunk;
1198 async_chunk = container_of(work, struct async_chunk, work);
1199 if (async_chunk->inode)
1200 btrfs_add_delayed_iput(async_chunk->inode);
1202 * Since the pointer to 'pending' is at the beginning of the array of
1203 * async_chunk's, freeing it ensures the whole array has been freed.
1205 if (atomic_dec_and_test(async_chunk->pending))
1206 kvfree(async_chunk->pending);
1209 static int cow_file_range_async(struct inode *inode, struct page *locked_page,
1210 u64 start, u64 end, int *page_started,
1211 unsigned long *nr_written,
1212 unsigned int write_flags)
1214 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1215 struct async_cow *ctx;
1216 struct async_chunk *async_chunk;
1217 unsigned long nr_pages;
1219 u64 num_chunks = DIV_ROUND_UP(end - start, SZ_512K);
1221 bool should_compress;
1224 unlock_extent(&BTRFS_I(inode)->io_tree, start, end);
1226 if (BTRFS_I(inode)->flags & BTRFS_INODE_NOCOMPRESS &&
1227 !btrfs_test_opt(fs_info, FORCE_COMPRESS)) {
1229 should_compress = false;
1231 should_compress = true;
1234 nofs_flag = memalloc_nofs_save();
1235 ctx = kvmalloc(struct_size(ctx, chunks, num_chunks), GFP_KERNEL);
1236 memalloc_nofs_restore(nofs_flag);
1239 unsigned clear_bits = EXTENT_LOCKED | EXTENT_DELALLOC |
1240 EXTENT_DELALLOC_NEW | EXTENT_DEFRAG |
1241 EXTENT_DO_ACCOUNTING;
1242 unsigned long page_ops = PAGE_UNLOCK | PAGE_CLEAR_DIRTY |
1243 PAGE_SET_WRITEBACK | PAGE_END_WRITEBACK |
1246 extent_clear_unlock_delalloc(inode, start, end, locked_page,
1247 clear_bits, page_ops);
1251 async_chunk = ctx->chunks;
1252 atomic_set(&ctx->num_chunks, num_chunks);
1254 for (i = 0; i < num_chunks; i++) {
1255 if (should_compress)
1256 cur_end = min(end, start + SZ_512K - 1);
1261 * igrab is called higher up in the call chain, take only the
1262 * lightweight reference for the callback lifetime
1265 async_chunk[i].pending = &ctx->num_chunks;
1266 async_chunk[i].inode = inode;
1267 async_chunk[i].start = start;
1268 async_chunk[i].end = cur_end;
1269 async_chunk[i].write_flags = write_flags;
1270 INIT_LIST_HEAD(&async_chunk[i].extents);
1273 * The locked_page comes all the way from writepage and its
1274 * the original page we were actually given. As we spread
1275 * this large delalloc region across multiple async_chunk
1276 * structs, only the first struct needs a pointer to locked_page
1278 * This way we don't need racey decisions about who is supposed
1282 async_chunk[i].locked_page = locked_page;
1285 async_chunk[i].locked_page = NULL;
1288 btrfs_init_work(&async_chunk[i].work, async_cow_start,
1289 async_cow_submit, async_cow_free);
1291 nr_pages = DIV_ROUND_UP(cur_end - start, PAGE_SIZE);
1292 atomic_add(nr_pages, &fs_info->async_delalloc_pages);
1294 btrfs_queue_work(fs_info->delalloc_workers, &async_chunk[i].work);
1296 *nr_written += nr_pages;
1297 start = cur_end + 1;
1303 static noinline int csum_exist_in_range(struct btrfs_fs_info *fs_info,
1304 u64 bytenr, u64 num_bytes)
1307 struct btrfs_ordered_sum *sums;
1310 ret = btrfs_lookup_csums_range(fs_info->csum_root, bytenr,
1311 bytenr + num_bytes - 1, &list, 0);
1312 if (ret == 0 && list_empty(&list))
1315 while (!list_empty(&list)) {
1316 sums = list_entry(list.next, struct btrfs_ordered_sum, list);
1317 list_del(&sums->list);
1326 * when nowcow writeback call back. This checks for snapshots or COW copies
1327 * of the extents that exist in the file, and COWs the file as required.
1329 * If no cow copies or snapshots exist, we write directly to the existing
1332 static noinline int run_delalloc_nocow(struct inode *inode,
1333 struct page *locked_page,
1334 const u64 start, const u64 end,
1335 int *page_started, int force,
1336 unsigned long *nr_written)
1338 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1339 struct btrfs_root *root = BTRFS_I(inode)->root;
1340 struct btrfs_path *path;
1341 u64 cow_start = (u64)-1;
1342 u64 cur_offset = start;
1344 bool check_prev = true;
1345 const bool freespace_inode = btrfs_is_free_space_inode(BTRFS_I(inode));
1346 u64 ino = btrfs_ino(BTRFS_I(inode));
1348 u64 disk_bytenr = 0;
1350 path = btrfs_alloc_path();
1352 extent_clear_unlock_delalloc(inode, start, end, locked_page,
1353 EXTENT_LOCKED | EXTENT_DELALLOC |
1354 EXTENT_DO_ACCOUNTING |
1355 EXTENT_DEFRAG, PAGE_UNLOCK |
1357 PAGE_SET_WRITEBACK |
1358 PAGE_END_WRITEBACK);
1363 struct btrfs_key found_key;
1364 struct btrfs_file_extent_item *fi;
1365 struct extent_buffer *leaf;
1375 ret = btrfs_lookup_file_extent(NULL, root, path, ino,
1381 * If there is no extent for our range when doing the initial
1382 * search, then go back to the previous slot as it will be the
1383 * one containing the search offset
1385 if (ret > 0 && path->slots[0] > 0 && check_prev) {
1386 leaf = path->nodes[0];
1387 btrfs_item_key_to_cpu(leaf, &found_key,
1388 path->slots[0] - 1);
1389 if (found_key.objectid == ino &&
1390 found_key.type == BTRFS_EXTENT_DATA_KEY)
1395 /* Go to next leaf if we have exhausted the current one */
1396 leaf = path->nodes[0];
1397 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
1398 ret = btrfs_next_leaf(root, path);
1400 if (cow_start != (u64)-1)
1401 cur_offset = cow_start;
1406 leaf = path->nodes[0];
1409 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
1411 /* Didn't find anything for our INO */
1412 if (found_key.objectid > ino)
1415 * Keep searching until we find an EXTENT_ITEM or there are no
1416 * more extents for this inode
1418 if (WARN_ON_ONCE(found_key.objectid < ino) ||
1419 found_key.type < BTRFS_EXTENT_DATA_KEY) {
1424 /* Found key is not EXTENT_DATA_KEY or starts after req range */
1425 if (found_key.type > BTRFS_EXTENT_DATA_KEY ||
1426 found_key.offset > end)
1430 * If the found extent starts after requested offset, then
1431 * adjust extent_end to be right before this extent begins
1433 if (found_key.offset > cur_offset) {
1434 extent_end = found_key.offset;
1440 * Found extent which begins before our range and potentially
1443 fi = btrfs_item_ptr(leaf, path->slots[0],
1444 struct btrfs_file_extent_item);
1445 extent_type = btrfs_file_extent_type(leaf, fi);
1447 ram_bytes = btrfs_file_extent_ram_bytes(leaf, fi);
1448 if (extent_type == BTRFS_FILE_EXTENT_REG ||
1449 extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
1450 disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
1451 extent_offset = btrfs_file_extent_offset(leaf, fi);
1452 extent_end = found_key.offset +
1453 btrfs_file_extent_num_bytes(leaf, fi);
1455 btrfs_file_extent_disk_num_bytes(leaf, fi);
1457 * If the extent we got ends before our current offset,
1458 * skip to the next extent.
1460 if (extent_end <= cur_offset) {
1465 if (disk_bytenr == 0)
1467 /* Skip compressed/encrypted/encoded extents */
1468 if (btrfs_file_extent_compression(leaf, fi) ||
1469 btrfs_file_extent_encryption(leaf, fi) ||
1470 btrfs_file_extent_other_encoding(leaf, fi))
1473 * If extent is created before the last volume's snapshot
1474 * this implies the extent is shared, hence we can't do
1475 * nocow. This is the same check as in
1476 * btrfs_cross_ref_exist but without calling
1477 * btrfs_search_slot.
1479 if (!freespace_inode &&
1480 btrfs_file_extent_generation(leaf, fi) <=
1481 btrfs_root_last_snapshot(&root->root_item))
1483 if (extent_type == BTRFS_FILE_EXTENT_REG && !force)
1485 /* If extent is RO, we must COW it */
1486 if (btrfs_extent_readonly(fs_info, disk_bytenr))
1488 ret = btrfs_cross_ref_exist(root, ino,
1490 extent_offset, disk_bytenr);
1493 * ret could be -EIO if the above fails to read
1497 if (cow_start != (u64)-1)
1498 cur_offset = cow_start;
1502 WARN_ON_ONCE(freespace_inode);
1505 disk_bytenr += extent_offset;
1506 disk_bytenr += cur_offset - found_key.offset;
1507 num_bytes = min(end + 1, extent_end) - cur_offset;
1509 * If there are pending snapshots for this root, we
1510 * fall into common COW way
1512 if (!freespace_inode && atomic_read(&root->snapshot_force_cow))
1515 * force cow if csum exists in the range.
1516 * this ensure that csum for a given extent are
1517 * either valid or do not exist.
1519 ret = csum_exist_in_range(fs_info, disk_bytenr,
1523 * ret could be -EIO if the above fails to read
1527 if (cow_start != (u64)-1)
1528 cur_offset = cow_start;
1531 WARN_ON_ONCE(freespace_inode);
1534 if (!btrfs_inc_nocow_writers(fs_info, disk_bytenr))
1537 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
1538 extent_end = found_key.offset + ram_bytes;
1539 extent_end = ALIGN(extent_end, fs_info->sectorsize);
1540 /* Skip extents outside of our requested range */
1541 if (extent_end <= start) {
1546 /* If this triggers then we have a memory corruption */
1551 * If nocow is false then record the beginning of the range
1552 * that needs to be COWed
1555 if (cow_start == (u64)-1)
1556 cow_start = cur_offset;
1557 cur_offset = extent_end;
1558 if (cur_offset > end)
1564 btrfs_release_path(path);
1567 * COW range from cow_start to found_key.offset - 1. As the key
1568 * will contain the beginning of the first extent that can be
1569 * NOCOW, following one which needs to be COW'ed
1571 if (cow_start != (u64)-1) {
1572 ret = cow_file_range(inode, locked_page,
1573 cow_start, found_key.offset - 1,
1574 page_started, nr_written, 1);
1577 btrfs_dec_nocow_writers(fs_info,
1581 cow_start = (u64)-1;
1584 if (extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
1585 u64 orig_start = found_key.offset - extent_offset;
1586 struct extent_map *em;
1588 em = create_io_em(inode, cur_offset, num_bytes,
1590 disk_bytenr, /* block_start */
1591 num_bytes, /* block_len */
1592 disk_num_bytes, /* orig_block_len */
1593 ram_bytes, BTRFS_COMPRESS_NONE,
1594 BTRFS_ORDERED_PREALLOC);
1597 btrfs_dec_nocow_writers(fs_info,
1602 free_extent_map(em);
1603 ret = btrfs_add_ordered_extent(inode, cur_offset,
1604 disk_bytenr, num_bytes,
1606 BTRFS_ORDERED_PREALLOC);
1608 btrfs_drop_extent_cache(BTRFS_I(inode),
1610 cur_offset + num_bytes - 1,
1615 ret = btrfs_add_ordered_extent(inode, cur_offset,
1616 disk_bytenr, num_bytes,
1618 BTRFS_ORDERED_NOCOW);
1624 btrfs_dec_nocow_writers(fs_info, disk_bytenr);
1627 if (root->root_key.objectid ==
1628 BTRFS_DATA_RELOC_TREE_OBJECTID)
1630 * Error handled later, as we must prevent
1631 * extent_clear_unlock_delalloc() in error handler
1632 * from freeing metadata of created ordered extent.
1634 ret = btrfs_reloc_clone_csums(inode, cur_offset,
1637 extent_clear_unlock_delalloc(inode, cur_offset,
1638 cur_offset + num_bytes - 1,
1639 locked_page, EXTENT_LOCKED |
1641 EXTENT_CLEAR_DATA_RESV,
1642 PAGE_UNLOCK | PAGE_SET_PRIVATE2);
1644 cur_offset = extent_end;
1647 * btrfs_reloc_clone_csums() error, now we're OK to call error
1648 * handler, as metadata for created ordered extent will only
1649 * be freed by btrfs_finish_ordered_io().
1653 if (cur_offset > end)
1656 btrfs_release_path(path);
1658 if (cur_offset <= end && cow_start == (u64)-1)
1659 cow_start = cur_offset;
1661 if (cow_start != (u64)-1) {
1663 ret = cow_file_range(inode, locked_page, cow_start, end,
1664 page_started, nr_written, 1);
1671 btrfs_dec_nocow_writers(fs_info, disk_bytenr);
1673 if (ret && cur_offset < end)
1674 extent_clear_unlock_delalloc(inode, cur_offset, end,
1675 locked_page, EXTENT_LOCKED |
1676 EXTENT_DELALLOC | EXTENT_DEFRAG |
1677 EXTENT_DO_ACCOUNTING, PAGE_UNLOCK |
1679 PAGE_SET_WRITEBACK |
1680 PAGE_END_WRITEBACK);
1681 btrfs_free_path(path);
1685 static inline int need_force_cow(struct inode *inode, u64 start, u64 end)
1688 if (!(BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW) &&
1689 !(BTRFS_I(inode)->flags & BTRFS_INODE_PREALLOC))
1693 * @defrag_bytes is a hint value, no spinlock held here,
1694 * if is not zero, it means the file is defragging.
1695 * Force cow if given extent needs to be defragged.
1697 if (BTRFS_I(inode)->defrag_bytes &&
1698 test_range_bit(&BTRFS_I(inode)->io_tree, start, end,
1699 EXTENT_DEFRAG, 0, NULL))
1706 * Function to process delayed allocation (create CoW) for ranges which are
1707 * being touched for the first time.
1709 int btrfs_run_delalloc_range(struct inode *inode, struct page *locked_page,
1710 u64 start, u64 end, int *page_started, unsigned long *nr_written,
1711 struct writeback_control *wbc)
1714 int force_cow = need_force_cow(inode, start, end);
1715 unsigned int write_flags = wbc_to_write_flags(wbc);
1717 if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW && !force_cow) {
1718 ret = run_delalloc_nocow(inode, locked_page, start, end,
1719 page_started, 1, nr_written);
1720 } else if (BTRFS_I(inode)->flags & BTRFS_INODE_PREALLOC && !force_cow) {
1721 ret = run_delalloc_nocow(inode, locked_page, start, end,
1722 page_started, 0, nr_written);
1723 } else if (!inode_can_compress(inode) ||
1724 !inode_need_compress(inode, start, end)) {
1725 ret = cow_file_range(inode, locked_page, start, end,
1726 page_started, nr_written, 1);
1728 set_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
1729 &BTRFS_I(inode)->runtime_flags);
1730 ret = cow_file_range_async(inode, locked_page, start, end,
1731 page_started, nr_written,
1735 btrfs_cleanup_ordered_extents(inode, locked_page, start,
1740 void btrfs_split_delalloc_extent(struct inode *inode,
1741 struct extent_state *orig, u64 split)
1745 /* not delalloc, ignore it */
1746 if (!(orig->state & EXTENT_DELALLOC))
1749 size = orig->end - orig->start + 1;
1750 if (size > BTRFS_MAX_EXTENT_SIZE) {
1755 * See the explanation in btrfs_merge_delalloc_extent, the same
1756 * applies here, just in reverse.
1758 new_size = orig->end - split + 1;
1759 num_extents = count_max_extents(new_size);
1760 new_size = split - orig->start;
1761 num_extents += count_max_extents(new_size);
1762 if (count_max_extents(size) >= num_extents)
1766 spin_lock(&BTRFS_I(inode)->lock);
1767 btrfs_mod_outstanding_extents(BTRFS_I(inode), 1);
1768 spin_unlock(&BTRFS_I(inode)->lock);
1772 * Handle merged delayed allocation extents so we can keep track of new extents
1773 * that are just merged onto old extents, such as when we are doing sequential
1774 * writes, so we can properly account for the metadata space we'll need.
1776 void btrfs_merge_delalloc_extent(struct inode *inode, struct extent_state *new,
1777 struct extent_state *other)
1779 u64 new_size, old_size;
1782 /* not delalloc, ignore it */
1783 if (!(other->state & EXTENT_DELALLOC))
1786 if (new->start > other->start)
1787 new_size = new->end - other->start + 1;
1789 new_size = other->end - new->start + 1;
1791 /* we're not bigger than the max, unreserve the space and go */
1792 if (new_size <= BTRFS_MAX_EXTENT_SIZE) {
1793 spin_lock(&BTRFS_I(inode)->lock);
1794 btrfs_mod_outstanding_extents(BTRFS_I(inode), -1);
1795 spin_unlock(&BTRFS_I(inode)->lock);
1800 * We have to add up either side to figure out how many extents were
1801 * accounted for before we merged into one big extent. If the number of
1802 * extents we accounted for is <= the amount we need for the new range
1803 * then we can return, otherwise drop. Think of it like this
1807 * So we've grown the extent by a MAX_SIZE extent, this would mean we
1808 * need 2 outstanding extents, on one side we have 1 and the other side
1809 * we have 1 so they are == and we can return. But in this case
1811 * [MAX_SIZE+4k][MAX_SIZE+4k]
1813 * Each range on their own accounts for 2 extents, but merged together
1814 * they are only 3 extents worth of accounting, so we need to drop in
1817 old_size = other->end - other->start + 1;
1818 num_extents = count_max_extents(old_size);
1819 old_size = new->end - new->start + 1;
1820 num_extents += count_max_extents(old_size);
1821 if (count_max_extents(new_size) >= num_extents)
1824 spin_lock(&BTRFS_I(inode)->lock);
1825 btrfs_mod_outstanding_extents(BTRFS_I(inode), -1);
1826 spin_unlock(&BTRFS_I(inode)->lock);
1829 static void btrfs_add_delalloc_inodes(struct btrfs_root *root,
1830 struct inode *inode)
1832 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1834 spin_lock(&root->delalloc_lock);
1835 if (list_empty(&BTRFS_I(inode)->delalloc_inodes)) {
1836 list_add_tail(&BTRFS_I(inode)->delalloc_inodes,
1837 &root->delalloc_inodes);
1838 set_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1839 &BTRFS_I(inode)->runtime_flags);
1840 root->nr_delalloc_inodes++;
1841 if (root->nr_delalloc_inodes == 1) {
1842 spin_lock(&fs_info->delalloc_root_lock);
1843 BUG_ON(!list_empty(&root->delalloc_root));
1844 list_add_tail(&root->delalloc_root,
1845 &fs_info->delalloc_roots);
1846 spin_unlock(&fs_info->delalloc_root_lock);
1849 spin_unlock(&root->delalloc_lock);
1853 void __btrfs_del_delalloc_inode(struct btrfs_root *root,
1854 struct btrfs_inode *inode)
1856 struct btrfs_fs_info *fs_info = root->fs_info;
1858 if (!list_empty(&inode->delalloc_inodes)) {
1859 list_del_init(&inode->delalloc_inodes);
1860 clear_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1861 &inode->runtime_flags);
1862 root->nr_delalloc_inodes--;
1863 if (!root->nr_delalloc_inodes) {
1864 ASSERT(list_empty(&root->delalloc_inodes));
1865 spin_lock(&fs_info->delalloc_root_lock);
1866 BUG_ON(list_empty(&root->delalloc_root));
1867 list_del_init(&root->delalloc_root);
1868 spin_unlock(&fs_info->delalloc_root_lock);
1873 static void btrfs_del_delalloc_inode(struct btrfs_root *root,
1874 struct btrfs_inode *inode)
1876 spin_lock(&root->delalloc_lock);
1877 __btrfs_del_delalloc_inode(root, inode);
1878 spin_unlock(&root->delalloc_lock);
1882 * Properly track delayed allocation bytes in the inode and to maintain the
1883 * list of inodes that have pending delalloc work to be done.
1885 void btrfs_set_delalloc_extent(struct inode *inode, struct extent_state *state,
1888 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1890 if ((*bits & EXTENT_DEFRAG) && !(*bits & EXTENT_DELALLOC))
1893 * set_bit and clear bit hooks normally require _irqsave/restore
1894 * but in this case, we are only testing for the DELALLOC
1895 * bit, which is only set or cleared with irqs on
1897 if (!(state->state & EXTENT_DELALLOC) && (*bits & EXTENT_DELALLOC)) {
1898 struct btrfs_root *root = BTRFS_I(inode)->root;
1899 u64 len = state->end + 1 - state->start;
1900 u32 num_extents = count_max_extents(len);
1901 bool do_list = !btrfs_is_free_space_inode(BTRFS_I(inode));
1903 spin_lock(&BTRFS_I(inode)->lock);
1904 btrfs_mod_outstanding_extents(BTRFS_I(inode), num_extents);
1905 spin_unlock(&BTRFS_I(inode)->lock);
1907 /* For sanity tests */
1908 if (btrfs_is_testing(fs_info))
1911 percpu_counter_add_batch(&fs_info->delalloc_bytes, len,
1912 fs_info->delalloc_batch);
1913 spin_lock(&BTRFS_I(inode)->lock);
1914 BTRFS_I(inode)->delalloc_bytes += len;
1915 if (*bits & EXTENT_DEFRAG)
1916 BTRFS_I(inode)->defrag_bytes += len;
1917 if (do_list && !test_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1918 &BTRFS_I(inode)->runtime_flags))
1919 btrfs_add_delalloc_inodes(root, inode);
1920 spin_unlock(&BTRFS_I(inode)->lock);
1923 if (!(state->state & EXTENT_DELALLOC_NEW) &&
1924 (*bits & EXTENT_DELALLOC_NEW)) {
1925 spin_lock(&BTRFS_I(inode)->lock);
1926 BTRFS_I(inode)->new_delalloc_bytes += state->end + 1 -
1928 spin_unlock(&BTRFS_I(inode)->lock);
1933 * Once a range is no longer delalloc this function ensures that proper
1934 * accounting happens.
1936 void btrfs_clear_delalloc_extent(struct inode *vfs_inode,
1937 struct extent_state *state, unsigned *bits)
1939 struct btrfs_inode *inode = BTRFS_I(vfs_inode);
1940 struct btrfs_fs_info *fs_info = btrfs_sb(vfs_inode->i_sb);
1941 u64 len = state->end + 1 - state->start;
1942 u32 num_extents = count_max_extents(len);
1944 if ((state->state & EXTENT_DEFRAG) && (*bits & EXTENT_DEFRAG)) {
1945 spin_lock(&inode->lock);
1946 inode->defrag_bytes -= len;
1947 spin_unlock(&inode->lock);
1951 * set_bit and clear bit hooks normally require _irqsave/restore
1952 * but in this case, we are only testing for the DELALLOC
1953 * bit, which is only set or cleared with irqs on
1955 if ((state->state & EXTENT_DELALLOC) && (*bits & EXTENT_DELALLOC)) {
1956 struct btrfs_root *root = inode->root;
1957 bool do_list = !btrfs_is_free_space_inode(inode);
1959 spin_lock(&inode->lock);
1960 btrfs_mod_outstanding_extents(inode, -num_extents);
1961 spin_unlock(&inode->lock);
1964 * We don't reserve metadata space for space cache inodes so we
1965 * don't need to call delalloc_release_metadata if there is an
1968 if (*bits & EXTENT_CLEAR_META_RESV &&
1969 root != fs_info->tree_root)
1970 btrfs_delalloc_release_metadata(inode, len, false);
1972 /* For sanity tests. */
1973 if (btrfs_is_testing(fs_info))
1976 if (root->root_key.objectid != BTRFS_DATA_RELOC_TREE_OBJECTID &&
1977 do_list && !(state->state & EXTENT_NORESERVE) &&
1978 (*bits & EXTENT_CLEAR_DATA_RESV))
1979 btrfs_free_reserved_data_space_noquota(
1983 percpu_counter_add_batch(&fs_info->delalloc_bytes, -len,
1984 fs_info->delalloc_batch);
1985 spin_lock(&inode->lock);
1986 inode->delalloc_bytes -= len;
1987 if (do_list && inode->delalloc_bytes == 0 &&
1988 test_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1989 &inode->runtime_flags))
1990 btrfs_del_delalloc_inode(root, inode);
1991 spin_unlock(&inode->lock);
1994 if ((state->state & EXTENT_DELALLOC_NEW) &&
1995 (*bits & EXTENT_DELALLOC_NEW)) {
1996 spin_lock(&inode->lock);
1997 ASSERT(inode->new_delalloc_bytes >= len);
1998 inode->new_delalloc_bytes -= len;
1999 spin_unlock(&inode->lock);
2004 * btrfs_bio_fits_in_stripe - Checks whether the size of the given bio will fit
2005 * in a chunk's stripe. This function ensures that bios do not span a
2008 * @page - The page we are about to add to the bio
2009 * @size - size we want to add to the bio
2010 * @bio - bio we want to ensure is smaller than a stripe
2011 * @bio_flags - flags of the bio
2013 * return 1 if page cannot be added to the bio
2014 * return 0 if page can be added to the bio
2015 * return error otherwise
2017 int btrfs_bio_fits_in_stripe(struct page *page, size_t size, struct bio *bio,
2018 unsigned long bio_flags)
2020 struct inode *inode = page->mapping->host;
2021 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2022 u64 logical = (u64)bio->bi_iter.bi_sector << 9;
2026 struct btrfs_io_geometry geom;
2028 if (bio_flags & EXTENT_BIO_COMPRESSED)
2031 length = bio->bi_iter.bi_size;
2032 map_length = length;
2033 ret = btrfs_get_io_geometry(fs_info, btrfs_op(bio), logical, map_length,
2038 if (geom.len < length + size)
2044 * in order to insert checksums into the metadata in large chunks,
2045 * we wait until bio submission time. All the pages in the bio are
2046 * checksummed and sums are attached onto the ordered extent record.
2048 * At IO completion time the cums attached on the ordered extent record
2049 * are inserted into the btree
2051 static blk_status_t btrfs_submit_bio_start(void *private_data, struct bio *bio,
2054 struct inode *inode = private_data;
2055 blk_status_t ret = 0;
2057 ret = btrfs_csum_one_bio(inode, bio, 0, 0);
2058 BUG_ON(ret); /* -ENOMEM */
2063 * extent_io.c submission hook. This does the right thing for csum calculation
2064 * on write, or reading the csums from the tree before a read.
2066 * Rules about async/sync submit,
2067 * a) read: sync submit
2069 * b) write without checksum: sync submit
2071 * c) write with checksum:
2072 * c-1) if bio is issued by fsync: sync submit
2073 * (sync_writers != 0)
2075 * c-2) if root is reloc root: sync submit
2076 * (only in case of buffered IO)
2078 * c-3) otherwise: async submit
2080 static blk_status_t btrfs_submit_bio_hook(struct inode *inode, struct bio *bio,
2082 unsigned long bio_flags)
2085 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2086 struct btrfs_root *root = BTRFS_I(inode)->root;
2087 enum btrfs_wq_endio_type metadata = BTRFS_WQ_ENDIO_DATA;
2088 blk_status_t ret = 0;
2090 int async = !atomic_read(&BTRFS_I(inode)->sync_writers);
2092 skip_sum = BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM;
2094 if (btrfs_is_free_space_inode(BTRFS_I(inode)))
2095 metadata = BTRFS_WQ_ENDIO_FREE_SPACE;
2097 if (bio_op(bio) != REQ_OP_WRITE) {
2098 ret = btrfs_bio_wq_end_io(fs_info, bio, metadata);
2102 if (bio_flags & EXTENT_BIO_COMPRESSED) {
2103 ret = btrfs_submit_compressed_read(inode, bio,
2107 } else if (!skip_sum) {
2108 ret = btrfs_lookup_bio_sums(inode, bio, NULL);
2113 } else if (async && !skip_sum) {
2114 /* csum items have already been cloned */
2115 if (root->root_key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID)
2117 /* we're doing a write, do the async checksumming */
2118 ret = btrfs_wq_submit_bio(fs_info, bio, mirror_num, bio_flags,
2119 0, inode, btrfs_submit_bio_start);
2121 } else if (!skip_sum) {
2122 ret = btrfs_csum_one_bio(inode, bio, 0, 0);
2128 ret = btrfs_map_bio(fs_info, bio, mirror_num, 0);
2132 bio->bi_status = ret;
2139 * given a list of ordered sums record them in the inode. This happens
2140 * at IO completion time based on sums calculated at bio submission time.
2142 static noinline int add_pending_csums(struct btrfs_trans_handle *trans,
2143 struct inode *inode, struct list_head *list)
2145 struct btrfs_ordered_sum *sum;
2148 list_for_each_entry(sum, list, list) {
2149 trans->adding_csums = true;
2150 ret = btrfs_csum_file_blocks(trans,
2151 BTRFS_I(inode)->root->fs_info->csum_root, sum);
2152 trans->adding_csums = false;
2159 int btrfs_set_extent_delalloc(struct inode *inode, u64 start, u64 end,
2160 unsigned int extra_bits,
2161 struct extent_state **cached_state)
2163 WARN_ON(PAGE_ALIGNED(end));
2164 return set_extent_delalloc(&BTRFS_I(inode)->io_tree, start, end,
2165 extra_bits, cached_state);
2168 /* see btrfs_writepage_start_hook for details on why this is required */
2169 struct btrfs_writepage_fixup {
2171 struct btrfs_work work;
2174 static void btrfs_writepage_fixup_worker(struct btrfs_work *work)
2176 struct btrfs_writepage_fixup *fixup;
2177 struct btrfs_ordered_extent *ordered;
2178 struct extent_state *cached_state = NULL;
2179 struct extent_changeset *data_reserved = NULL;
2181 struct inode *inode;
2186 fixup = container_of(work, struct btrfs_writepage_fixup, work);
2190 if (!page->mapping || !PageDirty(page) || !PageChecked(page)) {
2191 ClearPageChecked(page);
2195 inode = page->mapping->host;
2196 page_start = page_offset(page);
2197 page_end = page_offset(page) + PAGE_SIZE - 1;
2199 lock_extent_bits(&BTRFS_I(inode)->io_tree, page_start, page_end,
2202 /* already ordered? We're done */
2203 if (PagePrivate2(page))
2206 ordered = btrfs_lookup_ordered_range(BTRFS_I(inode), page_start,
2209 unlock_extent_cached(&BTRFS_I(inode)->io_tree, page_start,
2210 page_end, &cached_state);
2212 btrfs_start_ordered_extent(inode, ordered, 1);
2213 btrfs_put_ordered_extent(ordered);
2217 ret = btrfs_delalloc_reserve_space(inode, &data_reserved, page_start,
2220 mapping_set_error(page->mapping, ret);
2221 end_extent_writepage(page, ret, page_start, page_end);
2222 ClearPageChecked(page);
2226 ret = btrfs_set_extent_delalloc(inode, page_start, page_end, 0,
2229 mapping_set_error(page->mapping, ret);
2230 end_extent_writepage(page, ret, page_start, page_end);
2231 ClearPageChecked(page);
2235 ClearPageChecked(page);
2236 set_page_dirty(page);
2238 btrfs_delalloc_release_extents(BTRFS_I(inode), PAGE_SIZE);
2240 btrfs_delalloc_release_space(inode, data_reserved, page_start,
2243 unlock_extent_cached(&BTRFS_I(inode)->io_tree, page_start, page_end,
2249 extent_changeset_free(data_reserved);
2253 * There are a few paths in the higher layers of the kernel that directly
2254 * set the page dirty bit without asking the filesystem if it is a
2255 * good idea. This causes problems because we want to make sure COW
2256 * properly happens and the data=ordered rules are followed.
2258 * In our case any range that doesn't have the ORDERED bit set
2259 * hasn't been properly setup for IO. We kick off an async process
2260 * to fix it up. The async helper will wait for ordered extents, set
2261 * the delalloc bit and make it safe to write the page.
2263 int btrfs_writepage_cow_fixup(struct page *page, u64 start, u64 end)
2265 struct inode *inode = page->mapping->host;
2266 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2267 struct btrfs_writepage_fixup *fixup;
2269 /* this page is properly in the ordered list */
2270 if (TestClearPagePrivate2(page))
2273 if (PageChecked(page))
2276 fixup = kzalloc(sizeof(*fixup), GFP_NOFS);
2280 SetPageChecked(page);
2282 btrfs_init_work(&fixup->work, btrfs_writepage_fixup_worker, NULL, NULL);
2284 btrfs_queue_work(fs_info->fixup_workers, &fixup->work);
2288 static int insert_reserved_file_extent(struct btrfs_trans_handle *trans,
2289 struct inode *inode, u64 file_pos,
2290 u64 disk_bytenr, u64 disk_num_bytes,
2291 u64 num_bytes, u64 ram_bytes,
2292 u8 compression, u8 encryption,
2293 u16 other_encoding, int extent_type)
2295 struct btrfs_root *root = BTRFS_I(inode)->root;
2296 struct btrfs_file_extent_item *fi;
2297 struct btrfs_path *path;
2298 struct extent_buffer *leaf;
2299 struct btrfs_key ins;
2301 int extent_inserted = 0;
2304 path = btrfs_alloc_path();
2309 * we may be replacing one extent in the tree with another.
2310 * The new extent is pinned in the extent map, and we don't want
2311 * to drop it from the cache until it is completely in the btree.
2313 * So, tell btrfs_drop_extents to leave this extent in the cache.
2314 * the caller is expected to unpin it and allow it to be merged
2317 ret = __btrfs_drop_extents(trans, root, inode, path, file_pos,
2318 file_pos + num_bytes, NULL, 0,
2319 1, sizeof(*fi), &extent_inserted);
2323 if (!extent_inserted) {
2324 ins.objectid = btrfs_ino(BTRFS_I(inode));
2325 ins.offset = file_pos;
2326 ins.type = BTRFS_EXTENT_DATA_KEY;
2328 path->leave_spinning = 1;
2329 ret = btrfs_insert_empty_item(trans, root, path, &ins,
2334 leaf = path->nodes[0];
2335 fi = btrfs_item_ptr(leaf, path->slots[0],
2336 struct btrfs_file_extent_item);
2337 btrfs_set_file_extent_generation(leaf, fi, trans->transid);
2338 btrfs_set_file_extent_type(leaf, fi, extent_type);
2339 btrfs_set_file_extent_disk_bytenr(leaf, fi, disk_bytenr);
2340 btrfs_set_file_extent_disk_num_bytes(leaf, fi, disk_num_bytes);
2341 btrfs_set_file_extent_offset(leaf, fi, 0);
2342 btrfs_set_file_extent_num_bytes(leaf, fi, num_bytes);
2343 btrfs_set_file_extent_ram_bytes(leaf, fi, ram_bytes);
2344 btrfs_set_file_extent_compression(leaf, fi, compression);
2345 btrfs_set_file_extent_encryption(leaf, fi, encryption);
2346 btrfs_set_file_extent_other_encoding(leaf, fi, other_encoding);
2348 btrfs_mark_buffer_dirty(leaf);
2349 btrfs_release_path(path);
2351 inode_add_bytes(inode, num_bytes);
2353 ins.objectid = disk_bytenr;
2354 ins.offset = disk_num_bytes;
2355 ins.type = BTRFS_EXTENT_ITEM_KEY;
2358 * Release the reserved range from inode dirty range map, as it is
2359 * already moved into delayed_ref_head
2361 ret = btrfs_qgroup_release_data(inode, file_pos, ram_bytes);
2365 ret = btrfs_alloc_reserved_file_extent(trans, root,
2366 btrfs_ino(BTRFS_I(inode)),
2367 file_pos, qg_released, &ins);
2369 btrfs_free_path(path);
2374 /* snapshot-aware defrag */
2375 struct sa_defrag_extent_backref {
2376 struct rb_node node;
2377 struct old_sa_defrag_extent *old;
2386 struct old_sa_defrag_extent {
2387 struct list_head list;
2388 struct new_sa_defrag_extent *new;
2397 struct new_sa_defrag_extent {
2398 struct rb_root root;
2399 struct list_head head;
2400 struct btrfs_path *path;
2401 struct inode *inode;
2409 static int backref_comp(struct sa_defrag_extent_backref *b1,
2410 struct sa_defrag_extent_backref *b2)
2412 if (b1->root_id < b2->root_id)
2414 else if (b1->root_id > b2->root_id)
2417 if (b1->inum < b2->inum)
2419 else if (b1->inum > b2->inum)
2422 if (b1->file_pos < b2->file_pos)
2424 else if (b1->file_pos > b2->file_pos)
2428 * [------------------------------] ===> (a range of space)
2429 * |<--->| |<---->| =============> (fs/file tree A)
2430 * |<---------------------------->| ===> (fs/file tree B)
2432 * A range of space can refer to two file extents in one tree while
2433 * refer to only one file extent in another tree.
2435 * So we may process a disk offset more than one time(two extents in A)
2436 * and locate at the same extent(one extent in B), then insert two same
2437 * backrefs(both refer to the extent in B).
2442 static void backref_insert(struct rb_root *root,
2443 struct sa_defrag_extent_backref *backref)
2445 struct rb_node **p = &root->rb_node;
2446 struct rb_node *parent = NULL;
2447 struct sa_defrag_extent_backref *entry;
2452 entry = rb_entry(parent, struct sa_defrag_extent_backref, node);
2454 ret = backref_comp(backref, entry);
2458 p = &(*p)->rb_right;
2461 rb_link_node(&backref->node, parent, p);
2462 rb_insert_color(&backref->node, root);
2466 * Note the backref might has changed, and in this case we just return 0.
2468 static noinline int record_one_backref(u64 inum, u64 offset, u64 root_id,
2471 struct btrfs_file_extent_item *extent;
2472 struct old_sa_defrag_extent *old = ctx;
2473 struct new_sa_defrag_extent *new = old->new;
2474 struct btrfs_path *path = new->path;
2475 struct btrfs_key key;
2476 struct btrfs_root *root;
2477 struct sa_defrag_extent_backref *backref;
2478 struct extent_buffer *leaf;
2479 struct inode *inode = new->inode;
2480 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2486 if (BTRFS_I(inode)->root->root_key.objectid == root_id &&
2487 inum == btrfs_ino(BTRFS_I(inode)))
2490 key.objectid = root_id;
2491 key.type = BTRFS_ROOT_ITEM_KEY;
2492 key.offset = (u64)-1;
2494 root = btrfs_read_fs_root_no_name(fs_info, &key);
2496 if (PTR_ERR(root) == -ENOENT)
2499 btrfs_debug(fs_info, "inum=%llu, offset=%llu, root_id=%llu",
2500 inum, offset, root_id);
2501 return PTR_ERR(root);
2504 key.objectid = inum;
2505 key.type = BTRFS_EXTENT_DATA_KEY;
2506 if (offset > (u64)-1 << 32)
2509 key.offset = offset;
2511 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2512 if (WARN_ON(ret < 0))
2519 leaf = path->nodes[0];
2520 slot = path->slots[0];
2522 if (slot >= btrfs_header_nritems(leaf)) {
2523 ret = btrfs_next_leaf(root, path);
2526 } else if (ret > 0) {
2535 btrfs_item_key_to_cpu(leaf, &key, slot);
2537 if (key.objectid > inum)
2540 if (key.objectid < inum || key.type != BTRFS_EXTENT_DATA_KEY)
2543 extent = btrfs_item_ptr(leaf, slot,
2544 struct btrfs_file_extent_item);
2546 if (btrfs_file_extent_disk_bytenr(leaf, extent) != old->bytenr)
2550 * 'offset' refers to the exact key.offset,
2551 * NOT the 'offset' field in btrfs_extent_data_ref, ie.
2552 * (key.offset - extent_offset).
2554 if (key.offset != offset)
2557 extent_offset = btrfs_file_extent_offset(leaf, extent);
2558 num_bytes = btrfs_file_extent_num_bytes(leaf, extent);
2560 if (extent_offset >= old->extent_offset + old->offset +
2561 old->len || extent_offset + num_bytes <=
2562 old->extent_offset + old->offset)
2567 backref = kmalloc(sizeof(*backref), GFP_NOFS);
2573 backref->root_id = root_id;
2574 backref->inum = inum;
2575 backref->file_pos = offset;
2576 backref->num_bytes = num_bytes;
2577 backref->extent_offset = extent_offset;
2578 backref->generation = btrfs_file_extent_generation(leaf, extent);
2580 backref_insert(&new->root, backref);
2583 btrfs_release_path(path);
2588 static noinline bool record_extent_backrefs(struct btrfs_path *path,
2589 struct new_sa_defrag_extent *new)
2591 struct btrfs_fs_info *fs_info = btrfs_sb(new->inode->i_sb);
2592 struct old_sa_defrag_extent *old, *tmp;
2597 list_for_each_entry_safe(old, tmp, &new->head, list) {
2598 ret = iterate_inodes_from_logical(old->bytenr +
2599 old->extent_offset, fs_info,
2600 path, record_one_backref,
2602 if (ret < 0 && ret != -ENOENT)
2605 /* no backref to be processed for this extent */
2607 list_del(&old->list);
2612 if (list_empty(&new->head))
2618 static int relink_is_mergable(struct extent_buffer *leaf,
2619 struct btrfs_file_extent_item *fi,
2620 struct new_sa_defrag_extent *new)
2622 if (btrfs_file_extent_disk_bytenr(leaf, fi) != new->bytenr)
2625 if (btrfs_file_extent_type(leaf, fi) != BTRFS_FILE_EXTENT_REG)
2628 if (btrfs_file_extent_compression(leaf, fi) != new->compress_type)
2631 if (btrfs_file_extent_encryption(leaf, fi) ||
2632 btrfs_file_extent_other_encoding(leaf, fi))
2639 * Note the backref might has changed, and in this case we just return 0.
2641 static noinline int relink_extent_backref(struct btrfs_path *path,
2642 struct sa_defrag_extent_backref *prev,
2643 struct sa_defrag_extent_backref *backref)
2645 struct btrfs_file_extent_item *extent;
2646 struct btrfs_file_extent_item *item;
2647 struct btrfs_ordered_extent *ordered;
2648 struct btrfs_trans_handle *trans;
2649 struct btrfs_ref ref = { 0 };
2650 struct btrfs_root *root;
2651 struct btrfs_key key;
2652 struct extent_buffer *leaf;
2653 struct old_sa_defrag_extent *old = backref->old;
2654 struct new_sa_defrag_extent *new = old->new;
2655 struct btrfs_fs_info *fs_info = btrfs_sb(new->inode->i_sb);
2656 struct inode *inode;
2657 struct extent_state *cached = NULL;
2666 if (prev && prev->root_id == backref->root_id &&
2667 prev->inum == backref->inum &&
2668 prev->file_pos + prev->num_bytes == backref->file_pos)
2671 /* step 1: get root */
2672 key.objectid = backref->root_id;
2673 key.type = BTRFS_ROOT_ITEM_KEY;
2674 key.offset = (u64)-1;
2676 index = srcu_read_lock(&fs_info->subvol_srcu);
2678 root = btrfs_read_fs_root_no_name(fs_info, &key);
2680 srcu_read_unlock(&fs_info->subvol_srcu, index);
2681 if (PTR_ERR(root) == -ENOENT)
2683 return PTR_ERR(root);
2686 if (btrfs_root_readonly(root)) {
2687 srcu_read_unlock(&fs_info->subvol_srcu, index);
2691 /* step 2: get inode */
2692 key.objectid = backref->inum;
2693 key.type = BTRFS_INODE_ITEM_KEY;
2696 inode = btrfs_iget(fs_info->sb, &key, root, NULL);
2697 if (IS_ERR(inode)) {
2698 srcu_read_unlock(&fs_info->subvol_srcu, index);
2702 srcu_read_unlock(&fs_info->subvol_srcu, index);
2704 /* step 3: relink backref */
2705 lock_start = backref->file_pos;
2706 lock_end = backref->file_pos + backref->num_bytes - 1;
2707 lock_extent_bits(&BTRFS_I(inode)->io_tree, lock_start, lock_end,
2710 ordered = btrfs_lookup_first_ordered_extent(inode, lock_end);
2712 btrfs_put_ordered_extent(ordered);
2716 trans = btrfs_join_transaction(root);
2717 if (IS_ERR(trans)) {
2718 ret = PTR_ERR(trans);
2722 key.objectid = backref->inum;
2723 key.type = BTRFS_EXTENT_DATA_KEY;
2724 key.offset = backref->file_pos;
2726 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2729 } else if (ret > 0) {
2734 extent = btrfs_item_ptr(path->nodes[0], path->slots[0],
2735 struct btrfs_file_extent_item);
2737 if (btrfs_file_extent_generation(path->nodes[0], extent) !=
2738 backref->generation)
2741 btrfs_release_path(path);
2743 start = backref->file_pos;
2744 if (backref->extent_offset < old->extent_offset + old->offset)
2745 start += old->extent_offset + old->offset -
2746 backref->extent_offset;
2748 len = min(backref->extent_offset + backref->num_bytes,
2749 old->extent_offset + old->offset + old->len);
2750 len -= max(backref->extent_offset, old->extent_offset + old->offset);
2752 ret = btrfs_drop_extents(trans, root, inode, start,
2757 key.objectid = btrfs_ino(BTRFS_I(inode));
2758 key.type = BTRFS_EXTENT_DATA_KEY;
2761 path->leave_spinning = 1;
2763 struct btrfs_file_extent_item *fi;
2765 struct btrfs_key found_key;
2767 ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
2772 leaf = path->nodes[0];
2773 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
2775 fi = btrfs_item_ptr(leaf, path->slots[0],
2776 struct btrfs_file_extent_item);
2777 extent_len = btrfs_file_extent_num_bytes(leaf, fi);
2779 if (extent_len + found_key.offset == start &&
2780 relink_is_mergable(leaf, fi, new)) {
2781 btrfs_set_file_extent_num_bytes(leaf, fi,
2783 btrfs_mark_buffer_dirty(leaf);
2784 inode_add_bytes(inode, len);
2790 btrfs_release_path(path);
2795 ret = btrfs_insert_empty_item(trans, root, path, &key,
2798 btrfs_abort_transaction(trans, ret);
2802 leaf = path->nodes[0];
2803 item = btrfs_item_ptr(leaf, path->slots[0],
2804 struct btrfs_file_extent_item);
2805 btrfs_set_file_extent_disk_bytenr(leaf, item, new->bytenr);
2806 btrfs_set_file_extent_disk_num_bytes(leaf, item, new->disk_len);
2807 btrfs_set_file_extent_offset(leaf, item, start - new->file_pos);
2808 btrfs_set_file_extent_num_bytes(leaf, item, len);
2809 btrfs_set_file_extent_ram_bytes(leaf, item, new->len);
2810 btrfs_set_file_extent_generation(leaf, item, trans->transid);
2811 btrfs_set_file_extent_type(leaf, item, BTRFS_FILE_EXTENT_REG);
2812 btrfs_set_file_extent_compression(leaf, item, new->compress_type);
2813 btrfs_set_file_extent_encryption(leaf, item, 0);
2814 btrfs_set_file_extent_other_encoding(leaf, item, 0);
2816 btrfs_mark_buffer_dirty(leaf);
2817 inode_add_bytes(inode, len);
2818 btrfs_release_path(path);
2820 btrfs_init_generic_ref(&ref, BTRFS_ADD_DELAYED_REF, new->bytenr,
2822 btrfs_init_data_ref(&ref, backref->root_id, backref->inum,
2823 new->file_pos); /* start - extent_offset */
2824 ret = btrfs_inc_extent_ref(trans, &ref);
2826 btrfs_abort_transaction(trans, ret);
2832 btrfs_release_path(path);
2833 path->leave_spinning = 0;
2834 btrfs_end_transaction(trans);
2836 unlock_extent_cached(&BTRFS_I(inode)->io_tree, lock_start, lock_end,
2842 static void free_sa_defrag_extent(struct new_sa_defrag_extent *new)
2844 struct old_sa_defrag_extent *old, *tmp;
2849 list_for_each_entry_safe(old, tmp, &new->head, list) {
2855 static void relink_file_extents(struct new_sa_defrag_extent *new)
2857 struct btrfs_fs_info *fs_info = btrfs_sb(new->inode->i_sb);
2858 struct btrfs_path *path;
2859 struct sa_defrag_extent_backref *backref;
2860 struct sa_defrag_extent_backref *prev = NULL;
2861 struct rb_node *node;
2864 path = btrfs_alloc_path();
2868 if (!record_extent_backrefs(path, new)) {
2869 btrfs_free_path(path);
2872 btrfs_release_path(path);
2875 node = rb_first(&new->root);
2878 rb_erase(node, &new->root);
2880 backref = rb_entry(node, struct sa_defrag_extent_backref, node);
2882 ret = relink_extent_backref(path, prev, backref);
2895 btrfs_free_path(path);
2897 free_sa_defrag_extent(new);
2899 atomic_dec(&fs_info->defrag_running);
2900 wake_up(&fs_info->transaction_wait);
2903 static struct new_sa_defrag_extent *
2904 record_old_file_extents(struct inode *inode,
2905 struct btrfs_ordered_extent *ordered)
2907 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2908 struct btrfs_root *root = BTRFS_I(inode)->root;
2909 struct btrfs_path *path;
2910 struct btrfs_key key;
2911 struct old_sa_defrag_extent *old;
2912 struct new_sa_defrag_extent *new;
2915 new = kmalloc(sizeof(*new), GFP_NOFS);
2920 new->file_pos = ordered->file_offset;
2921 new->len = ordered->len;
2922 new->bytenr = ordered->start;
2923 new->disk_len = ordered->disk_len;
2924 new->compress_type = ordered->compress_type;
2925 new->root = RB_ROOT;
2926 INIT_LIST_HEAD(&new->head);
2928 path = btrfs_alloc_path();
2932 key.objectid = btrfs_ino(BTRFS_I(inode));
2933 key.type = BTRFS_EXTENT_DATA_KEY;
2934 key.offset = new->file_pos;
2936 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2939 if (ret > 0 && path->slots[0] > 0)
2942 /* find out all the old extents for the file range */
2944 struct btrfs_file_extent_item *extent;
2945 struct extent_buffer *l;
2954 slot = path->slots[0];
2956 if (slot >= btrfs_header_nritems(l)) {
2957 ret = btrfs_next_leaf(root, path);
2965 btrfs_item_key_to_cpu(l, &key, slot);
2967 if (key.objectid != btrfs_ino(BTRFS_I(inode)))
2969 if (key.type != BTRFS_EXTENT_DATA_KEY)
2971 if (key.offset >= new->file_pos + new->len)
2974 extent = btrfs_item_ptr(l, slot, struct btrfs_file_extent_item);
2976 num_bytes = btrfs_file_extent_num_bytes(l, extent);
2977 if (key.offset + num_bytes < new->file_pos)
2980 disk_bytenr = btrfs_file_extent_disk_bytenr(l, extent);
2984 extent_offset = btrfs_file_extent_offset(l, extent);
2986 old = kmalloc(sizeof(*old), GFP_NOFS);
2990 offset = max(new->file_pos, key.offset);
2991 end = min(new->file_pos + new->len, key.offset + num_bytes);
2993 old->bytenr = disk_bytenr;
2994 old->extent_offset = extent_offset;
2995 old->offset = offset - key.offset;
2996 old->len = end - offset;
2999 list_add_tail(&old->list, &new->head);
3005 btrfs_free_path(path);
3006 atomic_inc(&fs_info->defrag_running);
3011 btrfs_free_path(path);
3013 free_sa_defrag_extent(new);
3017 static void btrfs_release_delalloc_bytes(struct btrfs_fs_info *fs_info,
3020 struct btrfs_block_group_cache *cache;
3022 cache = btrfs_lookup_block_group(fs_info, start);
3025 spin_lock(&cache->lock);
3026 cache->delalloc_bytes -= len;
3027 spin_unlock(&cache->lock);
3029 btrfs_put_block_group(cache);
3032 /* as ordered data IO finishes, this gets called so we can finish
3033 * an ordered extent if the range of bytes in the file it covers are
3036 static int btrfs_finish_ordered_io(struct btrfs_ordered_extent *ordered_extent)
3038 struct inode *inode = ordered_extent->inode;
3039 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
3040 struct btrfs_root *root = BTRFS_I(inode)->root;
3041 struct btrfs_trans_handle *trans = NULL;
3042 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
3043 struct extent_state *cached_state = NULL;
3044 struct new_sa_defrag_extent *new = NULL;
3045 int compress_type = 0;
3047 u64 logical_len = ordered_extent->len;
3049 bool truncated = false;
3050 bool range_locked = false;
3051 bool clear_new_delalloc_bytes = false;
3052 bool clear_reserved_extent = true;
3054 if (!test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags) &&
3055 !test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags) &&
3056 !test_bit(BTRFS_ORDERED_DIRECT, &ordered_extent->flags))
3057 clear_new_delalloc_bytes = true;
3059 nolock = btrfs_is_free_space_inode(BTRFS_I(inode));
3061 if (test_bit(BTRFS_ORDERED_IOERR, &ordered_extent->flags)) {
3066 btrfs_free_io_failure_record(BTRFS_I(inode),
3067 ordered_extent->file_offset,
3068 ordered_extent->file_offset +
3069 ordered_extent->len - 1);
3071 if (test_bit(BTRFS_ORDERED_TRUNCATED, &ordered_extent->flags)) {
3073 logical_len = ordered_extent->truncated_len;
3074 /* Truncated the entire extent, don't bother adding */
3079 if (test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags)) {
3080 BUG_ON(!list_empty(&ordered_extent->list)); /* Logic error */
3083 * For mwrite(mmap + memset to write) case, we still reserve
3084 * space for NOCOW range.
3085 * As NOCOW won't cause a new delayed ref, just free the space
3087 btrfs_qgroup_free_data(inode, NULL, ordered_extent->file_offset,
3088 ordered_extent->len);
3089 btrfs_ordered_update_i_size(inode, 0, ordered_extent);
3091 trans = btrfs_join_transaction_nolock(root);
3093 trans = btrfs_join_transaction(root);
3094 if (IS_ERR(trans)) {
3095 ret = PTR_ERR(trans);
3099 trans->block_rsv = &BTRFS_I(inode)->block_rsv;
3100 ret = btrfs_update_inode_fallback(trans, root, inode);
3101 if (ret) /* -ENOMEM or corruption */
3102 btrfs_abort_transaction(trans, ret);
3106 range_locked = true;
3107 lock_extent_bits(io_tree, ordered_extent->file_offset,
3108 ordered_extent->file_offset + ordered_extent->len - 1,
3111 ret = test_range_bit(io_tree, ordered_extent->file_offset,
3112 ordered_extent->file_offset + ordered_extent->len - 1,
3113 EXTENT_DEFRAG, 0, cached_state);
3115 u64 last_snapshot = btrfs_root_last_snapshot(&root->root_item);
3116 if (0 && last_snapshot >= BTRFS_I(inode)->generation)
3117 /* the inode is shared */
3118 new = record_old_file_extents(inode, ordered_extent);
3120 clear_extent_bit(io_tree, ordered_extent->file_offset,
3121 ordered_extent->file_offset + ordered_extent->len - 1,
3122 EXTENT_DEFRAG, 0, 0, &cached_state);
3126 trans = btrfs_join_transaction_nolock(root);
3128 trans = btrfs_join_transaction(root);
3129 if (IS_ERR(trans)) {
3130 ret = PTR_ERR(trans);
3135 trans->block_rsv = &BTRFS_I(inode)->block_rsv;
3137 if (test_bit(BTRFS_ORDERED_COMPRESSED, &ordered_extent->flags))
3138 compress_type = ordered_extent->compress_type;
3139 if (test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags)) {
3140 BUG_ON(compress_type);
3141 btrfs_qgroup_free_data(inode, NULL, ordered_extent->file_offset,
3142 ordered_extent->len);
3143 ret = btrfs_mark_extent_written(trans, BTRFS_I(inode),
3144 ordered_extent->file_offset,
3145 ordered_extent->file_offset +
3148 BUG_ON(root == fs_info->tree_root);
3149 ret = insert_reserved_file_extent(trans, inode,
3150 ordered_extent->file_offset,
3151 ordered_extent->start,
3152 ordered_extent->disk_len,
3153 logical_len, logical_len,
3154 compress_type, 0, 0,
3155 BTRFS_FILE_EXTENT_REG);
3157 clear_reserved_extent = false;
3158 btrfs_release_delalloc_bytes(fs_info,
3159 ordered_extent->start,
3160 ordered_extent->disk_len);
3163 unpin_extent_cache(&BTRFS_I(inode)->extent_tree,
3164 ordered_extent->file_offset, ordered_extent->len,
3167 btrfs_abort_transaction(trans, ret);
3171 ret = add_pending_csums(trans, inode, &ordered_extent->list);
3173 btrfs_abort_transaction(trans, ret);
3177 btrfs_ordered_update_i_size(inode, 0, ordered_extent);
3178 ret = btrfs_update_inode_fallback(trans, root, inode);
3179 if (ret) { /* -ENOMEM or corruption */
3180 btrfs_abort_transaction(trans, ret);
3185 if (range_locked || clear_new_delalloc_bytes) {
3186 unsigned int clear_bits = 0;
3189 clear_bits |= EXTENT_LOCKED;
3190 if (clear_new_delalloc_bytes)
3191 clear_bits |= EXTENT_DELALLOC_NEW;
3192 clear_extent_bit(&BTRFS_I(inode)->io_tree,
3193 ordered_extent->file_offset,
3194 ordered_extent->file_offset +
3195 ordered_extent->len - 1,
3197 (clear_bits & EXTENT_LOCKED) ? 1 : 0,
3202 btrfs_end_transaction(trans);
3204 if (ret || truncated) {
3208 start = ordered_extent->file_offset + logical_len;
3210 start = ordered_extent->file_offset;
3211 end = ordered_extent->file_offset + ordered_extent->len - 1;
3212 clear_extent_uptodate(io_tree, start, end, NULL);
3214 /* Drop the cache for the part of the extent we didn't write. */
3215 btrfs_drop_extent_cache(BTRFS_I(inode), start, end, 0);
3218 * If the ordered extent had an IOERR or something else went
3219 * wrong we need to return the space for this ordered extent
3220 * back to the allocator. We only free the extent in the
3221 * truncated case if we didn't write out the extent at all.
3223 * If we made it past insert_reserved_file_extent before we
3224 * errored out then we don't need to do this as the accounting
3225 * has already been done.
3227 if ((ret || !logical_len) &&
3228 clear_reserved_extent &&
3229 !test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags) &&
3230 !test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags))
3231 btrfs_free_reserved_extent(fs_info,
3232 ordered_extent->start,
3233 ordered_extent->disk_len, 1);
3238 * This needs to be done to make sure anybody waiting knows we are done
3239 * updating everything for this ordered extent.
3241 btrfs_remove_ordered_extent(inode, ordered_extent);
3243 /* for snapshot-aware defrag */
3246 free_sa_defrag_extent(new);
3247 atomic_dec(&fs_info->defrag_running);
3249 relink_file_extents(new);
3254 btrfs_put_ordered_extent(ordered_extent);
3255 /* once for the tree */
3256 btrfs_put_ordered_extent(ordered_extent);
3261 static void finish_ordered_fn(struct btrfs_work *work)
3263 struct btrfs_ordered_extent *ordered_extent;
3264 ordered_extent = container_of(work, struct btrfs_ordered_extent, work);
3265 btrfs_finish_ordered_io(ordered_extent);
3268 void btrfs_writepage_endio_finish_ordered(struct page *page, u64 start,
3269 u64 end, int uptodate)
3271 struct inode *inode = page->mapping->host;
3272 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
3273 struct btrfs_ordered_extent *ordered_extent = NULL;
3274 struct btrfs_workqueue *wq;
3276 trace_btrfs_writepage_end_io_hook(page, start, end, uptodate);
3278 ClearPagePrivate2(page);
3279 if (!btrfs_dec_test_ordered_pending(inode, &ordered_extent, start,
3280 end - start + 1, uptodate))
3283 if (btrfs_is_free_space_inode(BTRFS_I(inode)))
3284 wq = fs_info->endio_freespace_worker;
3286 wq = fs_info->endio_write_workers;
3288 btrfs_init_work(&ordered_extent->work, finish_ordered_fn, NULL, NULL);
3289 btrfs_queue_work(wq, &ordered_extent->work);
3292 static int __readpage_endio_check(struct inode *inode,
3293 struct btrfs_io_bio *io_bio,
3294 int icsum, struct page *page,
3295 int pgoff, u64 start, size_t len)
3297 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
3298 SHASH_DESC_ON_STACK(shash, fs_info->csum_shash);
3300 u16 csum_size = btrfs_super_csum_size(fs_info->super_copy);
3302 u8 csum[BTRFS_CSUM_SIZE];
3304 csum_expected = ((u8 *)io_bio->csum) + icsum * csum_size;
3306 kaddr = kmap_atomic(page);
3307 shash->tfm = fs_info->csum_shash;
3309 crypto_shash_init(shash);
3310 crypto_shash_update(shash, kaddr + pgoff, len);
3311 crypto_shash_final(shash, csum);
3313 if (memcmp(csum, csum_expected, csum_size))
3316 kunmap_atomic(kaddr);
3319 btrfs_print_data_csum_error(BTRFS_I(inode), start, csum, csum_expected,
3320 io_bio->mirror_num);
3321 memset(kaddr + pgoff, 1, len);
3322 flush_dcache_page(page);
3323 kunmap_atomic(kaddr);
3328 * when reads are done, we need to check csums to verify the data is correct
3329 * if there's a match, we allow the bio to finish. If not, the code in
3330 * extent_io.c will try to find good copies for us.
3332 static int btrfs_readpage_end_io_hook(struct btrfs_io_bio *io_bio,
3333 u64 phy_offset, struct page *page,
3334 u64 start, u64 end, int mirror)
3336 size_t offset = start - page_offset(page);
3337 struct inode *inode = page->mapping->host;
3338 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
3339 struct btrfs_root *root = BTRFS_I(inode)->root;
3341 if (PageChecked(page)) {
3342 ClearPageChecked(page);
3346 if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)
3349 if (root->root_key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID &&
3350 test_range_bit(io_tree, start, end, EXTENT_NODATASUM, 1, NULL)) {
3351 clear_extent_bits(io_tree, start, end, EXTENT_NODATASUM);
3355 phy_offset >>= inode->i_sb->s_blocksize_bits;
3356 return __readpage_endio_check(inode, io_bio, phy_offset, page, offset,
3357 start, (size_t)(end - start + 1));
3361 * btrfs_add_delayed_iput - perform a delayed iput on @inode
3363 * @inode: The inode we want to perform iput on
3365 * This function uses the generic vfs_inode::i_count to track whether we should
3366 * just decrement it (in case it's > 1) or if this is the last iput then link
3367 * the inode to the delayed iput machinery. Delayed iputs are processed at
3368 * transaction commit time/superblock commit/cleaner kthread.
3370 void btrfs_add_delayed_iput(struct inode *inode)
3372 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
3373 struct btrfs_inode *binode = BTRFS_I(inode);
3375 if (atomic_add_unless(&inode->i_count, -1, 1))
3378 atomic_inc(&fs_info->nr_delayed_iputs);
3379 spin_lock(&fs_info->delayed_iput_lock);
3380 ASSERT(list_empty(&binode->delayed_iput));
3381 list_add_tail(&binode->delayed_iput, &fs_info->delayed_iputs);
3382 spin_unlock(&fs_info->delayed_iput_lock);
3383 if (!test_bit(BTRFS_FS_CLEANER_RUNNING, &fs_info->flags))
3384 wake_up_process(fs_info->cleaner_kthread);
3387 static void run_delayed_iput_locked(struct btrfs_fs_info *fs_info,
3388 struct btrfs_inode *inode)
3390 list_del_init(&inode->delayed_iput);
3391 spin_unlock(&fs_info->delayed_iput_lock);
3392 iput(&inode->vfs_inode);
3393 if (atomic_dec_and_test(&fs_info->nr_delayed_iputs))
3394 wake_up(&fs_info->delayed_iputs_wait);
3395 spin_lock(&fs_info->delayed_iput_lock);
3398 static void btrfs_run_delayed_iput(struct btrfs_fs_info *fs_info,
3399 struct btrfs_inode *inode)
3401 if (!list_empty(&inode->delayed_iput)) {
3402 spin_lock(&fs_info->delayed_iput_lock);
3403 if (!list_empty(&inode->delayed_iput))
3404 run_delayed_iput_locked(fs_info, inode);
3405 spin_unlock(&fs_info->delayed_iput_lock);
3409 void btrfs_run_delayed_iputs(struct btrfs_fs_info *fs_info)
3412 spin_lock(&fs_info->delayed_iput_lock);
3413 while (!list_empty(&fs_info->delayed_iputs)) {
3414 struct btrfs_inode *inode;
3416 inode = list_first_entry(&fs_info->delayed_iputs,
3417 struct btrfs_inode, delayed_iput);
3418 run_delayed_iput_locked(fs_info, inode);
3420 spin_unlock(&fs_info->delayed_iput_lock);
3424 * btrfs_wait_on_delayed_iputs - wait on the delayed iputs to be done running
3425 * @fs_info - the fs_info for this fs
3426 * @return - EINTR if we were killed, 0 if nothing's pending
3428 * This will wait on any delayed iputs that are currently running with KILLABLE
3429 * set. Once they are all done running we will return, unless we are killed in
3430 * which case we return EINTR. This helps in user operations like fallocate etc
3431 * that might get blocked on the iputs.
3433 int btrfs_wait_on_delayed_iputs(struct btrfs_fs_info *fs_info)
3435 int ret = wait_event_killable(fs_info->delayed_iputs_wait,
3436 atomic_read(&fs_info->nr_delayed_iputs) == 0);
3443 * This creates an orphan entry for the given inode in case something goes wrong
3444 * in the middle of an unlink.
3446 int btrfs_orphan_add(struct btrfs_trans_handle *trans,
3447 struct btrfs_inode *inode)
3451 ret = btrfs_insert_orphan_item(trans, inode->root, btrfs_ino(inode));
3452 if (ret && ret != -EEXIST) {
3453 btrfs_abort_transaction(trans, ret);
3461 * We have done the delete so we can go ahead and remove the orphan item for
3462 * this particular inode.
3464 static int btrfs_orphan_del(struct btrfs_trans_handle *trans,
3465 struct btrfs_inode *inode)
3467 return btrfs_del_orphan_item(trans, inode->root, btrfs_ino(inode));
3471 * this cleans up any orphans that may be left on the list from the last use
3474 int btrfs_orphan_cleanup(struct btrfs_root *root)
3476 struct btrfs_fs_info *fs_info = root->fs_info;
3477 struct btrfs_path *path;
3478 struct extent_buffer *leaf;
3479 struct btrfs_key key, found_key;
3480 struct btrfs_trans_handle *trans;
3481 struct inode *inode;
3482 u64 last_objectid = 0;
3483 int ret = 0, nr_unlink = 0;
3485 if (cmpxchg(&root->orphan_cleanup_state, 0, ORPHAN_CLEANUP_STARTED))
3488 path = btrfs_alloc_path();
3493 path->reada = READA_BACK;
3495 key.objectid = BTRFS_ORPHAN_OBJECTID;
3496 key.type = BTRFS_ORPHAN_ITEM_KEY;
3497 key.offset = (u64)-1;
3500 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
3505 * if ret == 0 means we found what we were searching for, which
3506 * is weird, but possible, so only screw with path if we didn't
3507 * find the key and see if we have stuff that matches
3511 if (path->slots[0] == 0)
3516 /* pull out the item */
3517 leaf = path->nodes[0];
3518 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
3520 /* make sure the item matches what we want */
3521 if (found_key.objectid != BTRFS_ORPHAN_OBJECTID)
3523 if (found_key.type != BTRFS_ORPHAN_ITEM_KEY)
3526 /* release the path since we're done with it */
3527 btrfs_release_path(path);
3530 * this is where we are basically btrfs_lookup, without the
3531 * crossing root thing. we store the inode number in the
3532 * offset of the orphan item.
3535 if (found_key.offset == last_objectid) {
3537 "Error removing orphan entry, stopping orphan cleanup");
3542 last_objectid = found_key.offset;
3544 found_key.objectid = found_key.offset;
3545 found_key.type = BTRFS_INODE_ITEM_KEY;
3546 found_key.offset = 0;
3547 inode = btrfs_iget(fs_info->sb, &found_key, root, NULL);
3548 ret = PTR_ERR_OR_ZERO(inode);
3549 if (ret && ret != -ENOENT)
3552 if (ret == -ENOENT && root == fs_info->tree_root) {
3553 struct btrfs_root *dead_root;
3554 struct btrfs_fs_info *fs_info = root->fs_info;
3555 int is_dead_root = 0;
3558 * this is an orphan in the tree root. Currently these
3559 * could come from 2 sources:
3560 * a) a snapshot deletion in progress
3561 * b) a free space cache inode
3562 * We need to distinguish those two, as the snapshot
3563 * orphan must not get deleted.
3564 * find_dead_roots already ran before us, so if this
3565 * is a snapshot deletion, we should find the root
3566 * in the dead_roots list
3568 spin_lock(&fs_info->trans_lock);
3569 list_for_each_entry(dead_root, &fs_info->dead_roots,
3571 if (dead_root->root_key.objectid ==
3572 found_key.objectid) {
3577 spin_unlock(&fs_info->trans_lock);
3579 /* prevent this orphan from being found again */
3580 key.offset = found_key.objectid - 1;
3587 * If we have an inode with links, there are a couple of
3588 * possibilities. Old kernels (before v3.12) used to create an
3589 * orphan item for truncate indicating that there were possibly
3590 * extent items past i_size that needed to be deleted. In v3.12,
3591 * truncate was changed to update i_size in sync with the extent
3592 * items, but the (useless) orphan item was still created. Since
3593 * v4.18, we don't create the orphan item for truncate at all.
3595 * So, this item could mean that we need to do a truncate, but
3596 * only if this filesystem was last used on a pre-v3.12 kernel
3597 * and was not cleanly unmounted. The odds of that are quite
3598 * slim, and it's a pain to do the truncate now, so just delete
3601 * It's also possible that this orphan item was supposed to be
3602 * deleted but wasn't. The inode number may have been reused,
3603 * but either way, we can delete the orphan item.
3605 if (ret == -ENOENT || inode->i_nlink) {
3608 trans = btrfs_start_transaction(root, 1);
3609 if (IS_ERR(trans)) {
3610 ret = PTR_ERR(trans);
3613 btrfs_debug(fs_info, "auto deleting %Lu",
3614 found_key.objectid);
3615 ret = btrfs_del_orphan_item(trans, root,
3616 found_key.objectid);
3617 btrfs_end_transaction(trans);
3625 /* this will do delete_inode and everything for us */
3628 /* release the path since we're done with it */
3629 btrfs_release_path(path);
3631 root->orphan_cleanup_state = ORPHAN_CLEANUP_DONE;
3633 if (test_bit(BTRFS_ROOT_ORPHAN_ITEM_INSERTED, &root->state)) {
3634 trans = btrfs_join_transaction(root);
3636 btrfs_end_transaction(trans);
3640 btrfs_debug(fs_info, "unlinked %d orphans", nr_unlink);
3644 btrfs_err(fs_info, "could not do orphan cleanup %d", ret);
3645 btrfs_free_path(path);
3650 * very simple check to peek ahead in the leaf looking for xattrs. If we
3651 * don't find any xattrs, we know there can't be any acls.
3653 * slot is the slot the inode is in, objectid is the objectid of the inode
3655 static noinline int acls_after_inode_item(struct extent_buffer *leaf,
3656 int slot, u64 objectid,
3657 int *first_xattr_slot)
3659 u32 nritems = btrfs_header_nritems(leaf);
3660 struct btrfs_key found_key;
3661 static u64 xattr_access = 0;
3662 static u64 xattr_default = 0;
3665 if (!xattr_access) {
3666 xattr_access = btrfs_name_hash(XATTR_NAME_POSIX_ACL_ACCESS,
3667 strlen(XATTR_NAME_POSIX_ACL_ACCESS));
3668 xattr_default = btrfs_name_hash(XATTR_NAME_POSIX_ACL_DEFAULT,
3669 strlen(XATTR_NAME_POSIX_ACL_DEFAULT));
3673 *first_xattr_slot = -1;
3674 while (slot < nritems) {
3675 btrfs_item_key_to_cpu(leaf, &found_key, slot);
3677 /* we found a different objectid, there must not be acls */
3678 if (found_key.objectid != objectid)
3681 /* we found an xattr, assume we've got an acl */
3682 if (found_key.type == BTRFS_XATTR_ITEM_KEY) {
3683 if (*first_xattr_slot == -1)
3684 *first_xattr_slot = slot;
3685 if (found_key.offset == xattr_access ||
3686 found_key.offset == xattr_default)
3691 * we found a key greater than an xattr key, there can't
3692 * be any acls later on
3694 if (found_key.type > BTRFS_XATTR_ITEM_KEY)
3701 * it goes inode, inode backrefs, xattrs, extents,
3702 * so if there are a ton of hard links to an inode there can
3703 * be a lot of backrefs. Don't waste time searching too hard,
3704 * this is just an optimization
3709 /* we hit the end of the leaf before we found an xattr or
3710 * something larger than an xattr. We have to assume the inode
3713 if (*first_xattr_slot == -1)
3714 *first_xattr_slot = slot;
3719 * read an inode from the btree into the in-memory inode
3721 static int btrfs_read_locked_inode(struct inode *inode,
3722 struct btrfs_path *in_path)
3724 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
3725 struct btrfs_path *path = in_path;
3726 struct extent_buffer *leaf;
3727 struct btrfs_inode_item *inode_item;
3728 struct btrfs_root *root = BTRFS_I(inode)->root;
3729 struct btrfs_key location;
3734 bool filled = false;
3735 int first_xattr_slot;
3737 ret = btrfs_fill_inode(inode, &rdev);
3742 path = btrfs_alloc_path();
3747 memcpy(&location, &BTRFS_I(inode)->location, sizeof(location));
3749 ret = btrfs_lookup_inode(NULL, root, path, &location, 0);
3751 if (path != in_path)
3752 btrfs_free_path(path);
3756 leaf = path->nodes[0];
3761 inode_item = btrfs_item_ptr(leaf, path->slots[0],
3762 struct btrfs_inode_item);
3763 inode->i_mode = btrfs_inode_mode(leaf, inode_item);
3764 set_nlink(inode, btrfs_inode_nlink(leaf, inode_item));
3765 i_uid_write(inode, btrfs_inode_uid(leaf, inode_item));
3766 i_gid_write(inode, btrfs_inode_gid(leaf, inode_item));
3767 btrfs_i_size_write(BTRFS_I(inode), btrfs_inode_size(leaf, inode_item));
3769 inode->i_atime.tv_sec = btrfs_timespec_sec(leaf, &inode_item->atime);
3770 inode->i_atime.tv_nsec = btrfs_timespec_nsec(leaf, &inode_item->atime);
3772 inode->i_mtime.tv_sec = btrfs_timespec_sec(leaf, &inode_item->mtime);
3773 inode->i_mtime.tv_nsec = btrfs_timespec_nsec(leaf, &inode_item->mtime);
3775 inode->i_ctime.tv_sec = btrfs_timespec_sec(leaf, &inode_item->ctime);
3776 inode->i_ctime.tv_nsec = btrfs_timespec_nsec(leaf, &inode_item->ctime);
3778 BTRFS_I(inode)->i_otime.tv_sec =
3779 btrfs_timespec_sec(leaf, &inode_item->otime);
3780 BTRFS_I(inode)->i_otime.tv_nsec =
3781 btrfs_timespec_nsec(leaf, &inode_item->otime);
3783 inode_set_bytes(inode, btrfs_inode_nbytes(leaf, inode_item));
3784 BTRFS_I(inode)->generation = btrfs_inode_generation(leaf, inode_item);
3785 BTRFS_I(inode)->last_trans = btrfs_inode_transid(leaf, inode_item);
3787 inode_set_iversion_queried(inode,
3788 btrfs_inode_sequence(leaf, inode_item));
3789 inode->i_generation = BTRFS_I(inode)->generation;
3791 rdev = btrfs_inode_rdev(leaf, inode_item);
3793 BTRFS_I(inode)->index_cnt = (u64)-1;
3794 BTRFS_I(inode)->flags = btrfs_inode_flags(leaf, inode_item);
3798 * If we were modified in the current generation and evicted from memory
3799 * and then re-read we need to do a full sync since we don't have any
3800 * idea about which extents were modified before we were evicted from
3803 * This is required for both inode re-read from disk and delayed inode
3804 * in delayed_nodes_tree.
3806 if (BTRFS_I(inode)->last_trans == fs_info->generation)
3807 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
3808 &BTRFS_I(inode)->runtime_flags);
3811 * We don't persist the id of the transaction where an unlink operation
3812 * against the inode was last made. So here we assume the inode might
3813 * have been evicted, and therefore the exact value of last_unlink_trans
3814 * lost, and set it to last_trans to avoid metadata inconsistencies
3815 * between the inode and its parent if the inode is fsync'ed and the log
3816 * replayed. For example, in the scenario:
3819 * ln mydir/foo mydir/bar
3822 * echo 2 > /proc/sys/vm/drop_caches # evicts inode
3823 * xfs_io -c fsync mydir/foo
3825 * mount fs, triggers fsync log replay
3827 * We must make sure that when we fsync our inode foo we also log its
3828 * parent inode, otherwise after log replay the parent still has the
3829 * dentry with the "bar" name but our inode foo has a link count of 1
3830 * and doesn't have an inode ref with the name "bar" anymore.
3832 * Setting last_unlink_trans to last_trans is a pessimistic approach,
3833 * but it guarantees correctness at the expense of occasional full
3834 * transaction commits on fsync if our inode is a directory, or if our
3835 * inode is not a directory, logging its parent unnecessarily.
3837 BTRFS_I(inode)->last_unlink_trans = BTRFS_I(inode)->last_trans;
3840 if (inode->i_nlink != 1 ||
3841 path->slots[0] >= btrfs_header_nritems(leaf))
3844 btrfs_item_key_to_cpu(leaf, &location, path->slots[0]);
3845 if (location.objectid != btrfs_ino(BTRFS_I(inode)))
3848 ptr = btrfs_item_ptr_offset(leaf, path->slots[0]);
3849 if (location.type == BTRFS_INODE_REF_KEY) {
3850 struct btrfs_inode_ref *ref;
3852 ref = (struct btrfs_inode_ref *)ptr;
3853 BTRFS_I(inode)->dir_index = btrfs_inode_ref_index(leaf, ref);
3854 } else if (location.type == BTRFS_INODE_EXTREF_KEY) {
3855 struct btrfs_inode_extref *extref;
3857 extref = (struct btrfs_inode_extref *)ptr;
3858 BTRFS_I(inode)->dir_index = btrfs_inode_extref_index(leaf,
3863 * try to precache a NULL acl entry for files that don't have
3864 * any xattrs or acls
3866 maybe_acls = acls_after_inode_item(leaf, path->slots[0],
3867 btrfs_ino(BTRFS_I(inode)), &first_xattr_slot);
3868 if (first_xattr_slot != -1) {
3869 path->slots[0] = first_xattr_slot;
3870 ret = btrfs_load_inode_props(inode, path);
3873 "error loading props for ino %llu (root %llu): %d",
3874 btrfs_ino(BTRFS_I(inode)),
3875 root->root_key.objectid, ret);
3877 if (path != in_path)
3878 btrfs_free_path(path);
3881 cache_no_acl(inode);
3883 switch (inode->i_mode & S_IFMT) {
3885 inode->i_mapping->a_ops = &btrfs_aops;
3886 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
3887 inode->i_fop = &btrfs_file_operations;
3888 inode->i_op = &btrfs_file_inode_operations;
3891 inode->i_fop = &btrfs_dir_file_operations;
3892 inode->i_op = &btrfs_dir_inode_operations;
3895 inode->i_op = &btrfs_symlink_inode_operations;
3896 inode_nohighmem(inode);
3897 inode->i_mapping->a_ops = &btrfs_aops;
3900 inode->i_op = &btrfs_special_inode_operations;
3901 init_special_inode(inode, inode->i_mode, rdev);
3905 btrfs_sync_inode_flags_to_i_flags(inode);
3910 * given a leaf and an inode, copy the inode fields into the leaf
3912 static void fill_inode_item(struct btrfs_trans_handle *trans,
3913 struct extent_buffer *leaf,
3914 struct btrfs_inode_item *item,
3915 struct inode *inode)
3917 struct btrfs_map_token token;
3919 btrfs_init_map_token(&token, leaf);
3921 btrfs_set_token_inode_uid(leaf, item, i_uid_read(inode), &token);
3922 btrfs_set_token_inode_gid(leaf, item, i_gid_read(inode), &token);
3923 btrfs_set_token_inode_size(leaf, item, BTRFS_I(inode)->disk_i_size,
3925 btrfs_set_token_inode_mode(leaf, item, inode->i_mode, &token);
3926 btrfs_set_token_inode_nlink(leaf, item, inode->i_nlink, &token);
3928 btrfs_set_token_timespec_sec(leaf, &item->atime,
3929 inode->i_atime.tv_sec, &token);
3930 btrfs_set_token_timespec_nsec(leaf, &item->atime,
3931 inode->i_atime.tv_nsec, &token);
3933 btrfs_set_token_timespec_sec(leaf, &item->mtime,
3934 inode->i_mtime.tv_sec, &token);
3935 btrfs_set_token_timespec_nsec(leaf, &item->mtime,
3936 inode->i_mtime.tv_nsec, &token);
3938 btrfs_set_token_timespec_sec(leaf, &item->ctime,
3939 inode->i_ctime.tv_sec, &token);
3940 btrfs_set_token_timespec_nsec(leaf, &item->ctime,
3941 inode->i_ctime.tv_nsec, &token);
3943 btrfs_set_token_timespec_sec(leaf, &item->otime,
3944 BTRFS_I(inode)->i_otime.tv_sec, &token);
3945 btrfs_set_token_timespec_nsec(leaf, &item->otime,
3946 BTRFS_I(inode)->i_otime.tv_nsec, &token);
3948 btrfs_set_token_inode_nbytes(leaf, item, inode_get_bytes(inode),
3950 btrfs_set_token_inode_generation(leaf, item, BTRFS_I(inode)->generation,
3952 btrfs_set_token_inode_sequence(leaf, item, inode_peek_iversion(inode),
3954 btrfs_set_token_inode_transid(leaf, item, trans->transid, &token);
3955 btrfs_set_token_inode_rdev(leaf, item, inode->i_rdev, &token);
3956 btrfs_set_token_inode_flags(leaf, item, BTRFS_I(inode)->flags, &token);
3957 btrfs_set_token_inode_block_group(leaf, item, 0, &token);
3961 * copy everything in the in-memory inode into the btree.
3963 static noinline int btrfs_update_inode_item(struct btrfs_trans_handle *trans,
3964 struct btrfs_root *root, struct inode *inode)
3966 struct btrfs_inode_item *inode_item;
3967 struct btrfs_path *path;
3968 struct extent_buffer *leaf;
3971 path = btrfs_alloc_path();
3975 path->leave_spinning = 1;
3976 ret = btrfs_lookup_inode(trans, root, path, &BTRFS_I(inode)->location,
3984 leaf = path->nodes[0];
3985 inode_item = btrfs_item_ptr(leaf, path->slots[0],
3986 struct btrfs_inode_item);
3988 fill_inode_item(trans, leaf, inode_item, inode);
3989 btrfs_mark_buffer_dirty(leaf);
3990 btrfs_set_inode_last_trans(trans, inode);
3993 btrfs_free_path(path);
3998 * copy everything in the in-memory inode into the btree.
4000 noinline int btrfs_update_inode(struct btrfs_trans_handle *trans,
4001 struct btrfs_root *root, struct inode *inode)
4003 struct btrfs_fs_info *fs_info = root->fs_info;
4007 * If the inode is a free space inode, we can deadlock during commit
4008 * if we put it into the delayed code.
4010 * The data relocation inode should also be directly updated
4013 if (!btrfs_is_free_space_inode(BTRFS_I(inode))
4014 && root->root_key.objectid != BTRFS_DATA_RELOC_TREE_OBJECTID
4015 && !test_bit(BTRFS_FS_LOG_RECOVERING, &fs_info->flags)) {
4016 btrfs_update_root_times(trans, root);
4018 ret = btrfs_delayed_update_inode(trans, root, inode);
4020 btrfs_set_inode_last_trans(trans, inode);
4024 return btrfs_update_inode_item(trans, root, inode);
4027 noinline int btrfs_update_inode_fallback(struct btrfs_trans_handle *trans,
4028 struct btrfs_root *root,
4029 struct inode *inode)
4033 ret = btrfs_update_inode(trans, root, inode);
4035 return btrfs_update_inode_item(trans, root, inode);
4040 * unlink helper that gets used here in inode.c and in the tree logging
4041 * recovery code. It remove a link in a directory with a given name, and
4042 * also drops the back refs in the inode to the directory
4044 static int __btrfs_unlink_inode(struct btrfs_trans_handle *trans,
4045 struct btrfs_root *root,
4046 struct btrfs_inode *dir,
4047 struct btrfs_inode *inode,
4048 const char *name, int name_len)
4050 struct btrfs_fs_info *fs_info = root->fs_info;
4051 struct btrfs_path *path;
4053 struct btrfs_dir_item *di;
4055 u64 ino = btrfs_ino(inode);
4056 u64 dir_ino = btrfs_ino(dir);
4058 path = btrfs_alloc_path();
4064 path->leave_spinning = 1;
4065 di = btrfs_lookup_dir_item(trans, root, path, dir_ino,
4066 name, name_len, -1);
4067 if (IS_ERR_OR_NULL(di)) {
4068 ret = di ? PTR_ERR(di) : -ENOENT;
4071 ret = btrfs_delete_one_dir_name(trans, root, path, di);
4074 btrfs_release_path(path);
4077 * If we don't have dir index, we have to get it by looking up
4078 * the inode ref, since we get the inode ref, remove it directly,
4079 * it is unnecessary to do delayed deletion.
4081 * But if we have dir index, needn't search inode ref to get it.
4082 * Since the inode ref is close to the inode item, it is better
4083 * that we delay to delete it, and just do this deletion when
4084 * we update the inode item.
4086 if (inode->dir_index) {
4087 ret = btrfs_delayed_delete_inode_ref(inode);
4089 index = inode->dir_index;
4094 ret = btrfs_del_inode_ref(trans, root, name, name_len, ino,
4098 "failed to delete reference to %.*s, inode %llu parent %llu",
4099 name_len, name, ino, dir_ino);
4100 btrfs_abort_transaction(trans, ret);
4104 ret = btrfs_delete_delayed_dir_index(trans, dir, index);
4106 btrfs_abort_transaction(trans, ret);
4110 ret = btrfs_del_inode_ref_in_log(trans, root, name, name_len, inode,
4112 if (ret != 0 && ret != -ENOENT) {
4113 btrfs_abort_transaction(trans, ret);
4117 ret = btrfs_del_dir_entries_in_log(trans, root, name, name_len, dir,
4122 btrfs_abort_transaction(trans, ret);
4125 * If we have a pending delayed iput we could end up with the final iput
4126 * being run in btrfs-cleaner context. If we have enough of these built
4127 * up we can end up burning a lot of time in btrfs-cleaner without any
4128 * way to throttle the unlinks. Since we're currently holding a ref on
4129 * the inode we can run the delayed iput here without any issues as the
4130 * final iput won't be done until after we drop the ref we're currently
4133 btrfs_run_delayed_iput(fs_info, inode);
4135 btrfs_free_path(path);
4139 btrfs_i_size_write(dir, dir->vfs_inode.i_size - name_len * 2);
4140 inode_inc_iversion(&inode->vfs_inode);
4141 inode_inc_iversion(&dir->vfs_inode);
4142 inode->vfs_inode.i_ctime = dir->vfs_inode.i_mtime =
4143 dir->vfs_inode.i_ctime = current_time(&inode->vfs_inode);
4144 ret = btrfs_update_inode(trans, root, &dir->vfs_inode);
4149 int btrfs_unlink_inode(struct btrfs_trans_handle *trans,
4150 struct btrfs_root *root,
4151 struct btrfs_inode *dir, struct btrfs_inode *inode,
4152 const char *name, int name_len)
4155 ret = __btrfs_unlink_inode(trans, root, dir, inode, name, name_len);
4157 drop_nlink(&inode->vfs_inode);
4158 ret = btrfs_update_inode(trans, root, &inode->vfs_inode);
4164 * helper to start transaction for unlink and rmdir.
4166 * unlink and rmdir are special in btrfs, they do not always free space, so
4167 * if we cannot make our reservations the normal way try and see if there is
4168 * plenty of slack room in the global reserve to migrate, otherwise we cannot
4169 * allow the unlink to occur.
4171 static struct btrfs_trans_handle *__unlink_start_trans(struct inode *dir)
4173 struct btrfs_root *root = BTRFS_I(dir)->root;
4176 * 1 for the possible orphan item
4177 * 1 for the dir item
4178 * 1 for the dir index
4179 * 1 for the inode ref
4182 return btrfs_start_transaction_fallback_global_rsv(root, 5, 5);
4185 static int btrfs_unlink(struct inode *dir, struct dentry *dentry)
4187 struct btrfs_root *root = BTRFS_I(dir)->root;
4188 struct btrfs_trans_handle *trans;
4189 struct inode *inode = d_inode(dentry);
4192 trans = __unlink_start_trans(dir);
4194 return PTR_ERR(trans);
4196 btrfs_record_unlink_dir(trans, BTRFS_I(dir), BTRFS_I(d_inode(dentry)),
4199 ret = btrfs_unlink_inode(trans, root, BTRFS_I(dir),
4200 BTRFS_I(d_inode(dentry)), dentry->d_name.name,
4201 dentry->d_name.len);
4205 if (inode->i_nlink == 0) {
4206 ret = btrfs_orphan_add(trans, BTRFS_I(inode));
4212 btrfs_end_transaction(trans);
4213 btrfs_btree_balance_dirty(root->fs_info);
4217 static int btrfs_unlink_subvol(struct btrfs_trans_handle *trans,
4218 struct inode *dir, struct dentry *dentry)
4220 struct btrfs_root *root = BTRFS_I(dir)->root;
4221 struct btrfs_inode *inode = BTRFS_I(d_inode(dentry));
4222 struct btrfs_path *path;
4223 struct extent_buffer *leaf;
4224 struct btrfs_dir_item *di;
4225 struct btrfs_key key;
4226 const char *name = dentry->d_name.name;
4227 int name_len = dentry->d_name.len;
4231 u64 dir_ino = btrfs_ino(BTRFS_I(dir));
4233 if (btrfs_ino(inode) == BTRFS_FIRST_FREE_OBJECTID) {
4234 objectid = inode->root->root_key.objectid;
4235 } else if (btrfs_ino(inode) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID) {
4236 objectid = inode->location.objectid;
4242 path = btrfs_alloc_path();
4246 di = btrfs_lookup_dir_item(trans, root, path, dir_ino,
4247 name, name_len, -1);
4248 if (IS_ERR_OR_NULL(di)) {
4249 ret = di ? PTR_ERR(di) : -ENOENT;
4253 leaf = path->nodes[0];
4254 btrfs_dir_item_key_to_cpu(leaf, di, &key);
4255 WARN_ON(key.type != BTRFS_ROOT_ITEM_KEY || key.objectid != objectid);
4256 ret = btrfs_delete_one_dir_name(trans, root, path, di);
4258 btrfs_abort_transaction(trans, ret);
4261 btrfs_release_path(path);
4264 * This is a placeholder inode for a subvolume we didn't have a
4265 * reference to at the time of the snapshot creation. In the meantime
4266 * we could have renamed the real subvol link into our snapshot, so
4267 * depending on btrfs_del_root_ref to return -ENOENT here is incorret.
4268 * Instead simply lookup the dir_index_item for this entry so we can
4269 * remove it. Otherwise we know we have a ref to the root and we can
4270 * call btrfs_del_root_ref, and it _shouldn't_ fail.
4272 if (btrfs_ino(inode) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID) {
4273 di = btrfs_search_dir_index_item(root, path, dir_ino,
4275 if (IS_ERR_OR_NULL(di)) {
4280 btrfs_abort_transaction(trans, ret);
4284 leaf = path->nodes[0];
4285 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
4287 btrfs_release_path(path);
4289 ret = btrfs_del_root_ref(trans, objectid,
4290 root->root_key.objectid, dir_ino,
4291 &index, name, name_len);
4293 btrfs_abort_transaction(trans, ret);
4298 ret = btrfs_delete_delayed_dir_index(trans, BTRFS_I(dir), index);
4300 btrfs_abort_transaction(trans, ret);
4304 btrfs_i_size_write(BTRFS_I(dir), dir->i_size - name_len * 2);
4305 inode_inc_iversion(dir);
4306 dir->i_mtime = dir->i_ctime = current_time(dir);
4307 ret = btrfs_update_inode_fallback(trans, root, dir);
4309 btrfs_abort_transaction(trans, ret);
4311 btrfs_free_path(path);
4316 * Helper to check if the subvolume references other subvolumes or if it's
4319 static noinline int may_destroy_subvol(struct btrfs_root *root)
4321 struct btrfs_fs_info *fs_info = root->fs_info;
4322 struct btrfs_path *path;
4323 struct btrfs_dir_item *di;
4324 struct btrfs_key key;
4328 path = btrfs_alloc_path();
4332 /* Make sure this root isn't set as the default subvol */
4333 dir_id = btrfs_super_root_dir(fs_info->super_copy);
4334 di = btrfs_lookup_dir_item(NULL, fs_info->tree_root, path,
4335 dir_id, "default", 7, 0);
4336 if (di && !IS_ERR(di)) {
4337 btrfs_dir_item_key_to_cpu(path->nodes[0], di, &key);
4338 if (key.objectid == root->root_key.objectid) {
4341 "deleting default subvolume %llu is not allowed",
4345 btrfs_release_path(path);
4348 key.objectid = root->root_key.objectid;
4349 key.type = BTRFS_ROOT_REF_KEY;
4350 key.offset = (u64)-1;
4352 ret = btrfs_search_slot(NULL, fs_info->tree_root, &key, path, 0, 0);
4358 if (path->slots[0] > 0) {
4360 btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
4361 if (key.objectid == root->root_key.objectid &&
4362 key.type == BTRFS_ROOT_REF_KEY)
4366 btrfs_free_path(path);
4370 /* Delete all dentries for inodes belonging to the root */
4371 static void btrfs_prune_dentries(struct btrfs_root *root)
4373 struct btrfs_fs_info *fs_info = root->fs_info;
4374 struct rb_node *node;
4375 struct rb_node *prev;
4376 struct btrfs_inode *entry;
4377 struct inode *inode;
4380 if (!test_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state))
4381 WARN_ON(btrfs_root_refs(&root->root_item) != 0);
4383 spin_lock(&root->inode_lock);
4385 node = root->inode_tree.rb_node;
4389 entry = rb_entry(node, struct btrfs_inode, rb_node);
4391 if (objectid < btrfs_ino(entry))
4392 node = node->rb_left;
4393 else if (objectid > btrfs_ino(entry))
4394 node = node->rb_right;
4400 entry = rb_entry(prev, struct btrfs_inode, rb_node);
4401 if (objectid <= btrfs_ino(entry)) {
4405 prev = rb_next(prev);
4409 entry = rb_entry(node, struct btrfs_inode, rb_node);
4410 objectid = btrfs_ino(entry) + 1;
4411 inode = igrab(&entry->vfs_inode);
4413 spin_unlock(&root->inode_lock);
4414 if (atomic_read(&inode->i_count) > 1)
4415 d_prune_aliases(inode);
4417 * btrfs_drop_inode will have it removed from the inode
4418 * cache when its usage count hits zero.
4422 spin_lock(&root->inode_lock);
4426 if (cond_resched_lock(&root->inode_lock))
4429 node = rb_next(node);
4431 spin_unlock(&root->inode_lock);
4434 int btrfs_delete_subvolume(struct inode *dir, struct dentry *dentry)
4436 struct btrfs_fs_info *fs_info = btrfs_sb(dentry->d_sb);
4437 struct btrfs_root *root = BTRFS_I(dir)->root;
4438 struct inode *inode = d_inode(dentry);
4439 struct btrfs_root *dest = BTRFS_I(inode)->root;
4440 struct btrfs_trans_handle *trans;
4441 struct btrfs_block_rsv block_rsv;
4447 * Don't allow to delete a subvolume with send in progress. This is
4448 * inside the inode lock so the error handling that has to drop the bit
4449 * again is not run concurrently.
4451 spin_lock(&dest->root_item_lock);
4452 if (dest->send_in_progress) {
4453 spin_unlock(&dest->root_item_lock);
4455 "attempt to delete subvolume %llu during send",
4456 dest->root_key.objectid);
4459 root_flags = btrfs_root_flags(&dest->root_item);
4460 btrfs_set_root_flags(&dest->root_item,
4461 root_flags | BTRFS_ROOT_SUBVOL_DEAD);
4462 spin_unlock(&dest->root_item_lock);
4464 down_write(&fs_info->subvol_sem);
4466 err = may_destroy_subvol(dest);
4470 btrfs_init_block_rsv(&block_rsv, BTRFS_BLOCK_RSV_TEMP);
4472 * One for dir inode,
4473 * two for dir entries,
4474 * two for root ref/backref.
4476 err = btrfs_subvolume_reserve_metadata(root, &block_rsv, 5, true);
4480 trans = btrfs_start_transaction(root, 0);
4481 if (IS_ERR(trans)) {
4482 err = PTR_ERR(trans);
4485 trans->block_rsv = &block_rsv;
4486 trans->bytes_reserved = block_rsv.size;
4488 btrfs_record_snapshot_destroy(trans, BTRFS_I(dir));
4490 ret = btrfs_unlink_subvol(trans, dir, dentry);
4493 btrfs_abort_transaction(trans, ret);
4497 btrfs_record_root_in_trans(trans, dest);
4499 memset(&dest->root_item.drop_progress, 0,
4500 sizeof(dest->root_item.drop_progress));
4501 dest->root_item.drop_level = 0;
4502 btrfs_set_root_refs(&dest->root_item, 0);
4504 if (!test_and_set_bit(BTRFS_ROOT_ORPHAN_ITEM_INSERTED, &dest->state)) {
4505 ret = btrfs_insert_orphan_item(trans,
4507 dest->root_key.objectid);
4509 btrfs_abort_transaction(trans, ret);
4515 ret = btrfs_uuid_tree_remove(trans, dest->root_item.uuid,
4516 BTRFS_UUID_KEY_SUBVOL,
4517 dest->root_key.objectid);
4518 if (ret && ret != -ENOENT) {
4519 btrfs_abort_transaction(trans, ret);
4523 if (!btrfs_is_empty_uuid(dest->root_item.received_uuid)) {
4524 ret = btrfs_uuid_tree_remove(trans,
4525 dest->root_item.received_uuid,
4526 BTRFS_UUID_KEY_RECEIVED_SUBVOL,
4527 dest->root_key.objectid);
4528 if (ret && ret != -ENOENT) {
4529 btrfs_abort_transaction(trans, ret);
4536 trans->block_rsv = NULL;
4537 trans->bytes_reserved = 0;
4538 ret = btrfs_end_transaction(trans);
4541 inode->i_flags |= S_DEAD;
4543 btrfs_subvolume_release_metadata(fs_info, &block_rsv);
4545 up_write(&fs_info->subvol_sem);
4547 spin_lock(&dest->root_item_lock);
4548 root_flags = btrfs_root_flags(&dest->root_item);
4549 btrfs_set_root_flags(&dest->root_item,
4550 root_flags & ~BTRFS_ROOT_SUBVOL_DEAD);
4551 spin_unlock(&dest->root_item_lock);
4553 d_invalidate(dentry);
4554 btrfs_prune_dentries(dest);
4555 ASSERT(dest->send_in_progress == 0);
4558 if (dest->ino_cache_inode) {
4559 iput(dest->ino_cache_inode);
4560 dest->ino_cache_inode = NULL;
4567 static int btrfs_rmdir(struct inode *dir, struct dentry *dentry)
4569 struct inode *inode = d_inode(dentry);
4571 struct btrfs_root *root = BTRFS_I(dir)->root;
4572 struct btrfs_trans_handle *trans;
4573 u64 last_unlink_trans;
4575 if (inode->i_size > BTRFS_EMPTY_DIR_SIZE)
4577 if (btrfs_ino(BTRFS_I(inode)) == BTRFS_FIRST_FREE_OBJECTID)
4578 return btrfs_delete_subvolume(dir, dentry);
4580 trans = __unlink_start_trans(dir);
4582 return PTR_ERR(trans);
4584 if (unlikely(btrfs_ino(BTRFS_I(inode)) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)) {
4585 err = btrfs_unlink_subvol(trans, dir, dentry);
4589 err = btrfs_orphan_add(trans, BTRFS_I(inode));
4593 last_unlink_trans = BTRFS_I(inode)->last_unlink_trans;
4595 /* now the directory is empty */
4596 err = btrfs_unlink_inode(trans, root, BTRFS_I(dir),
4597 BTRFS_I(d_inode(dentry)), dentry->d_name.name,
4598 dentry->d_name.len);
4600 btrfs_i_size_write(BTRFS_I(inode), 0);
4602 * Propagate the last_unlink_trans value of the deleted dir to
4603 * its parent directory. This is to prevent an unrecoverable
4604 * log tree in the case we do something like this:
4606 * 2) create snapshot under dir foo
4607 * 3) delete the snapshot
4610 * 6) fsync foo or some file inside foo
4612 if (last_unlink_trans >= trans->transid)
4613 BTRFS_I(dir)->last_unlink_trans = last_unlink_trans;
4616 btrfs_end_transaction(trans);
4617 btrfs_btree_balance_dirty(root->fs_info);
4623 * Return this if we need to call truncate_block for the last bit of the
4626 #define NEED_TRUNCATE_BLOCK 1
4629 * this can truncate away extent items, csum items and directory items.
4630 * It starts at a high offset and removes keys until it can't find
4631 * any higher than new_size
4633 * csum items that cross the new i_size are truncated to the new size
4636 * min_type is the minimum key type to truncate down to. If set to 0, this
4637 * will kill all the items on this inode, including the INODE_ITEM_KEY.
4639 int btrfs_truncate_inode_items(struct btrfs_trans_handle *trans,
4640 struct btrfs_root *root,
4641 struct inode *inode,
4642 u64 new_size, u32 min_type)
4644 struct btrfs_fs_info *fs_info = root->fs_info;
4645 struct btrfs_path *path;
4646 struct extent_buffer *leaf;
4647 struct btrfs_file_extent_item *fi;
4648 struct btrfs_key key;
4649 struct btrfs_key found_key;
4650 u64 extent_start = 0;
4651 u64 extent_num_bytes = 0;
4652 u64 extent_offset = 0;
4654 u64 last_size = new_size;
4655 u32 found_type = (u8)-1;
4658 int pending_del_nr = 0;
4659 int pending_del_slot = 0;
4660 int extent_type = -1;
4662 u64 ino = btrfs_ino(BTRFS_I(inode));
4663 u64 bytes_deleted = 0;
4664 bool be_nice = false;
4665 bool should_throttle = false;
4667 BUG_ON(new_size > 0 && min_type != BTRFS_EXTENT_DATA_KEY);
4670 * for non-free space inodes and ref cows, we want to back off from
4673 if (!btrfs_is_free_space_inode(BTRFS_I(inode)) &&
4674 test_bit(BTRFS_ROOT_REF_COWS, &root->state))
4677 path = btrfs_alloc_path();
4680 path->reada = READA_BACK;
4683 * We want to drop from the next block forward in case this new size is
4684 * not block aligned since we will be keeping the last block of the
4685 * extent just the way it is.
4687 if (test_bit(BTRFS_ROOT_REF_COWS, &root->state) ||
4688 root == fs_info->tree_root)
4689 btrfs_drop_extent_cache(BTRFS_I(inode), ALIGN(new_size,
4690 fs_info->sectorsize),
4694 * This function is also used to drop the items in the log tree before
4695 * we relog the inode, so if root != BTRFS_I(inode)->root, it means
4696 * it is used to drop the logged items. So we shouldn't kill the delayed
4699 if (min_type == 0 && root == BTRFS_I(inode)->root)
4700 btrfs_kill_delayed_inode_items(BTRFS_I(inode));
4703 key.offset = (u64)-1;
4708 * with a 16K leaf size and 128MB extents, you can actually queue
4709 * up a huge file in a single leaf. Most of the time that
4710 * bytes_deleted is > 0, it will be huge by the time we get here
4712 if (be_nice && bytes_deleted > SZ_32M &&
4713 btrfs_should_end_transaction(trans)) {
4718 path->leave_spinning = 1;
4719 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
4725 /* there are no items in the tree for us to truncate, we're
4728 if (path->slots[0] == 0)
4735 leaf = path->nodes[0];
4736 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
4737 found_type = found_key.type;
4739 if (found_key.objectid != ino)
4742 if (found_type < min_type)
4745 item_end = found_key.offset;
4746 if (found_type == BTRFS_EXTENT_DATA_KEY) {
4747 fi = btrfs_item_ptr(leaf, path->slots[0],
4748 struct btrfs_file_extent_item);
4749 extent_type = btrfs_file_extent_type(leaf, fi);
4750 if (extent_type != BTRFS_FILE_EXTENT_INLINE) {
4752 btrfs_file_extent_num_bytes(leaf, fi);
4754 trace_btrfs_truncate_show_fi_regular(
4755 BTRFS_I(inode), leaf, fi,
4757 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
4758 item_end += btrfs_file_extent_ram_bytes(leaf,
4761 trace_btrfs_truncate_show_fi_inline(
4762 BTRFS_I(inode), leaf, fi, path->slots[0],
4767 if (found_type > min_type) {
4770 if (item_end < new_size)
4772 if (found_key.offset >= new_size)
4778 /* FIXME, shrink the extent if the ref count is only 1 */
4779 if (found_type != BTRFS_EXTENT_DATA_KEY)
4782 if (extent_type != BTRFS_FILE_EXTENT_INLINE) {
4784 extent_start = btrfs_file_extent_disk_bytenr(leaf, fi);
4786 u64 orig_num_bytes =
4787 btrfs_file_extent_num_bytes(leaf, fi);
4788 extent_num_bytes = ALIGN(new_size -
4790 fs_info->sectorsize);
4791 btrfs_set_file_extent_num_bytes(leaf, fi,
4793 num_dec = (orig_num_bytes -
4795 if (test_bit(BTRFS_ROOT_REF_COWS,
4798 inode_sub_bytes(inode, num_dec);
4799 btrfs_mark_buffer_dirty(leaf);
4802 btrfs_file_extent_disk_num_bytes(leaf,
4804 extent_offset = found_key.offset -
4805 btrfs_file_extent_offset(leaf, fi);
4807 /* FIXME blocksize != 4096 */
4808 num_dec = btrfs_file_extent_num_bytes(leaf, fi);
4809 if (extent_start != 0) {
4811 if (test_bit(BTRFS_ROOT_REF_COWS,
4813 inode_sub_bytes(inode, num_dec);
4816 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
4818 * we can't truncate inline items that have had
4822 btrfs_file_extent_encryption(leaf, fi) == 0 &&
4823 btrfs_file_extent_other_encoding(leaf, fi) == 0 &&
4824 btrfs_file_extent_compression(leaf, fi) == 0) {
4825 u32 size = (u32)(new_size - found_key.offset);
4827 btrfs_set_file_extent_ram_bytes(leaf, fi, size);
4828 size = btrfs_file_extent_calc_inline_size(size);
4829 btrfs_truncate_item(path, size, 1);
4830 } else if (!del_item) {
4832 * We have to bail so the last_size is set to
4833 * just before this extent.
4835 ret = NEED_TRUNCATE_BLOCK;
4839 if (test_bit(BTRFS_ROOT_REF_COWS, &root->state))
4840 inode_sub_bytes(inode, item_end + 1 - new_size);
4844 last_size = found_key.offset;
4846 last_size = new_size;
4848 if (!pending_del_nr) {
4849 /* no pending yet, add ourselves */
4850 pending_del_slot = path->slots[0];
4852 } else if (pending_del_nr &&
4853 path->slots[0] + 1 == pending_del_slot) {
4854 /* hop on the pending chunk */
4856 pending_del_slot = path->slots[0];
4863 should_throttle = false;
4866 (test_bit(BTRFS_ROOT_REF_COWS, &root->state) ||
4867 root == fs_info->tree_root)) {
4868 struct btrfs_ref ref = { 0 };
4870 btrfs_set_path_blocking(path);
4871 bytes_deleted += extent_num_bytes;
4873 btrfs_init_generic_ref(&ref, BTRFS_DROP_DELAYED_REF,
4874 extent_start, extent_num_bytes, 0);
4875 ref.real_root = root->root_key.objectid;
4876 btrfs_init_data_ref(&ref, btrfs_header_owner(leaf),
4877 ino, extent_offset);
4878 ret = btrfs_free_extent(trans, &ref);
4880 btrfs_abort_transaction(trans, ret);
4884 if (btrfs_should_throttle_delayed_refs(trans))
4885 should_throttle = true;
4889 if (found_type == BTRFS_INODE_ITEM_KEY)
4892 if (path->slots[0] == 0 ||
4893 path->slots[0] != pending_del_slot ||
4895 if (pending_del_nr) {
4896 ret = btrfs_del_items(trans, root, path,
4900 btrfs_abort_transaction(trans, ret);
4905 btrfs_release_path(path);
4908 * We can generate a lot of delayed refs, so we need to
4909 * throttle every once and a while and make sure we're
4910 * adding enough space to keep up with the work we are
4911 * generating. Since we hold a transaction here we
4912 * can't flush, and we don't want to FLUSH_LIMIT because
4913 * we could have generated too many delayed refs to
4914 * actually allocate, so just bail if we're short and
4915 * let the normal reservation dance happen higher up.
4917 if (should_throttle) {
4918 ret = btrfs_delayed_refs_rsv_refill(fs_info,
4919 BTRFS_RESERVE_NO_FLUSH);
4931 if (ret >= 0 && pending_del_nr) {
4934 err = btrfs_del_items(trans, root, path, pending_del_slot,
4937 btrfs_abort_transaction(trans, err);
4941 if (root->root_key.objectid != BTRFS_TREE_LOG_OBJECTID) {
4942 ASSERT(last_size >= new_size);
4943 if (!ret && last_size > new_size)
4944 last_size = new_size;
4945 btrfs_ordered_update_i_size(inode, last_size, NULL);
4948 btrfs_free_path(path);
4953 * btrfs_truncate_block - read, zero a chunk and write a block
4954 * @inode - inode that we're zeroing
4955 * @from - the offset to start zeroing
4956 * @len - the length to zero, 0 to zero the entire range respective to the
4958 * @front - zero up to the offset instead of from the offset on
4960 * This will find the block for the "from" offset and cow the block and zero the
4961 * part we want to zero. This is used with truncate and hole punching.
4963 int btrfs_truncate_block(struct inode *inode, loff_t from, loff_t len,
4966 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
4967 struct address_space *mapping = inode->i_mapping;
4968 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
4969 struct btrfs_ordered_extent *ordered;
4970 struct extent_state *cached_state = NULL;
4971 struct extent_changeset *data_reserved = NULL;
4973 u32 blocksize = fs_info->sectorsize;
4974 pgoff_t index = from >> PAGE_SHIFT;
4975 unsigned offset = from & (blocksize - 1);
4977 gfp_t mask = btrfs_alloc_write_mask(mapping);
4982 if (IS_ALIGNED(offset, blocksize) &&
4983 (!len || IS_ALIGNED(len, blocksize)))
4986 block_start = round_down(from, blocksize);
4987 block_end = block_start + blocksize - 1;
4989 ret = btrfs_delalloc_reserve_space(inode, &data_reserved,
4990 block_start, blocksize);
4995 page = find_or_create_page(mapping, index, mask);
4997 btrfs_delalloc_release_space(inode, data_reserved,
4998 block_start, blocksize, true);
4999 btrfs_delalloc_release_extents(BTRFS_I(inode), blocksize);
5004 if (!PageUptodate(page)) {
5005 ret = btrfs_readpage(NULL, page);
5007 if (page->mapping != mapping) {
5012 if (!PageUptodate(page)) {
5017 wait_on_page_writeback(page);
5019 lock_extent_bits(io_tree, block_start, block_end, &cached_state);
5020 set_page_extent_mapped(page);
5022 ordered = btrfs_lookup_ordered_extent(inode, block_start);
5024 unlock_extent_cached(io_tree, block_start, block_end,
5028 btrfs_start_ordered_extent(inode, ordered, 1);
5029 btrfs_put_ordered_extent(ordered);
5033 clear_extent_bit(&BTRFS_I(inode)->io_tree, block_start, block_end,
5034 EXTENT_DELALLOC | EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG,
5035 0, 0, &cached_state);
5037 ret = btrfs_set_extent_delalloc(inode, block_start, block_end, 0,
5040 unlock_extent_cached(io_tree, block_start, block_end,
5045 if (offset != blocksize) {
5047 len = blocksize - offset;
5050 memset(kaddr + (block_start - page_offset(page)),
5053 memset(kaddr + (block_start - page_offset(page)) + offset,
5055 flush_dcache_page(page);
5058 ClearPageChecked(page);
5059 set_page_dirty(page);
5060 unlock_extent_cached(io_tree, block_start, block_end, &cached_state);
5064 btrfs_delalloc_release_space(inode, data_reserved, block_start,
5066 btrfs_delalloc_release_extents(BTRFS_I(inode), blocksize);
5070 extent_changeset_free(data_reserved);
5074 static int maybe_insert_hole(struct btrfs_root *root, struct inode *inode,
5075 u64 offset, u64 len)
5077 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
5078 struct btrfs_trans_handle *trans;
5082 * Still need to make sure the inode looks like it's been updated so
5083 * that any holes get logged if we fsync.
5085 if (btrfs_fs_incompat(fs_info, NO_HOLES)) {
5086 BTRFS_I(inode)->last_trans = fs_info->generation;
5087 BTRFS_I(inode)->last_sub_trans = root->log_transid;
5088 BTRFS_I(inode)->last_log_commit = root->last_log_commit;
5093 * 1 - for the one we're dropping
5094 * 1 - for the one we're adding
5095 * 1 - for updating the inode.
5097 trans = btrfs_start_transaction(root, 3);
5099 return PTR_ERR(trans);
5101 ret = btrfs_drop_extents(trans, root, inode, offset, offset + len, 1);
5103 btrfs_abort_transaction(trans, ret);
5104 btrfs_end_transaction(trans);
5108 ret = btrfs_insert_file_extent(trans, root, btrfs_ino(BTRFS_I(inode)),
5109 offset, 0, 0, len, 0, len, 0, 0, 0);
5111 btrfs_abort_transaction(trans, ret);
5113 btrfs_update_inode(trans, root, inode);
5114 btrfs_end_transaction(trans);
5119 * This function puts in dummy file extents for the area we're creating a hole
5120 * for. So if we are truncating this file to a larger size we need to insert
5121 * these file extents so that btrfs_get_extent will return a EXTENT_MAP_HOLE for
5122 * the range between oldsize and size
5124 int btrfs_cont_expand(struct inode *inode, loff_t oldsize, loff_t size)
5126 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
5127 struct btrfs_root *root = BTRFS_I(inode)->root;
5128 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
5129 struct extent_map *em = NULL;
5130 struct extent_state *cached_state = NULL;
5131 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
5132 u64 hole_start = ALIGN(oldsize, fs_info->sectorsize);
5133 u64 block_end = ALIGN(size, fs_info->sectorsize);
5140 * If our size started in the middle of a block we need to zero out the
5141 * rest of the block before we expand the i_size, otherwise we could
5142 * expose stale data.
5144 err = btrfs_truncate_block(inode, oldsize, 0, 0);
5148 if (size <= hole_start)
5151 btrfs_lock_and_flush_ordered_range(io_tree, BTRFS_I(inode), hole_start,
5152 block_end - 1, &cached_state);
5153 cur_offset = hole_start;
5155 em = btrfs_get_extent(BTRFS_I(inode), NULL, 0, cur_offset,
5156 block_end - cur_offset, 0);
5162 last_byte = min(extent_map_end(em), block_end);
5163 last_byte = ALIGN(last_byte, fs_info->sectorsize);
5164 if (!test_bit(EXTENT_FLAG_PREALLOC, &em->flags)) {
5165 struct extent_map *hole_em;
5166 hole_size = last_byte - cur_offset;
5168 err = maybe_insert_hole(root, inode, cur_offset,
5172 btrfs_drop_extent_cache(BTRFS_I(inode), cur_offset,
5173 cur_offset + hole_size - 1, 0);
5174 hole_em = alloc_extent_map();
5176 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
5177 &BTRFS_I(inode)->runtime_flags);
5180 hole_em->start = cur_offset;
5181 hole_em->len = hole_size;
5182 hole_em->orig_start = cur_offset;
5184 hole_em->block_start = EXTENT_MAP_HOLE;
5185 hole_em->block_len = 0;
5186 hole_em->orig_block_len = 0;
5187 hole_em->ram_bytes = hole_size;
5188 hole_em->bdev = fs_info->fs_devices->latest_bdev;
5189 hole_em->compress_type = BTRFS_COMPRESS_NONE;
5190 hole_em->generation = fs_info->generation;
5193 write_lock(&em_tree->lock);
5194 err = add_extent_mapping(em_tree, hole_em, 1);
5195 write_unlock(&em_tree->lock);
5198 btrfs_drop_extent_cache(BTRFS_I(inode),
5203 free_extent_map(hole_em);
5206 free_extent_map(em);
5208 cur_offset = last_byte;
5209 if (cur_offset >= block_end)
5212 free_extent_map(em);
5213 unlock_extent_cached(io_tree, hole_start, block_end - 1, &cached_state);
5217 static int btrfs_setsize(struct inode *inode, struct iattr *attr)
5219 struct btrfs_root *root = BTRFS_I(inode)->root;
5220 struct btrfs_trans_handle *trans;
5221 loff_t oldsize = i_size_read(inode);
5222 loff_t newsize = attr->ia_size;
5223 int mask = attr->ia_valid;
5227 * The regular truncate() case without ATTR_CTIME and ATTR_MTIME is a
5228 * special case where we need to update the times despite not having
5229 * these flags set. For all other operations the VFS set these flags
5230 * explicitly if it wants a timestamp update.
5232 if (newsize != oldsize) {
5233 inode_inc_iversion(inode);
5234 if (!(mask & (ATTR_CTIME | ATTR_MTIME)))
5235 inode->i_ctime = inode->i_mtime =
5236 current_time(inode);
5239 if (newsize > oldsize) {
5241 * Don't do an expanding truncate while snapshotting is ongoing.
5242 * This is to ensure the snapshot captures a fully consistent
5243 * state of this file - if the snapshot captures this expanding
5244 * truncation, it must capture all writes that happened before
5247 btrfs_wait_for_snapshot_creation(root);
5248 ret = btrfs_cont_expand(inode, oldsize, newsize);
5250 btrfs_end_write_no_snapshotting(root);
5254 trans = btrfs_start_transaction(root, 1);
5255 if (IS_ERR(trans)) {
5256 btrfs_end_write_no_snapshotting(root);
5257 return PTR_ERR(trans);
5260 i_size_write(inode, newsize);
5261 btrfs_ordered_update_i_size(inode, i_size_read(inode), NULL);
5262 pagecache_isize_extended(inode, oldsize, newsize);
5263 ret = btrfs_update_inode(trans, root, inode);
5264 btrfs_end_write_no_snapshotting(root);
5265 btrfs_end_transaction(trans);
5269 * We're truncating a file that used to have good data down to
5270 * zero. Make sure it gets into the ordered flush list so that
5271 * any new writes get down to disk quickly.
5274 set_bit(BTRFS_INODE_ORDERED_DATA_CLOSE,
5275 &BTRFS_I(inode)->runtime_flags);
5277 truncate_setsize(inode, newsize);
5279 /* Disable nonlocked read DIO to avoid the endless truncate */
5280 btrfs_inode_block_unlocked_dio(BTRFS_I(inode));
5281 inode_dio_wait(inode);
5282 btrfs_inode_resume_unlocked_dio(BTRFS_I(inode));
5284 ret = btrfs_truncate(inode, newsize == oldsize);
5285 if (ret && inode->i_nlink) {
5289 * Truncate failed, so fix up the in-memory size. We
5290 * adjusted disk_i_size down as we removed extents, so
5291 * wait for disk_i_size to be stable and then update the
5292 * in-memory size to match.
5294 err = btrfs_wait_ordered_range(inode, 0, (u64)-1);
5297 i_size_write(inode, BTRFS_I(inode)->disk_i_size);
5304 static int btrfs_setattr(struct dentry *dentry, struct iattr *attr)
5306 struct inode *inode = d_inode(dentry);
5307 struct btrfs_root *root = BTRFS_I(inode)->root;
5310 if (btrfs_root_readonly(root))
5313 err = setattr_prepare(dentry, attr);
5317 if (S_ISREG(inode->i_mode) && (attr->ia_valid & ATTR_SIZE)) {
5318 err = btrfs_setsize(inode, attr);
5323 if (attr->ia_valid) {
5324 setattr_copy(inode, attr);
5325 inode_inc_iversion(inode);
5326 err = btrfs_dirty_inode(inode);
5328 if (!err && attr->ia_valid & ATTR_MODE)
5329 err = posix_acl_chmod(inode, inode->i_mode);
5336 * While truncating the inode pages during eviction, we get the VFS calling
5337 * btrfs_invalidatepage() against each page of the inode. This is slow because
5338 * the calls to btrfs_invalidatepage() result in a huge amount of calls to
5339 * lock_extent_bits() and clear_extent_bit(), which keep merging and splitting
5340 * extent_state structures over and over, wasting lots of time.
5342 * Therefore if the inode is being evicted, let btrfs_invalidatepage() skip all
5343 * those expensive operations on a per page basis and do only the ordered io
5344 * finishing, while we release here the extent_map and extent_state structures,
5345 * without the excessive merging and splitting.
5347 static void evict_inode_truncate_pages(struct inode *inode)
5349 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
5350 struct extent_map_tree *map_tree = &BTRFS_I(inode)->extent_tree;
5351 struct rb_node *node;
5353 ASSERT(inode->i_state & I_FREEING);
5354 truncate_inode_pages_final(&inode->i_data);
5356 write_lock(&map_tree->lock);
5357 while (!RB_EMPTY_ROOT(&map_tree->map.rb_root)) {
5358 struct extent_map *em;
5360 node = rb_first_cached(&map_tree->map);
5361 em = rb_entry(node, struct extent_map, rb_node);
5362 clear_bit(EXTENT_FLAG_PINNED, &em->flags);
5363 clear_bit(EXTENT_FLAG_LOGGING, &em->flags);
5364 remove_extent_mapping(map_tree, em);
5365 free_extent_map(em);
5366 if (need_resched()) {
5367 write_unlock(&map_tree->lock);
5369 write_lock(&map_tree->lock);
5372 write_unlock(&map_tree->lock);
5375 * Keep looping until we have no more ranges in the io tree.
5376 * We can have ongoing bios started by readpages (called from readahead)
5377 * that have their endio callback (extent_io.c:end_bio_extent_readpage)
5378 * still in progress (unlocked the pages in the bio but did not yet
5379 * unlocked the ranges in the io tree). Therefore this means some
5380 * ranges can still be locked and eviction started because before
5381 * submitting those bios, which are executed by a separate task (work
5382 * queue kthread), inode references (inode->i_count) were not taken
5383 * (which would be dropped in the end io callback of each bio).
5384 * Therefore here we effectively end up waiting for those bios and
5385 * anyone else holding locked ranges without having bumped the inode's
5386 * reference count - if we don't do it, when they access the inode's
5387 * io_tree to unlock a range it may be too late, leading to an
5388 * use-after-free issue.
5390 spin_lock(&io_tree->lock);
5391 while (!RB_EMPTY_ROOT(&io_tree->state)) {
5392 struct extent_state *state;
5393 struct extent_state *cached_state = NULL;
5396 unsigned state_flags;
5398 node = rb_first(&io_tree->state);
5399 state = rb_entry(node, struct extent_state, rb_node);
5400 start = state->start;
5402 state_flags = state->state;
5403 spin_unlock(&io_tree->lock);
5405 lock_extent_bits(io_tree, start, end, &cached_state);
5408 * If still has DELALLOC flag, the extent didn't reach disk,
5409 * and its reserved space won't be freed by delayed_ref.
5410 * So we need to free its reserved space here.
5411 * (Refer to comment in btrfs_invalidatepage, case 2)
5413 * Note, end is the bytenr of last byte, so we need + 1 here.
5415 if (state_flags & EXTENT_DELALLOC)
5416 btrfs_qgroup_free_data(inode, NULL, start, end - start + 1);
5418 clear_extent_bit(io_tree, start, end,
5419 EXTENT_LOCKED | EXTENT_DELALLOC |
5420 EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG, 1, 1,
5424 spin_lock(&io_tree->lock);
5426 spin_unlock(&io_tree->lock);
5429 static struct btrfs_trans_handle *evict_refill_and_join(struct btrfs_root *root,
5430 struct btrfs_block_rsv *rsv)
5432 struct btrfs_fs_info *fs_info = root->fs_info;
5433 struct btrfs_block_rsv *global_rsv = &fs_info->global_block_rsv;
5434 struct btrfs_trans_handle *trans;
5435 u64 delayed_refs_extra = btrfs_calc_insert_metadata_size(fs_info, 1);
5439 * Eviction should be taking place at some place safe because of our
5440 * delayed iputs. However the normal flushing code will run delayed
5441 * iputs, so we cannot use FLUSH_ALL otherwise we'll deadlock.
5443 * We reserve the delayed_refs_extra here again because we can't use
5444 * btrfs_start_transaction(root, 0) for the same deadlocky reason as
5445 * above. We reserve our extra bit here because we generate a ton of
5446 * delayed refs activity by truncating.
5448 * If we cannot make our reservation we'll attempt to steal from the
5449 * global reserve, because we really want to be able to free up space.
5451 ret = btrfs_block_rsv_refill(root, rsv, rsv->size + delayed_refs_extra,
5452 BTRFS_RESERVE_FLUSH_EVICT);
5455 * Try to steal from the global reserve if there is space for
5458 if (btrfs_check_space_for_delayed_refs(fs_info) ||
5459 btrfs_block_rsv_migrate(global_rsv, rsv, rsv->size, 0)) {
5461 "could not allocate space for delete; will truncate on mount");
5462 return ERR_PTR(-ENOSPC);
5464 delayed_refs_extra = 0;
5467 trans = btrfs_join_transaction(root);
5471 if (delayed_refs_extra) {
5472 trans->block_rsv = &fs_info->trans_block_rsv;
5473 trans->bytes_reserved = delayed_refs_extra;
5474 btrfs_block_rsv_migrate(rsv, trans->block_rsv,
5475 delayed_refs_extra, 1);
5480 void btrfs_evict_inode(struct inode *inode)
5482 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
5483 struct btrfs_trans_handle *trans;
5484 struct btrfs_root *root = BTRFS_I(inode)->root;
5485 struct btrfs_block_rsv *rsv;
5488 trace_btrfs_inode_evict(inode);
5495 evict_inode_truncate_pages(inode);
5497 if (inode->i_nlink &&
5498 ((btrfs_root_refs(&root->root_item) != 0 &&
5499 root->root_key.objectid != BTRFS_ROOT_TREE_OBJECTID) ||
5500 btrfs_is_free_space_inode(BTRFS_I(inode))))
5503 if (is_bad_inode(inode))
5506 btrfs_free_io_failure_record(BTRFS_I(inode), 0, (u64)-1);
5508 if (test_bit(BTRFS_FS_LOG_RECOVERING, &fs_info->flags))
5511 if (inode->i_nlink > 0) {
5512 BUG_ON(btrfs_root_refs(&root->root_item) != 0 &&
5513 root->root_key.objectid != BTRFS_ROOT_TREE_OBJECTID);
5517 ret = btrfs_commit_inode_delayed_inode(BTRFS_I(inode));
5521 rsv = btrfs_alloc_block_rsv(fs_info, BTRFS_BLOCK_RSV_TEMP);
5524 rsv->size = btrfs_calc_metadata_size(fs_info, 1);
5527 btrfs_i_size_write(BTRFS_I(inode), 0);
5530 trans = evict_refill_and_join(root, rsv);
5534 trans->block_rsv = rsv;
5536 ret = btrfs_truncate_inode_items(trans, root, inode, 0, 0);
5537 trans->block_rsv = &fs_info->trans_block_rsv;
5538 btrfs_end_transaction(trans);
5539 btrfs_btree_balance_dirty(fs_info);
5540 if (ret && ret != -ENOSPC && ret != -EAGAIN)
5547 * Errors here aren't a big deal, it just means we leave orphan items in
5548 * the tree. They will be cleaned up on the next mount. If the inode
5549 * number gets reused, cleanup deletes the orphan item without doing
5550 * anything, and unlink reuses the existing orphan item.
5552 * If it turns out that we are dropping too many of these, we might want
5553 * to add a mechanism for retrying these after a commit.
5555 trans = evict_refill_and_join(root, rsv);
5556 if (!IS_ERR(trans)) {
5557 trans->block_rsv = rsv;
5558 btrfs_orphan_del(trans, BTRFS_I(inode));
5559 trans->block_rsv = &fs_info->trans_block_rsv;
5560 btrfs_end_transaction(trans);
5563 if (!(root == fs_info->tree_root ||
5564 root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID))
5565 btrfs_return_ino(root, btrfs_ino(BTRFS_I(inode)));
5568 btrfs_free_block_rsv(fs_info, rsv);
5571 * If we didn't successfully delete, the orphan item will still be in
5572 * the tree and we'll retry on the next mount. Again, we might also want
5573 * to retry these periodically in the future.
5575 btrfs_remove_delayed_node(BTRFS_I(inode));
5580 * Return the key found in the dir entry in the location pointer, fill @type
5581 * with BTRFS_FT_*, and return 0.
5583 * If no dir entries were found, returns -ENOENT.
5584 * If found a corrupted location in dir entry, returns -EUCLEAN.
5586 static int btrfs_inode_by_name(struct inode *dir, struct dentry *dentry,
5587 struct btrfs_key *location, u8 *type)
5589 const char *name = dentry->d_name.name;
5590 int namelen = dentry->d_name.len;
5591 struct btrfs_dir_item *di;
5592 struct btrfs_path *path;
5593 struct btrfs_root *root = BTRFS_I(dir)->root;
5596 path = btrfs_alloc_path();
5600 di = btrfs_lookup_dir_item(NULL, root, path, btrfs_ino(BTRFS_I(dir)),
5602 if (IS_ERR_OR_NULL(di)) {
5603 ret = di ? PTR_ERR(di) : -ENOENT;
5607 btrfs_dir_item_key_to_cpu(path->nodes[0], di, location);
5608 if (location->type != BTRFS_INODE_ITEM_KEY &&
5609 location->type != BTRFS_ROOT_ITEM_KEY) {
5611 btrfs_warn(root->fs_info,
5612 "%s gets something invalid in DIR_ITEM (name %s, directory ino %llu, location(%llu %u %llu))",
5613 __func__, name, btrfs_ino(BTRFS_I(dir)),
5614 location->objectid, location->type, location->offset);
5617 *type = btrfs_dir_type(path->nodes[0], di);
5619 btrfs_free_path(path);
5624 * when we hit a tree root in a directory, the btrfs part of the inode
5625 * needs to be changed to reflect the root directory of the tree root. This
5626 * is kind of like crossing a mount point.
5628 static int fixup_tree_root_location(struct btrfs_fs_info *fs_info,
5630 struct dentry *dentry,
5631 struct btrfs_key *location,
5632 struct btrfs_root **sub_root)
5634 struct btrfs_path *path;
5635 struct btrfs_root *new_root;
5636 struct btrfs_root_ref *ref;
5637 struct extent_buffer *leaf;
5638 struct btrfs_key key;
5642 path = btrfs_alloc_path();
5649 key.objectid = BTRFS_I(dir)->root->root_key.objectid;
5650 key.type = BTRFS_ROOT_REF_KEY;
5651 key.offset = location->objectid;
5653 ret = btrfs_search_slot(NULL, fs_info->tree_root, &key, path, 0, 0);
5660 leaf = path->nodes[0];
5661 ref = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_root_ref);
5662 if (btrfs_root_ref_dirid(leaf, ref) != btrfs_ino(BTRFS_I(dir)) ||
5663 btrfs_root_ref_name_len(leaf, ref) != dentry->d_name.len)
5666 ret = memcmp_extent_buffer(leaf, dentry->d_name.name,
5667 (unsigned long)(ref + 1),
5668 dentry->d_name.len);
5672 btrfs_release_path(path);
5674 new_root = btrfs_read_fs_root_no_name(fs_info, location);
5675 if (IS_ERR(new_root)) {
5676 err = PTR_ERR(new_root);
5680 *sub_root = new_root;
5681 location->objectid = btrfs_root_dirid(&new_root->root_item);
5682 location->type = BTRFS_INODE_ITEM_KEY;
5683 location->offset = 0;
5686 btrfs_free_path(path);
5690 static void inode_tree_add(struct inode *inode)
5692 struct btrfs_root *root = BTRFS_I(inode)->root;
5693 struct btrfs_inode *entry;
5695 struct rb_node *parent;
5696 struct rb_node *new = &BTRFS_I(inode)->rb_node;
5697 u64 ino = btrfs_ino(BTRFS_I(inode));
5699 if (inode_unhashed(inode))
5702 spin_lock(&root->inode_lock);
5703 p = &root->inode_tree.rb_node;
5706 entry = rb_entry(parent, struct btrfs_inode, rb_node);
5708 if (ino < btrfs_ino(entry))
5709 p = &parent->rb_left;
5710 else if (ino > btrfs_ino(entry))
5711 p = &parent->rb_right;
5713 WARN_ON(!(entry->vfs_inode.i_state &
5714 (I_WILL_FREE | I_FREEING)));
5715 rb_replace_node(parent, new, &root->inode_tree);
5716 RB_CLEAR_NODE(parent);
5717 spin_unlock(&root->inode_lock);
5721 rb_link_node(new, parent, p);
5722 rb_insert_color(new, &root->inode_tree);
5723 spin_unlock(&root->inode_lock);
5726 static void inode_tree_del(struct inode *inode)
5728 struct btrfs_root *root = BTRFS_I(inode)->root;
5731 spin_lock(&root->inode_lock);
5732 if (!RB_EMPTY_NODE(&BTRFS_I(inode)->rb_node)) {
5733 rb_erase(&BTRFS_I(inode)->rb_node, &root->inode_tree);
5734 RB_CLEAR_NODE(&BTRFS_I(inode)->rb_node);
5735 empty = RB_EMPTY_ROOT(&root->inode_tree);
5737 spin_unlock(&root->inode_lock);
5739 if (empty && btrfs_root_refs(&root->root_item) == 0) {
5740 spin_lock(&root->inode_lock);
5741 empty = RB_EMPTY_ROOT(&root->inode_tree);
5742 spin_unlock(&root->inode_lock);
5744 btrfs_add_dead_root(root);
5749 static int btrfs_init_locked_inode(struct inode *inode, void *p)
5751 struct btrfs_iget_args *args = p;
5752 inode->i_ino = args->location->objectid;
5753 memcpy(&BTRFS_I(inode)->location, args->location,
5754 sizeof(*args->location));
5755 BTRFS_I(inode)->root = args->root;
5759 static int btrfs_find_actor(struct inode *inode, void *opaque)
5761 struct btrfs_iget_args *args = opaque;
5762 return args->location->objectid == BTRFS_I(inode)->location.objectid &&
5763 args->root == BTRFS_I(inode)->root;
5766 static struct inode *btrfs_iget_locked(struct super_block *s,
5767 struct btrfs_key *location,
5768 struct btrfs_root *root)
5770 struct inode *inode;
5771 struct btrfs_iget_args args;
5772 unsigned long hashval = btrfs_inode_hash(location->objectid, root);
5774 args.location = location;
5777 inode = iget5_locked(s, hashval, btrfs_find_actor,
5778 btrfs_init_locked_inode,
5783 /* Get an inode object given its location and corresponding root.
5784 * Returns in *is_new if the inode was read from disk
5786 struct inode *btrfs_iget_path(struct super_block *s, struct btrfs_key *location,
5787 struct btrfs_root *root, int *new,
5788 struct btrfs_path *path)
5790 struct inode *inode;
5792 inode = btrfs_iget_locked(s, location, root);
5794 return ERR_PTR(-ENOMEM);
5796 if (inode->i_state & I_NEW) {
5799 ret = btrfs_read_locked_inode(inode, path);
5801 inode_tree_add(inode);
5802 unlock_new_inode(inode);
5808 * ret > 0 can come from btrfs_search_slot called by
5809 * btrfs_read_locked_inode, this means the inode item
5814 inode = ERR_PTR(ret);
5821 struct inode *btrfs_iget(struct super_block *s, struct btrfs_key *location,
5822 struct btrfs_root *root, int *new)
5824 return btrfs_iget_path(s, location, root, new, NULL);
5827 static struct inode *new_simple_dir(struct super_block *s,
5828 struct btrfs_key *key,
5829 struct btrfs_root *root)
5831 struct inode *inode = new_inode(s);
5834 return ERR_PTR(-ENOMEM);
5836 BTRFS_I(inode)->root = root;
5837 memcpy(&BTRFS_I(inode)->location, key, sizeof(*key));
5838 set_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags);
5840 inode->i_ino = BTRFS_EMPTY_SUBVOL_DIR_OBJECTID;
5841 inode->i_op = &btrfs_dir_ro_inode_operations;
5842 inode->i_opflags &= ~IOP_XATTR;
5843 inode->i_fop = &simple_dir_operations;
5844 inode->i_mode = S_IFDIR | S_IRUGO | S_IWUSR | S_IXUGO;
5845 inode->i_mtime = current_time(inode);
5846 inode->i_atime = inode->i_mtime;
5847 inode->i_ctime = inode->i_mtime;
5848 BTRFS_I(inode)->i_otime = inode->i_mtime;
5853 static inline u8 btrfs_inode_type(struct inode *inode)
5856 * Compile-time asserts that generic FT_* types still match
5859 BUILD_BUG_ON(BTRFS_FT_UNKNOWN != FT_UNKNOWN);
5860 BUILD_BUG_ON(BTRFS_FT_REG_FILE != FT_REG_FILE);
5861 BUILD_BUG_ON(BTRFS_FT_DIR != FT_DIR);
5862 BUILD_BUG_ON(BTRFS_FT_CHRDEV != FT_CHRDEV);
5863 BUILD_BUG_ON(BTRFS_FT_BLKDEV != FT_BLKDEV);
5864 BUILD_BUG_ON(BTRFS_FT_FIFO != FT_FIFO);
5865 BUILD_BUG_ON(BTRFS_FT_SOCK != FT_SOCK);
5866 BUILD_BUG_ON(BTRFS_FT_SYMLINK != FT_SYMLINK);
5868 return fs_umode_to_ftype(inode->i_mode);
5871 struct inode *btrfs_lookup_dentry(struct inode *dir, struct dentry *dentry)
5873 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
5874 struct inode *inode;
5875 struct btrfs_root *root = BTRFS_I(dir)->root;
5876 struct btrfs_root *sub_root = root;
5877 struct btrfs_key location;
5882 if (dentry->d_name.len > BTRFS_NAME_LEN)
5883 return ERR_PTR(-ENAMETOOLONG);
5885 ret = btrfs_inode_by_name(dir, dentry, &location, &di_type);
5887 return ERR_PTR(ret);
5889 if (location.type == BTRFS_INODE_ITEM_KEY) {
5890 inode = btrfs_iget(dir->i_sb, &location, root, NULL);
5894 /* Do extra check against inode mode with di_type */
5895 if (btrfs_inode_type(inode) != di_type) {
5897 "inode mode mismatch with dir: inode mode=0%o btrfs type=%u dir type=%u",
5898 inode->i_mode, btrfs_inode_type(inode),
5901 return ERR_PTR(-EUCLEAN);
5906 index = srcu_read_lock(&fs_info->subvol_srcu);
5907 ret = fixup_tree_root_location(fs_info, dir, dentry,
5908 &location, &sub_root);
5911 inode = ERR_PTR(ret);
5913 inode = new_simple_dir(dir->i_sb, &location, sub_root);
5915 inode = btrfs_iget(dir->i_sb, &location, sub_root, NULL);
5917 srcu_read_unlock(&fs_info->subvol_srcu, index);
5919 if (!IS_ERR(inode) && root != sub_root) {
5920 down_read(&fs_info->cleanup_work_sem);
5921 if (!sb_rdonly(inode->i_sb))
5922 ret = btrfs_orphan_cleanup(sub_root);
5923 up_read(&fs_info->cleanup_work_sem);
5926 inode = ERR_PTR(ret);
5933 static int btrfs_dentry_delete(const struct dentry *dentry)
5935 struct btrfs_root *root;
5936 struct inode *inode = d_inode(dentry);
5938 if (!inode && !IS_ROOT(dentry))
5939 inode = d_inode(dentry->d_parent);
5942 root = BTRFS_I(inode)->root;
5943 if (btrfs_root_refs(&root->root_item) == 0)
5946 if (btrfs_ino(BTRFS_I(inode)) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)
5952 static struct dentry *btrfs_lookup(struct inode *dir, struct dentry *dentry,
5955 struct inode *inode = btrfs_lookup_dentry(dir, dentry);
5957 if (inode == ERR_PTR(-ENOENT))
5959 return d_splice_alias(inode, dentry);
5963 * All this infrastructure exists because dir_emit can fault, and we are holding
5964 * the tree lock when doing readdir. For now just allocate a buffer and copy
5965 * our information into that, and then dir_emit from the buffer. This is
5966 * similar to what NFS does, only we don't keep the buffer around in pagecache
5967 * because I'm afraid I'll mess that up. Long term we need to make filldir do
5968 * copy_to_user_inatomic so we don't have to worry about page faulting under the
5971 static int btrfs_opendir(struct inode *inode, struct file *file)
5973 struct btrfs_file_private *private;
5975 private = kzalloc(sizeof(struct btrfs_file_private), GFP_KERNEL);
5978 private->filldir_buf = kzalloc(PAGE_SIZE, GFP_KERNEL);
5979 if (!private->filldir_buf) {
5983 file->private_data = private;
5994 static int btrfs_filldir(void *addr, int entries, struct dir_context *ctx)
5997 struct dir_entry *entry = addr;
5998 char *name = (char *)(entry + 1);
6000 ctx->pos = get_unaligned(&entry->offset);
6001 if (!dir_emit(ctx, name, get_unaligned(&entry->name_len),
6002 get_unaligned(&entry->ino),
6003 get_unaligned(&entry->type)))
6005 addr += sizeof(struct dir_entry) +
6006 get_unaligned(&entry->name_len);
6012 static int btrfs_real_readdir(struct file *file, struct dir_context *ctx)
6014 struct inode *inode = file_inode(file);
6015 struct btrfs_root *root = BTRFS_I(inode)->root;
6016 struct btrfs_file_private *private = file->private_data;
6017 struct btrfs_dir_item *di;
6018 struct btrfs_key key;
6019 struct btrfs_key found_key;
6020 struct btrfs_path *path;
6022 struct list_head ins_list;
6023 struct list_head del_list;
6025 struct extent_buffer *leaf;
6032 struct btrfs_key location;
6034 if (!dir_emit_dots(file, ctx))
6037 path = btrfs_alloc_path();
6041 addr = private->filldir_buf;
6042 path->reada = READA_FORWARD;
6044 INIT_LIST_HEAD(&ins_list);
6045 INIT_LIST_HEAD(&del_list);
6046 put = btrfs_readdir_get_delayed_items(inode, &ins_list, &del_list);
6049 key.type = BTRFS_DIR_INDEX_KEY;
6050 key.offset = ctx->pos;
6051 key.objectid = btrfs_ino(BTRFS_I(inode));
6053 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
6058 struct dir_entry *entry;
6060 leaf = path->nodes[0];
6061 slot = path->slots[0];
6062 if (slot >= btrfs_header_nritems(leaf)) {
6063 ret = btrfs_next_leaf(root, path);
6071 btrfs_item_key_to_cpu(leaf, &found_key, slot);
6073 if (found_key.objectid != key.objectid)
6075 if (found_key.type != BTRFS_DIR_INDEX_KEY)
6077 if (found_key.offset < ctx->pos)
6079 if (btrfs_should_delete_dir_index(&del_list, found_key.offset))
6081 di = btrfs_item_ptr(leaf, slot, struct btrfs_dir_item);
6082 name_len = btrfs_dir_name_len(leaf, di);
6083 if ((total_len + sizeof(struct dir_entry) + name_len) >=
6085 btrfs_release_path(path);
6086 ret = btrfs_filldir(private->filldir_buf, entries, ctx);
6089 addr = private->filldir_buf;
6096 put_unaligned(name_len, &entry->name_len);
6097 name_ptr = (char *)(entry + 1);
6098 read_extent_buffer(leaf, name_ptr, (unsigned long)(di + 1),
6100 put_unaligned(fs_ftype_to_dtype(btrfs_dir_type(leaf, di)),
6102 btrfs_dir_item_key_to_cpu(leaf, di, &location);
6103 put_unaligned(location.objectid, &entry->ino);
6104 put_unaligned(found_key.offset, &entry->offset);
6106 addr += sizeof(struct dir_entry) + name_len;
6107 total_len += sizeof(struct dir_entry) + name_len;
6111 btrfs_release_path(path);
6113 ret = btrfs_filldir(private->filldir_buf, entries, ctx);
6117 ret = btrfs_readdir_delayed_dir_index(ctx, &ins_list);
6122 * Stop new entries from being returned after we return the last
6125 * New directory entries are assigned a strictly increasing
6126 * offset. This means that new entries created during readdir
6127 * are *guaranteed* to be seen in the future by that readdir.
6128 * This has broken buggy programs which operate on names as
6129 * they're returned by readdir. Until we re-use freed offsets
6130 * we have this hack to stop new entries from being returned
6131 * under the assumption that they'll never reach this huge
6134 * This is being careful not to overflow 32bit loff_t unless the
6135 * last entry requires it because doing so has broken 32bit apps
6138 if (ctx->pos >= INT_MAX)
6139 ctx->pos = LLONG_MAX;
6146 btrfs_readdir_put_delayed_items(inode, &ins_list, &del_list);
6147 btrfs_free_path(path);
6152 * This is somewhat expensive, updating the tree every time the
6153 * inode changes. But, it is most likely to find the inode in cache.
6154 * FIXME, needs more benchmarking...there are no reasons other than performance
6155 * to keep or drop this code.
6157 static int btrfs_dirty_inode(struct inode *inode)
6159 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
6160 struct btrfs_root *root = BTRFS_I(inode)->root;
6161 struct btrfs_trans_handle *trans;
6164 if (test_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags))
6167 trans = btrfs_join_transaction(root);
6169 return PTR_ERR(trans);
6171 ret = btrfs_update_inode(trans, root, inode);
6172 if (ret && ret == -ENOSPC) {
6173 /* whoops, lets try again with the full transaction */
6174 btrfs_end_transaction(trans);
6175 trans = btrfs_start_transaction(root, 1);
6177 return PTR_ERR(trans);
6179 ret = btrfs_update_inode(trans, root, inode);
6181 btrfs_end_transaction(trans);
6182 if (BTRFS_I(inode)->delayed_node)
6183 btrfs_balance_delayed_items(fs_info);
6189 * This is a copy of file_update_time. We need this so we can return error on
6190 * ENOSPC for updating the inode in the case of file write and mmap writes.
6192 static int btrfs_update_time(struct inode *inode, struct timespec64 *now,
6195 struct btrfs_root *root = BTRFS_I(inode)->root;
6196 bool dirty = flags & ~S_VERSION;
6198 if (btrfs_root_readonly(root))
6201 if (flags & S_VERSION)
6202 dirty |= inode_maybe_inc_iversion(inode, dirty);
6203 if (flags & S_CTIME)
6204 inode->i_ctime = *now;
6205 if (flags & S_MTIME)
6206 inode->i_mtime = *now;
6207 if (flags & S_ATIME)
6208 inode->i_atime = *now;
6209 return dirty ? btrfs_dirty_inode(inode) : 0;
6213 * find the highest existing sequence number in a directory
6214 * and then set the in-memory index_cnt variable to reflect
6215 * free sequence numbers
6217 static int btrfs_set_inode_index_count(struct btrfs_inode *inode)
6219 struct btrfs_root *root = inode->root;
6220 struct btrfs_key key, found_key;
6221 struct btrfs_path *path;
6222 struct extent_buffer *leaf;
6225 key.objectid = btrfs_ino(inode);
6226 key.type = BTRFS_DIR_INDEX_KEY;
6227 key.offset = (u64)-1;
6229 path = btrfs_alloc_path();
6233 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
6236 /* FIXME: we should be able to handle this */
6242 * MAGIC NUMBER EXPLANATION:
6243 * since we search a directory based on f_pos we have to start at 2
6244 * since '.' and '..' have f_pos of 0 and 1 respectively, so everybody
6245 * else has to start at 2
6247 if (path->slots[0] == 0) {
6248 inode->index_cnt = 2;
6254 leaf = path->nodes[0];
6255 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
6257 if (found_key.objectid != btrfs_ino(inode) ||
6258 found_key.type != BTRFS_DIR_INDEX_KEY) {
6259 inode->index_cnt = 2;
6263 inode->index_cnt = found_key.offset + 1;
6265 btrfs_free_path(path);
6270 * helper to find a free sequence number in a given directory. This current
6271 * code is very simple, later versions will do smarter things in the btree
6273 int btrfs_set_inode_index(struct btrfs_inode *dir, u64 *index)
6277 if (dir->index_cnt == (u64)-1) {
6278 ret = btrfs_inode_delayed_dir_index_count(dir);
6280 ret = btrfs_set_inode_index_count(dir);
6286 *index = dir->index_cnt;
6292 static int btrfs_insert_inode_locked(struct inode *inode)
6294 struct btrfs_iget_args args;
6295 args.location = &BTRFS_I(inode)->location;
6296 args.root = BTRFS_I(inode)->root;
6298 return insert_inode_locked4(inode,
6299 btrfs_inode_hash(inode->i_ino, BTRFS_I(inode)->root),
6300 btrfs_find_actor, &args);
6304 * Inherit flags from the parent inode.
6306 * Currently only the compression flags and the cow flags are inherited.
6308 static void btrfs_inherit_iflags(struct inode *inode, struct inode *dir)
6315 flags = BTRFS_I(dir)->flags;
6317 if (flags & BTRFS_INODE_NOCOMPRESS) {
6318 BTRFS_I(inode)->flags &= ~BTRFS_INODE_COMPRESS;
6319 BTRFS_I(inode)->flags |= BTRFS_INODE_NOCOMPRESS;
6320 } else if (flags & BTRFS_INODE_COMPRESS) {
6321 BTRFS_I(inode)->flags &= ~BTRFS_INODE_NOCOMPRESS;
6322 BTRFS_I(inode)->flags |= BTRFS_INODE_COMPRESS;
6325 if (flags & BTRFS_INODE_NODATACOW) {
6326 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATACOW;
6327 if (S_ISREG(inode->i_mode))
6328 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATASUM;
6331 btrfs_sync_inode_flags_to_i_flags(inode);
6334 static struct inode *btrfs_new_inode(struct btrfs_trans_handle *trans,
6335 struct btrfs_root *root,
6337 const char *name, int name_len,
6338 u64 ref_objectid, u64 objectid,
6339 umode_t mode, u64 *index)
6341 struct btrfs_fs_info *fs_info = root->fs_info;
6342 struct inode *inode;
6343 struct btrfs_inode_item *inode_item;
6344 struct btrfs_key *location;
6345 struct btrfs_path *path;
6346 struct btrfs_inode_ref *ref;
6347 struct btrfs_key key[2];
6349 int nitems = name ? 2 : 1;
6351 unsigned int nofs_flag;
6354 path = btrfs_alloc_path();
6356 return ERR_PTR(-ENOMEM);
6358 nofs_flag = memalloc_nofs_save();
6359 inode = new_inode(fs_info->sb);
6360 memalloc_nofs_restore(nofs_flag);
6362 btrfs_free_path(path);
6363 return ERR_PTR(-ENOMEM);
6367 * O_TMPFILE, set link count to 0, so that after this point,
6368 * we fill in an inode item with the correct link count.
6371 set_nlink(inode, 0);
6374 * we have to initialize this early, so we can reclaim the inode
6375 * number if we fail afterwards in this function.
6377 inode->i_ino = objectid;
6380 trace_btrfs_inode_request(dir);
6382 ret = btrfs_set_inode_index(BTRFS_I(dir), index);
6384 btrfs_free_path(path);
6386 return ERR_PTR(ret);
6392 * index_cnt is ignored for everything but a dir,
6393 * btrfs_set_inode_index_count has an explanation for the magic
6396 BTRFS_I(inode)->index_cnt = 2;
6397 BTRFS_I(inode)->dir_index = *index;
6398 BTRFS_I(inode)->root = root;
6399 BTRFS_I(inode)->generation = trans->transid;
6400 inode->i_generation = BTRFS_I(inode)->generation;
6403 * We could have gotten an inode number from somebody who was fsynced
6404 * and then removed in this same transaction, so let's just set full
6405 * sync since it will be a full sync anyway and this will blow away the
6406 * old info in the log.
6408 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &BTRFS_I(inode)->runtime_flags);
6410 key[0].objectid = objectid;
6411 key[0].type = BTRFS_INODE_ITEM_KEY;
6414 sizes[0] = sizeof(struct btrfs_inode_item);
6418 * Start new inodes with an inode_ref. This is slightly more
6419 * efficient for small numbers of hard links since they will
6420 * be packed into one item. Extended refs will kick in if we
6421 * add more hard links than can fit in the ref item.
6423 key[1].objectid = objectid;
6424 key[1].type = BTRFS_INODE_REF_KEY;
6425 key[1].offset = ref_objectid;
6427 sizes[1] = name_len + sizeof(*ref);
6430 location = &BTRFS_I(inode)->location;
6431 location->objectid = objectid;
6432 location->offset = 0;
6433 location->type = BTRFS_INODE_ITEM_KEY;
6435 ret = btrfs_insert_inode_locked(inode);
6441 path->leave_spinning = 1;
6442 ret = btrfs_insert_empty_items(trans, root, path, key, sizes, nitems);
6446 inode_init_owner(inode, dir, mode);
6447 inode_set_bytes(inode, 0);
6449 inode->i_mtime = current_time(inode);
6450 inode->i_atime = inode->i_mtime;
6451 inode->i_ctime = inode->i_mtime;
6452 BTRFS_I(inode)->i_otime = inode->i_mtime;
6454 inode_item = btrfs_item_ptr(path->nodes[0], path->slots[0],
6455 struct btrfs_inode_item);
6456 memzero_extent_buffer(path->nodes[0], (unsigned long)inode_item,
6457 sizeof(*inode_item));
6458 fill_inode_item(trans, path->nodes[0], inode_item, inode);
6461 ref = btrfs_item_ptr(path->nodes[0], path->slots[0] + 1,
6462 struct btrfs_inode_ref);
6463 btrfs_set_inode_ref_name_len(path->nodes[0], ref, name_len);
6464 btrfs_set_inode_ref_index(path->nodes[0], ref, *index);
6465 ptr = (unsigned long)(ref + 1);
6466 write_extent_buffer(path->nodes[0], name, ptr, name_len);
6469 btrfs_mark_buffer_dirty(path->nodes[0]);
6470 btrfs_free_path(path);
6472 btrfs_inherit_iflags(inode, dir);
6474 if (S_ISREG(mode)) {
6475 if (btrfs_test_opt(fs_info, NODATASUM))
6476 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATASUM;
6477 if (btrfs_test_opt(fs_info, NODATACOW))
6478 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATACOW |
6479 BTRFS_INODE_NODATASUM;
6482 inode_tree_add(inode);
6484 trace_btrfs_inode_new(inode);
6485 btrfs_set_inode_last_trans(trans, inode);
6487 btrfs_update_root_times(trans, root);
6489 ret = btrfs_inode_inherit_props(trans, inode, dir);
6492 "error inheriting props for ino %llu (root %llu): %d",
6493 btrfs_ino(BTRFS_I(inode)), root->root_key.objectid, ret);
6498 discard_new_inode(inode);
6501 BTRFS_I(dir)->index_cnt--;
6502 btrfs_free_path(path);
6503 return ERR_PTR(ret);
6507 * utility function to add 'inode' into 'parent_inode' with
6508 * a give name and a given sequence number.
6509 * if 'add_backref' is true, also insert a backref from the
6510 * inode to the parent directory.
6512 int btrfs_add_link(struct btrfs_trans_handle *trans,
6513 struct btrfs_inode *parent_inode, struct btrfs_inode *inode,
6514 const char *name, int name_len, int add_backref, u64 index)
6517 struct btrfs_key key;
6518 struct btrfs_root *root = parent_inode->root;
6519 u64 ino = btrfs_ino(inode);
6520 u64 parent_ino = btrfs_ino(parent_inode);
6522 if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
6523 memcpy(&key, &inode->root->root_key, sizeof(key));
6526 key.type = BTRFS_INODE_ITEM_KEY;
6530 if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
6531 ret = btrfs_add_root_ref(trans, key.objectid,
6532 root->root_key.objectid, parent_ino,
6533 index, name, name_len);
6534 } else if (add_backref) {
6535 ret = btrfs_insert_inode_ref(trans, root, name, name_len, ino,
6539 /* Nothing to clean up yet */
6543 ret = btrfs_insert_dir_item(trans, name, name_len, parent_inode, &key,
6544 btrfs_inode_type(&inode->vfs_inode), index);
6545 if (ret == -EEXIST || ret == -EOVERFLOW)
6548 btrfs_abort_transaction(trans, ret);
6552 btrfs_i_size_write(parent_inode, parent_inode->vfs_inode.i_size +
6554 inode_inc_iversion(&parent_inode->vfs_inode);
6556 * If we are replaying a log tree, we do not want to update the mtime
6557 * and ctime of the parent directory with the current time, since the
6558 * log replay procedure is responsible for setting them to their correct
6559 * values (the ones it had when the fsync was done).
6561 if (!test_bit(BTRFS_FS_LOG_RECOVERING, &root->fs_info->flags)) {
6562 struct timespec64 now = current_time(&parent_inode->vfs_inode);
6564 parent_inode->vfs_inode.i_mtime = now;
6565 parent_inode->vfs_inode.i_ctime = now;
6567 ret = btrfs_update_inode(trans, root, &parent_inode->vfs_inode);
6569 btrfs_abort_transaction(trans, ret);
6573 if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
6576 err = btrfs_del_root_ref(trans, key.objectid,
6577 root->root_key.objectid, parent_ino,
6578 &local_index, name, name_len);
6580 btrfs_abort_transaction(trans, err);
6581 } else if (add_backref) {
6585 err = btrfs_del_inode_ref(trans, root, name, name_len,
6586 ino, parent_ino, &local_index);
6588 btrfs_abort_transaction(trans, err);
6591 /* Return the original error code */
6595 static int btrfs_add_nondir(struct btrfs_trans_handle *trans,
6596 struct btrfs_inode *dir, struct dentry *dentry,
6597 struct btrfs_inode *inode, int backref, u64 index)
6599 int err = btrfs_add_link(trans, dir, inode,
6600 dentry->d_name.name, dentry->d_name.len,
6607 static int btrfs_mknod(struct inode *dir, struct dentry *dentry,
6608 umode_t mode, dev_t rdev)
6610 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
6611 struct btrfs_trans_handle *trans;
6612 struct btrfs_root *root = BTRFS_I(dir)->root;
6613 struct inode *inode = NULL;
6619 * 2 for inode item and ref
6621 * 1 for xattr if selinux is on
6623 trans = btrfs_start_transaction(root, 5);
6625 return PTR_ERR(trans);
6627 err = btrfs_find_free_ino(root, &objectid);
6631 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
6632 dentry->d_name.len, btrfs_ino(BTRFS_I(dir)), objectid,
6634 if (IS_ERR(inode)) {
6635 err = PTR_ERR(inode);
6641 * If the active LSM wants to access the inode during
6642 * d_instantiate it needs these. Smack checks to see
6643 * if the filesystem supports xattrs by looking at the
6646 inode->i_op = &btrfs_special_inode_operations;
6647 init_special_inode(inode, inode->i_mode, rdev);
6649 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
6653 err = btrfs_add_nondir(trans, BTRFS_I(dir), dentry, BTRFS_I(inode),
6658 btrfs_update_inode(trans, root, inode);
6659 d_instantiate_new(dentry, inode);
6662 btrfs_end_transaction(trans);
6663 btrfs_btree_balance_dirty(fs_info);
6665 inode_dec_link_count(inode);
6666 discard_new_inode(inode);
6671 static int btrfs_create(struct inode *dir, struct dentry *dentry,
6672 umode_t mode, bool excl)
6674 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
6675 struct btrfs_trans_handle *trans;
6676 struct btrfs_root *root = BTRFS_I(dir)->root;
6677 struct inode *inode = NULL;
6683 * 2 for inode item and ref
6685 * 1 for xattr if selinux is on
6687 trans = btrfs_start_transaction(root, 5);
6689 return PTR_ERR(trans);
6691 err = btrfs_find_free_ino(root, &objectid);
6695 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
6696 dentry->d_name.len, btrfs_ino(BTRFS_I(dir)), objectid,
6698 if (IS_ERR(inode)) {
6699 err = PTR_ERR(inode);
6704 * If the active LSM wants to access the inode during
6705 * d_instantiate it needs these. Smack checks to see
6706 * if the filesystem supports xattrs by looking at the
6709 inode->i_fop = &btrfs_file_operations;
6710 inode->i_op = &btrfs_file_inode_operations;
6711 inode->i_mapping->a_ops = &btrfs_aops;
6713 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
6717 err = btrfs_update_inode(trans, root, inode);
6721 err = btrfs_add_nondir(trans, BTRFS_I(dir), dentry, BTRFS_I(inode),
6726 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
6727 d_instantiate_new(dentry, inode);
6730 btrfs_end_transaction(trans);
6732 inode_dec_link_count(inode);
6733 discard_new_inode(inode);
6735 btrfs_btree_balance_dirty(fs_info);
6739 static int btrfs_link(struct dentry *old_dentry, struct inode *dir,
6740 struct dentry *dentry)
6742 struct btrfs_trans_handle *trans = NULL;
6743 struct btrfs_root *root = BTRFS_I(dir)->root;
6744 struct inode *inode = d_inode(old_dentry);
6745 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
6750 /* do not allow sys_link's with other subvols of the same device */
6751 if (root->root_key.objectid != BTRFS_I(inode)->root->root_key.objectid)
6754 if (inode->i_nlink >= BTRFS_LINK_MAX)
6757 err = btrfs_set_inode_index(BTRFS_I(dir), &index);
6762 * 2 items for inode and inode ref
6763 * 2 items for dir items
6764 * 1 item for parent inode
6765 * 1 item for orphan item deletion if O_TMPFILE
6767 trans = btrfs_start_transaction(root, inode->i_nlink ? 5 : 6);
6768 if (IS_ERR(trans)) {
6769 err = PTR_ERR(trans);
6774 /* There are several dir indexes for this inode, clear the cache. */
6775 BTRFS_I(inode)->dir_index = 0ULL;
6777 inode_inc_iversion(inode);
6778 inode->i_ctime = current_time(inode);
6780 set_bit(BTRFS_INODE_COPY_EVERYTHING, &BTRFS_I(inode)->runtime_flags);
6782 err = btrfs_add_nondir(trans, BTRFS_I(dir), dentry, BTRFS_I(inode),
6788 struct dentry *parent = dentry->d_parent;
6791 err = btrfs_update_inode(trans, root, inode);
6794 if (inode->i_nlink == 1) {
6796 * If new hard link count is 1, it's a file created
6797 * with open(2) O_TMPFILE flag.
6799 err = btrfs_orphan_del(trans, BTRFS_I(inode));
6803 d_instantiate(dentry, inode);
6804 ret = btrfs_log_new_name(trans, BTRFS_I(inode), NULL, parent,
6806 if (ret == BTRFS_NEED_TRANS_COMMIT) {
6807 err = btrfs_commit_transaction(trans);
6814 btrfs_end_transaction(trans);
6816 inode_dec_link_count(inode);
6819 btrfs_btree_balance_dirty(fs_info);
6823 static int btrfs_mkdir(struct inode *dir, struct dentry *dentry, umode_t mode)
6825 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
6826 struct inode *inode = NULL;
6827 struct btrfs_trans_handle *trans;
6828 struct btrfs_root *root = BTRFS_I(dir)->root;
6834 * 2 items for inode and ref
6835 * 2 items for dir items
6836 * 1 for xattr if selinux is on
6838 trans = btrfs_start_transaction(root, 5);
6840 return PTR_ERR(trans);
6842 err = btrfs_find_free_ino(root, &objectid);
6846 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
6847 dentry->d_name.len, btrfs_ino(BTRFS_I(dir)), objectid,
6848 S_IFDIR | mode, &index);
6849 if (IS_ERR(inode)) {
6850 err = PTR_ERR(inode);
6855 /* these must be set before we unlock the inode */
6856 inode->i_op = &btrfs_dir_inode_operations;
6857 inode->i_fop = &btrfs_dir_file_operations;
6859 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
6863 btrfs_i_size_write(BTRFS_I(inode), 0);
6864 err = btrfs_update_inode(trans, root, inode);
6868 err = btrfs_add_link(trans, BTRFS_I(dir), BTRFS_I(inode),
6869 dentry->d_name.name,
6870 dentry->d_name.len, 0, index);
6874 d_instantiate_new(dentry, inode);
6877 btrfs_end_transaction(trans);
6879 inode_dec_link_count(inode);
6880 discard_new_inode(inode);
6882 btrfs_btree_balance_dirty(fs_info);
6886 static noinline int uncompress_inline(struct btrfs_path *path,
6888 size_t pg_offset, u64 extent_offset,
6889 struct btrfs_file_extent_item *item)
6892 struct extent_buffer *leaf = path->nodes[0];
6895 unsigned long inline_size;
6899 WARN_ON(pg_offset != 0);
6900 compress_type = btrfs_file_extent_compression(leaf, item);
6901 max_size = btrfs_file_extent_ram_bytes(leaf, item);
6902 inline_size = btrfs_file_extent_inline_item_len(leaf,
6903 btrfs_item_nr(path->slots[0]));
6904 tmp = kmalloc(inline_size, GFP_NOFS);
6907 ptr = btrfs_file_extent_inline_start(item);
6909 read_extent_buffer(leaf, tmp, ptr, inline_size);
6911 max_size = min_t(unsigned long, PAGE_SIZE, max_size);
6912 ret = btrfs_decompress(compress_type, tmp, page,
6913 extent_offset, inline_size, max_size);
6916 * decompression code contains a memset to fill in any space between the end
6917 * of the uncompressed data and the end of max_size in case the decompressed
6918 * data ends up shorter than ram_bytes. That doesn't cover the hole between
6919 * the end of an inline extent and the beginning of the next block, so we
6920 * cover that region here.
6923 if (max_size + pg_offset < PAGE_SIZE) {
6924 char *map = kmap(page);
6925 memset(map + pg_offset + max_size, 0, PAGE_SIZE - max_size - pg_offset);
6933 * a bit scary, this does extent mapping from logical file offset to the disk.
6934 * the ugly parts come from merging extents from the disk with the in-ram
6935 * representation. This gets more complex because of the data=ordered code,
6936 * where the in-ram extents might be locked pending data=ordered completion.
6938 * This also copies inline extents directly into the page.
6940 struct extent_map *btrfs_get_extent(struct btrfs_inode *inode,
6942 size_t pg_offset, u64 start, u64 len,
6945 struct btrfs_fs_info *fs_info = inode->root->fs_info;
6948 u64 extent_start = 0;
6950 u64 objectid = btrfs_ino(inode);
6951 int extent_type = -1;
6952 struct btrfs_path *path = NULL;
6953 struct btrfs_root *root = inode->root;
6954 struct btrfs_file_extent_item *item;
6955 struct extent_buffer *leaf;
6956 struct btrfs_key found_key;
6957 struct extent_map *em = NULL;
6958 struct extent_map_tree *em_tree = &inode->extent_tree;
6959 struct extent_io_tree *io_tree = &inode->io_tree;
6960 const bool new_inline = !page || create;
6962 read_lock(&em_tree->lock);
6963 em = lookup_extent_mapping(em_tree, start, len);
6965 em->bdev = fs_info->fs_devices->latest_bdev;
6966 read_unlock(&em_tree->lock);
6969 if (em->start > start || em->start + em->len <= start)
6970 free_extent_map(em);
6971 else if (em->block_start == EXTENT_MAP_INLINE && page)
6972 free_extent_map(em);
6976 em = alloc_extent_map();
6981 em->bdev = fs_info->fs_devices->latest_bdev;
6982 em->start = EXTENT_MAP_HOLE;
6983 em->orig_start = EXTENT_MAP_HOLE;
6985 em->block_len = (u64)-1;
6987 path = btrfs_alloc_path();
6993 /* Chances are we'll be called again, so go ahead and do readahead */
6994 path->reada = READA_FORWARD;
6997 * Unless we're going to uncompress the inline extent, no sleep would
7000 path->leave_spinning = 1;
7002 ret = btrfs_lookup_file_extent(NULL, root, path, objectid, start, 0);
7006 } else if (ret > 0) {
7007 if (path->slots[0] == 0)
7012 leaf = path->nodes[0];
7013 item = btrfs_item_ptr(leaf, path->slots[0],
7014 struct btrfs_file_extent_item);
7015 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
7016 if (found_key.objectid != objectid ||
7017 found_key.type != BTRFS_EXTENT_DATA_KEY) {
7019 * If we backup past the first extent we want to move forward
7020 * and see if there is an extent in front of us, otherwise we'll
7021 * say there is a hole for our whole search range which can
7028 extent_type = btrfs_file_extent_type(leaf, item);
7029 extent_start = found_key.offset;
7030 if (extent_type == BTRFS_FILE_EXTENT_REG ||
7031 extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
7032 /* Only regular file could have regular/prealloc extent */
7033 if (!S_ISREG(inode->vfs_inode.i_mode)) {
7036 "regular/prealloc extent found for non-regular inode %llu",
7040 extent_end = extent_start +
7041 btrfs_file_extent_num_bytes(leaf, item);
7043 trace_btrfs_get_extent_show_fi_regular(inode, leaf, item,
7045 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
7048 size = btrfs_file_extent_ram_bytes(leaf, item);
7049 extent_end = ALIGN(extent_start + size,
7050 fs_info->sectorsize);
7052 trace_btrfs_get_extent_show_fi_inline(inode, leaf, item,
7057 if (start >= extent_end) {
7059 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
7060 ret = btrfs_next_leaf(root, path);
7064 } else if (ret > 0) {
7067 leaf = path->nodes[0];
7069 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
7070 if (found_key.objectid != objectid ||
7071 found_key.type != BTRFS_EXTENT_DATA_KEY)
7073 if (start + len <= found_key.offset)
7075 if (start > found_key.offset)
7078 /* New extent overlaps with existing one */
7080 em->orig_start = start;
7081 em->len = found_key.offset - start;
7082 em->block_start = EXTENT_MAP_HOLE;
7086 btrfs_extent_item_to_extent_map(inode, path, item,
7089 if (extent_type == BTRFS_FILE_EXTENT_REG ||
7090 extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
7092 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
7096 size_t extent_offset;
7102 size = btrfs_file_extent_ram_bytes(leaf, item);
7103 extent_offset = page_offset(page) + pg_offset - extent_start;
7104 copy_size = min_t(u64, PAGE_SIZE - pg_offset,
7105 size - extent_offset);
7106 em->start = extent_start + extent_offset;
7107 em->len = ALIGN(copy_size, fs_info->sectorsize);
7108 em->orig_block_len = em->len;
7109 em->orig_start = em->start;
7110 ptr = btrfs_file_extent_inline_start(item) + extent_offset;
7112 btrfs_set_path_blocking(path);
7113 if (!PageUptodate(page)) {
7114 if (btrfs_file_extent_compression(leaf, item) !=
7115 BTRFS_COMPRESS_NONE) {
7116 ret = uncompress_inline(path, page, pg_offset,
7117 extent_offset, item);
7124 read_extent_buffer(leaf, map + pg_offset, ptr,
7126 if (pg_offset + copy_size < PAGE_SIZE) {
7127 memset(map + pg_offset + copy_size, 0,
7128 PAGE_SIZE - pg_offset -
7133 flush_dcache_page(page);
7135 set_extent_uptodate(io_tree, em->start,
7136 extent_map_end(em) - 1, NULL, GFP_NOFS);
7141 em->orig_start = start;
7143 em->block_start = EXTENT_MAP_HOLE;
7145 btrfs_release_path(path);
7146 if (em->start > start || extent_map_end(em) <= start) {
7148 "bad extent! em: [%llu %llu] passed [%llu %llu]",
7149 em->start, em->len, start, len);
7155 write_lock(&em_tree->lock);
7156 err = btrfs_add_extent_mapping(fs_info, em_tree, &em, start, len);
7157 write_unlock(&em_tree->lock);
7159 btrfs_free_path(path);
7161 trace_btrfs_get_extent(root, inode, em);
7164 free_extent_map(em);
7165 return ERR_PTR(err);
7167 BUG_ON(!em); /* Error is always set */
7171 struct extent_map *btrfs_get_extent_fiemap(struct btrfs_inode *inode,
7174 struct extent_map *em;
7175 struct extent_map *hole_em = NULL;
7176 u64 delalloc_start = start;
7182 em = btrfs_get_extent(inode, NULL, 0, start, len, 0);
7186 * If our em maps to:
7188 * - a pre-alloc extent,
7189 * there might actually be delalloc bytes behind it.
7191 if (em->block_start != EXTENT_MAP_HOLE &&
7192 !test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
7197 /* check to see if we've wrapped (len == -1 or similar) */
7206 /* ok, we didn't find anything, lets look for delalloc */
7207 delalloc_len = count_range_bits(&inode->io_tree, &delalloc_start,
7208 end, len, EXTENT_DELALLOC, 1);
7209 delalloc_end = delalloc_start + delalloc_len;
7210 if (delalloc_end < delalloc_start)
7211 delalloc_end = (u64)-1;
7214 * We didn't find anything useful, return the original results from
7217 if (delalloc_start > end || delalloc_end <= start) {
7224 * Adjust the delalloc_start to make sure it doesn't go backwards from
7225 * the start they passed in
7227 delalloc_start = max(start, delalloc_start);
7228 delalloc_len = delalloc_end - delalloc_start;
7230 if (delalloc_len > 0) {
7233 const u64 hole_end = extent_map_end(hole_em);
7235 em = alloc_extent_map();
7244 * When btrfs_get_extent can't find anything it returns one
7247 * Make sure what it found really fits our range, and adjust to
7248 * make sure it is based on the start from the caller
7250 if (hole_end <= start || hole_em->start > end) {
7251 free_extent_map(hole_em);
7254 hole_start = max(hole_em->start, start);
7255 hole_len = hole_end - hole_start;
7258 if (hole_em && delalloc_start > hole_start) {
7260 * Our hole starts before our delalloc, so we have to
7261 * return just the parts of the hole that go until the
7264 em->len = min(hole_len, delalloc_start - hole_start);
7265 em->start = hole_start;
7266 em->orig_start = hole_start;
7268 * Don't adjust block start at all, it is fixed at
7271 em->block_start = hole_em->block_start;
7272 em->block_len = hole_len;
7273 if (test_bit(EXTENT_FLAG_PREALLOC, &hole_em->flags))
7274 set_bit(EXTENT_FLAG_PREALLOC, &em->flags);
7277 * Hole is out of passed range or it starts after
7280 em->start = delalloc_start;
7281 em->len = delalloc_len;
7282 em->orig_start = delalloc_start;
7283 em->block_start = EXTENT_MAP_DELALLOC;
7284 em->block_len = delalloc_len;
7291 free_extent_map(hole_em);
7293 free_extent_map(em);
7294 return ERR_PTR(err);
7299 static struct extent_map *btrfs_create_dio_extent(struct inode *inode,
7302 const u64 orig_start,
7303 const u64 block_start,
7304 const u64 block_len,
7305 const u64 orig_block_len,
7306 const u64 ram_bytes,
7309 struct extent_map *em = NULL;
7312 if (type != BTRFS_ORDERED_NOCOW) {
7313 em = create_io_em(inode, start, len, orig_start,
7314 block_start, block_len, orig_block_len,
7316 BTRFS_COMPRESS_NONE, /* compress_type */
7321 ret = btrfs_add_ordered_extent_dio(inode, start, block_start,
7322 len, block_len, type);
7325 free_extent_map(em);
7326 btrfs_drop_extent_cache(BTRFS_I(inode), start,
7327 start + len - 1, 0);
7336 static struct extent_map *btrfs_new_extent_direct(struct inode *inode,
7339 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7340 struct btrfs_root *root = BTRFS_I(inode)->root;
7341 struct extent_map *em;
7342 struct btrfs_key ins;
7346 alloc_hint = get_extent_allocation_hint(inode, start, len);
7347 ret = btrfs_reserve_extent(root, len, len, fs_info->sectorsize,
7348 0, alloc_hint, &ins, 1, 1);
7350 return ERR_PTR(ret);
7352 em = btrfs_create_dio_extent(inode, start, ins.offset, start,
7353 ins.objectid, ins.offset, ins.offset,
7354 ins.offset, BTRFS_ORDERED_REGULAR);
7355 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
7357 btrfs_free_reserved_extent(fs_info, ins.objectid,
7364 * returns 1 when the nocow is safe, < 1 on error, 0 if the
7365 * block must be cow'd
7367 noinline int can_nocow_extent(struct inode *inode, u64 offset, u64 *len,
7368 u64 *orig_start, u64 *orig_block_len,
7371 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7372 struct btrfs_path *path;
7374 struct extent_buffer *leaf;
7375 struct btrfs_root *root = BTRFS_I(inode)->root;
7376 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
7377 struct btrfs_file_extent_item *fi;
7378 struct btrfs_key key;
7385 bool nocow = (BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW);
7387 path = btrfs_alloc_path();
7391 ret = btrfs_lookup_file_extent(NULL, root, path,
7392 btrfs_ino(BTRFS_I(inode)), offset, 0);
7396 slot = path->slots[0];
7399 /* can't find the item, must cow */
7406 leaf = path->nodes[0];
7407 btrfs_item_key_to_cpu(leaf, &key, slot);
7408 if (key.objectid != btrfs_ino(BTRFS_I(inode)) ||
7409 key.type != BTRFS_EXTENT_DATA_KEY) {
7410 /* not our file or wrong item type, must cow */
7414 if (key.offset > offset) {
7415 /* Wrong offset, must cow */
7419 fi = btrfs_item_ptr(leaf, slot, struct btrfs_file_extent_item);
7420 found_type = btrfs_file_extent_type(leaf, fi);
7421 if (found_type != BTRFS_FILE_EXTENT_REG &&
7422 found_type != BTRFS_FILE_EXTENT_PREALLOC) {
7423 /* not a regular extent, must cow */
7427 if (!nocow && found_type == BTRFS_FILE_EXTENT_REG)
7430 extent_end = key.offset + btrfs_file_extent_num_bytes(leaf, fi);
7431 if (extent_end <= offset)
7434 disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
7435 if (disk_bytenr == 0)
7438 if (btrfs_file_extent_compression(leaf, fi) ||
7439 btrfs_file_extent_encryption(leaf, fi) ||
7440 btrfs_file_extent_other_encoding(leaf, fi))
7444 * Do the same check as in btrfs_cross_ref_exist but without the
7445 * unnecessary search.
7447 if (btrfs_file_extent_generation(leaf, fi) <=
7448 btrfs_root_last_snapshot(&root->root_item))
7451 backref_offset = btrfs_file_extent_offset(leaf, fi);
7454 *orig_start = key.offset - backref_offset;
7455 *orig_block_len = btrfs_file_extent_disk_num_bytes(leaf, fi);
7456 *ram_bytes = btrfs_file_extent_ram_bytes(leaf, fi);
7459 if (btrfs_extent_readonly(fs_info, disk_bytenr))
7462 num_bytes = min(offset + *len, extent_end) - offset;
7463 if (!nocow && found_type == BTRFS_FILE_EXTENT_PREALLOC) {
7466 range_end = round_up(offset + num_bytes,
7467 root->fs_info->sectorsize) - 1;
7468 ret = test_range_bit(io_tree, offset, range_end,
7469 EXTENT_DELALLOC, 0, NULL);
7476 btrfs_release_path(path);
7479 * look for other files referencing this extent, if we
7480 * find any we must cow
7483 ret = btrfs_cross_ref_exist(root, btrfs_ino(BTRFS_I(inode)),
7484 key.offset - backref_offset, disk_bytenr);
7491 * adjust disk_bytenr and num_bytes to cover just the bytes
7492 * in this extent we are about to write. If there
7493 * are any csums in that range we have to cow in order
7494 * to keep the csums correct
7496 disk_bytenr += backref_offset;
7497 disk_bytenr += offset - key.offset;
7498 if (csum_exist_in_range(fs_info, disk_bytenr, num_bytes))
7501 * all of the above have passed, it is safe to overwrite this extent
7507 btrfs_free_path(path);
7511 static int lock_extent_direct(struct inode *inode, u64 lockstart, u64 lockend,
7512 struct extent_state **cached_state, int writing)
7514 struct btrfs_ordered_extent *ordered;
7518 lock_extent_bits(&BTRFS_I(inode)->io_tree, lockstart, lockend,
7521 * We're concerned with the entire range that we're going to be
7522 * doing DIO to, so we need to make sure there's no ordered
7523 * extents in this range.
7525 ordered = btrfs_lookup_ordered_range(BTRFS_I(inode), lockstart,
7526 lockend - lockstart + 1);
7529 * We need to make sure there are no buffered pages in this
7530 * range either, we could have raced between the invalidate in
7531 * generic_file_direct_write and locking the extent. The
7532 * invalidate needs to happen so that reads after a write do not
7536 (!writing || !filemap_range_has_page(inode->i_mapping,
7537 lockstart, lockend)))
7540 unlock_extent_cached(&BTRFS_I(inode)->io_tree, lockstart, lockend,
7545 * If we are doing a DIO read and the ordered extent we
7546 * found is for a buffered write, we can not wait for it
7547 * to complete and retry, because if we do so we can
7548 * deadlock with concurrent buffered writes on page
7549 * locks. This happens only if our DIO read covers more
7550 * than one extent map, if at this point has already
7551 * created an ordered extent for a previous extent map
7552 * and locked its range in the inode's io tree, and a
7553 * concurrent write against that previous extent map's
7554 * range and this range started (we unlock the ranges
7555 * in the io tree only when the bios complete and
7556 * buffered writes always lock pages before attempting
7557 * to lock range in the io tree).
7560 test_bit(BTRFS_ORDERED_DIRECT, &ordered->flags))
7561 btrfs_start_ordered_extent(inode, ordered, 1);
7564 btrfs_put_ordered_extent(ordered);
7567 * We could trigger writeback for this range (and wait
7568 * for it to complete) and then invalidate the pages for
7569 * this range (through invalidate_inode_pages2_range()),
7570 * but that can lead us to a deadlock with a concurrent
7571 * call to readpages() (a buffered read or a defrag call
7572 * triggered a readahead) on a page lock due to an
7573 * ordered dio extent we created before but did not have
7574 * yet a corresponding bio submitted (whence it can not
7575 * complete), which makes readpages() wait for that
7576 * ordered extent to complete while holding a lock on
7591 /* The callers of this must take lock_extent() */
7592 static struct extent_map *create_io_em(struct inode *inode, u64 start, u64 len,
7593 u64 orig_start, u64 block_start,
7594 u64 block_len, u64 orig_block_len,
7595 u64 ram_bytes, int compress_type,
7598 struct extent_map_tree *em_tree;
7599 struct extent_map *em;
7600 struct btrfs_root *root = BTRFS_I(inode)->root;
7603 ASSERT(type == BTRFS_ORDERED_PREALLOC ||
7604 type == BTRFS_ORDERED_COMPRESSED ||
7605 type == BTRFS_ORDERED_NOCOW ||
7606 type == BTRFS_ORDERED_REGULAR);
7608 em_tree = &BTRFS_I(inode)->extent_tree;
7609 em = alloc_extent_map();
7611 return ERR_PTR(-ENOMEM);
7614 em->orig_start = orig_start;
7616 em->block_len = block_len;
7617 em->block_start = block_start;
7618 em->bdev = root->fs_info->fs_devices->latest_bdev;
7619 em->orig_block_len = orig_block_len;
7620 em->ram_bytes = ram_bytes;
7621 em->generation = -1;
7622 set_bit(EXTENT_FLAG_PINNED, &em->flags);
7623 if (type == BTRFS_ORDERED_PREALLOC) {
7624 set_bit(EXTENT_FLAG_FILLING, &em->flags);
7625 } else if (type == BTRFS_ORDERED_COMPRESSED) {
7626 set_bit(EXTENT_FLAG_COMPRESSED, &em->flags);
7627 em->compress_type = compress_type;
7631 btrfs_drop_extent_cache(BTRFS_I(inode), em->start,
7632 em->start + em->len - 1, 0);
7633 write_lock(&em_tree->lock);
7634 ret = add_extent_mapping(em_tree, em, 1);
7635 write_unlock(&em_tree->lock);
7637 * The caller has taken lock_extent(), who could race with us
7640 } while (ret == -EEXIST);
7643 free_extent_map(em);
7644 return ERR_PTR(ret);
7647 /* em got 2 refs now, callers needs to do free_extent_map once. */
7652 static int btrfs_get_blocks_direct_read(struct extent_map *em,
7653 struct buffer_head *bh_result,
7654 struct inode *inode,
7657 if (em->block_start == EXTENT_MAP_HOLE ||
7658 test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
7661 len = min(len, em->len - (start - em->start));
7663 bh_result->b_blocknr = (em->block_start + (start - em->start)) >>
7665 bh_result->b_size = len;
7666 bh_result->b_bdev = em->bdev;
7667 set_buffer_mapped(bh_result);
7672 static int btrfs_get_blocks_direct_write(struct extent_map **map,
7673 struct buffer_head *bh_result,
7674 struct inode *inode,
7675 struct btrfs_dio_data *dio_data,
7678 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7679 struct extent_map *em = *map;
7683 * We don't allocate a new extent in the following cases
7685 * 1) The inode is marked as NODATACOW. In this case we'll just use the
7687 * 2) The extent is marked as PREALLOC. We're good to go here and can
7688 * just use the extent.
7691 if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags) ||
7692 ((BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW) &&
7693 em->block_start != EXTENT_MAP_HOLE)) {
7695 u64 block_start, orig_start, orig_block_len, ram_bytes;
7697 if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
7698 type = BTRFS_ORDERED_PREALLOC;
7700 type = BTRFS_ORDERED_NOCOW;
7701 len = min(len, em->len - (start - em->start));
7702 block_start = em->block_start + (start - em->start);
7704 if (can_nocow_extent(inode, start, &len, &orig_start,
7705 &orig_block_len, &ram_bytes) == 1 &&
7706 btrfs_inc_nocow_writers(fs_info, block_start)) {
7707 struct extent_map *em2;
7709 em2 = btrfs_create_dio_extent(inode, start, len,
7710 orig_start, block_start,
7711 len, orig_block_len,
7713 btrfs_dec_nocow_writers(fs_info, block_start);
7714 if (type == BTRFS_ORDERED_PREALLOC) {
7715 free_extent_map(em);
7719 if (em2 && IS_ERR(em2)) {
7724 * For inode marked NODATACOW or extent marked PREALLOC,
7725 * use the existing or preallocated extent, so does not
7726 * need to adjust btrfs_space_info's bytes_may_use.
7728 btrfs_free_reserved_data_space_noquota(inode, start,
7734 /* this will cow the extent */
7735 len = bh_result->b_size;
7736 free_extent_map(em);
7737 *map = em = btrfs_new_extent_direct(inode, start, len);
7743 len = min(len, em->len - (start - em->start));
7746 bh_result->b_blocknr = (em->block_start + (start - em->start)) >>
7748 bh_result->b_size = len;
7749 bh_result->b_bdev = em->bdev;
7750 set_buffer_mapped(bh_result);
7752 if (!test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
7753 set_buffer_new(bh_result);
7756 * Need to update the i_size under the extent lock so buffered
7757 * readers will get the updated i_size when we unlock.
7759 if (!dio_data->overwrite && start + len > i_size_read(inode))
7760 i_size_write(inode, start + len);
7762 WARN_ON(dio_data->reserve < len);
7763 dio_data->reserve -= len;
7764 dio_data->unsubmitted_oe_range_end = start + len;
7765 current->journal_info = dio_data;
7770 static int btrfs_get_blocks_direct(struct inode *inode, sector_t iblock,
7771 struct buffer_head *bh_result, int create)
7773 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7774 struct extent_map *em;
7775 struct extent_state *cached_state = NULL;
7776 struct btrfs_dio_data *dio_data = NULL;
7777 u64 start = iblock << inode->i_blkbits;
7778 u64 lockstart, lockend;
7779 u64 len = bh_result->b_size;
7783 len = min_t(u64, len, fs_info->sectorsize);
7786 lockend = start + len - 1;
7788 if (current->journal_info) {
7790 * Need to pull our outstanding extents and set journal_info to NULL so
7791 * that anything that needs to check if there's a transaction doesn't get
7794 dio_data = current->journal_info;
7795 current->journal_info = NULL;
7799 * If this errors out it's because we couldn't invalidate pagecache for
7800 * this range and we need to fallback to buffered.
7802 if (lock_extent_direct(inode, lockstart, lockend, &cached_state,
7808 em = btrfs_get_extent(BTRFS_I(inode), NULL, 0, start, len, 0);
7815 * Ok for INLINE and COMPRESSED extents we need to fallback on buffered
7816 * io. INLINE is special, and we could probably kludge it in here, but
7817 * it's still buffered so for safety lets just fall back to the generic
7820 * For COMPRESSED we _have_ to read the entire extent in so we can
7821 * decompress it, so there will be buffering required no matter what we
7822 * do, so go ahead and fallback to buffered.
7824 * We return -ENOTBLK because that's what makes DIO go ahead and go back
7825 * to buffered IO. Don't blame me, this is the price we pay for using
7828 if (test_bit(EXTENT_FLAG_COMPRESSED, &em->flags) ||
7829 em->block_start == EXTENT_MAP_INLINE) {
7830 free_extent_map(em);
7836 ret = btrfs_get_blocks_direct_write(&em, bh_result, inode,
7837 dio_data, start, len);
7841 unlock_extent_cached(&BTRFS_I(inode)->io_tree, lockstart,
7842 lockend, &cached_state);
7844 ret = btrfs_get_blocks_direct_read(em, bh_result, inode,
7846 /* Can be negative only if we read from a hole */
7849 free_extent_map(em);
7853 * We need to unlock only the end area that we aren't using.
7854 * The rest is going to be unlocked by the endio routine.
7856 lockstart = start + bh_result->b_size;
7857 if (lockstart < lockend) {
7858 unlock_extent_cached(&BTRFS_I(inode)->io_tree,
7859 lockstart, lockend, &cached_state);
7861 free_extent_state(cached_state);
7865 free_extent_map(em);
7870 unlock_extent_cached(&BTRFS_I(inode)->io_tree, lockstart, lockend,
7874 current->journal_info = dio_data;
7878 static inline blk_status_t submit_dio_repair_bio(struct inode *inode,
7882 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7885 BUG_ON(bio_op(bio) == REQ_OP_WRITE);
7887 ret = btrfs_bio_wq_end_io(fs_info, bio, BTRFS_WQ_ENDIO_DIO_REPAIR);
7891 ret = btrfs_map_bio(fs_info, bio, mirror_num, 0);
7896 static int btrfs_check_dio_repairable(struct inode *inode,
7897 struct bio *failed_bio,
7898 struct io_failure_record *failrec,
7901 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7904 num_copies = btrfs_num_copies(fs_info, failrec->logical, failrec->len);
7905 if (num_copies == 1) {
7907 * we only have a single copy of the data, so don't bother with
7908 * all the retry and error correction code that follows. no
7909 * matter what the error is, it is very likely to persist.
7911 btrfs_debug(fs_info,
7912 "Check DIO Repairable: cannot repair, num_copies=%d, next_mirror %d, failed_mirror %d",
7913 num_copies, failrec->this_mirror, failed_mirror);
7917 failrec->failed_mirror = failed_mirror;
7918 failrec->this_mirror++;
7919 if (failrec->this_mirror == failed_mirror)
7920 failrec->this_mirror++;
7922 if (failrec->this_mirror > num_copies) {
7923 btrfs_debug(fs_info,
7924 "Check DIO Repairable: (fail) num_copies=%d, next_mirror %d, failed_mirror %d",
7925 num_copies, failrec->this_mirror, failed_mirror);
7932 static blk_status_t dio_read_error(struct inode *inode, struct bio *failed_bio,
7933 struct page *page, unsigned int pgoff,
7934 u64 start, u64 end, int failed_mirror,
7935 bio_end_io_t *repair_endio, void *repair_arg)
7937 struct io_failure_record *failrec;
7938 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
7939 struct extent_io_tree *failure_tree = &BTRFS_I(inode)->io_failure_tree;
7942 unsigned int read_mode = 0;
7945 blk_status_t status;
7946 struct bio_vec bvec;
7948 BUG_ON(bio_op(failed_bio) == REQ_OP_WRITE);
7950 ret = btrfs_get_io_failure_record(inode, start, end, &failrec);
7952 return errno_to_blk_status(ret);
7954 ret = btrfs_check_dio_repairable(inode, failed_bio, failrec,
7957 free_io_failure(failure_tree, io_tree, failrec);
7958 return BLK_STS_IOERR;
7961 segs = bio_segments(failed_bio);
7962 bio_get_first_bvec(failed_bio, &bvec);
7964 (bvec.bv_len > btrfs_inode_sectorsize(inode)))
7965 read_mode |= REQ_FAILFAST_DEV;
7967 isector = start - btrfs_io_bio(failed_bio)->logical;
7968 isector >>= inode->i_sb->s_blocksize_bits;
7969 bio = btrfs_create_repair_bio(inode, failed_bio, failrec, page,
7970 pgoff, isector, repair_endio, repair_arg);
7971 bio->bi_opf = REQ_OP_READ | read_mode;
7973 btrfs_debug(BTRFS_I(inode)->root->fs_info,
7974 "repair DIO read error: submitting new dio read[%#x] to this_mirror=%d, in_validation=%d",
7975 read_mode, failrec->this_mirror, failrec->in_validation);
7977 status = submit_dio_repair_bio(inode, bio, failrec->this_mirror);
7979 free_io_failure(failure_tree, io_tree, failrec);
7986 struct btrfs_retry_complete {
7987 struct completion done;
7988 struct inode *inode;
7993 static void btrfs_retry_endio_nocsum(struct bio *bio)
7995 struct btrfs_retry_complete *done = bio->bi_private;
7996 struct inode *inode = done->inode;
7997 struct bio_vec *bvec;
7998 struct extent_io_tree *io_tree, *failure_tree;
7999 struct bvec_iter_all iter_all;
8004 ASSERT(bio->bi_vcnt == 1);
8005 io_tree = &BTRFS_I(inode)->io_tree;
8006 failure_tree = &BTRFS_I(inode)->io_failure_tree;
8007 ASSERT(bio_first_bvec_all(bio)->bv_len == btrfs_inode_sectorsize(inode));
8010 ASSERT(!bio_flagged(bio, BIO_CLONED));
8011 bio_for_each_segment_all(bvec, bio, iter_all)
8012 clean_io_failure(BTRFS_I(inode)->root->fs_info, failure_tree,
8013 io_tree, done->start, bvec->bv_page,
8014 btrfs_ino(BTRFS_I(inode)), 0);
8016 complete(&done->done);
8020 static blk_status_t __btrfs_correct_data_nocsum(struct inode *inode,
8021 struct btrfs_io_bio *io_bio)
8023 struct btrfs_fs_info *fs_info;
8024 struct bio_vec bvec;
8025 struct bvec_iter iter;
8026 struct btrfs_retry_complete done;
8032 blk_status_t err = BLK_STS_OK;
8034 fs_info = BTRFS_I(inode)->root->fs_info;
8035 sectorsize = fs_info->sectorsize;
8037 start = io_bio->logical;
8039 io_bio->bio.bi_iter = io_bio->iter;
8041 bio_for_each_segment(bvec, &io_bio->bio, iter) {
8042 nr_sectors = BTRFS_BYTES_TO_BLKS(fs_info, bvec.bv_len);
8043 pgoff = bvec.bv_offset;
8045 next_block_or_try_again:
8048 init_completion(&done.done);
8050 ret = dio_read_error(inode, &io_bio->bio, bvec.bv_page,
8051 pgoff, start, start + sectorsize - 1,
8053 btrfs_retry_endio_nocsum, &done);
8059 wait_for_completion_io(&done.done);
8061 if (!done.uptodate) {
8062 /* We might have another mirror, so try again */
8063 goto next_block_or_try_again;
8067 start += sectorsize;
8071 pgoff += sectorsize;
8072 ASSERT(pgoff < PAGE_SIZE);
8073 goto next_block_or_try_again;
8080 static void btrfs_retry_endio(struct bio *bio)
8082 struct btrfs_retry_complete *done = bio->bi_private;
8083 struct btrfs_io_bio *io_bio = btrfs_io_bio(bio);
8084 struct extent_io_tree *io_tree, *failure_tree;
8085 struct inode *inode = done->inode;
8086 struct bio_vec *bvec;
8090 struct bvec_iter_all iter_all;
8097 ASSERT(bio->bi_vcnt == 1);
8098 ASSERT(bio_first_bvec_all(bio)->bv_len == btrfs_inode_sectorsize(done->inode));
8100 io_tree = &BTRFS_I(inode)->io_tree;
8101 failure_tree = &BTRFS_I(inode)->io_failure_tree;
8103 ASSERT(!bio_flagged(bio, BIO_CLONED));
8104 bio_for_each_segment_all(bvec, bio, iter_all) {
8105 ret = __readpage_endio_check(inode, io_bio, i, bvec->bv_page,
8106 bvec->bv_offset, done->start,
8109 clean_io_failure(BTRFS_I(inode)->root->fs_info,
8110 failure_tree, io_tree, done->start,
8112 btrfs_ino(BTRFS_I(inode)),
8119 done->uptodate = uptodate;
8121 complete(&done->done);
8125 static blk_status_t __btrfs_subio_endio_read(struct inode *inode,
8126 struct btrfs_io_bio *io_bio, blk_status_t err)
8128 struct btrfs_fs_info *fs_info;
8129 struct bio_vec bvec;
8130 struct bvec_iter iter;
8131 struct btrfs_retry_complete done;
8138 bool uptodate = (err == 0);
8140 blk_status_t status;
8142 fs_info = BTRFS_I(inode)->root->fs_info;
8143 sectorsize = fs_info->sectorsize;
8146 start = io_bio->logical;
8148 io_bio->bio.bi_iter = io_bio->iter;
8150 bio_for_each_segment(bvec, &io_bio->bio, iter) {
8151 nr_sectors = BTRFS_BYTES_TO_BLKS(fs_info, bvec.bv_len);
8153 pgoff = bvec.bv_offset;
8156 csum_pos = BTRFS_BYTES_TO_BLKS(fs_info, offset);
8157 ret = __readpage_endio_check(inode, io_bio, csum_pos,
8158 bvec.bv_page, pgoff, start, sectorsize);
8165 init_completion(&done.done);
8167 status = dio_read_error(inode, &io_bio->bio, bvec.bv_page,
8168 pgoff, start, start + sectorsize - 1,
8169 io_bio->mirror_num, btrfs_retry_endio,
8176 wait_for_completion_io(&done.done);
8178 if (!done.uptodate) {
8179 /* We might have another mirror, so try again */
8183 offset += sectorsize;
8184 start += sectorsize;
8190 pgoff += sectorsize;
8191 ASSERT(pgoff < PAGE_SIZE);
8199 static blk_status_t btrfs_subio_endio_read(struct inode *inode,
8200 struct btrfs_io_bio *io_bio, blk_status_t err)
8202 bool skip_csum = BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM;
8206 return __btrfs_correct_data_nocsum(inode, io_bio);
8210 return __btrfs_subio_endio_read(inode, io_bio, err);
8214 static void btrfs_endio_direct_read(struct bio *bio)
8216 struct btrfs_dio_private *dip = bio->bi_private;
8217 struct inode *inode = dip->inode;
8218 struct bio *dio_bio;
8219 struct btrfs_io_bio *io_bio = btrfs_io_bio(bio);
8220 blk_status_t err = bio->bi_status;
8222 if (dip->flags & BTRFS_DIO_ORIG_BIO_SUBMITTED)
8223 err = btrfs_subio_endio_read(inode, io_bio, err);
8225 unlock_extent(&BTRFS_I(inode)->io_tree, dip->logical_offset,
8226 dip->logical_offset + dip->bytes - 1);
8227 dio_bio = dip->dio_bio;
8231 dio_bio->bi_status = err;
8232 dio_end_io(dio_bio);
8233 btrfs_io_bio_free_csum(io_bio);
8237 static void __endio_write_update_ordered(struct inode *inode,
8238 const u64 offset, const u64 bytes,
8239 const bool uptodate)
8241 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
8242 struct btrfs_ordered_extent *ordered = NULL;
8243 struct btrfs_workqueue *wq;
8244 u64 ordered_offset = offset;
8245 u64 ordered_bytes = bytes;
8248 if (btrfs_is_free_space_inode(BTRFS_I(inode)))
8249 wq = fs_info->endio_freespace_worker;
8251 wq = fs_info->endio_write_workers;
8253 while (ordered_offset < offset + bytes) {
8254 last_offset = ordered_offset;
8255 if (btrfs_dec_test_first_ordered_pending(inode, &ordered,
8259 btrfs_init_work(&ordered->work, finish_ordered_fn, NULL,
8261 btrfs_queue_work(wq, &ordered->work);
8264 * If btrfs_dec_test_ordered_pending does not find any ordered
8265 * extent in the range, we can exit.
8267 if (ordered_offset == last_offset)
8270 * Our bio might span multiple ordered extents. In this case
8271 * we keep going until we have accounted the whole dio.
8273 if (ordered_offset < offset + bytes) {
8274 ordered_bytes = offset + bytes - ordered_offset;
8280 static void btrfs_endio_direct_write(struct bio *bio)
8282 struct btrfs_dio_private *dip = bio->bi_private;
8283 struct bio *dio_bio = dip->dio_bio;
8285 __endio_write_update_ordered(dip->inode, dip->logical_offset,
8286 dip->bytes, !bio->bi_status);
8290 dio_bio->bi_status = bio->bi_status;
8291 dio_end_io(dio_bio);
8295 static blk_status_t btrfs_submit_bio_start_direct_io(void *private_data,
8296 struct bio *bio, u64 offset)
8298 struct inode *inode = private_data;
8300 ret = btrfs_csum_one_bio(inode, bio, offset, 1);
8301 BUG_ON(ret); /* -ENOMEM */
8305 static void btrfs_end_dio_bio(struct bio *bio)
8307 struct btrfs_dio_private *dip = bio->bi_private;
8308 blk_status_t err = bio->bi_status;
8311 btrfs_warn(BTRFS_I(dip->inode)->root->fs_info,
8312 "direct IO failed ino %llu rw %d,%u sector %#Lx len %u err no %d",
8313 btrfs_ino(BTRFS_I(dip->inode)), bio_op(bio),
8315 (unsigned long long)bio->bi_iter.bi_sector,
8316 bio->bi_iter.bi_size, err);
8318 if (dip->subio_endio)
8319 err = dip->subio_endio(dip->inode, btrfs_io_bio(bio), err);
8323 * We want to perceive the errors flag being set before
8324 * decrementing the reference count. We don't need a barrier
8325 * since atomic operations with a return value are fully
8326 * ordered as per atomic_t.txt
8331 /* if there are more bios still pending for this dio, just exit */
8332 if (!atomic_dec_and_test(&dip->pending_bios))
8336 bio_io_error(dip->orig_bio);
8338 dip->dio_bio->bi_status = BLK_STS_OK;
8339 bio_endio(dip->orig_bio);
8345 static inline blk_status_t btrfs_lookup_and_bind_dio_csum(struct inode *inode,
8346 struct btrfs_dio_private *dip,
8350 struct btrfs_io_bio *io_bio = btrfs_io_bio(bio);
8351 struct btrfs_io_bio *orig_io_bio = btrfs_io_bio(dip->orig_bio);
8355 * We load all the csum data we need when we submit
8356 * the first bio to reduce the csum tree search and
8359 if (dip->logical_offset == file_offset) {
8360 ret = btrfs_lookup_bio_sums_dio(inode, dip->orig_bio,
8366 if (bio == dip->orig_bio)
8369 file_offset -= dip->logical_offset;
8370 file_offset >>= inode->i_sb->s_blocksize_bits;
8371 io_bio->csum = (u8 *)(((u32 *)orig_io_bio->csum) + file_offset);
8376 static inline blk_status_t btrfs_submit_dio_bio(struct bio *bio,
8377 struct inode *inode, u64 file_offset, int async_submit)
8379 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
8380 struct btrfs_dio_private *dip = bio->bi_private;
8381 bool write = bio_op(bio) == REQ_OP_WRITE;
8384 /* Check btrfs_submit_bio_hook() for rules about async submit. */
8386 async_submit = !atomic_read(&BTRFS_I(inode)->sync_writers);
8389 ret = btrfs_bio_wq_end_io(fs_info, bio, BTRFS_WQ_ENDIO_DATA);
8394 if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)
8397 if (write && async_submit) {
8398 ret = btrfs_wq_submit_bio(fs_info, bio, 0, 0,
8400 btrfs_submit_bio_start_direct_io);
8404 * If we aren't doing async submit, calculate the csum of the
8407 ret = btrfs_csum_one_bio(inode, bio, file_offset, 1);
8411 ret = btrfs_lookup_and_bind_dio_csum(inode, dip, bio,
8417 ret = btrfs_map_bio(fs_info, bio, 0, 0);
8422 static int btrfs_submit_direct_hook(struct btrfs_dio_private *dip)
8424 struct inode *inode = dip->inode;
8425 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
8427 struct bio *orig_bio = dip->orig_bio;
8428 u64 start_sector = orig_bio->bi_iter.bi_sector;
8429 u64 file_offset = dip->logical_offset;
8430 int async_submit = 0;
8432 int clone_offset = 0;
8435 blk_status_t status;
8436 struct btrfs_io_geometry geom;
8438 submit_len = orig_bio->bi_iter.bi_size;
8439 ret = btrfs_get_io_geometry(fs_info, btrfs_op(orig_bio),
8440 start_sector << 9, submit_len, &geom);
8444 if (geom.len >= submit_len) {
8446 dip->flags |= BTRFS_DIO_ORIG_BIO_SUBMITTED;
8450 /* async crcs make it difficult to collect full stripe writes. */
8451 if (btrfs_data_alloc_profile(fs_info) & BTRFS_BLOCK_GROUP_RAID56_MASK)
8457 ASSERT(geom.len <= INT_MAX);
8458 atomic_inc(&dip->pending_bios);
8460 clone_len = min_t(int, submit_len, geom.len);
8463 * This will never fail as it's passing GPF_NOFS and
8464 * the allocation is backed by btrfs_bioset.
8466 bio = btrfs_bio_clone_partial(orig_bio, clone_offset,
8468 bio->bi_private = dip;
8469 bio->bi_end_io = btrfs_end_dio_bio;
8470 btrfs_io_bio(bio)->logical = file_offset;
8472 ASSERT(submit_len >= clone_len);
8473 submit_len -= clone_len;
8474 if (submit_len == 0)
8478 * Increase the count before we submit the bio so we know
8479 * the end IO handler won't happen before we increase the
8480 * count. Otherwise, the dip might get freed before we're
8481 * done setting it up.
8483 atomic_inc(&dip->pending_bios);
8485 status = btrfs_submit_dio_bio(bio, inode, file_offset,
8489 atomic_dec(&dip->pending_bios);
8493 clone_offset += clone_len;
8494 start_sector += clone_len >> 9;
8495 file_offset += clone_len;
8497 ret = btrfs_get_io_geometry(fs_info, btrfs_op(orig_bio),
8498 start_sector << 9, submit_len, &geom);
8501 } while (submit_len > 0);
8504 status = btrfs_submit_dio_bio(bio, inode, file_offset, async_submit);
8512 * Before atomic variable goto zero, we must make sure dip->errors is
8513 * perceived to be set. This ordering is ensured by the fact that an
8514 * atomic operations with a return value are fully ordered as per
8517 if (atomic_dec_and_test(&dip->pending_bios))
8518 bio_io_error(dip->orig_bio);
8520 /* bio_end_io() will handle error, so we needn't return it */
8524 static void btrfs_submit_direct(struct bio *dio_bio, struct inode *inode,
8527 struct btrfs_dio_private *dip = NULL;
8528 struct bio *bio = NULL;
8529 struct btrfs_io_bio *io_bio;
8530 bool write = (bio_op(dio_bio) == REQ_OP_WRITE);
8533 bio = btrfs_bio_clone(dio_bio);
8535 dip = kzalloc(sizeof(*dip), GFP_NOFS);
8541 dip->private = dio_bio->bi_private;
8543 dip->logical_offset = file_offset;
8544 dip->bytes = dio_bio->bi_iter.bi_size;
8545 dip->disk_bytenr = (u64)dio_bio->bi_iter.bi_sector << 9;
8546 bio->bi_private = dip;
8547 dip->orig_bio = bio;
8548 dip->dio_bio = dio_bio;
8549 atomic_set(&dip->pending_bios, 0);
8550 io_bio = btrfs_io_bio(bio);
8551 io_bio->logical = file_offset;
8554 bio->bi_end_io = btrfs_endio_direct_write;
8556 bio->bi_end_io = btrfs_endio_direct_read;
8557 dip->subio_endio = btrfs_subio_endio_read;
8561 * Reset the range for unsubmitted ordered extents (to a 0 length range)
8562 * even if we fail to submit a bio, because in such case we do the
8563 * corresponding error handling below and it must not be done a second
8564 * time by btrfs_direct_IO().
8567 struct btrfs_dio_data *dio_data = current->journal_info;
8569 dio_data->unsubmitted_oe_range_end = dip->logical_offset +
8571 dio_data->unsubmitted_oe_range_start =
8572 dio_data->unsubmitted_oe_range_end;
8575 ret = btrfs_submit_direct_hook(dip);
8579 btrfs_io_bio_free_csum(io_bio);
8583 * If we arrived here it means either we failed to submit the dip
8584 * or we either failed to clone the dio_bio or failed to allocate the
8585 * dip. If we cloned the dio_bio and allocated the dip, we can just
8586 * call bio_endio against our io_bio so that we get proper resource
8587 * cleanup if we fail to submit the dip, otherwise, we must do the
8588 * same as btrfs_endio_direct_[write|read] because we can't call these
8589 * callbacks - they require an allocated dip and a clone of dio_bio.
8594 * The end io callbacks free our dip, do the final put on bio
8595 * and all the cleanup and final put for dio_bio (through
8602 __endio_write_update_ordered(inode,
8604 dio_bio->bi_iter.bi_size,
8607 unlock_extent(&BTRFS_I(inode)->io_tree, file_offset,
8608 file_offset + dio_bio->bi_iter.bi_size - 1);
8610 dio_bio->bi_status = BLK_STS_IOERR;
8612 * Releases and cleans up our dio_bio, no need to bio_put()
8613 * nor bio_endio()/bio_io_error() against dio_bio.
8615 dio_end_io(dio_bio);
8622 static ssize_t check_direct_IO(struct btrfs_fs_info *fs_info,
8623 const struct iov_iter *iter, loff_t offset)
8627 unsigned int blocksize_mask = fs_info->sectorsize - 1;
8628 ssize_t retval = -EINVAL;
8630 if (offset & blocksize_mask)
8633 if (iov_iter_alignment(iter) & blocksize_mask)
8636 /* If this is a write we don't need to check anymore */
8637 if (iov_iter_rw(iter) != READ || !iter_is_iovec(iter))
8640 * Check to make sure we don't have duplicate iov_base's in this
8641 * iovec, if so return EINVAL, otherwise we'll get csum errors
8642 * when reading back.
8644 for (seg = 0; seg < iter->nr_segs; seg++) {
8645 for (i = seg + 1; i < iter->nr_segs; i++) {
8646 if (iter->iov[seg].iov_base == iter->iov[i].iov_base)
8655 static ssize_t btrfs_direct_IO(struct kiocb *iocb, struct iov_iter *iter)
8657 struct file *file = iocb->ki_filp;
8658 struct inode *inode = file->f_mapping->host;
8659 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
8660 struct btrfs_dio_data dio_data = { 0 };
8661 struct extent_changeset *data_reserved = NULL;
8662 loff_t offset = iocb->ki_pos;
8666 bool relock = false;
8669 if (check_direct_IO(fs_info, iter, offset))
8672 inode_dio_begin(inode);
8675 * The generic stuff only does filemap_write_and_wait_range, which
8676 * isn't enough if we've written compressed pages to this area, so
8677 * we need to flush the dirty pages again to make absolutely sure
8678 * that any outstanding dirty pages are on disk.
8680 count = iov_iter_count(iter);
8681 if (test_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
8682 &BTRFS_I(inode)->runtime_flags))
8683 filemap_fdatawrite_range(inode->i_mapping, offset,
8684 offset + count - 1);
8686 if (iov_iter_rw(iter) == WRITE) {
8688 * If the write DIO is beyond the EOF, we need update
8689 * the isize, but it is protected by i_mutex. So we can
8690 * not unlock the i_mutex at this case.
8692 if (offset + count <= inode->i_size) {
8693 dio_data.overwrite = 1;
8694 inode_unlock(inode);
8696 } else if (iocb->ki_flags & IOCB_NOWAIT) {
8700 ret = btrfs_delalloc_reserve_space(inode, &data_reserved,
8706 * We need to know how many extents we reserved so that we can
8707 * do the accounting properly if we go over the number we
8708 * originally calculated. Abuse current->journal_info for this.
8710 dio_data.reserve = round_up(count,
8711 fs_info->sectorsize);
8712 dio_data.unsubmitted_oe_range_start = (u64)offset;
8713 dio_data.unsubmitted_oe_range_end = (u64)offset;
8714 current->journal_info = &dio_data;
8715 down_read(&BTRFS_I(inode)->dio_sem);
8716 } else if (test_bit(BTRFS_INODE_READDIO_NEED_LOCK,
8717 &BTRFS_I(inode)->runtime_flags)) {
8718 inode_dio_end(inode);
8719 flags = DIO_LOCKING | DIO_SKIP_HOLES;
8723 ret = __blockdev_direct_IO(iocb, inode,
8724 fs_info->fs_devices->latest_bdev,
8725 iter, btrfs_get_blocks_direct, NULL,
8726 btrfs_submit_direct, flags);
8727 if (iov_iter_rw(iter) == WRITE) {
8728 up_read(&BTRFS_I(inode)->dio_sem);
8729 current->journal_info = NULL;
8730 if (ret < 0 && ret != -EIOCBQUEUED) {
8731 if (dio_data.reserve)
8732 btrfs_delalloc_release_space(inode, data_reserved,
8733 offset, dio_data.reserve, true);
8735 * On error we might have left some ordered extents
8736 * without submitting corresponding bios for them, so
8737 * cleanup them up to avoid other tasks getting them
8738 * and waiting for them to complete forever.
8740 if (dio_data.unsubmitted_oe_range_start <
8741 dio_data.unsubmitted_oe_range_end)
8742 __endio_write_update_ordered(inode,
8743 dio_data.unsubmitted_oe_range_start,
8744 dio_data.unsubmitted_oe_range_end -
8745 dio_data.unsubmitted_oe_range_start,
8747 } else if (ret >= 0 && (size_t)ret < count)
8748 btrfs_delalloc_release_space(inode, data_reserved,
8749 offset, count - (size_t)ret, true);
8750 btrfs_delalloc_release_extents(BTRFS_I(inode), count);
8754 inode_dio_end(inode);
8758 extent_changeset_free(data_reserved);
8762 #define BTRFS_FIEMAP_FLAGS (FIEMAP_FLAG_SYNC)
8764 static int btrfs_fiemap(struct inode *inode, struct fiemap_extent_info *fieinfo,
8765 __u64 start, __u64 len)
8769 ret = fiemap_check_flags(fieinfo, BTRFS_FIEMAP_FLAGS);
8773 return extent_fiemap(inode, fieinfo, start, len);
8776 int btrfs_readpage(struct file *file, struct page *page)
8778 struct extent_io_tree *tree;
8779 tree = &BTRFS_I(page->mapping->host)->io_tree;
8780 return extent_read_full_page(tree, page, btrfs_get_extent, 0);
8783 static int btrfs_writepage(struct page *page, struct writeback_control *wbc)
8785 struct inode *inode = page->mapping->host;
8788 if (current->flags & PF_MEMALLOC) {
8789 redirty_page_for_writepage(wbc, page);
8795 * If we are under memory pressure we will call this directly from the
8796 * VM, we need to make sure we have the inode referenced for the ordered
8797 * extent. If not just return like we didn't do anything.
8799 if (!igrab(inode)) {
8800 redirty_page_for_writepage(wbc, page);
8801 return AOP_WRITEPAGE_ACTIVATE;
8803 ret = extent_write_full_page(page, wbc);
8804 btrfs_add_delayed_iput(inode);
8808 static int btrfs_writepages(struct address_space *mapping,
8809 struct writeback_control *wbc)
8811 return extent_writepages(mapping, wbc);
8815 btrfs_readpages(struct file *file, struct address_space *mapping,
8816 struct list_head *pages, unsigned nr_pages)
8818 return extent_readpages(mapping, pages, nr_pages);
8821 static int __btrfs_releasepage(struct page *page, gfp_t gfp_flags)
8823 int ret = try_release_extent_mapping(page, gfp_flags);
8825 ClearPagePrivate(page);
8826 set_page_private(page, 0);
8832 static int btrfs_releasepage(struct page *page, gfp_t gfp_flags)
8834 if (PageWriteback(page) || PageDirty(page))
8836 return __btrfs_releasepage(page, gfp_flags);
8839 static void btrfs_invalidatepage(struct page *page, unsigned int offset,
8840 unsigned int length)
8842 struct inode *inode = page->mapping->host;
8843 struct extent_io_tree *tree;
8844 struct btrfs_ordered_extent *ordered;
8845 struct extent_state *cached_state = NULL;
8846 u64 page_start = page_offset(page);
8847 u64 page_end = page_start + PAGE_SIZE - 1;
8850 int inode_evicting = inode->i_state & I_FREEING;
8853 * we have the page locked, so new writeback can't start,
8854 * and the dirty bit won't be cleared while we are here.
8856 * Wait for IO on this page so that we can safely clear
8857 * the PagePrivate2 bit and do ordered accounting
8859 wait_on_page_writeback(page);
8861 tree = &BTRFS_I(inode)->io_tree;
8863 btrfs_releasepage(page, GFP_NOFS);
8867 if (!inode_evicting)
8868 lock_extent_bits(tree, page_start, page_end, &cached_state);
8871 ordered = btrfs_lookup_ordered_range(BTRFS_I(inode), start,
8872 page_end - start + 1);
8874 end = min(page_end, ordered->file_offset + ordered->len - 1);
8876 * IO on this page will never be started, so we need
8877 * to account for any ordered extents now
8879 if (!inode_evicting)
8880 clear_extent_bit(tree, start, end,
8881 EXTENT_DELALLOC | EXTENT_DELALLOC_NEW |
8882 EXTENT_LOCKED | EXTENT_DO_ACCOUNTING |
8883 EXTENT_DEFRAG, 1, 0, &cached_state);
8885 * whoever cleared the private bit is responsible
8886 * for the finish_ordered_io
8888 if (TestClearPagePrivate2(page)) {
8889 struct btrfs_ordered_inode_tree *tree;
8892 tree = &BTRFS_I(inode)->ordered_tree;
8894 spin_lock_irq(&tree->lock);
8895 set_bit(BTRFS_ORDERED_TRUNCATED, &ordered->flags);
8896 new_len = start - ordered->file_offset;
8897 if (new_len < ordered->truncated_len)
8898 ordered->truncated_len = new_len;
8899 spin_unlock_irq(&tree->lock);
8901 if (btrfs_dec_test_ordered_pending(inode, &ordered,
8903 end - start + 1, 1))
8904 btrfs_finish_ordered_io(ordered);
8906 btrfs_put_ordered_extent(ordered);
8907 if (!inode_evicting) {
8908 cached_state = NULL;
8909 lock_extent_bits(tree, start, end,
8914 if (start < page_end)
8919 * Qgroup reserved space handler
8920 * Page here will be either
8921 * 1) Already written to disk
8922 * In this case, its reserved space is released from data rsv map
8923 * and will be freed by delayed_ref handler finally.
8924 * So even we call qgroup_free_data(), it won't decrease reserved
8926 * 2) Not written to disk
8927 * This means the reserved space should be freed here. However,
8928 * if a truncate invalidates the page (by clearing PageDirty)
8929 * and the page is accounted for while allocating extent
8930 * in btrfs_check_data_free_space() we let delayed_ref to
8931 * free the entire extent.
8933 if (PageDirty(page))
8934 btrfs_qgroup_free_data(inode, NULL, page_start, PAGE_SIZE);
8935 if (!inode_evicting) {
8936 clear_extent_bit(tree, page_start, page_end, EXTENT_LOCKED |
8937 EXTENT_DELALLOC | EXTENT_DELALLOC_NEW |
8938 EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG, 1, 1,
8941 __btrfs_releasepage(page, GFP_NOFS);
8944 ClearPageChecked(page);
8945 if (PagePrivate(page)) {
8946 ClearPagePrivate(page);
8947 set_page_private(page, 0);
8953 * btrfs_page_mkwrite() is not allowed to change the file size as it gets
8954 * called from a page fault handler when a page is first dirtied. Hence we must
8955 * be careful to check for EOF conditions here. We set the page up correctly
8956 * for a written page which means we get ENOSPC checking when writing into
8957 * holes and correct delalloc and unwritten extent mapping on filesystems that
8958 * support these features.
8960 * We are not allowed to take the i_mutex here so we have to play games to
8961 * protect against truncate races as the page could now be beyond EOF. Because
8962 * truncate_setsize() writes the inode size before removing pages, once we have
8963 * the page lock we can determine safely if the page is beyond EOF. If it is not
8964 * beyond EOF, then the page is guaranteed safe against truncation until we
8967 vm_fault_t btrfs_page_mkwrite(struct vm_fault *vmf)
8969 struct page *page = vmf->page;
8970 struct inode *inode = file_inode(vmf->vma->vm_file);
8971 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
8972 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
8973 struct btrfs_ordered_extent *ordered;
8974 struct extent_state *cached_state = NULL;
8975 struct extent_changeset *data_reserved = NULL;
8977 unsigned long zero_start;
8987 reserved_space = PAGE_SIZE;
8989 sb_start_pagefault(inode->i_sb);
8990 page_start = page_offset(page);
8991 page_end = page_start + PAGE_SIZE - 1;
8995 * Reserving delalloc space after obtaining the page lock can lead to
8996 * deadlock. For example, if a dirty page is locked by this function
8997 * and the call to btrfs_delalloc_reserve_space() ends up triggering
8998 * dirty page write out, then the btrfs_writepage() function could
8999 * end up waiting indefinitely to get a lock on the page currently
9000 * being processed by btrfs_page_mkwrite() function.
9002 ret2 = btrfs_delalloc_reserve_space(inode, &data_reserved, page_start,
9005 ret2 = file_update_time(vmf->vma->vm_file);
9009 ret = vmf_error(ret2);
9015 ret = VM_FAULT_NOPAGE; /* make the VM retry the fault */
9018 size = i_size_read(inode);
9020 if ((page->mapping != inode->i_mapping) ||
9021 (page_start >= size)) {
9022 /* page got truncated out from underneath us */
9025 wait_on_page_writeback(page);
9027 lock_extent_bits(io_tree, page_start, page_end, &cached_state);
9028 set_page_extent_mapped(page);
9031 * we can't set the delalloc bits if there are pending ordered
9032 * extents. Drop our locks and wait for them to finish
9034 ordered = btrfs_lookup_ordered_range(BTRFS_I(inode), page_start,
9037 unlock_extent_cached(io_tree, page_start, page_end,
9040 btrfs_start_ordered_extent(inode, ordered, 1);
9041 btrfs_put_ordered_extent(ordered);
9045 if (page->index == ((size - 1) >> PAGE_SHIFT)) {
9046 reserved_space = round_up(size - page_start,
9047 fs_info->sectorsize);
9048 if (reserved_space < PAGE_SIZE) {
9049 end = page_start + reserved_space - 1;
9050 btrfs_delalloc_release_space(inode, data_reserved,
9051 page_start, PAGE_SIZE - reserved_space,
9057 * page_mkwrite gets called when the page is firstly dirtied after it's
9058 * faulted in, but write(2) could also dirty a page and set delalloc
9059 * bits, thus in this case for space account reason, we still need to
9060 * clear any delalloc bits within this page range since we have to
9061 * reserve data&meta space before lock_page() (see above comments).
9063 clear_extent_bit(&BTRFS_I(inode)->io_tree, page_start, end,
9064 EXTENT_DELALLOC | EXTENT_DO_ACCOUNTING |
9065 EXTENT_DEFRAG, 0, 0, &cached_state);
9067 ret2 = btrfs_set_extent_delalloc(inode, page_start, end, 0,
9070 unlock_extent_cached(io_tree, page_start, page_end,
9072 ret = VM_FAULT_SIGBUS;
9077 /* page is wholly or partially inside EOF */
9078 if (page_start + PAGE_SIZE > size)
9079 zero_start = offset_in_page(size);
9081 zero_start = PAGE_SIZE;
9083 if (zero_start != PAGE_SIZE) {
9085 memset(kaddr + zero_start, 0, PAGE_SIZE - zero_start);
9086 flush_dcache_page(page);
9089 ClearPageChecked(page);
9090 set_page_dirty(page);
9091 SetPageUptodate(page);
9093 BTRFS_I(inode)->last_trans = fs_info->generation;
9094 BTRFS_I(inode)->last_sub_trans = BTRFS_I(inode)->root->log_transid;
9095 BTRFS_I(inode)->last_log_commit = BTRFS_I(inode)->root->last_log_commit;
9097 unlock_extent_cached(io_tree, page_start, page_end, &cached_state);
9100 btrfs_delalloc_release_extents(BTRFS_I(inode), PAGE_SIZE);
9101 sb_end_pagefault(inode->i_sb);
9102 extent_changeset_free(data_reserved);
9103 return VM_FAULT_LOCKED;
9109 btrfs_delalloc_release_extents(BTRFS_I(inode), PAGE_SIZE);
9110 btrfs_delalloc_release_space(inode, data_reserved, page_start,
9111 reserved_space, (ret != 0));
9113 sb_end_pagefault(inode->i_sb);
9114 extent_changeset_free(data_reserved);
9118 static int btrfs_truncate(struct inode *inode, bool skip_writeback)
9120 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
9121 struct btrfs_root *root = BTRFS_I(inode)->root;
9122 struct btrfs_block_rsv *rsv;
9124 struct btrfs_trans_handle *trans;
9125 u64 mask = fs_info->sectorsize - 1;
9126 u64 min_size = btrfs_calc_metadata_size(fs_info, 1);
9128 if (!skip_writeback) {
9129 ret = btrfs_wait_ordered_range(inode, inode->i_size & (~mask),
9136 * Yes ladies and gentlemen, this is indeed ugly. We have a couple of
9137 * things going on here:
9139 * 1) We need to reserve space to update our inode.
9141 * 2) We need to have something to cache all the space that is going to
9142 * be free'd up by the truncate operation, but also have some slack
9143 * space reserved in case it uses space during the truncate (thank you
9144 * very much snapshotting).
9146 * And we need these to be separate. The fact is we can use a lot of
9147 * space doing the truncate, and we have no earthly idea how much space
9148 * we will use, so we need the truncate reservation to be separate so it
9149 * doesn't end up using space reserved for updating the inode. We also
9150 * need to be able to stop the transaction and start a new one, which
9151 * means we need to be able to update the inode several times, and we
9152 * have no idea of knowing how many times that will be, so we can't just
9153 * reserve 1 item for the entirety of the operation, so that has to be
9154 * done separately as well.
9156 * So that leaves us with
9158 * 1) rsv - for the truncate reservation, which we will steal from the
9159 * transaction reservation.
9160 * 2) fs_info->trans_block_rsv - this will have 1 items worth left for
9161 * updating the inode.
9163 rsv = btrfs_alloc_block_rsv(fs_info, BTRFS_BLOCK_RSV_TEMP);
9166 rsv->size = min_size;
9170 * 1 for the truncate slack space
9171 * 1 for updating the inode.
9173 trans = btrfs_start_transaction(root, 2);
9174 if (IS_ERR(trans)) {
9175 ret = PTR_ERR(trans);
9179 /* Migrate the slack space for the truncate to our reserve */
9180 ret = btrfs_block_rsv_migrate(&fs_info->trans_block_rsv, rsv,
9185 * So if we truncate and then write and fsync we normally would just
9186 * write the extents that changed, which is a problem if we need to
9187 * first truncate that entire inode. So set this flag so we write out
9188 * all of the extents in the inode to the sync log so we're completely
9191 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &BTRFS_I(inode)->runtime_flags);
9192 trans->block_rsv = rsv;
9195 ret = btrfs_truncate_inode_items(trans, root, inode,
9197 BTRFS_EXTENT_DATA_KEY);
9198 trans->block_rsv = &fs_info->trans_block_rsv;
9199 if (ret != -ENOSPC && ret != -EAGAIN)
9202 ret = btrfs_update_inode(trans, root, inode);
9206 btrfs_end_transaction(trans);
9207 btrfs_btree_balance_dirty(fs_info);
9209 trans = btrfs_start_transaction(root, 2);
9210 if (IS_ERR(trans)) {
9211 ret = PTR_ERR(trans);
9216 btrfs_block_rsv_release(fs_info, rsv, -1);
9217 ret = btrfs_block_rsv_migrate(&fs_info->trans_block_rsv,
9218 rsv, min_size, false);
9219 BUG_ON(ret); /* shouldn't happen */
9220 trans->block_rsv = rsv;
9224 * We can't call btrfs_truncate_block inside a trans handle as we could
9225 * deadlock with freeze, if we got NEED_TRUNCATE_BLOCK then we know
9226 * we've truncated everything except the last little bit, and can do
9227 * btrfs_truncate_block and then update the disk_i_size.
9229 if (ret == NEED_TRUNCATE_BLOCK) {
9230 btrfs_end_transaction(trans);
9231 btrfs_btree_balance_dirty(fs_info);
9233 ret = btrfs_truncate_block(inode, inode->i_size, 0, 0);
9236 trans = btrfs_start_transaction(root, 1);
9237 if (IS_ERR(trans)) {
9238 ret = PTR_ERR(trans);
9241 btrfs_ordered_update_i_size(inode, inode->i_size, NULL);
9247 trans->block_rsv = &fs_info->trans_block_rsv;
9248 ret2 = btrfs_update_inode(trans, root, inode);
9252 ret2 = btrfs_end_transaction(trans);
9255 btrfs_btree_balance_dirty(fs_info);
9258 btrfs_free_block_rsv(fs_info, rsv);
9264 * create a new subvolume directory/inode (helper for the ioctl).
9266 int btrfs_create_subvol_root(struct btrfs_trans_handle *trans,
9267 struct btrfs_root *new_root,
9268 struct btrfs_root *parent_root,
9271 struct inode *inode;
9275 inode = btrfs_new_inode(trans, new_root, NULL, "..", 2,
9276 new_dirid, new_dirid,
9277 S_IFDIR | (~current_umask() & S_IRWXUGO),
9280 return PTR_ERR(inode);
9281 inode->i_op = &btrfs_dir_inode_operations;
9282 inode->i_fop = &btrfs_dir_file_operations;
9284 set_nlink(inode, 1);
9285 btrfs_i_size_write(BTRFS_I(inode), 0);
9286 unlock_new_inode(inode);
9288 err = btrfs_subvol_inherit_props(trans, new_root, parent_root);
9290 btrfs_err(new_root->fs_info,
9291 "error inheriting subvolume %llu properties: %d",
9292 new_root->root_key.objectid, err);
9294 err = btrfs_update_inode(trans, new_root, inode);
9300 struct inode *btrfs_alloc_inode(struct super_block *sb)
9302 struct btrfs_fs_info *fs_info = btrfs_sb(sb);
9303 struct btrfs_inode *ei;
9304 struct inode *inode;
9306 ei = kmem_cache_alloc(btrfs_inode_cachep, GFP_KERNEL);
9313 ei->last_sub_trans = 0;
9314 ei->logged_trans = 0;
9315 ei->delalloc_bytes = 0;
9316 ei->new_delalloc_bytes = 0;
9317 ei->defrag_bytes = 0;
9318 ei->disk_i_size = 0;
9321 ei->index_cnt = (u64)-1;
9323 ei->last_unlink_trans = 0;
9324 ei->last_log_commit = 0;
9326 spin_lock_init(&ei->lock);
9327 ei->outstanding_extents = 0;
9328 if (sb->s_magic != BTRFS_TEST_MAGIC)
9329 btrfs_init_metadata_block_rsv(fs_info, &ei->block_rsv,
9330 BTRFS_BLOCK_RSV_DELALLOC);
9331 ei->runtime_flags = 0;
9332 ei->prop_compress = BTRFS_COMPRESS_NONE;
9333 ei->defrag_compress = BTRFS_COMPRESS_NONE;
9335 ei->delayed_node = NULL;
9337 ei->i_otime.tv_sec = 0;
9338 ei->i_otime.tv_nsec = 0;
9340 inode = &ei->vfs_inode;
9341 extent_map_tree_init(&ei->extent_tree);
9342 extent_io_tree_init(fs_info, &ei->io_tree, IO_TREE_INODE_IO, inode);
9343 extent_io_tree_init(fs_info, &ei->io_failure_tree,
9344 IO_TREE_INODE_IO_FAILURE, inode);
9345 ei->io_tree.track_uptodate = true;
9346 ei->io_failure_tree.track_uptodate = true;
9347 atomic_set(&ei->sync_writers, 0);
9348 mutex_init(&ei->log_mutex);
9349 mutex_init(&ei->delalloc_mutex);
9350 btrfs_ordered_inode_tree_init(&ei->ordered_tree);
9351 INIT_LIST_HEAD(&ei->delalloc_inodes);
9352 INIT_LIST_HEAD(&ei->delayed_iput);
9353 RB_CLEAR_NODE(&ei->rb_node);
9354 init_rwsem(&ei->dio_sem);
9359 #ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
9360 void btrfs_test_destroy_inode(struct inode *inode)
9362 btrfs_drop_extent_cache(BTRFS_I(inode), 0, (u64)-1, 0);
9363 kmem_cache_free(btrfs_inode_cachep, BTRFS_I(inode));
9367 void btrfs_free_inode(struct inode *inode)
9369 kmem_cache_free(btrfs_inode_cachep, BTRFS_I(inode));
9372 void btrfs_destroy_inode(struct inode *inode)
9374 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
9375 struct btrfs_ordered_extent *ordered;
9376 struct btrfs_root *root = BTRFS_I(inode)->root;
9378 WARN_ON(!hlist_empty(&inode->i_dentry));
9379 WARN_ON(inode->i_data.nrpages);
9380 WARN_ON(BTRFS_I(inode)->block_rsv.reserved);
9381 WARN_ON(BTRFS_I(inode)->block_rsv.size);
9382 WARN_ON(BTRFS_I(inode)->outstanding_extents);
9383 WARN_ON(BTRFS_I(inode)->delalloc_bytes);
9384 WARN_ON(BTRFS_I(inode)->new_delalloc_bytes);
9385 WARN_ON(BTRFS_I(inode)->csum_bytes);
9386 WARN_ON(BTRFS_I(inode)->defrag_bytes);
9389 * This can happen where we create an inode, but somebody else also
9390 * created the same inode and we need to destroy the one we already
9397 ordered = btrfs_lookup_first_ordered_extent(inode, (u64)-1);
9402 "found ordered extent %llu %llu on inode cleanup",
9403 ordered->file_offset, ordered->len);
9404 btrfs_remove_ordered_extent(inode, ordered);
9405 btrfs_put_ordered_extent(ordered);
9406 btrfs_put_ordered_extent(ordered);
9409 btrfs_qgroup_check_reserved_leak(inode);
9410 inode_tree_del(inode);
9411 btrfs_drop_extent_cache(BTRFS_I(inode), 0, (u64)-1, 0);
9414 int btrfs_drop_inode(struct inode *inode)
9416 struct btrfs_root *root = BTRFS_I(inode)->root;
9421 /* the snap/subvol tree is on deleting */
9422 if (btrfs_root_refs(&root->root_item) == 0)
9425 return generic_drop_inode(inode);
9428 static void init_once(void *foo)
9430 struct btrfs_inode *ei = (struct btrfs_inode *) foo;
9432 inode_init_once(&ei->vfs_inode);
9435 void __cold btrfs_destroy_cachep(void)
9438 * Make sure all delayed rcu free inodes are flushed before we
9442 kmem_cache_destroy(btrfs_inode_cachep);
9443 kmem_cache_destroy(btrfs_trans_handle_cachep);
9444 kmem_cache_destroy(btrfs_path_cachep);
9445 kmem_cache_destroy(btrfs_free_space_cachep);
9446 kmem_cache_destroy(btrfs_free_space_bitmap_cachep);
9449 int __init btrfs_init_cachep(void)
9451 btrfs_inode_cachep = kmem_cache_create("btrfs_inode",
9452 sizeof(struct btrfs_inode), 0,
9453 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD | SLAB_ACCOUNT,
9455 if (!btrfs_inode_cachep)
9458 btrfs_trans_handle_cachep = kmem_cache_create("btrfs_trans_handle",
9459 sizeof(struct btrfs_trans_handle), 0,
9460 SLAB_TEMPORARY | SLAB_MEM_SPREAD, NULL);
9461 if (!btrfs_trans_handle_cachep)
9464 btrfs_path_cachep = kmem_cache_create("btrfs_path",
9465 sizeof(struct btrfs_path), 0,
9466 SLAB_MEM_SPREAD, NULL);
9467 if (!btrfs_path_cachep)
9470 btrfs_free_space_cachep = kmem_cache_create("btrfs_free_space",
9471 sizeof(struct btrfs_free_space), 0,
9472 SLAB_MEM_SPREAD, NULL);
9473 if (!btrfs_free_space_cachep)
9476 btrfs_free_space_bitmap_cachep = kmem_cache_create("btrfs_free_space_bitmap",
9477 PAGE_SIZE, PAGE_SIZE,
9478 SLAB_RED_ZONE, NULL);
9479 if (!btrfs_free_space_bitmap_cachep)
9484 btrfs_destroy_cachep();
9488 static int btrfs_getattr(const struct path *path, struct kstat *stat,
9489 u32 request_mask, unsigned int flags)
9492 struct inode *inode = d_inode(path->dentry);
9493 u32 blocksize = inode->i_sb->s_blocksize;
9494 u32 bi_flags = BTRFS_I(inode)->flags;
9496 stat->result_mask |= STATX_BTIME;
9497 stat->btime.tv_sec = BTRFS_I(inode)->i_otime.tv_sec;
9498 stat->btime.tv_nsec = BTRFS_I(inode)->i_otime.tv_nsec;
9499 if (bi_flags & BTRFS_INODE_APPEND)
9500 stat->attributes |= STATX_ATTR_APPEND;
9501 if (bi_flags & BTRFS_INODE_COMPRESS)
9502 stat->attributes |= STATX_ATTR_COMPRESSED;
9503 if (bi_flags & BTRFS_INODE_IMMUTABLE)
9504 stat->attributes |= STATX_ATTR_IMMUTABLE;
9505 if (bi_flags & BTRFS_INODE_NODUMP)
9506 stat->attributes |= STATX_ATTR_NODUMP;
9508 stat->attributes_mask |= (STATX_ATTR_APPEND |
9509 STATX_ATTR_COMPRESSED |
9510 STATX_ATTR_IMMUTABLE |
9513 generic_fillattr(inode, stat);
9514 stat->dev = BTRFS_I(inode)->root->anon_dev;
9516 spin_lock(&BTRFS_I(inode)->lock);
9517 delalloc_bytes = BTRFS_I(inode)->new_delalloc_bytes;
9518 spin_unlock(&BTRFS_I(inode)->lock);
9519 stat->blocks = (ALIGN(inode_get_bytes(inode), blocksize) +
9520 ALIGN(delalloc_bytes, blocksize)) >> 9;
9524 static int btrfs_rename_exchange(struct inode *old_dir,
9525 struct dentry *old_dentry,
9526 struct inode *new_dir,
9527 struct dentry *new_dentry)
9529 struct btrfs_fs_info *fs_info = btrfs_sb(old_dir->i_sb);
9530 struct btrfs_trans_handle *trans;
9531 struct btrfs_root *root = BTRFS_I(old_dir)->root;
9532 struct btrfs_root *dest = BTRFS_I(new_dir)->root;
9533 struct inode *new_inode = new_dentry->d_inode;
9534 struct inode *old_inode = old_dentry->d_inode;
9535 struct timespec64 ctime = current_time(old_inode);
9536 struct dentry *parent;
9537 u64 old_ino = btrfs_ino(BTRFS_I(old_inode));
9538 u64 new_ino = btrfs_ino(BTRFS_I(new_inode));
9542 bool root_log_pinned = false;
9543 bool dest_log_pinned = false;
9544 struct btrfs_log_ctx ctx_root;
9545 struct btrfs_log_ctx ctx_dest;
9546 bool sync_log_root = false;
9547 bool sync_log_dest = false;
9548 bool commit_transaction = false;
9550 /* we only allow rename subvolume link between subvolumes */
9551 if (old_ino != BTRFS_FIRST_FREE_OBJECTID && root != dest)
9554 btrfs_init_log_ctx(&ctx_root, old_inode);
9555 btrfs_init_log_ctx(&ctx_dest, new_inode);
9557 /* close the race window with snapshot create/destroy ioctl */
9558 if (old_ino == BTRFS_FIRST_FREE_OBJECTID ||
9559 new_ino == BTRFS_FIRST_FREE_OBJECTID)
9560 down_read(&fs_info->subvol_sem);
9563 * We want to reserve the absolute worst case amount of items. So if
9564 * both inodes are subvols and we need to unlink them then that would
9565 * require 4 item modifications, but if they are both normal inodes it
9566 * would require 5 item modifications, so we'll assume their normal
9567 * inodes. So 5 * 2 is 10, plus 2 for the new links, so 12 total items
9568 * should cover the worst case number of items we'll modify.
9570 trans = btrfs_start_transaction(root, 12);
9571 if (IS_ERR(trans)) {
9572 ret = PTR_ERR(trans);
9577 btrfs_record_root_in_trans(trans, dest);
9580 * We need to find a free sequence number both in the source and
9581 * in the destination directory for the exchange.
9583 ret = btrfs_set_inode_index(BTRFS_I(new_dir), &old_idx);
9586 ret = btrfs_set_inode_index(BTRFS_I(old_dir), &new_idx);
9590 BTRFS_I(old_inode)->dir_index = 0ULL;
9591 BTRFS_I(new_inode)->dir_index = 0ULL;
9593 /* Reference for the source. */
9594 if (old_ino == BTRFS_FIRST_FREE_OBJECTID) {
9595 /* force full log commit if subvolume involved. */
9596 btrfs_set_log_full_commit(trans);
9598 btrfs_pin_log_trans(root);
9599 root_log_pinned = true;
9600 ret = btrfs_insert_inode_ref(trans, dest,
9601 new_dentry->d_name.name,
9602 new_dentry->d_name.len,
9604 btrfs_ino(BTRFS_I(new_dir)),
9610 /* And now for the dest. */
9611 if (new_ino == BTRFS_FIRST_FREE_OBJECTID) {
9612 /* force full log commit if subvolume involved. */
9613 btrfs_set_log_full_commit(trans);
9615 btrfs_pin_log_trans(dest);
9616 dest_log_pinned = true;
9617 ret = btrfs_insert_inode_ref(trans, root,
9618 old_dentry->d_name.name,
9619 old_dentry->d_name.len,
9621 btrfs_ino(BTRFS_I(old_dir)),
9627 /* Update inode version and ctime/mtime. */
9628 inode_inc_iversion(old_dir);
9629 inode_inc_iversion(new_dir);
9630 inode_inc_iversion(old_inode);
9631 inode_inc_iversion(new_inode);
9632 old_dir->i_ctime = old_dir->i_mtime = ctime;
9633 new_dir->i_ctime = new_dir->i_mtime = ctime;
9634 old_inode->i_ctime = ctime;
9635 new_inode->i_ctime = ctime;
9637 if (old_dentry->d_parent != new_dentry->d_parent) {
9638 btrfs_record_unlink_dir(trans, BTRFS_I(old_dir),
9639 BTRFS_I(old_inode), 1);
9640 btrfs_record_unlink_dir(trans, BTRFS_I(new_dir),
9641 BTRFS_I(new_inode), 1);
9644 /* src is a subvolume */
9645 if (old_ino == BTRFS_FIRST_FREE_OBJECTID) {
9646 ret = btrfs_unlink_subvol(trans, old_dir, old_dentry);
9647 } else { /* src is an inode */
9648 ret = __btrfs_unlink_inode(trans, root, BTRFS_I(old_dir),
9649 BTRFS_I(old_dentry->d_inode),
9650 old_dentry->d_name.name,
9651 old_dentry->d_name.len);
9653 ret = btrfs_update_inode(trans, root, old_inode);
9656 btrfs_abort_transaction(trans, ret);
9660 /* dest is a subvolume */
9661 if (new_ino == BTRFS_FIRST_FREE_OBJECTID) {
9662 ret = btrfs_unlink_subvol(trans, new_dir, new_dentry);
9663 } else { /* dest is an inode */
9664 ret = __btrfs_unlink_inode(trans, dest, BTRFS_I(new_dir),
9665 BTRFS_I(new_dentry->d_inode),
9666 new_dentry->d_name.name,
9667 new_dentry->d_name.len);
9669 ret = btrfs_update_inode(trans, dest, new_inode);
9672 btrfs_abort_transaction(trans, ret);
9676 ret = btrfs_add_link(trans, BTRFS_I(new_dir), BTRFS_I(old_inode),
9677 new_dentry->d_name.name,
9678 new_dentry->d_name.len, 0, old_idx);
9680 btrfs_abort_transaction(trans, ret);
9684 ret = btrfs_add_link(trans, BTRFS_I(old_dir), BTRFS_I(new_inode),
9685 old_dentry->d_name.name,
9686 old_dentry->d_name.len, 0, new_idx);
9688 btrfs_abort_transaction(trans, ret);
9692 if (old_inode->i_nlink == 1)
9693 BTRFS_I(old_inode)->dir_index = old_idx;
9694 if (new_inode->i_nlink == 1)
9695 BTRFS_I(new_inode)->dir_index = new_idx;
9697 if (root_log_pinned) {
9698 parent = new_dentry->d_parent;
9699 ret = btrfs_log_new_name(trans, BTRFS_I(old_inode),
9700 BTRFS_I(old_dir), parent,
9702 if (ret == BTRFS_NEED_LOG_SYNC)
9703 sync_log_root = true;
9704 else if (ret == BTRFS_NEED_TRANS_COMMIT)
9705 commit_transaction = true;
9707 btrfs_end_log_trans(root);
9708 root_log_pinned = false;
9710 if (dest_log_pinned) {
9711 if (!commit_transaction) {
9712 parent = old_dentry->d_parent;
9713 ret = btrfs_log_new_name(trans, BTRFS_I(new_inode),
9714 BTRFS_I(new_dir), parent,
9716 if (ret == BTRFS_NEED_LOG_SYNC)
9717 sync_log_dest = true;
9718 else if (ret == BTRFS_NEED_TRANS_COMMIT)
9719 commit_transaction = true;
9722 btrfs_end_log_trans(dest);
9723 dest_log_pinned = false;
9727 * If we have pinned a log and an error happened, we unpin tasks
9728 * trying to sync the log and force them to fallback to a transaction
9729 * commit if the log currently contains any of the inodes involved in
9730 * this rename operation (to ensure we do not persist a log with an
9731 * inconsistent state for any of these inodes or leading to any
9732 * inconsistencies when replayed). If the transaction was aborted, the
9733 * abortion reason is propagated to userspace when attempting to commit
9734 * the transaction. If the log does not contain any of these inodes, we
9735 * allow the tasks to sync it.
9737 if (ret && (root_log_pinned || dest_log_pinned)) {
9738 if (btrfs_inode_in_log(BTRFS_I(old_dir), fs_info->generation) ||
9739 btrfs_inode_in_log(BTRFS_I(new_dir), fs_info->generation) ||
9740 btrfs_inode_in_log(BTRFS_I(old_inode), fs_info->generation) ||
9742 btrfs_inode_in_log(BTRFS_I(new_inode), fs_info->generation)))
9743 btrfs_set_log_full_commit(trans);
9745 if (root_log_pinned) {
9746 btrfs_end_log_trans(root);
9747 root_log_pinned = false;
9749 if (dest_log_pinned) {
9750 btrfs_end_log_trans(dest);
9751 dest_log_pinned = false;
9754 if (!ret && sync_log_root && !commit_transaction) {
9755 ret = btrfs_sync_log(trans, BTRFS_I(old_inode)->root,
9758 commit_transaction = true;
9760 if (!ret && sync_log_dest && !commit_transaction) {
9761 ret = btrfs_sync_log(trans, BTRFS_I(new_inode)->root,
9764 commit_transaction = true;
9766 if (commit_transaction) {
9768 * We may have set commit_transaction when logging the new name
9769 * in the destination root, in which case we left the source
9770 * root context in the list of log contextes. So make sure we
9771 * remove it to avoid invalid memory accesses, since the context
9772 * was allocated in our stack frame.
9774 if (sync_log_root) {
9775 mutex_lock(&root->log_mutex);
9776 list_del_init(&ctx_root.list);
9777 mutex_unlock(&root->log_mutex);
9779 ret = btrfs_commit_transaction(trans);
9783 ret2 = btrfs_end_transaction(trans);
9784 ret = ret ? ret : ret2;
9787 if (new_ino == BTRFS_FIRST_FREE_OBJECTID ||
9788 old_ino == BTRFS_FIRST_FREE_OBJECTID)
9789 up_read(&fs_info->subvol_sem);
9791 ASSERT(list_empty(&ctx_root.list));
9792 ASSERT(list_empty(&ctx_dest.list));
9797 static int btrfs_whiteout_for_rename(struct btrfs_trans_handle *trans,
9798 struct btrfs_root *root,
9800 struct dentry *dentry)
9803 struct inode *inode;
9807 ret = btrfs_find_free_ino(root, &objectid);
9811 inode = btrfs_new_inode(trans, root, dir,
9812 dentry->d_name.name,
9814 btrfs_ino(BTRFS_I(dir)),
9816 S_IFCHR | WHITEOUT_MODE,
9819 if (IS_ERR(inode)) {
9820 ret = PTR_ERR(inode);
9824 inode->i_op = &btrfs_special_inode_operations;
9825 init_special_inode(inode, inode->i_mode,
9828 ret = btrfs_init_inode_security(trans, inode, dir,
9833 ret = btrfs_add_nondir(trans, BTRFS_I(dir), dentry,
9834 BTRFS_I(inode), 0, index);
9838 ret = btrfs_update_inode(trans, root, inode);
9840 unlock_new_inode(inode);
9842 inode_dec_link_count(inode);
9848 static int btrfs_rename(struct inode *old_dir, struct dentry *old_dentry,
9849 struct inode *new_dir, struct dentry *new_dentry,
9852 struct btrfs_fs_info *fs_info = btrfs_sb(old_dir->i_sb);
9853 struct btrfs_trans_handle *trans;
9854 unsigned int trans_num_items;
9855 struct btrfs_root *root = BTRFS_I(old_dir)->root;
9856 struct btrfs_root *dest = BTRFS_I(new_dir)->root;
9857 struct inode *new_inode = d_inode(new_dentry);
9858 struct inode *old_inode = d_inode(old_dentry);
9861 u64 old_ino = btrfs_ino(BTRFS_I(old_inode));
9862 bool log_pinned = false;
9863 struct btrfs_log_ctx ctx;
9864 bool sync_log = false;
9865 bool commit_transaction = false;
9867 if (btrfs_ino(BTRFS_I(new_dir)) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)
9870 /* we only allow rename subvolume link between subvolumes */
9871 if (old_ino != BTRFS_FIRST_FREE_OBJECTID && root != dest)
9874 if (old_ino == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID ||
9875 (new_inode && btrfs_ino(BTRFS_I(new_inode)) == BTRFS_FIRST_FREE_OBJECTID))
9878 if (S_ISDIR(old_inode->i_mode) && new_inode &&
9879 new_inode->i_size > BTRFS_EMPTY_DIR_SIZE)
9883 /* check for collisions, even if the name isn't there */
9884 ret = btrfs_check_dir_item_collision(dest, new_dir->i_ino,
9885 new_dentry->d_name.name,
9886 new_dentry->d_name.len);
9889 if (ret == -EEXIST) {
9891 * eexist without a new_inode */
9892 if (WARN_ON(!new_inode)) {
9896 /* maybe -EOVERFLOW */
9903 * we're using rename to replace one file with another. Start IO on it
9904 * now so we don't add too much work to the end of the transaction
9906 if (new_inode && S_ISREG(old_inode->i_mode) && new_inode->i_size)
9907 filemap_flush(old_inode->i_mapping);
9909 /* close the racy window with snapshot create/destroy ioctl */
9910 if (old_ino == BTRFS_FIRST_FREE_OBJECTID)
9911 down_read(&fs_info->subvol_sem);
9913 * We want to reserve the absolute worst case amount of items. So if
9914 * both inodes are subvols and we need to unlink them then that would
9915 * require 4 item modifications, but if they are both normal inodes it
9916 * would require 5 item modifications, so we'll assume they are normal
9917 * inodes. So 5 * 2 is 10, plus 1 for the new link, so 11 total items
9918 * should cover the worst case number of items we'll modify.
9919 * If our rename has the whiteout flag, we need more 5 units for the
9920 * new inode (1 inode item, 1 inode ref, 2 dir items and 1 xattr item
9921 * when selinux is enabled).
9923 trans_num_items = 11;
9924 if (flags & RENAME_WHITEOUT)
9925 trans_num_items += 5;
9926 trans = btrfs_start_transaction(root, trans_num_items);
9927 if (IS_ERR(trans)) {
9928 ret = PTR_ERR(trans);
9933 btrfs_record_root_in_trans(trans, dest);
9935 ret = btrfs_set_inode_index(BTRFS_I(new_dir), &index);
9939 BTRFS_I(old_inode)->dir_index = 0ULL;
9940 if (unlikely(old_ino == BTRFS_FIRST_FREE_OBJECTID)) {
9941 /* force full log commit if subvolume involved. */
9942 btrfs_set_log_full_commit(trans);
9944 btrfs_pin_log_trans(root);
9946 ret = btrfs_insert_inode_ref(trans, dest,
9947 new_dentry->d_name.name,
9948 new_dentry->d_name.len,
9950 btrfs_ino(BTRFS_I(new_dir)), index);
9955 inode_inc_iversion(old_dir);
9956 inode_inc_iversion(new_dir);
9957 inode_inc_iversion(old_inode);
9958 old_dir->i_ctime = old_dir->i_mtime =
9959 new_dir->i_ctime = new_dir->i_mtime =
9960 old_inode->i_ctime = current_time(old_dir);
9962 if (old_dentry->d_parent != new_dentry->d_parent)
9963 btrfs_record_unlink_dir(trans, BTRFS_I(old_dir),
9964 BTRFS_I(old_inode), 1);
9966 if (unlikely(old_ino == BTRFS_FIRST_FREE_OBJECTID)) {
9967 ret = btrfs_unlink_subvol(trans, old_dir, old_dentry);
9969 ret = __btrfs_unlink_inode(trans, root, BTRFS_I(old_dir),
9970 BTRFS_I(d_inode(old_dentry)),
9971 old_dentry->d_name.name,
9972 old_dentry->d_name.len);
9974 ret = btrfs_update_inode(trans, root, old_inode);
9977 btrfs_abort_transaction(trans, ret);
9982 inode_inc_iversion(new_inode);
9983 new_inode->i_ctime = current_time(new_inode);
9984 if (unlikely(btrfs_ino(BTRFS_I(new_inode)) ==
9985 BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)) {
9986 ret = btrfs_unlink_subvol(trans, new_dir, new_dentry);
9987 BUG_ON(new_inode->i_nlink == 0);
9989 ret = btrfs_unlink_inode(trans, dest, BTRFS_I(new_dir),
9990 BTRFS_I(d_inode(new_dentry)),
9991 new_dentry->d_name.name,
9992 new_dentry->d_name.len);
9994 if (!ret && new_inode->i_nlink == 0)
9995 ret = btrfs_orphan_add(trans,
9996 BTRFS_I(d_inode(new_dentry)));
9998 btrfs_abort_transaction(trans, ret);
10003 ret = btrfs_add_link(trans, BTRFS_I(new_dir), BTRFS_I(old_inode),
10004 new_dentry->d_name.name,
10005 new_dentry->d_name.len, 0, index);
10007 btrfs_abort_transaction(trans, ret);
10011 if (old_inode->i_nlink == 1)
10012 BTRFS_I(old_inode)->dir_index = index;
10015 struct dentry *parent = new_dentry->d_parent;
10017 btrfs_init_log_ctx(&ctx, old_inode);
10018 ret = btrfs_log_new_name(trans, BTRFS_I(old_inode),
10019 BTRFS_I(old_dir), parent,
10021 if (ret == BTRFS_NEED_LOG_SYNC)
10023 else if (ret == BTRFS_NEED_TRANS_COMMIT)
10024 commit_transaction = true;
10026 btrfs_end_log_trans(root);
10027 log_pinned = false;
10030 if (flags & RENAME_WHITEOUT) {
10031 ret = btrfs_whiteout_for_rename(trans, root, old_dir,
10035 btrfs_abort_transaction(trans, ret);
10041 * If we have pinned the log and an error happened, we unpin tasks
10042 * trying to sync the log and force them to fallback to a transaction
10043 * commit if the log currently contains any of the inodes involved in
10044 * this rename operation (to ensure we do not persist a log with an
10045 * inconsistent state for any of these inodes or leading to any
10046 * inconsistencies when replayed). If the transaction was aborted, the
10047 * abortion reason is propagated to userspace when attempting to commit
10048 * the transaction. If the log does not contain any of these inodes, we
10049 * allow the tasks to sync it.
10051 if (ret && log_pinned) {
10052 if (btrfs_inode_in_log(BTRFS_I(old_dir), fs_info->generation) ||
10053 btrfs_inode_in_log(BTRFS_I(new_dir), fs_info->generation) ||
10054 btrfs_inode_in_log(BTRFS_I(old_inode), fs_info->generation) ||
10056 btrfs_inode_in_log(BTRFS_I(new_inode), fs_info->generation)))
10057 btrfs_set_log_full_commit(trans);
10059 btrfs_end_log_trans(root);
10060 log_pinned = false;
10062 if (!ret && sync_log) {
10063 ret = btrfs_sync_log(trans, BTRFS_I(old_inode)->root, &ctx);
10065 commit_transaction = true;
10067 if (commit_transaction) {
10068 ret = btrfs_commit_transaction(trans);
10072 ret2 = btrfs_end_transaction(trans);
10073 ret = ret ? ret : ret2;
10076 if (old_ino == BTRFS_FIRST_FREE_OBJECTID)
10077 up_read(&fs_info->subvol_sem);
10082 static int btrfs_rename2(struct inode *old_dir, struct dentry *old_dentry,
10083 struct inode *new_dir, struct dentry *new_dentry,
10084 unsigned int flags)
10086 if (flags & ~(RENAME_NOREPLACE | RENAME_EXCHANGE | RENAME_WHITEOUT))
10089 if (flags & RENAME_EXCHANGE)
10090 return btrfs_rename_exchange(old_dir, old_dentry, new_dir,
10093 return btrfs_rename(old_dir, old_dentry, new_dir, new_dentry, flags);
10096 struct btrfs_delalloc_work {
10097 struct inode *inode;
10098 struct completion completion;
10099 struct list_head list;
10100 struct btrfs_work work;
10103 static void btrfs_run_delalloc_work(struct btrfs_work *work)
10105 struct btrfs_delalloc_work *delalloc_work;
10106 struct inode *inode;
10108 delalloc_work = container_of(work, struct btrfs_delalloc_work,
10110 inode = delalloc_work->inode;
10111 filemap_flush(inode->i_mapping);
10112 if (test_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
10113 &BTRFS_I(inode)->runtime_flags))
10114 filemap_flush(inode->i_mapping);
10117 complete(&delalloc_work->completion);
10120 static struct btrfs_delalloc_work *btrfs_alloc_delalloc_work(struct inode *inode)
10122 struct btrfs_delalloc_work *work;
10124 work = kmalloc(sizeof(*work), GFP_NOFS);
10128 init_completion(&work->completion);
10129 INIT_LIST_HEAD(&work->list);
10130 work->inode = inode;
10131 btrfs_init_work(&work->work, btrfs_run_delalloc_work, NULL, NULL);
10137 * some fairly slow code that needs optimization. This walks the list
10138 * of all the inodes with pending delalloc and forces them to disk.
10140 static int start_delalloc_inodes(struct btrfs_root *root, int nr, bool snapshot)
10142 struct btrfs_inode *binode;
10143 struct inode *inode;
10144 struct btrfs_delalloc_work *work, *next;
10145 struct list_head works;
10146 struct list_head splice;
10149 INIT_LIST_HEAD(&works);
10150 INIT_LIST_HEAD(&splice);
10152 mutex_lock(&root->delalloc_mutex);
10153 spin_lock(&root->delalloc_lock);
10154 list_splice_init(&root->delalloc_inodes, &splice);
10155 while (!list_empty(&splice)) {
10156 binode = list_entry(splice.next, struct btrfs_inode,
10159 list_move_tail(&binode->delalloc_inodes,
10160 &root->delalloc_inodes);
10161 inode = igrab(&binode->vfs_inode);
10163 cond_resched_lock(&root->delalloc_lock);
10166 spin_unlock(&root->delalloc_lock);
10169 set_bit(BTRFS_INODE_SNAPSHOT_FLUSH,
10170 &binode->runtime_flags);
10171 work = btrfs_alloc_delalloc_work(inode);
10177 list_add_tail(&work->list, &works);
10178 btrfs_queue_work(root->fs_info->flush_workers,
10181 if (nr != -1 && ret >= nr)
10184 spin_lock(&root->delalloc_lock);
10186 spin_unlock(&root->delalloc_lock);
10189 list_for_each_entry_safe(work, next, &works, list) {
10190 list_del_init(&work->list);
10191 wait_for_completion(&work->completion);
10195 if (!list_empty(&splice)) {
10196 spin_lock(&root->delalloc_lock);
10197 list_splice_tail(&splice, &root->delalloc_inodes);
10198 spin_unlock(&root->delalloc_lock);
10200 mutex_unlock(&root->delalloc_mutex);
10204 int btrfs_start_delalloc_snapshot(struct btrfs_root *root)
10206 struct btrfs_fs_info *fs_info = root->fs_info;
10209 if (test_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state))
10212 ret = start_delalloc_inodes(root, -1, true);
10218 int btrfs_start_delalloc_roots(struct btrfs_fs_info *fs_info, int nr)
10220 struct btrfs_root *root;
10221 struct list_head splice;
10224 if (test_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state))
10227 INIT_LIST_HEAD(&splice);
10229 mutex_lock(&fs_info->delalloc_root_mutex);
10230 spin_lock(&fs_info->delalloc_root_lock);
10231 list_splice_init(&fs_info->delalloc_roots, &splice);
10232 while (!list_empty(&splice) && nr) {
10233 root = list_first_entry(&splice, struct btrfs_root,
10235 root = btrfs_grab_fs_root(root);
10237 list_move_tail(&root->delalloc_root,
10238 &fs_info->delalloc_roots);
10239 spin_unlock(&fs_info->delalloc_root_lock);
10241 ret = start_delalloc_inodes(root, nr, false);
10242 btrfs_put_fs_root(root);
10250 spin_lock(&fs_info->delalloc_root_lock);
10252 spin_unlock(&fs_info->delalloc_root_lock);
10256 if (!list_empty(&splice)) {
10257 spin_lock(&fs_info->delalloc_root_lock);
10258 list_splice_tail(&splice, &fs_info->delalloc_roots);
10259 spin_unlock(&fs_info->delalloc_root_lock);
10261 mutex_unlock(&fs_info->delalloc_root_mutex);
10265 static int btrfs_symlink(struct inode *dir, struct dentry *dentry,
10266 const char *symname)
10268 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
10269 struct btrfs_trans_handle *trans;
10270 struct btrfs_root *root = BTRFS_I(dir)->root;
10271 struct btrfs_path *path;
10272 struct btrfs_key key;
10273 struct inode *inode = NULL;
10280 struct btrfs_file_extent_item *ei;
10281 struct extent_buffer *leaf;
10283 name_len = strlen(symname);
10284 if (name_len > BTRFS_MAX_INLINE_DATA_SIZE(fs_info))
10285 return -ENAMETOOLONG;
10288 * 2 items for inode item and ref
10289 * 2 items for dir items
10290 * 1 item for updating parent inode item
10291 * 1 item for the inline extent item
10292 * 1 item for xattr if selinux is on
10294 trans = btrfs_start_transaction(root, 7);
10296 return PTR_ERR(trans);
10298 err = btrfs_find_free_ino(root, &objectid);
10302 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
10303 dentry->d_name.len, btrfs_ino(BTRFS_I(dir)),
10304 objectid, S_IFLNK|S_IRWXUGO, &index);
10305 if (IS_ERR(inode)) {
10306 err = PTR_ERR(inode);
10312 * If the active LSM wants to access the inode during
10313 * d_instantiate it needs these. Smack checks to see
10314 * if the filesystem supports xattrs by looking at the
10317 inode->i_fop = &btrfs_file_operations;
10318 inode->i_op = &btrfs_file_inode_operations;
10319 inode->i_mapping->a_ops = &btrfs_aops;
10320 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
10322 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
10326 path = btrfs_alloc_path();
10331 key.objectid = btrfs_ino(BTRFS_I(inode));
10333 key.type = BTRFS_EXTENT_DATA_KEY;
10334 datasize = btrfs_file_extent_calc_inline_size(name_len);
10335 err = btrfs_insert_empty_item(trans, root, path, &key,
10338 btrfs_free_path(path);
10341 leaf = path->nodes[0];
10342 ei = btrfs_item_ptr(leaf, path->slots[0],
10343 struct btrfs_file_extent_item);
10344 btrfs_set_file_extent_generation(leaf, ei, trans->transid);
10345 btrfs_set_file_extent_type(leaf, ei,
10346 BTRFS_FILE_EXTENT_INLINE);
10347 btrfs_set_file_extent_encryption(leaf, ei, 0);
10348 btrfs_set_file_extent_compression(leaf, ei, 0);
10349 btrfs_set_file_extent_other_encoding(leaf, ei, 0);
10350 btrfs_set_file_extent_ram_bytes(leaf, ei, name_len);
10352 ptr = btrfs_file_extent_inline_start(ei);
10353 write_extent_buffer(leaf, symname, ptr, name_len);
10354 btrfs_mark_buffer_dirty(leaf);
10355 btrfs_free_path(path);
10357 inode->i_op = &btrfs_symlink_inode_operations;
10358 inode_nohighmem(inode);
10359 inode_set_bytes(inode, name_len);
10360 btrfs_i_size_write(BTRFS_I(inode), name_len);
10361 err = btrfs_update_inode(trans, root, inode);
10363 * Last step, add directory indexes for our symlink inode. This is the
10364 * last step to avoid extra cleanup of these indexes if an error happens
10368 err = btrfs_add_nondir(trans, BTRFS_I(dir), dentry,
10369 BTRFS_I(inode), 0, index);
10373 d_instantiate_new(dentry, inode);
10376 btrfs_end_transaction(trans);
10377 if (err && inode) {
10378 inode_dec_link_count(inode);
10379 discard_new_inode(inode);
10381 btrfs_btree_balance_dirty(fs_info);
10385 static int __btrfs_prealloc_file_range(struct inode *inode, int mode,
10386 u64 start, u64 num_bytes, u64 min_size,
10387 loff_t actual_len, u64 *alloc_hint,
10388 struct btrfs_trans_handle *trans)
10390 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
10391 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
10392 struct extent_map *em;
10393 struct btrfs_root *root = BTRFS_I(inode)->root;
10394 struct btrfs_key ins;
10395 u64 cur_offset = start;
10398 u64 last_alloc = (u64)-1;
10400 bool own_trans = true;
10401 u64 end = start + num_bytes - 1;
10405 while (num_bytes > 0) {
10407 trans = btrfs_start_transaction(root, 3);
10408 if (IS_ERR(trans)) {
10409 ret = PTR_ERR(trans);
10414 cur_bytes = min_t(u64, num_bytes, SZ_256M);
10415 cur_bytes = max(cur_bytes, min_size);
10417 * If we are severely fragmented we could end up with really
10418 * small allocations, so if the allocator is returning small
10419 * chunks lets make its job easier by only searching for those
10422 cur_bytes = min(cur_bytes, last_alloc);
10423 ret = btrfs_reserve_extent(root, cur_bytes, cur_bytes,
10424 min_size, 0, *alloc_hint, &ins, 1, 0);
10427 btrfs_end_transaction(trans);
10430 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
10432 last_alloc = ins.offset;
10433 ret = insert_reserved_file_extent(trans, inode,
10434 cur_offset, ins.objectid,
10435 ins.offset, ins.offset,
10436 ins.offset, 0, 0, 0,
10437 BTRFS_FILE_EXTENT_PREALLOC);
10439 btrfs_free_reserved_extent(fs_info, ins.objectid,
10441 btrfs_abort_transaction(trans, ret);
10443 btrfs_end_transaction(trans);
10447 btrfs_drop_extent_cache(BTRFS_I(inode), cur_offset,
10448 cur_offset + ins.offset -1, 0);
10450 em = alloc_extent_map();
10452 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
10453 &BTRFS_I(inode)->runtime_flags);
10457 em->start = cur_offset;
10458 em->orig_start = cur_offset;
10459 em->len = ins.offset;
10460 em->block_start = ins.objectid;
10461 em->block_len = ins.offset;
10462 em->orig_block_len = ins.offset;
10463 em->ram_bytes = ins.offset;
10464 em->bdev = fs_info->fs_devices->latest_bdev;
10465 set_bit(EXTENT_FLAG_PREALLOC, &em->flags);
10466 em->generation = trans->transid;
10469 write_lock(&em_tree->lock);
10470 ret = add_extent_mapping(em_tree, em, 1);
10471 write_unlock(&em_tree->lock);
10472 if (ret != -EEXIST)
10474 btrfs_drop_extent_cache(BTRFS_I(inode), cur_offset,
10475 cur_offset + ins.offset - 1,
10478 free_extent_map(em);
10480 num_bytes -= ins.offset;
10481 cur_offset += ins.offset;
10482 *alloc_hint = ins.objectid + ins.offset;
10484 inode_inc_iversion(inode);
10485 inode->i_ctime = current_time(inode);
10486 BTRFS_I(inode)->flags |= BTRFS_INODE_PREALLOC;
10487 if (!(mode & FALLOC_FL_KEEP_SIZE) &&
10488 (actual_len > inode->i_size) &&
10489 (cur_offset > inode->i_size)) {
10490 if (cur_offset > actual_len)
10491 i_size = actual_len;
10493 i_size = cur_offset;
10494 i_size_write(inode, i_size);
10495 btrfs_ordered_update_i_size(inode, i_size, NULL);
10498 ret = btrfs_update_inode(trans, root, inode);
10501 btrfs_abort_transaction(trans, ret);
10503 btrfs_end_transaction(trans);
10508 btrfs_end_transaction(trans);
10510 if (cur_offset < end)
10511 btrfs_free_reserved_data_space(inode, NULL, cur_offset,
10512 end - cur_offset + 1);
10516 int btrfs_prealloc_file_range(struct inode *inode, int mode,
10517 u64 start, u64 num_bytes, u64 min_size,
10518 loff_t actual_len, u64 *alloc_hint)
10520 return __btrfs_prealloc_file_range(inode, mode, start, num_bytes,
10521 min_size, actual_len, alloc_hint,
10525 int btrfs_prealloc_file_range_trans(struct inode *inode,
10526 struct btrfs_trans_handle *trans, int mode,
10527 u64 start, u64 num_bytes, u64 min_size,
10528 loff_t actual_len, u64 *alloc_hint)
10530 return __btrfs_prealloc_file_range(inode, mode, start, num_bytes,
10531 min_size, actual_len, alloc_hint, trans);
10534 static int btrfs_set_page_dirty(struct page *page)
10536 return __set_page_dirty_nobuffers(page);
10539 static int btrfs_permission(struct inode *inode, int mask)
10541 struct btrfs_root *root = BTRFS_I(inode)->root;
10542 umode_t mode = inode->i_mode;
10544 if (mask & MAY_WRITE &&
10545 (S_ISREG(mode) || S_ISDIR(mode) || S_ISLNK(mode))) {
10546 if (btrfs_root_readonly(root))
10548 if (BTRFS_I(inode)->flags & BTRFS_INODE_READONLY)
10551 return generic_permission(inode, mask);
10554 static int btrfs_tmpfile(struct inode *dir, struct dentry *dentry, umode_t mode)
10556 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
10557 struct btrfs_trans_handle *trans;
10558 struct btrfs_root *root = BTRFS_I(dir)->root;
10559 struct inode *inode = NULL;
10565 * 5 units required for adding orphan entry
10567 trans = btrfs_start_transaction(root, 5);
10569 return PTR_ERR(trans);
10571 ret = btrfs_find_free_ino(root, &objectid);
10575 inode = btrfs_new_inode(trans, root, dir, NULL, 0,
10576 btrfs_ino(BTRFS_I(dir)), objectid, mode, &index);
10577 if (IS_ERR(inode)) {
10578 ret = PTR_ERR(inode);
10583 inode->i_fop = &btrfs_file_operations;
10584 inode->i_op = &btrfs_file_inode_operations;
10586 inode->i_mapping->a_ops = &btrfs_aops;
10587 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
10589 ret = btrfs_init_inode_security(trans, inode, dir, NULL);
10593 ret = btrfs_update_inode(trans, root, inode);
10596 ret = btrfs_orphan_add(trans, BTRFS_I(inode));
10601 * We set number of links to 0 in btrfs_new_inode(), and here we set
10602 * it to 1 because d_tmpfile() will issue a warning if the count is 0,
10605 * d_tmpfile() -> inode_dec_link_count() -> drop_nlink()
10607 set_nlink(inode, 1);
10608 d_tmpfile(dentry, inode);
10609 unlock_new_inode(inode);
10610 mark_inode_dirty(inode);
10612 btrfs_end_transaction(trans);
10614 discard_new_inode(inode);
10615 btrfs_btree_balance_dirty(fs_info);
10619 void btrfs_set_range_writeback(struct extent_io_tree *tree, u64 start, u64 end)
10621 struct inode *inode = tree->private_data;
10622 unsigned long index = start >> PAGE_SHIFT;
10623 unsigned long end_index = end >> PAGE_SHIFT;
10626 while (index <= end_index) {
10627 page = find_get_page(inode->i_mapping, index);
10628 ASSERT(page); /* Pages should be in the extent_io_tree */
10629 set_page_writeback(page);
10637 * Add an entry indicating a block group or device which is pinned by a
10638 * swapfile. Returns 0 on success, 1 if there is already an entry for it, or a
10639 * negative errno on failure.
10641 static int btrfs_add_swapfile_pin(struct inode *inode, void *ptr,
10642 bool is_block_group)
10644 struct btrfs_fs_info *fs_info = BTRFS_I(inode)->root->fs_info;
10645 struct btrfs_swapfile_pin *sp, *entry;
10646 struct rb_node **p;
10647 struct rb_node *parent = NULL;
10649 sp = kmalloc(sizeof(*sp), GFP_NOFS);
10654 sp->is_block_group = is_block_group;
10656 spin_lock(&fs_info->swapfile_pins_lock);
10657 p = &fs_info->swapfile_pins.rb_node;
10660 entry = rb_entry(parent, struct btrfs_swapfile_pin, node);
10661 if (sp->ptr < entry->ptr ||
10662 (sp->ptr == entry->ptr && sp->inode < entry->inode)) {
10663 p = &(*p)->rb_left;
10664 } else if (sp->ptr > entry->ptr ||
10665 (sp->ptr == entry->ptr && sp->inode > entry->inode)) {
10666 p = &(*p)->rb_right;
10668 spin_unlock(&fs_info->swapfile_pins_lock);
10673 rb_link_node(&sp->node, parent, p);
10674 rb_insert_color(&sp->node, &fs_info->swapfile_pins);
10675 spin_unlock(&fs_info->swapfile_pins_lock);
10679 /* Free all of the entries pinned by this swapfile. */
10680 static void btrfs_free_swapfile_pins(struct inode *inode)
10682 struct btrfs_fs_info *fs_info = BTRFS_I(inode)->root->fs_info;
10683 struct btrfs_swapfile_pin *sp;
10684 struct rb_node *node, *next;
10686 spin_lock(&fs_info->swapfile_pins_lock);
10687 node = rb_first(&fs_info->swapfile_pins);
10689 next = rb_next(node);
10690 sp = rb_entry(node, struct btrfs_swapfile_pin, node);
10691 if (sp->inode == inode) {
10692 rb_erase(&sp->node, &fs_info->swapfile_pins);
10693 if (sp->is_block_group)
10694 btrfs_put_block_group(sp->ptr);
10699 spin_unlock(&fs_info->swapfile_pins_lock);
10702 struct btrfs_swap_info {
10708 unsigned long nr_pages;
10712 static int btrfs_add_swap_extent(struct swap_info_struct *sis,
10713 struct btrfs_swap_info *bsi)
10715 unsigned long nr_pages;
10716 u64 first_ppage, first_ppage_reported, next_ppage;
10719 first_ppage = ALIGN(bsi->block_start, PAGE_SIZE) >> PAGE_SHIFT;
10720 next_ppage = ALIGN_DOWN(bsi->block_start + bsi->block_len,
10721 PAGE_SIZE) >> PAGE_SHIFT;
10723 if (first_ppage >= next_ppage)
10725 nr_pages = next_ppage - first_ppage;
10727 first_ppage_reported = first_ppage;
10728 if (bsi->start == 0)
10729 first_ppage_reported++;
10730 if (bsi->lowest_ppage > first_ppage_reported)
10731 bsi->lowest_ppage = first_ppage_reported;
10732 if (bsi->highest_ppage < (next_ppage - 1))
10733 bsi->highest_ppage = next_ppage - 1;
10735 ret = add_swap_extent(sis, bsi->nr_pages, nr_pages, first_ppage);
10738 bsi->nr_extents += ret;
10739 bsi->nr_pages += nr_pages;
10743 static void btrfs_swap_deactivate(struct file *file)
10745 struct inode *inode = file_inode(file);
10747 btrfs_free_swapfile_pins(inode);
10748 atomic_dec(&BTRFS_I(inode)->root->nr_swapfiles);
10751 static int btrfs_swap_activate(struct swap_info_struct *sis, struct file *file,
10754 struct inode *inode = file_inode(file);
10755 struct btrfs_fs_info *fs_info = BTRFS_I(inode)->root->fs_info;
10756 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
10757 struct extent_state *cached_state = NULL;
10758 struct extent_map *em = NULL;
10759 struct btrfs_device *device = NULL;
10760 struct btrfs_swap_info bsi = {
10761 .lowest_ppage = (sector_t)-1ULL,
10768 * If the swap file was just created, make sure delalloc is done. If the
10769 * file changes again after this, the user is doing something stupid and
10770 * we don't really care.
10772 ret = btrfs_wait_ordered_range(inode, 0, (u64)-1);
10777 * The inode is locked, so these flags won't change after we check them.
10779 if (BTRFS_I(inode)->flags & BTRFS_INODE_COMPRESS) {
10780 btrfs_warn(fs_info, "swapfile must not be compressed");
10783 if (!(BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW)) {
10784 btrfs_warn(fs_info, "swapfile must not be copy-on-write");
10787 if (!(BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)) {
10788 btrfs_warn(fs_info, "swapfile must not be checksummed");
10793 * Balance or device remove/replace/resize can move stuff around from
10794 * under us. The EXCL_OP flag makes sure they aren't running/won't run
10795 * concurrently while we are mapping the swap extents, and
10796 * fs_info->swapfile_pins prevents them from running while the swap file
10797 * is active and moving the extents. Note that this also prevents a
10798 * concurrent device add which isn't actually necessary, but it's not
10799 * really worth the trouble to allow it.
10801 if (test_and_set_bit(BTRFS_FS_EXCL_OP, &fs_info->flags)) {
10802 btrfs_warn(fs_info,
10803 "cannot activate swapfile while exclusive operation is running");
10807 * Snapshots can create extents which require COW even if NODATACOW is
10808 * set. We use this counter to prevent snapshots. We must increment it
10809 * before walking the extents because we don't want a concurrent
10810 * snapshot to run after we've already checked the extents.
10812 atomic_inc(&BTRFS_I(inode)->root->nr_swapfiles);
10814 isize = ALIGN_DOWN(inode->i_size, fs_info->sectorsize);
10816 lock_extent_bits(io_tree, 0, isize - 1, &cached_state);
10818 while (start < isize) {
10819 u64 logical_block_start, physical_block_start;
10820 struct btrfs_block_group_cache *bg;
10821 u64 len = isize - start;
10823 em = btrfs_get_extent(BTRFS_I(inode), NULL, 0, start, len, 0);
10829 if (em->block_start == EXTENT_MAP_HOLE) {
10830 btrfs_warn(fs_info, "swapfile must not have holes");
10834 if (em->block_start == EXTENT_MAP_INLINE) {
10836 * It's unlikely we'll ever actually find ourselves
10837 * here, as a file small enough to fit inline won't be
10838 * big enough to store more than the swap header, but in
10839 * case something changes in the future, let's catch it
10840 * here rather than later.
10842 btrfs_warn(fs_info, "swapfile must not be inline");
10846 if (test_bit(EXTENT_FLAG_COMPRESSED, &em->flags)) {
10847 btrfs_warn(fs_info, "swapfile must not be compressed");
10852 logical_block_start = em->block_start + (start - em->start);
10853 len = min(len, em->len - (start - em->start));
10854 free_extent_map(em);
10857 ret = can_nocow_extent(inode, start, &len, NULL, NULL, NULL);
10863 btrfs_warn(fs_info,
10864 "swapfile must not be copy-on-write");
10869 em = btrfs_get_chunk_map(fs_info, logical_block_start, len);
10875 if (em->map_lookup->type & BTRFS_BLOCK_GROUP_PROFILE_MASK) {
10876 btrfs_warn(fs_info,
10877 "swapfile must have single data profile");
10882 if (device == NULL) {
10883 device = em->map_lookup->stripes[0].dev;
10884 ret = btrfs_add_swapfile_pin(inode, device, false);
10889 } else if (device != em->map_lookup->stripes[0].dev) {
10890 btrfs_warn(fs_info, "swapfile must be on one device");
10895 physical_block_start = (em->map_lookup->stripes[0].physical +
10896 (logical_block_start - em->start));
10897 len = min(len, em->len - (logical_block_start - em->start));
10898 free_extent_map(em);
10901 bg = btrfs_lookup_block_group(fs_info, logical_block_start);
10903 btrfs_warn(fs_info,
10904 "could not find block group containing swapfile");
10909 ret = btrfs_add_swapfile_pin(inode, bg, true);
10911 btrfs_put_block_group(bg);
10918 if (bsi.block_len &&
10919 bsi.block_start + bsi.block_len == physical_block_start) {
10920 bsi.block_len += len;
10922 if (bsi.block_len) {
10923 ret = btrfs_add_swap_extent(sis, &bsi);
10928 bsi.block_start = physical_block_start;
10929 bsi.block_len = len;
10936 ret = btrfs_add_swap_extent(sis, &bsi);
10939 if (!IS_ERR_OR_NULL(em))
10940 free_extent_map(em);
10942 unlock_extent_cached(io_tree, 0, isize - 1, &cached_state);
10945 btrfs_swap_deactivate(file);
10947 clear_bit(BTRFS_FS_EXCL_OP, &fs_info->flags);
10953 sis->bdev = device->bdev;
10954 *span = bsi.highest_ppage - bsi.lowest_ppage + 1;
10955 sis->max = bsi.nr_pages;
10956 sis->pages = bsi.nr_pages - 1;
10957 sis->highest_bit = bsi.nr_pages - 1;
10958 return bsi.nr_extents;
10961 static void btrfs_swap_deactivate(struct file *file)
10965 static int btrfs_swap_activate(struct swap_info_struct *sis, struct file *file,
10968 return -EOPNOTSUPP;
10972 static const struct inode_operations btrfs_dir_inode_operations = {
10973 .getattr = btrfs_getattr,
10974 .lookup = btrfs_lookup,
10975 .create = btrfs_create,
10976 .unlink = btrfs_unlink,
10977 .link = btrfs_link,
10978 .mkdir = btrfs_mkdir,
10979 .rmdir = btrfs_rmdir,
10980 .rename = btrfs_rename2,
10981 .symlink = btrfs_symlink,
10982 .setattr = btrfs_setattr,
10983 .mknod = btrfs_mknod,
10984 .listxattr = btrfs_listxattr,
10985 .permission = btrfs_permission,
10986 .get_acl = btrfs_get_acl,
10987 .set_acl = btrfs_set_acl,
10988 .update_time = btrfs_update_time,
10989 .tmpfile = btrfs_tmpfile,
10991 static const struct inode_operations btrfs_dir_ro_inode_operations = {
10992 .lookup = btrfs_lookup,
10993 .permission = btrfs_permission,
10994 .update_time = btrfs_update_time,
10997 static const struct file_operations btrfs_dir_file_operations = {
10998 .llseek = generic_file_llseek,
10999 .read = generic_read_dir,
11000 .iterate_shared = btrfs_real_readdir,
11001 .open = btrfs_opendir,
11002 .unlocked_ioctl = btrfs_ioctl,
11003 #ifdef CONFIG_COMPAT
11004 .compat_ioctl = btrfs_compat_ioctl,
11006 .release = btrfs_release_file,
11007 .fsync = btrfs_sync_file,
11010 static const struct extent_io_ops btrfs_extent_io_ops = {
11011 /* mandatory callbacks */
11012 .submit_bio_hook = btrfs_submit_bio_hook,
11013 .readpage_end_io_hook = btrfs_readpage_end_io_hook,
11017 * btrfs doesn't support the bmap operation because swapfiles
11018 * use bmap to make a mapping of extents in the file. They assume
11019 * these extents won't change over the life of the file and they
11020 * use the bmap result to do IO directly to the drive.
11022 * the btrfs bmap call would return logical addresses that aren't
11023 * suitable for IO and they also will change frequently as COW
11024 * operations happen. So, swapfile + btrfs == corruption.
11026 * For now we're avoiding this by dropping bmap.
11028 static const struct address_space_operations btrfs_aops = {
11029 .readpage = btrfs_readpage,
11030 .writepage = btrfs_writepage,
11031 .writepages = btrfs_writepages,
11032 .readpages = btrfs_readpages,
11033 .direct_IO = btrfs_direct_IO,
11034 .invalidatepage = btrfs_invalidatepage,
11035 .releasepage = btrfs_releasepage,
11036 .set_page_dirty = btrfs_set_page_dirty,
11037 .error_remove_page = generic_error_remove_page,
11038 .swap_activate = btrfs_swap_activate,
11039 .swap_deactivate = btrfs_swap_deactivate,
11042 static const struct inode_operations btrfs_file_inode_operations = {
11043 .getattr = btrfs_getattr,
11044 .setattr = btrfs_setattr,
11045 .listxattr = btrfs_listxattr,
11046 .permission = btrfs_permission,
11047 .fiemap = btrfs_fiemap,
11048 .get_acl = btrfs_get_acl,
11049 .set_acl = btrfs_set_acl,
11050 .update_time = btrfs_update_time,
11052 static const struct inode_operations btrfs_special_inode_operations = {
11053 .getattr = btrfs_getattr,
11054 .setattr = btrfs_setattr,
11055 .permission = btrfs_permission,
11056 .listxattr = btrfs_listxattr,
11057 .get_acl = btrfs_get_acl,
11058 .set_acl = btrfs_set_acl,
11059 .update_time = btrfs_update_time,
11061 static const struct inode_operations btrfs_symlink_inode_operations = {
11062 .get_link = page_get_link,
11063 .getattr = btrfs_getattr,
11064 .setattr = btrfs_setattr,
11065 .permission = btrfs_permission,
11066 .listxattr = btrfs_listxattr,
11067 .update_time = btrfs_update_time,
11070 const struct dentry_operations btrfs_dentry_operations = {
11071 .d_delete = btrfs_dentry_delete,