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>
35 #include "transaction.h"
36 #include "btrfs_inode.h"
37 #include "print-tree.h"
38 #include "ordered-data.h"
42 #include "compression.h"
44 #include "free-space-cache.h"
45 #include "inode-map.h"
50 #include "delalloc-space.h"
52 struct btrfs_iget_args {
53 struct btrfs_key *location;
54 struct btrfs_root *root;
57 struct btrfs_dio_data {
59 u64 unsubmitted_oe_range_start;
60 u64 unsubmitted_oe_range_end;
64 static const struct inode_operations btrfs_dir_inode_operations;
65 static const struct inode_operations btrfs_symlink_inode_operations;
66 static const struct inode_operations btrfs_dir_ro_inode_operations;
67 static const struct inode_operations btrfs_special_inode_operations;
68 static const struct inode_operations btrfs_file_inode_operations;
69 static const struct address_space_operations btrfs_aops;
70 static const struct file_operations btrfs_dir_file_operations;
71 static const struct extent_io_ops btrfs_extent_io_ops;
73 static struct kmem_cache *btrfs_inode_cachep;
74 struct kmem_cache *btrfs_trans_handle_cachep;
75 struct kmem_cache *btrfs_path_cachep;
76 struct kmem_cache *btrfs_free_space_cachep;
78 static int btrfs_setsize(struct inode *inode, struct iattr *attr);
79 static int btrfs_truncate(struct inode *inode, bool skip_writeback);
80 static int btrfs_finish_ordered_io(struct btrfs_ordered_extent *ordered_extent);
81 static noinline int cow_file_range(struct inode *inode,
82 struct page *locked_page,
83 u64 start, u64 end, int *page_started,
84 unsigned long *nr_written, int unlock,
85 struct btrfs_dedupe_hash *hash);
86 static struct extent_map *create_io_em(struct inode *inode, u64 start, u64 len,
87 u64 orig_start, u64 block_start,
88 u64 block_len, u64 orig_block_len,
89 u64 ram_bytes, int compress_type,
92 static void __endio_write_update_ordered(struct inode *inode,
93 const u64 offset, const u64 bytes,
97 * Cleanup all submitted ordered extents in specified range to handle errors
98 * from the btrfs_run_delalloc_range() callback.
100 * NOTE: caller must ensure that when an error happens, it can not call
101 * extent_clear_unlock_delalloc() to clear both the bits EXTENT_DO_ACCOUNTING
102 * and EXTENT_DELALLOC simultaneously, because that causes the reserved metadata
103 * to be released, which we want to happen only when finishing the ordered
104 * extent (btrfs_finish_ordered_io()).
106 static inline void btrfs_cleanup_ordered_extents(struct inode *inode,
107 struct page *locked_page,
108 u64 offset, u64 bytes)
110 unsigned long index = offset >> PAGE_SHIFT;
111 unsigned long end_index = (offset + bytes - 1) >> PAGE_SHIFT;
112 u64 page_start = page_offset(locked_page);
113 u64 page_end = page_start + PAGE_SIZE - 1;
117 while (index <= end_index) {
118 page = find_get_page(inode->i_mapping, index);
122 ClearPagePrivate2(page);
127 * In case this page belongs to the delalloc range being instantiated
128 * then skip it, since the first page of a range is going to be
129 * properly cleaned up by the caller of run_delalloc_range
131 if (page_start >= offset && page_end <= (offset + bytes - 1)) {
136 return __endio_write_update_ordered(inode, offset, bytes, false);
139 static int btrfs_dirty_inode(struct inode *inode);
141 #ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
142 void btrfs_test_inode_set_ops(struct inode *inode)
144 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
148 static int btrfs_init_inode_security(struct btrfs_trans_handle *trans,
149 struct inode *inode, struct inode *dir,
150 const struct qstr *qstr)
154 err = btrfs_init_acl(trans, inode, dir);
156 err = btrfs_xattr_security_init(trans, inode, dir, qstr);
161 * this does all the hard work for inserting an inline extent into
162 * the btree. The caller should have done a btrfs_drop_extents so that
163 * no overlapping inline items exist in the btree
165 static int insert_inline_extent(struct btrfs_trans_handle *trans,
166 struct btrfs_path *path, int extent_inserted,
167 struct btrfs_root *root, struct inode *inode,
168 u64 start, size_t size, size_t compressed_size,
170 struct page **compressed_pages)
172 struct extent_buffer *leaf;
173 struct page *page = NULL;
176 struct btrfs_file_extent_item *ei;
178 size_t cur_size = size;
179 unsigned long offset;
181 if (compressed_size && compressed_pages)
182 cur_size = compressed_size;
184 inode_add_bytes(inode, size);
186 if (!extent_inserted) {
187 struct btrfs_key key;
190 key.objectid = btrfs_ino(BTRFS_I(inode));
192 key.type = BTRFS_EXTENT_DATA_KEY;
194 datasize = btrfs_file_extent_calc_inline_size(cur_size);
195 path->leave_spinning = 1;
196 ret = btrfs_insert_empty_item(trans, root, path, &key,
201 leaf = path->nodes[0];
202 ei = btrfs_item_ptr(leaf, path->slots[0],
203 struct btrfs_file_extent_item);
204 btrfs_set_file_extent_generation(leaf, ei, trans->transid);
205 btrfs_set_file_extent_type(leaf, ei, BTRFS_FILE_EXTENT_INLINE);
206 btrfs_set_file_extent_encryption(leaf, ei, 0);
207 btrfs_set_file_extent_other_encoding(leaf, ei, 0);
208 btrfs_set_file_extent_ram_bytes(leaf, ei, size);
209 ptr = btrfs_file_extent_inline_start(ei);
211 if (compress_type != BTRFS_COMPRESS_NONE) {
214 while (compressed_size > 0) {
215 cpage = compressed_pages[i];
216 cur_size = min_t(unsigned long, compressed_size,
219 kaddr = kmap_atomic(cpage);
220 write_extent_buffer(leaf, kaddr, ptr, cur_size);
221 kunmap_atomic(kaddr);
225 compressed_size -= cur_size;
227 btrfs_set_file_extent_compression(leaf, ei,
230 page = find_get_page(inode->i_mapping,
231 start >> PAGE_SHIFT);
232 btrfs_set_file_extent_compression(leaf, ei, 0);
233 kaddr = kmap_atomic(page);
234 offset = offset_in_page(start);
235 write_extent_buffer(leaf, kaddr + offset, ptr, size);
236 kunmap_atomic(kaddr);
239 btrfs_mark_buffer_dirty(leaf);
240 btrfs_release_path(path);
243 * we're an inline extent, so nobody can
244 * extend the file past i_size without locking
245 * a page we already have locked.
247 * We must do any isize and inode updates
248 * before we unlock the pages. Otherwise we
249 * could end up racing with unlink.
251 BTRFS_I(inode)->disk_i_size = inode->i_size;
252 ret = btrfs_update_inode(trans, root, inode);
260 * conditionally insert an inline extent into the file. This
261 * does the checks required to make sure the data is small enough
262 * to fit as an inline extent.
264 static noinline int cow_file_range_inline(struct inode *inode, u64 start,
265 u64 end, size_t compressed_size,
267 struct page **compressed_pages)
269 struct btrfs_root *root = BTRFS_I(inode)->root;
270 struct btrfs_fs_info *fs_info = root->fs_info;
271 struct btrfs_trans_handle *trans;
272 u64 isize = i_size_read(inode);
273 u64 actual_end = min(end + 1, isize);
274 u64 inline_len = actual_end - start;
275 u64 aligned_end = ALIGN(end, fs_info->sectorsize);
276 u64 data_len = inline_len;
278 struct btrfs_path *path;
279 int extent_inserted = 0;
280 u32 extent_item_size;
283 data_len = compressed_size;
286 actual_end > fs_info->sectorsize ||
287 data_len > BTRFS_MAX_INLINE_DATA_SIZE(fs_info) ||
289 (actual_end & (fs_info->sectorsize - 1)) == 0) ||
291 data_len > fs_info->max_inline) {
295 path = btrfs_alloc_path();
299 trans = btrfs_join_transaction(root);
301 btrfs_free_path(path);
302 return PTR_ERR(trans);
304 trans->block_rsv = &BTRFS_I(inode)->block_rsv;
306 if (compressed_size && compressed_pages)
307 extent_item_size = btrfs_file_extent_calc_inline_size(
310 extent_item_size = btrfs_file_extent_calc_inline_size(
313 ret = __btrfs_drop_extents(trans, root, inode, path,
314 start, aligned_end, NULL,
315 1, 1, extent_item_size, &extent_inserted);
317 btrfs_abort_transaction(trans, ret);
321 if (isize > actual_end)
322 inline_len = min_t(u64, isize, actual_end);
323 ret = insert_inline_extent(trans, path, extent_inserted,
325 inline_len, compressed_size,
326 compress_type, compressed_pages);
327 if (ret && ret != -ENOSPC) {
328 btrfs_abort_transaction(trans, ret);
330 } else if (ret == -ENOSPC) {
335 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &BTRFS_I(inode)->runtime_flags);
336 btrfs_drop_extent_cache(BTRFS_I(inode), start, aligned_end - 1, 0);
339 * Don't forget to free the reserved space, as for inlined extent
340 * it won't count as data extent, free them directly here.
341 * And at reserve time, it's always aligned to page size, so
342 * just free one page here.
344 btrfs_qgroup_free_data(inode, NULL, 0, PAGE_SIZE);
345 btrfs_free_path(path);
346 btrfs_end_transaction(trans);
350 struct async_extent {
355 unsigned long nr_pages;
357 struct list_head list;
362 struct page *locked_page;
365 unsigned int write_flags;
366 struct list_head extents;
367 struct btrfs_work work;
372 /* Number of chunks in flight; must be first in the structure */
374 struct async_chunk chunks[];
377 static noinline int add_async_extent(struct async_chunk *cow,
378 u64 start, u64 ram_size,
381 unsigned long nr_pages,
384 struct async_extent *async_extent;
386 async_extent = kmalloc(sizeof(*async_extent), GFP_NOFS);
387 BUG_ON(!async_extent); /* -ENOMEM */
388 async_extent->start = start;
389 async_extent->ram_size = ram_size;
390 async_extent->compressed_size = compressed_size;
391 async_extent->pages = pages;
392 async_extent->nr_pages = nr_pages;
393 async_extent->compress_type = compress_type;
394 list_add_tail(&async_extent->list, &cow->extents);
399 * Check if the inode has flags compatible with compression
401 static inline bool inode_can_compress(struct inode *inode)
403 if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW ||
404 BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)
410 * Check if the inode needs to be submitted to compression, based on mount
411 * options, defragmentation, properties or heuristics.
413 static inline int inode_need_compress(struct inode *inode, u64 start, u64 end)
415 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
417 if (!inode_can_compress(inode)) {
418 WARN(IS_ENABLED(CONFIG_BTRFS_DEBUG),
419 KERN_ERR "BTRFS: unexpected compression for ino %llu\n",
420 btrfs_ino(BTRFS_I(inode)));
424 if (btrfs_test_opt(fs_info, FORCE_COMPRESS))
427 if (BTRFS_I(inode)->defrag_compress)
429 /* bad compression ratios */
430 if (BTRFS_I(inode)->flags & BTRFS_INODE_NOCOMPRESS)
432 if (btrfs_test_opt(fs_info, COMPRESS) ||
433 BTRFS_I(inode)->flags & BTRFS_INODE_COMPRESS ||
434 BTRFS_I(inode)->prop_compress)
435 return btrfs_compress_heuristic(inode, start, end);
439 static inline void inode_should_defrag(struct btrfs_inode *inode,
440 u64 start, u64 end, u64 num_bytes, u64 small_write)
442 /* If this is a small write inside eof, kick off a defrag */
443 if (num_bytes < small_write &&
444 (start > 0 || end + 1 < inode->disk_i_size))
445 btrfs_add_inode_defrag(NULL, inode);
449 * we create compressed extents in two phases. The first
450 * phase compresses a range of pages that have already been
451 * locked (both pages and state bits are locked).
453 * This is done inside an ordered work queue, and the compression
454 * is spread across many cpus. The actual IO submission is step
455 * two, and the ordered work queue takes care of making sure that
456 * happens in the same order things were put onto the queue by
457 * writepages and friends.
459 * If this code finds it can't get good compression, it puts an
460 * entry onto the work queue to write the uncompressed bytes. This
461 * makes sure that both compressed inodes and uncompressed inodes
462 * are written in the same order that the flusher thread sent them
465 static noinline int compress_file_range(struct async_chunk *async_chunk)
467 struct inode *inode = async_chunk->inode;
468 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
469 u64 blocksize = fs_info->sectorsize;
470 u64 start = async_chunk->start;
471 u64 end = async_chunk->end;
474 struct page **pages = NULL;
475 unsigned long nr_pages;
476 unsigned long total_compressed = 0;
477 unsigned long total_in = 0;
480 int compress_type = fs_info->compress_type;
481 int compressed_extents = 0;
484 inode_should_defrag(BTRFS_I(inode), start, end, end - start + 1,
487 actual_end = min_t(u64, i_size_read(inode), end + 1);
490 nr_pages = (end >> PAGE_SHIFT) - (start >> PAGE_SHIFT) + 1;
491 BUILD_BUG_ON((BTRFS_MAX_COMPRESSED % PAGE_SIZE) != 0);
492 nr_pages = min_t(unsigned long, nr_pages,
493 BTRFS_MAX_COMPRESSED / PAGE_SIZE);
496 * we don't want to send crud past the end of i_size through
497 * compression, that's just a waste of CPU time. So, if the
498 * end of the file is before the start of our current
499 * requested range of bytes, we bail out to the uncompressed
500 * cleanup code that can deal with all of this.
502 * It isn't really the fastest way to fix things, but this is a
503 * very uncommon corner.
505 if (actual_end <= start)
506 goto cleanup_and_bail_uncompressed;
508 total_compressed = actual_end - start;
511 * skip compression for a small file range(<=blocksize) that
512 * isn't an inline extent, since it doesn't save disk space at all.
514 if (total_compressed <= blocksize &&
515 (start > 0 || end + 1 < BTRFS_I(inode)->disk_i_size))
516 goto cleanup_and_bail_uncompressed;
518 total_compressed = min_t(unsigned long, total_compressed,
519 BTRFS_MAX_UNCOMPRESSED);
524 * we do compression for mount -o compress and when the
525 * inode has not been flagged as nocompress. This flag can
526 * change at any time if we discover bad compression ratios.
528 if (inode_need_compress(inode, start, end)) {
530 pages = kcalloc(nr_pages, sizeof(struct page *), GFP_NOFS);
532 /* just bail out to the uncompressed code */
537 if (BTRFS_I(inode)->defrag_compress)
538 compress_type = BTRFS_I(inode)->defrag_compress;
539 else if (BTRFS_I(inode)->prop_compress)
540 compress_type = BTRFS_I(inode)->prop_compress;
543 * we need to call clear_page_dirty_for_io on each
544 * page in the range. Otherwise applications with the file
545 * mmap'd can wander in and change the page contents while
546 * we are compressing them.
548 * If the compression fails for any reason, we set the pages
549 * dirty again later on.
551 * Note that the remaining part is redirtied, the start pointer
552 * has moved, the end is the original one.
555 extent_range_clear_dirty_for_io(inode, start, end);
559 /* Compression level is applied here and only here */
560 ret = btrfs_compress_pages(
561 compress_type | (fs_info->compress_level << 4),
562 inode->i_mapping, start,
569 unsigned long offset = offset_in_page(total_compressed);
570 struct page *page = pages[nr_pages - 1];
573 /* zero the tail end of the last page, we might be
574 * sending it down to disk
577 kaddr = kmap_atomic(page);
578 memset(kaddr + offset, 0,
580 kunmap_atomic(kaddr);
587 /* lets try to make an inline extent */
588 if (ret || total_in < actual_end) {
589 /* we didn't compress the entire range, try
590 * to make an uncompressed inline extent.
592 ret = cow_file_range_inline(inode, start, end, 0,
593 BTRFS_COMPRESS_NONE, NULL);
595 /* try making a compressed inline extent */
596 ret = cow_file_range_inline(inode, start, end,
598 compress_type, pages);
601 unsigned long clear_flags = EXTENT_DELALLOC |
602 EXTENT_DELALLOC_NEW | EXTENT_DEFRAG |
603 EXTENT_DO_ACCOUNTING;
604 unsigned long page_error_op;
606 page_error_op = ret < 0 ? PAGE_SET_ERROR : 0;
609 * inline extent creation worked or returned error,
610 * we don't need to create any more async work items.
611 * Unlock and free up our temp pages.
613 * We use DO_ACCOUNTING here because we need the
614 * delalloc_release_metadata to be done _after_ we drop
615 * our outstanding extent for clearing delalloc for this
618 extent_clear_unlock_delalloc(inode, start, end, NULL,
626 for (i = 0; i < nr_pages; i++) {
627 WARN_ON(pages[i]->mapping);
638 * we aren't doing an inline extent round the compressed size
639 * up to a block size boundary so the allocator does sane
642 total_compressed = ALIGN(total_compressed, blocksize);
645 * one last check to make sure the compression is really a
646 * win, compare the page count read with the blocks on disk,
647 * compression must free at least one sector size
649 total_in = ALIGN(total_in, PAGE_SIZE);
650 if (total_compressed + blocksize <= total_in) {
651 compressed_extents++;
654 * The async work queues will take care of doing actual
655 * allocation on disk for these compressed pages, and
656 * will submit them to the elevator.
658 add_async_extent(async_chunk, start, total_in,
659 total_compressed, pages, nr_pages,
662 if (start + total_in < end) {
668 return compressed_extents;
673 * the compression code ran but failed to make things smaller,
674 * free any pages it allocated and our page pointer array
676 for (i = 0; i < nr_pages; i++) {
677 WARN_ON(pages[i]->mapping);
682 total_compressed = 0;
685 /* flag the file so we don't compress in the future */
686 if (!btrfs_test_opt(fs_info, FORCE_COMPRESS) &&
687 !(BTRFS_I(inode)->prop_compress)) {
688 BTRFS_I(inode)->flags |= BTRFS_INODE_NOCOMPRESS;
691 cleanup_and_bail_uncompressed:
693 * No compression, but we still need to write the pages in the file
694 * we've been given so far. redirty the locked page if it corresponds
695 * to our extent and set things up for the async work queue to run
696 * cow_file_range to do the normal delalloc dance.
698 if (page_offset(async_chunk->locked_page) >= start &&
699 page_offset(async_chunk->locked_page) <= end)
700 __set_page_dirty_nobuffers(async_chunk->locked_page);
701 /* unlocked later on in the async handlers */
704 extent_range_redirty_for_io(inode, start, end);
705 add_async_extent(async_chunk, start, end - start + 1, 0, NULL, 0,
706 BTRFS_COMPRESS_NONE);
707 compressed_extents++;
709 return compressed_extents;
712 static void free_async_extent_pages(struct async_extent *async_extent)
716 if (!async_extent->pages)
719 for (i = 0; i < async_extent->nr_pages; i++) {
720 WARN_ON(async_extent->pages[i]->mapping);
721 put_page(async_extent->pages[i]);
723 kfree(async_extent->pages);
724 async_extent->nr_pages = 0;
725 async_extent->pages = NULL;
729 * phase two of compressed writeback. This is the ordered portion
730 * of the code, which only gets called in the order the work was
731 * queued. We walk all the async extents created by compress_file_range
732 * and send them down to the disk.
734 static noinline void submit_compressed_extents(struct async_chunk *async_chunk)
736 struct inode *inode = async_chunk->inode;
737 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
738 struct async_extent *async_extent;
740 struct btrfs_key ins;
741 struct extent_map *em;
742 struct btrfs_root *root = BTRFS_I(inode)->root;
743 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
747 while (!list_empty(&async_chunk->extents)) {
748 async_extent = list_entry(async_chunk->extents.next,
749 struct async_extent, list);
750 list_del(&async_extent->list);
753 lock_extent(io_tree, async_extent->start,
754 async_extent->start + async_extent->ram_size - 1);
755 /* did the compression code fall back to uncompressed IO? */
756 if (!async_extent->pages) {
757 int page_started = 0;
758 unsigned long nr_written = 0;
760 /* allocate blocks */
761 ret = cow_file_range(inode, async_chunk->locked_page,
763 async_extent->start +
764 async_extent->ram_size - 1,
765 &page_started, &nr_written, 0,
771 * if page_started, cow_file_range inserted an
772 * inline extent and took care of all the unlocking
773 * and IO for us. Otherwise, we need to submit
774 * all those pages down to the drive.
776 if (!page_started && !ret)
777 extent_write_locked_range(inode,
779 async_extent->start +
780 async_extent->ram_size - 1,
783 unlock_page(async_chunk->locked_page);
789 ret = btrfs_reserve_extent(root, async_extent->ram_size,
790 async_extent->compressed_size,
791 async_extent->compressed_size,
792 0, alloc_hint, &ins, 1, 1);
794 free_async_extent_pages(async_extent);
796 if (ret == -ENOSPC) {
797 unlock_extent(io_tree, async_extent->start,
798 async_extent->start +
799 async_extent->ram_size - 1);
802 * we need to redirty the pages if we decide to
803 * fallback to uncompressed IO, otherwise we
804 * will not submit these pages down to lower
807 extent_range_redirty_for_io(inode,
809 async_extent->start +
810 async_extent->ram_size - 1);
817 * here we're doing allocation and writeback of the
820 em = create_io_em(inode, async_extent->start,
821 async_extent->ram_size, /* len */
822 async_extent->start, /* orig_start */
823 ins.objectid, /* block_start */
824 ins.offset, /* block_len */
825 ins.offset, /* orig_block_len */
826 async_extent->ram_size, /* ram_bytes */
827 async_extent->compress_type,
828 BTRFS_ORDERED_COMPRESSED);
830 /* ret value is not necessary due to void function */
831 goto out_free_reserve;
834 ret = btrfs_add_ordered_extent_compress(inode,
837 async_extent->ram_size,
839 BTRFS_ORDERED_COMPRESSED,
840 async_extent->compress_type);
842 btrfs_drop_extent_cache(BTRFS_I(inode),
844 async_extent->start +
845 async_extent->ram_size - 1, 0);
846 goto out_free_reserve;
848 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
851 * clear dirty, set writeback and unlock the pages.
853 extent_clear_unlock_delalloc(inode, async_extent->start,
854 async_extent->start +
855 async_extent->ram_size - 1,
856 NULL, EXTENT_LOCKED | EXTENT_DELALLOC,
857 PAGE_UNLOCK | PAGE_CLEAR_DIRTY |
859 if (btrfs_submit_compressed_write(inode,
861 async_extent->ram_size,
863 ins.offset, async_extent->pages,
864 async_extent->nr_pages,
865 async_chunk->write_flags)) {
866 struct page *p = async_extent->pages[0];
867 const u64 start = async_extent->start;
868 const u64 end = start + async_extent->ram_size - 1;
870 p->mapping = inode->i_mapping;
871 btrfs_writepage_endio_finish_ordered(p, start, end, 0);
874 extent_clear_unlock_delalloc(inode, start, end,
878 free_async_extent_pages(async_extent);
880 alloc_hint = ins.objectid + ins.offset;
886 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
887 btrfs_free_reserved_extent(fs_info, ins.objectid, ins.offset, 1);
889 extent_clear_unlock_delalloc(inode, async_extent->start,
890 async_extent->start +
891 async_extent->ram_size - 1,
892 NULL, EXTENT_LOCKED | EXTENT_DELALLOC |
893 EXTENT_DELALLOC_NEW |
894 EXTENT_DEFRAG | EXTENT_DO_ACCOUNTING,
895 PAGE_UNLOCK | PAGE_CLEAR_DIRTY |
896 PAGE_SET_WRITEBACK | PAGE_END_WRITEBACK |
898 free_async_extent_pages(async_extent);
903 static u64 get_extent_allocation_hint(struct inode *inode, u64 start,
906 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
907 struct extent_map *em;
910 read_lock(&em_tree->lock);
911 em = search_extent_mapping(em_tree, start, num_bytes);
914 * if block start isn't an actual block number then find the
915 * first block in this inode and use that as a hint. If that
916 * block is also bogus then just don't worry about it.
918 if (em->block_start >= EXTENT_MAP_LAST_BYTE) {
920 em = search_extent_mapping(em_tree, 0, 0);
921 if (em && em->block_start < EXTENT_MAP_LAST_BYTE)
922 alloc_hint = em->block_start;
926 alloc_hint = em->block_start;
930 read_unlock(&em_tree->lock);
936 * when extent_io.c finds a delayed allocation range in the file,
937 * the call backs end up in this code. The basic idea is to
938 * allocate extents on disk for the range, and create ordered data structs
939 * in ram to track those extents.
941 * locked_page is the page that writepage had locked already. We use
942 * it to make sure we don't do extra locks or unlocks.
944 * *page_started is set to one if we unlock locked_page and do everything
945 * required to start IO on it. It may be clean and already done with
948 static noinline int cow_file_range(struct inode *inode,
949 struct page *locked_page,
950 u64 start, u64 end, int *page_started,
951 unsigned long *nr_written, int unlock,
952 struct btrfs_dedupe_hash *hash)
954 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
955 struct btrfs_root *root = BTRFS_I(inode)->root;
958 unsigned long ram_size;
959 u64 cur_alloc_size = 0;
960 u64 blocksize = fs_info->sectorsize;
961 struct btrfs_key ins;
962 struct extent_map *em;
964 unsigned long page_ops;
965 bool extent_reserved = false;
968 if (btrfs_is_free_space_inode(BTRFS_I(inode))) {
974 num_bytes = ALIGN(end - start + 1, blocksize);
975 num_bytes = max(blocksize, num_bytes);
976 ASSERT(num_bytes <= btrfs_super_total_bytes(fs_info->super_copy));
978 inode_should_defrag(BTRFS_I(inode), start, end, num_bytes, SZ_64K);
981 /* lets try to make an inline extent */
982 ret = cow_file_range_inline(inode, start, end, 0,
983 BTRFS_COMPRESS_NONE, NULL);
986 * We use DO_ACCOUNTING here because we need the
987 * delalloc_release_metadata to be run _after_ we drop
988 * our outstanding extent for clearing delalloc for this
991 extent_clear_unlock_delalloc(inode, start, end, NULL,
992 EXTENT_LOCKED | EXTENT_DELALLOC |
993 EXTENT_DELALLOC_NEW | EXTENT_DEFRAG |
994 EXTENT_DO_ACCOUNTING, PAGE_UNLOCK |
995 PAGE_CLEAR_DIRTY | PAGE_SET_WRITEBACK |
997 *nr_written = *nr_written +
998 (end - start + PAGE_SIZE) / PAGE_SIZE;
1001 } else if (ret < 0) {
1006 alloc_hint = get_extent_allocation_hint(inode, start, num_bytes);
1007 btrfs_drop_extent_cache(BTRFS_I(inode), start,
1008 start + num_bytes - 1, 0);
1010 while (num_bytes > 0) {
1011 cur_alloc_size = num_bytes;
1012 ret = btrfs_reserve_extent(root, cur_alloc_size, cur_alloc_size,
1013 fs_info->sectorsize, 0, alloc_hint,
1017 cur_alloc_size = ins.offset;
1018 extent_reserved = true;
1020 ram_size = ins.offset;
1021 em = create_io_em(inode, start, ins.offset, /* len */
1022 start, /* orig_start */
1023 ins.objectid, /* block_start */
1024 ins.offset, /* block_len */
1025 ins.offset, /* orig_block_len */
1026 ram_size, /* ram_bytes */
1027 BTRFS_COMPRESS_NONE, /* compress_type */
1028 BTRFS_ORDERED_REGULAR /* type */);
1033 free_extent_map(em);
1035 ret = btrfs_add_ordered_extent(inode, start, ins.objectid,
1036 ram_size, cur_alloc_size, 0);
1038 goto out_drop_extent_cache;
1040 if (root->root_key.objectid ==
1041 BTRFS_DATA_RELOC_TREE_OBJECTID) {
1042 ret = btrfs_reloc_clone_csums(inode, start,
1045 * Only drop cache here, and process as normal.
1047 * We must not allow extent_clear_unlock_delalloc()
1048 * at out_unlock label to free meta of this ordered
1049 * extent, as its meta should be freed by
1050 * btrfs_finish_ordered_io().
1052 * So we must continue until @start is increased to
1053 * skip current ordered extent.
1056 btrfs_drop_extent_cache(BTRFS_I(inode), start,
1057 start + ram_size - 1, 0);
1060 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
1062 /* we're not doing compressed IO, don't unlock the first
1063 * page (which the caller expects to stay locked), don't
1064 * clear any dirty bits and don't set any writeback bits
1066 * Do set the Private2 bit so we know this page was properly
1067 * setup for writepage
1069 page_ops = unlock ? PAGE_UNLOCK : 0;
1070 page_ops |= PAGE_SET_PRIVATE2;
1072 extent_clear_unlock_delalloc(inode, start,
1073 start + ram_size - 1,
1075 EXTENT_LOCKED | EXTENT_DELALLOC,
1077 if (num_bytes < cur_alloc_size)
1080 num_bytes -= cur_alloc_size;
1081 alloc_hint = ins.objectid + ins.offset;
1082 start += cur_alloc_size;
1083 extent_reserved = false;
1086 * btrfs_reloc_clone_csums() error, since start is increased
1087 * extent_clear_unlock_delalloc() at out_unlock label won't
1088 * free metadata of current ordered extent, we're OK to exit.
1096 out_drop_extent_cache:
1097 btrfs_drop_extent_cache(BTRFS_I(inode), start, start + ram_size - 1, 0);
1099 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
1100 btrfs_free_reserved_extent(fs_info, ins.objectid, ins.offset, 1);
1102 clear_bits = EXTENT_LOCKED | EXTENT_DELALLOC | EXTENT_DELALLOC_NEW |
1103 EXTENT_DEFRAG | EXTENT_CLEAR_META_RESV;
1104 page_ops = PAGE_UNLOCK | PAGE_CLEAR_DIRTY | PAGE_SET_WRITEBACK |
1107 * If we reserved an extent for our delalloc range (or a subrange) and
1108 * failed to create the respective ordered extent, then it means that
1109 * when we reserved the extent we decremented the extent's size from
1110 * the data space_info's bytes_may_use counter and incremented the
1111 * space_info's bytes_reserved counter by the same amount. We must make
1112 * sure extent_clear_unlock_delalloc() does not try to decrement again
1113 * the data space_info's bytes_may_use counter, therefore we do not pass
1114 * it the flag EXTENT_CLEAR_DATA_RESV.
1116 if (extent_reserved) {
1117 extent_clear_unlock_delalloc(inode, start,
1118 start + cur_alloc_size,
1122 start += cur_alloc_size;
1126 extent_clear_unlock_delalloc(inode, start, end, locked_page,
1127 clear_bits | EXTENT_CLEAR_DATA_RESV,
1133 * work queue call back to started compression on a file and pages
1135 static noinline void async_cow_start(struct btrfs_work *work)
1137 struct async_chunk *async_chunk;
1138 int compressed_extents;
1140 async_chunk = container_of(work, struct async_chunk, work);
1142 compressed_extents = compress_file_range(async_chunk);
1143 if (compressed_extents == 0) {
1144 btrfs_add_delayed_iput(async_chunk->inode);
1145 async_chunk->inode = NULL;
1150 * work queue call back to submit previously compressed pages
1152 static noinline void async_cow_submit(struct btrfs_work *work)
1154 struct async_chunk *async_chunk = container_of(work, struct async_chunk,
1156 struct btrfs_fs_info *fs_info = btrfs_work_owner(work);
1157 unsigned long nr_pages;
1159 nr_pages = (async_chunk->end - async_chunk->start + PAGE_SIZE) >>
1162 /* atomic_sub_return implies a barrier */
1163 if (atomic_sub_return(nr_pages, &fs_info->async_delalloc_pages) <
1165 cond_wake_up_nomb(&fs_info->async_submit_wait);
1168 * ->inode could be NULL if async_chunk_start has failed to compress,
1169 * in which case we don't have anything to submit, yet we need to
1170 * always adjust ->async_delalloc_pages as its paired with the init
1171 * happening in cow_file_range_async
1173 if (async_chunk->inode)
1174 submit_compressed_extents(async_chunk);
1177 static noinline void async_cow_free(struct btrfs_work *work)
1179 struct async_chunk *async_chunk;
1181 async_chunk = container_of(work, struct async_chunk, work);
1182 if (async_chunk->inode)
1183 btrfs_add_delayed_iput(async_chunk->inode);
1185 * Since the pointer to 'pending' is at the beginning of the array of
1186 * async_chunk's, freeing it ensures the whole array has been freed.
1188 if (atomic_dec_and_test(async_chunk->pending))
1189 kvfree(async_chunk->pending);
1192 static int cow_file_range_async(struct inode *inode, struct page *locked_page,
1193 u64 start, u64 end, int *page_started,
1194 unsigned long *nr_written,
1195 unsigned int write_flags)
1197 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1198 struct async_cow *ctx;
1199 struct async_chunk *async_chunk;
1200 unsigned long nr_pages;
1202 u64 num_chunks = DIV_ROUND_UP(end - start, SZ_512K);
1204 bool should_compress;
1207 unlock_extent(&BTRFS_I(inode)->io_tree, start, end);
1209 if (BTRFS_I(inode)->flags & BTRFS_INODE_NOCOMPRESS &&
1210 !btrfs_test_opt(fs_info, FORCE_COMPRESS)) {
1212 should_compress = false;
1214 should_compress = true;
1217 nofs_flag = memalloc_nofs_save();
1218 ctx = kvmalloc(struct_size(ctx, chunks, num_chunks), GFP_KERNEL);
1219 memalloc_nofs_restore(nofs_flag);
1222 unsigned clear_bits = EXTENT_LOCKED | EXTENT_DELALLOC |
1223 EXTENT_DELALLOC_NEW | EXTENT_DEFRAG |
1224 EXTENT_DO_ACCOUNTING;
1225 unsigned long page_ops = PAGE_UNLOCK | PAGE_CLEAR_DIRTY |
1226 PAGE_SET_WRITEBACK | PAGE_END_WRITEBACK |
1229 extent_clear_unlock_delalloc(inode, start, end, locked_page,
1230 clear_bits, page_ops);
1234 async_chunk = ctx->chunks;
1235 atomic_set(&ctx->num_chunks, num_chunks);
1237 for (i = 0; i < num_chunks; i++) {
1238 if (should_compress)
1239 cur_end = min(end, start + SZ_512K - 1);
1244 * igrab is called higher up in the call chain, take only the
1245 * lightweight reference for the callback lifetime
1248 async_chunk[i].pending = &ctx->num_chunks;
1249 async_chunk[i].inode = inode;
1250 async_chunk[i].start = start;
1251 async_chunk[i].end = cur_end;
1252 async_chunk[i].locked_page = locked_page;
1253 async_chunk[i].write_flags = write_flags;
1254 INIT_LIST_HEAD(&async_chunk[i].extents);
1256 btrfs_init_work(&async_chunk[i].work,
1257 btrfs_delalloc_helper,
1258 async_cow_start, async_cow_submit,
1261 nr_pages = DIV_ROUND_UP(cur_end - start, PAGE_SIZE);
1262 atomic_add(nr_pages, &fs_info->async_delalloc_pages);
1264 btrfs_queue_work(fs_info->delalloc_workers, &async_chunk[i].work);
1266 *nr_written += nr_pages;
1267 start = cur_end + 1;
1273 static noinline int csum_exist_in_range(struct btrfs_fs_info *fs_info,
1274 u64 bytenr, u64 num_bytes)
1277 struct btrfs_ordered_sum *sums;
1280 ret = btrfs_lookup_csums_range(fs_info->csum_root, bytenr,
1281 bytenr + num_bytes - 1, &list, 0);
1282 if (ret == 0 && list_empty(&list))
1285 while (!list_empty(&list)) {
1286 sums = list_entry(list.next, struct btrfs_ordered_sum, list);
1287 list_del(&sums->list);
1296 * when nowcow writeback call back. This checks for snapshots or COW copies
1297 * of the extents that exist in the file, and COWs the file as required.
1299 * If no cow copies or snapshots exist, we write directly to the existing
1302 static noinline int run_delalloc_nocow(struct inode *inode,
1303 struct page *locked_page,
1304 u64 start, u64 end, int *page_started, int force,
1305 unsigned long *nr_written)
1307 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1308 struct btrfs_root *root = BTRFS_I(inode)->root;
1309 struct extent_buffer *leaf;
1310 struct btrfs_path *path;
1311 struct btrfs_file_extent_item *fi;
1312 struct btrfs_key found_key;
1313 struct extent_map *em;
1328 u64 ino = btrfs_ino(BTRFS_I(inode));
1330 path = btrfs_alloc_path();
1332 extent_clear_unlock_delalloc(inode, start, end, locked_page,
1333 EXTENT_LOCKED | EXTENT_DELALLOC |
1334 EXTENT_DO_ACCOUNTING |
1335 EXTENT_DEFRAG, PAGE_UNLOCK |
1337 PAGE_SET_WRITEBACK |
1338 PAGE_END_WRITEBACK);
1342 nolock = btrfs_is_free_space_inode(BTRFS_I(inode));
1344 cow_start = (u64)-1;
1347 ret = btrfs_lookup_file_extent(NULL, root, path, ino,
1351 if (ret > 0 && path->slots[0] > 0 && check_prev) {
1352 leaf = path->nodes[0];
1353 btrfs_item_key_to_cpu(leaf, &found_key,
1354 path->slots[0] - 1);
1355 if (found_key.objectid == ino &&
1356 found_key.type == BTRFS_EXTENT_DATA_KEY)
1361 leaf = path->nodes[0];
1362 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
1363 ret = btrfs_next_leaf(root, path);
1365 if (cow_start != (u64)-1)
1366 cur_offset = cow_start;
1371 leaf = path->nodes[0];
1377 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
1379 if (found_key.objectid > ino)
1381 if (WARN_ON_ONCE(found_key.objectid < ino) ||
1382 found_key.type < BTRFS_EXTENT_DATA_KEY) {
1386 if (found_key.type > BTRFS_EXTENT_DATA_KEY ||
1387 found_key.offset > end)
1390 if (found_key.offset > cur_offset) {
1391 extent_end = found_key.offset;
1396 fi = btrfs_item_ptr(leaf, path->slots[0],
1397 struct btrfs_file_extent_item);
1398 extent_type = btrfs_file_extent_type(leaf, fi);
1400 ram_bytes = btrfs_file_extent_ram_bytes(leaf, fi);
1401 if (extent_type == BTRFS_FILE_EXTENT_REG ||
1402 extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
1403 disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
1404 extent_offset = btrfs_file_extent_offset(leaf, fi);
1405 extent_end = found_key.offset +
1406 btrfs_file_extent_num_bytes(leaf, fi);
1408 btrfs_file_extent_disk_num_bytes(leaf, fi);
1409 if (extent_end <= start) {
1413 if (disk_bytenr == 0)
1415 if (btrfs_file_extent_compression(leaf, fi) ||
1416 btrfs_file_extent_encryption(leaf, fi) ||
1417 btrfs_file_extent_other_encoding(leaf, fi))
1420 * Do the same check as in btrfs_cross_ref_exist but
1421 * without the unnecessary search.
1424 btrfs_file_extent_generation(leaf, fi) <=
1425 btrfs_root_last_snapshot(&root->root_item))
1427 if (extent_type == BTRFS_FILE_EXTENT_REG && !force)
1429 if (btrfs_extent_readonly(fs_info, disk_bytenr))
1431 ret = btrfs_cross_ref_exist(root, ino,
1433 extent_offset, disk_bytenr);
1436 * ret could be -EIO if the above fails to read
1440 if (cow_start != (u64)-1)
1441 cur_offset = cow_start;
1445 WARN_ON_ONCE(nolock);
1448 disk_bytenr += extent_offset;
1449 disk_bytenr += cur_offset - found_key.offset;
1450 num_bytes = min(end + 1, extent_end) - cur_offset;
1452 * if there are pending snapshots for this root,
1453 * we fall into common COW way.
1455 if (!nolock && atomic_read(&root->snapshot_force_cow))
1458 * force cow if csum exists in the range.
1459 * this ensure that csum for a given extent are
1460 * either valid or do not exist.
1462 ret = csum_exist_in_range(fs_info, disk_bytenr,
1466 * ret could be -EIO if the above fails to read
1470 if (cow_start != (u64)-1)
1471 cur_offset = cow_start;
1474 WARN_ON_ONCE(nolock);
1477 if (!btrfs_inc_nocow_writers(fs_info, disk_bytenr))
1480 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
1481 extent_end = found_key.offset +
1482 btrfs_file_extent_ram_bytes(leaf, fi);
1483 extent_end = ALIGN(extent_end,
1484 fs_info->sectorsize);
1489 if (extent_end <= start) {
1492 btrfs_dec_nocow_writers(fs_info, disk_bytenr);
1496 if (cow_start == (u64)-1)
1497 cow_start = cur_offset;
1498 cur_offset = extent_end;
1499 if (cur_offset > end)
1505 btrfs_release_path(path);
1506 if (cow_start != (u64)-1) {
1507 ret = cow_file_range(inode, locked_page,
1508 cow_start, found_key.offset - 1,
1509 page_started, nr_written, 1,
1513 btrfs_dec_nocow_writers(fs_info,
1517 cow_start = (u64)-1;
1520 if (extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
1521 u64 orig_start = found_key.offset - extent_offset;
1523 em = create_io_em(inode, cur_offset, num_bytes,
1525 disk_bytenr, /* block_start */
1526 num_bytes, /* block_len */
1527 disk_num_bytes, /* orig_block_len */
1528 ram_bytes, BTRFS_COMPRESS_NONE,
1529 BTRFS_ORDERED_PREALLOC);
1532 btrfs_dec_nocow_writers(fs_info,
1537 free_extent_map(em);
1540 if (extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
1541 type = BTRFS_ORDERED_PREALLOC;
1543 type = BTRFS_ORDERED_NOCOW;
1546 ret = btrfs_add_ordered_extent(inode, cur_offset, disk_bytenr,
1547 num_bytes, num_bytes, type);
1549 btrfs_dec_nocow_writers(fs_info, disk_bytenr);
1550 BUG_ON(ret); /* -ENOMEM */
1552 if (root->root_key.objectid ==
1553 BTRFS_DATA_RELOC_TREE_OBJECTID)
1555 * Error handled later, as we must prevent
1556 * extent_clear_unlock_delalloc() in error handler
1557 * from freeing metadata of created ordered extent.
1559 ret = btrfs_reloc_clone_csums(inode, cur_offset,
1562 extent_clear_unlock_delalloc(inode, cur_offset,
1563 cur_offset + num_bytes - 1,
1564 locked_page, EXTENT_LOCKED |
1566 EXTENT_CLEAR_DATA_RESV,
1567 PAGE_UNLOCK | PAGE_SET_PRIVATE2);
1569 cur_offset = extent_end;
1572 * btrfs_reloc_clone_csums() error, now we're OK to call error
1573 * handler, as metadata for created ordered extent will only
1574 * be freed by btrfs_finish_ordered_io().
1578 if (cur_offset > end)
1581 btrfs_release_path(path);
1583 if (cur_offset <= end && cow_start == (u64)-1)
1584 cow_start = cur_offset;
1586 if (cow_start != (u64)-1) {
1588 ret = cow_file_range(inode, locked_page, cow_start, end,
1589 page_started, nr_written, 1, NULL);
1595 if (ret && cur_offset < end)
1596 extent_clear_unlock_delalloc(inode, cur_offset, end,
1597 locked_page, EXTENT_LOCKED |
1598 EXTENT_DELALLOC | EXTENT_DEFRAG |
1599 EXTENT_DO_ACCOUNTING, PAGE_UNLOCK |
1601 PAGE_SET_WRITEBACK |
1602 PAGE_END_WRITEBACK);
1603 btrfs_free_path(path);
1607 static inline int need_force_cow(struct inode *inode, u64 start, u64 end)
1610 if (!(BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW) &&
1611 !(BTRFS_I(inode)->flags & BTRFS_INODE_PREALLOC))
1615 * @defrag_bytes is a hint value, no spinlock held here,
1616 * if is not zero, it means the file is defragging.
1617 * Force cow if given extent needs to be defragged.
1619 if (BTRFS_I(inode)->defrag_bytes &&
1620 test_range_bit(&BTRFS_I(inode)->io_tree, start, end,
1621 EXTENT_DEFRAG, 0, NULL))
1628 * Function to process delayed allocation (create CoW) for ranges which are
1629 * being touched for the first time.
1631 int btrfs_run_delalloc_range(struct inode *inode, struct page *locked_page,
1632 u64 start, u64 end, int *page_started, unsigned long *nr_written,
1633 struct writeback_control *wbc)
1636 int force_cow = need_force_cow(inode, start, end);
1637 unsigned int write_flags = wbc_to_write_flags(wbc);
1639 if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW && !force_cow) {
1640 ret = run_delalloc_nocow(inode, locked_page, start, end,
1641 page_started, 1, nr_written);
1642 } else if (BTRFS_I(inode)->flags & BTRFS_INODE_PREALLOC && !force_cow) {
1643 ret = run_delalloc_nocow(inode, locked_page, start, end,
1644 page_started, 0, nr_written);
1645 } else if (!inode_can_compress(inode) ||
1646 !inode_need_compress(inode, start, end)) {
1647 ret = cow_file_range(inode, locked_page, start, end,
1648 page_started, nr_written, 1, NULL);
1650 set_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
1651 &BTRFS_I(inode)->runtime_flags);
1652 ret = cow_file_range_async(inode, locked_page, start, end,
1653 page_started, nr_written,
1657 btrfs_cleanup_ordered_extents(inode, locked_page, start,
1662 void btrfs_split_delalloc_extent(struct inode *inode,
1663 struct extent_state *orig, u64 split)
1667 /* not delalloc, ignore it */
1668 if (!(orig->state & EXTENT_DELALLOC))
1671 size = orig->end - orig->start + 1;
1672 if (size > BTRFS_MAX_EXTENT_SIZE) {
1677 * See the explanation in btrfs_merge_delalloc_extent, the same
1678 * applies here, just in reverse.
1680 new_size = orig->end - split + 1;
1681 num_extents = count_max_extents(new_size);
1682 new_size = split - orig->start;
1683 num_extents += count_max_extents(new_size);
1684 if (count_max_extents(size) >= num_extents)
1688 spin_lock(&BTRFS_I(inode)->lock);
1689 btrfs_mod_outstanding_extents(BTRFS_I(inode), 1);
1690 spin_unlock(&BTRFS_I(inode)->lock);
1694 * Handle merged delayed allocation extents so we can keep track of new extents
1695 * that are just merged onto old extents, such as when we are doing sequential
1696 * writes, so we can properly account for the metadata space we'll need.
1698 void btrfs_merge_delalloc_extent(struct inode *inode, struct extent_state *new,
1699 struct extent_state *other)
1701 u64 new_size, old_size;
1704 /* not delalloc, ignore it */
1705 if (!(other->state & EXTENT_DELALLOC))
1708 if (new->start > other->start)
1709 new_size = new->end - other->start + 1;
1711 new_size = other->end - new->start + 1;
1713 /* we're not bigger than the max, unreserve the space and go */
1714 if (new_size <= BTRFS_MAX_EXTENT_SIZE) {
1715 spin_lock(&BTRFS_I(inode)->lock);
1716 btrfs_mod_outstanding_extents(BTRFS_I(inode), -1);
1717 spin_unlock(&BTRFS_I(inode)->lock);
1722 * We have to add up either side to figure out how many extents were
1723 * accounted for before we merged into one big extent. If the number of
1724 * extents we accounted for is <= the amount we need for the new range
1725 * then we can return, otherwise drop. Think of it like this
1729 * So we've grown the extent by a MAX_SIZE extent, this would mean we
1730 * need 2 outstanding extents, on one side we have 1 and the other side
1731 * we have 1 so they are == and we can return. But in this case
1733 * [MAX_SIZE+4k][MAX_SIZE+4k]
1735 * Each range on their own accounts for 2 extents, but merged together
1736 * they are only 3 extents worth of accounting, so we need to drop in
1739 old_size = other->end - other->start + 1;
1740 num_extents = count_max_extents(old_size);
1741 old_size = new->end - new->start + 1;
1742 num_extents += count_max_extents(old_size);
1743 if (count_max_extents(new_size) >= num_extents)
1746 spin_lock(&BTRFS_I(inode)->lock);
1747 btrfs_mod_outstanding_extents(BTRFS_I(inode), -1);
1748 spin_unlock(&BTRFS_I(inode)->lock);
1751 static void btrfs_add_delalloc_inodes(struct btrfs_root *root,
1752 struct inode *inode)
1754 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1756 spin_lock(&root->delalloc_lock);
1757 if (list_empty(&BTRFS_I(inode)->delalloc_inodes)) {
1758 list_add_tail(&BTRFS_I(inode)->delalloc_inodes,
1759 &root->delalloc_inodes);
1760 set_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1761 &BTRFS_I(inode)->runtime_flags);
1762 root->nr_delalloc_inodes++;
1763 if (root->nr_delalloc_inodes == 1) {
1764 spin_lock(&fs_info->delalloc_root_lock);
1765 BUG_ON(!list_empty(&root->delalloc_root));
1766 list_add_tail(&root->delalloc_root,
1767 &fs_info->delalloc_roots);
1768 spin_unlock(&fs_info->delalloc_root_lock);
1771 spin_unlock(&root->delalloc_lock);
1775 void __btrfs_del_delalloc_inode(struct btrfs_root *root,
1776 struct btrfs_inode *inode)
1778 struct btrfs_fs_info *fs_info = root->fs_info;
1780 if (!list_empty(&inode->delalloc_inodes)) {
1781 list_del_init(&inode->delalloc_inodes);
1782 clear_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1783 &inode->runtime_flags);
1784 root->nr_delalloc_inodes--;
1785 if (!root->nr_delalloc_inodes) {
1786 ASSERT(list_empty(&root->delalloc_inodes));
1787 spin_lock(&fs_info->delalloc_root_lock);
1788 BUG_ON(list_empty(&root->delalloc_root));
1789 list_del_init(&root->delalloc_root);
1790 spin_unlock(&fs_info->delalloc_root_lock);
1795 static void btrfs_del_delalloc_inode(struct btrfs_root *root,
1796 struct btrfs_inode *inode)
1798 spin_lock(&root->delalloc_lock);
1799 __btrfs_del_delalloc_inode(root, inode);
1800 spin_unlock(&root->delalloc_lock);
1804 * Properly track delayed allocation bytes in the inode and to maintain the
1805 * list of inodes that have pending delalloc work to be done.
1807 void btrfs_set_delalloc_extent(struct inode *inode, struct extent_state *state,
1810 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1812 if ((*bits & EXTENT_DEFRAG) && !(*bits & EXTENT_DELALLOC))
1815 * set_bit and clear bit hooks normally require _irqsave/restore
1816 * but in this case, we are only testing for the DELALLOC
1817 * bit, which is only set or cleared with irqs on
1819 if (!(state->state & EXTENT_DELALLOC) && (*bits & EXTENT_DELALLOC)) {
1820 struct btrfs_root *root = BTRFS_I(inode)->root;
1821 u64 len = state->end + 1 - state->start;
1822 u32 num_extents = count_max_extents(len);
1823 bool do_list = !btrfs_is_free_space_inode(BTRFS_I(inode));
1825 spin_lock(&BTRFS_I(inode)->lock);
1826 btrfs_mod_outstanding_extents(BTRFS_I(inode), num_extents);
1827 spin_unlock(&BTRFS_I(inode)->lock);
1829 /* For sanity tests */
1830 if (btrfs_is_testing(fs_info))
1833 percpu_counter_add_batch(&fs_info->delalloc_bytes, len,
1834 fs_info->delalloc_batch);
1835 spin_lock(&BTRFS_I(inode)->lock);
1836 BTRFS_I(inode)->delalloc_bytes += len;
1837 if (*bits & EXTENT_DEFRAG)
1838 BTRFS_I(inode)->defrag_bytes += len;
1839 if (do_list && !test_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1840 &BTRFS_I(inode)->runtime_flags))
1841 btrfs_add_delalloc_inodes(root, inode);
1842 spin_unlock(&BTRFS_I(inode)->lock);
1845 if (!(state->state & EXTENT_DELALLOC_NEW) &&
1846 (*bits & EXTENT_DELALLOC_NEW)) {
1847 spin_lock(&BTRFS_I(inode)->lock);
1848 BTRFS_I(inode)->new_delalloc_bytes += state->end + 1 -
1850 spin_unlock(&BTRFS_I(inode)->lock);
1855 * Once a range is no longer delalloc this function ensures that proper
1856 * accounting happens.
1858 void btrfs_clear_delalloc_extent(struct inode *vfs_inode,
1859 struct extent_state *state, unsigned *bits)
1861 struct btrfs_inode *inode = BTRFS_I(vfs_inode);
1862 struct btrfs_fs_info *fs_info = btrfs_sb(vfs_inode->i_sb);
1863 u64 len = state->end + 1 - state->start;
1864 u32 num_extents = count_max_extents(len);
1866 if ((state->state & EXTENT_DEFRAG) && (*bits & EXTENT_DEFRAG)) {
1867 spin_lock(&inode->lock);
1868 inode->defrag_bytes -= len;
1869 spin_unlock(&inode->lock);
1873 * set_bit and clear bit hooks normally require _irqsave/restore
1874 * but in this case, we are only testing for the DELALLOC
1875 * bit, which is only set or cleared with irqs on
1877 if ((state->state & EXTENT_DELALLOC) && (*bits & EXTENT_DELALLOC)) {
1878 struct btrfs_root *root = inode->root;
1879 bool do_list = !btrfs_is_free_space_inode(inode);
1881 spin_lock(&inode->lock);
1882 btrfs_mod_outstanding_extents(inode, -num_extents);
1883 spin_unlock(&inode->lock);
1886 * We don't reserve metadata space for space cache inodes so we
1887 * don't need to call delalloc_release_metadata if there is an
1890 if (*bits & EXTENT_CLEAR_META_RESV &&
1891 root != fs_info->tree_root)
1892 btrfs_delalloc_release_metadata(inode, len, false);
1894 /* For sanity tests. */
1895 if (btrfs_is_testing(fs_info))
1898 if (root->root_key.objectid != BTRFS_DATA_RELOC_TREE_OBJECTID &&
1899 do_list && !(state->state & EXTENT_NORESERVE) &&
1900 (*bits & EXTENT_CLEAR_DATA_RESV))
1901 btrfs_free_reserved_data_space_noquota(
1905 percpu_counter_add_batch(&fs_info->delalloc_bytes, -len,
1906 fs_info->delalloc_batch);
1907 spin_lock(&inode->lock);
1908 inode->delalloc_bytes -= len;
1909 if (do_list && inode->delalloc_bytes == 0 &&
1910 test_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1911 &inode->runtime_flags))
1912 btrfs_del_delalloc_inode(root, inode);
1913 spin_unlock(&inode->lock);
1916 if ((state->state & EXTENT_DELALLOC_NEW) &&
1917 (*bits & EXTENT_DELALLOC_NEW)) {
1918 spin_lock(&inode->lock);
1919 ASSERT(inode->new_delalloc_bytes >= len);
1920 inode->new_delalloc_bytes -= len;
1921 spin_unlock(&inode->lock);
1926 * btrfs_bio_fits_in_stripe - Checks whether the size of the given bio will fit
1927 * in a chunk's stripe. This function ensures that bios do not span a
1930 * @page - The page we are about to add to the bio
1931 * @size - size we want to add to the bio
1932 * @bio - bio we want to ensure is smaller than a stripe
1933 * @bio_flags - flags of the bio
1935 * return 1 if page cannot be added to the bio
1936 * return 0 if page can be added to the bio
1937 * return error otherwise
1939 int btrfs_bio_fits_in_stripe(struct page *page, size_t size, struct bio *bio,
1940 unsigned long bio_flags)
1942 struct inode *inode = page->mapping->host;
1943 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1944 u64 logical = (u64)bio->bi_iter.bi_sector << 9;
1948 struct btrfs_io_geometry geom;
1950 if (bio_flags & EXTENT_BIO_COMPRESSED)
1953 length = bio->bi_iter.bi_size;
1954 map_length = length;
1955 ret = btrfs_get_io_geometry(fs_info, btrfs_op(bio), logical, map_length,
1960 if (geom.len < length + size)
1966 * in order to insert checksums into the metadata in large chunks,
1967 * we wait until bio submission time. All the pages in the bio are
1968 * checksummed and sums are attached onto the ordered extent record.
1970 * At IO completion time the cums attached on the ordered extent record
1971 * are inserted into the btree
1973 static blk_status_t btrfs_submit_bio_start(void *private_data, struct bio *bio,
1976 struct inode *inode = private_data;
1977 blk_status_t ret = 0;
1979 ret = btrfs_csum_one_bio(inode, bio, 0, 0);
1980 BUG_ON(ret); /* -ENOMEM */
1985 * extent_io.c submission hook. This does the right thing for csum calculation
1986 * on write, or reading the csums from the tree before a read.
1988 * Rules about async/sync submit,
1989 * a) read: sync submit
1991 * b) write without checksum: sync submit
1993 * c) write with checksum:
1994 * c-1) if bio is issued by fsync: sync submit
1995 * (sync_writers != 0)
1997 * c-2) if root is reloc root: sync submit
1998 * (only in case of buffered IO)
2000 * c-3) otherwise: async submit
2002 static blk_status_t btrfs_submit_bio_hook(struct inode *inode, struct bio *bio,
2004 unsigned long bio_flags)
2007 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2008 struct btrfs_root *root = BTRFS_I(inode)->root;
2009 enum btrfs_wq_endio_type metadata = BTRFS_WQ_ENDIO_DATA;
2010 blk_status_t ret = 0;
2012 int async = !atomic_read(&BTRFS_I(inode)->sync_writers);
2014 skip_sum = BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM;
2016 if (btrfs_is_free_space_inode(BTRFS_I(inode)))
2017 metadata = BTRFS_WQ_ENDIO_FREE_SPACE;
2019 if (bio_op(bio) != REQ_OP_WRITE) {
2020 ret = btrfs_bio_wq_end_io(fs_info, bio, metadata);
2024 if (bio_flags & EXTENT_BIO_COMPRESSED) {
2025 ret = btrfs_submit_compressed_read(inode, bio,
2029 } else if (!skip_sum) {
2030 ret = btrfs_lookup_bio_sums(inode, bio, NULL);
2035 } else if (async && !skip_sum) {
2036 /* csum items have already been cloned */
2037 if (root->root_key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID)
2039 /* we're doing a write, do the async checksumming */
2040 ret = btrfs_wq_submit_bio(fs_info, bio, mirror_num, bio_flags,
2041 0, inode, btrfs_submit_bio_start);
2043 } else if (!skip_sum) {
2044 ret = btrfs_csum_one_bio(inode, bio, 0, 0);
2050 ret = btrfs_map_bio(fs_info, bio, mirror_num, 0);
2054 bio->bi_status = ret;
2061 * given a list of ordered sums record them in the inode. This happens
2062 * at IO completion time based on sums calculated at bio submission time.
2064 static noinline int add_pending_csums(struct btrfs_trans_handle *trans,
2065 struct inode *inode, struct list_head *list)
2067 struct btrfs_ordered_sum *sum;
2070 list_for_each_entry(sum, list, list) {
2071 trans->adding_csums = true;
2072 ret = btrfs_csum_file_blocks(trans,
2073 BTRFS_I(inode)->root->fs_info->csum_root, sum);
2074 trans->adding_csums = false;
2081 int btrfs_set_extent_delalloc(struct inode *inode, u64 start, u64 end,
2082 unsigned int extra_bits,
2083 struct extent_state **cached_state, int dedupe)
2085 WARN_ON(PAGE_ALIGNED(end));
2086 return set_extent_delalloc(&BTRFS_I(inode)->io_tree, start, end,
2087 extra_bits, cached_state);
2090 /* see btrfs_writepage_start_hook for details on why this is required */
2091 struct btrfs_writepage_fixup {
2093 struct btrfs_work work;
2096 static void btrfs_writepage_fixup_worker(struct btrfs_work *work)
2098 struct btrfs_writepage_fixup *fixup;
2099 struct btrfs_ordered_extent *ordered;
2100 struct extent_state *cached_state = NULL;
2101 struct extent_changeset *data_reserved = NULL;
2103 struct inode *inode;
2108 fixup = container_of(work, struct btrfs_writepage_fixup, work);
2112 if (!page->mapping || !PageDirty(page) || !PageChecked(page)) {
2113 ClearPageChecked(page);
2117 inode = page->mapping->host;
2118 page_start = page_offset(page);
2119 page_end = page_offset(page) + PAGE_SIZE - 1;
2121 lock_extent_bits(&BTRFS_I(inode)->io_tree, page_start, page_end,
2124 /* already ordered? We're done */
2125 if (PagePrivate2(page))
2128 ordered = btrfs_lookup_ordered_range(BTRFS_I(inode), page_start,
2131 unlock_extent_cached(&BTRFS_I(inode)->io_tree, page_start,
2132 page_end, &cached_state);
2134 btrfs_start_ordered_extent(inode, ordered, 1);
2135 btrfs_put_ordered_extent(ordered);
2139 ret = btrfs_delalloc_reserve_space(inode, &data_reserved, page_start,
2142 mapping_set_error(page->mapping, ret);
2143 end_extent_writepage(page, ret, page_start, page_end);
2144 ClearPageChecked(page);
2148 ret = btrfs_set_extent_delalloc(inode, page_start, page_end, 0,
2151 mapping_set_error(page->mapping, ret);
2152 end_extent_writepage(page, ret, page_start, page_end);
2153 ClearPageChecked(page);
2157 ClearPageChecked(page);
2158 set_page_dirty(page);
2159 btrfs_delalloc_release_extents(BTRFS_I(inode), PAGE_SIZE, false);
2161 unlock_extent_cached(&BTRFS_I(inode)->io_tree, page_start, page_end,
2167 extent_changeset_free(data_reserved);
2171 * There are a few paths in the higher layers of the kernel that directly
2172 * set the page dirty bit without asking the filesystem if it is a
2173 * good idea. This causes problems because we want to make sure COW
2174 * properly happens and the data=ordered rules are followed.
2176 * In our case any range that doesn't have the ORDERED bit set
2177 * hasn't been properly setup for IO. We kick off an async process
2178 * to fix it up. The async helper will wait for ordered extents, set
2179 * the delalloc bit and make it safe to write the page.
2181 int btrfs_writepage_cow_fixup(struct page *page, u64 start, u64 end)
2183 struct inode *inode = page->mapping->host;
2184 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2185 struct btrfs_writepage_fixup *fixup;
2187 /* this page is properly in the ordered list */
2188 if (TestClearPagePrivate2(page))
2191 if (PageChecked(page))
2194 fixup = kzalloc(sizeof(*fixup), GFP_NOFS);
2198 SetPageChecked(page);
2200 btrfs_init_work(&fixup->work, btrfs_fixup_helper,
2201 btrfs_writepage_fixup_worker, NULL, NULL);
2203 btrfs_queue_work(fs_info->fixup_workers, &fixup->work);
2207 static int insert_reserved_file_extent(struct btrfs_trans_handle *trans,
2208 struct inode *inode, u64 file_pos,
2209 u64 disk_bytenr, u64 disk_num_bytes,
2210 u64 num_bytes, u64 ram_bytes,
2211 u8 compression, u8 encryption,
2212 u16 other_encoding, int extent_type)
2214 struct btrfs_root *root = BTRFS_I(inode)->root;
2215 struct btrfs_file_extent_item *fi;
2216 struct btrfs_path *path;
2217 struct extent_buffer *leaf;
2218 struct btrfs_key ins;
2220 int extent_inserted = 0;
2223 path = btrfs_alloc_path();
2228 * we may be replacing one extent in the tree with another.
2229 * The new extent is pinned in the extent map, and we don't want
2230 * to drop it from the cache until it is completely in the btree.
2232 * So, tell btrfs_drop_extents to leave this extent in the cache.
2233 * the caller is expected to unpin it and allow it to be merged
2236 ret = __btrfs_drop_extents(trans, root, inode, path, file_pos,
2237 file_pos + num_bytes, NULL, 0,
2238 1, sizeof(*fi), &extent_inserted);
2242 if (!extent_inserted) {
2243 ins.objectid = btrfs_ino(BTRFS_I(inode));
2244 ins.offset = file_pos;
2245 ins.type = BTRFS_EXTENT_DATA_KEY;
2247 path->leave_spinning = 1;
2248 ret = btrfs_insert_empty_item(trans, root, path, &ins,
2253 leaf = path->nodes[0];
2254 fi = btrfs_item_ptr(leaf, path->slots[0],
2255 struct btrfs_file_extent_item);
2256 btrfs_set_file_extent_generation(leaf, fi, trans->transid);
2257 btrfs_set_file_extent_type(leaf, fi, extent_type);
2258 btrfs_set_file_extent_disk_bytenr(leaf, fi, disk_bytenr);
2259 btrfs_set_file_extent_disk_num_bytes(leaf, fi, disk_num_bytes);
2260 btrfs_set_file_extent_offset(leaf, fi, 0);
2261 btrfs_set_file_extent_num_bytes(leaf, fi, num_bytes);
2262 btrfs_set_file_extent_ram_bytes(leaf, fi, ram_bytes);
2263 btrfs_set_file_extent_compression(leaf, fi, compression);
2264 btrfs_set_file_extent_encryption(leaf, fi, encryption);
2265 btrfs_set_file_extent_other_encoding(leaf, fi, other_encoding);
2267 btrfs_mark_buffer_dirty(leaf);
2268 btrfs_release_path(path);
2270 inode_add_bytes(inode, num_bytes);
2272 ins.objectid = disk_bytenr;
2273 ins.offset = disk_num_bytes;
2274 ins.type = BTRFS_EXTENT_ITEM_KEY;
2277 * Release the reserved range from inode dirty range map, as it is
2278 * already moved into delayed_ref_head
2280 ret = btrfs_qgroup_release_data(inode, file_pos, ram_bytes);
2284 ret = btrfs_alloc_reserved_file_extent(trans, root,
2285 btrfs_ino(BTRFS_I(inode)),
2286 file_pos, qg_released, &ins);
2288 btrfs_free_path(path);
2293 /* snapshot-aware defrag */
2294 struct sa_defrag_extent_backref {
2295 struct rb_node node;
2296 struct old_sa_defrag_extent *old;
2305 struct old_sa_defrag_extent {
2306 struct list_head list;
2307 struct new_sa_defrag_extent *new;
2316 struct new_sa_defrag_extent {
2317 struct rb_root root;
2318 struct list_head head;
2319 struct btrfs_path *path;
2320 struct inode *inode;
2328 static int backref_comp(struct sa_defrag_extent_backref *b1,
2329 struct sa_defrag_extent_backref *b2)
2331 if (b1->root_id < b2->root_id)
2333 else if (b1->root_id > b2->root_id)
2336 if (b1->inum < b2->inum)
2338 else if (b1->inum > b2->inum)
2341 if (b1->file_pos < b2->file_pos)
2343 else if (b1->file_pos > b2->file_pos)
2347 * [------------------------------] ===> (a range of space)
2348 * |<--->| |<---->| =============> (fs/file tree A)
2349 * |<---------------------------->| ===> (fs/file tree B)
2351 * A range of space can refer to two file extents in one tree while
2352 * refer to only one file extent in another tree.
2354 * So we may process a disk offset more than one time(two extents in A)
2355 * and locate at the same extent(one extent in B), then insert two same
2356 * backrefs(both refer to the extent in B).
2361 static void backref_insert(struct rb_root *root,
2362 struct sa_defrag_extent_backref *backref)
2364 struct rb_node **p = &root->rb_node;
2365 struct rb_node *parent = NULL;
2366 struct sa_defrag_extent_backref *entry;
2371 entry = rb_entry(parent, struct sa_defrag_extent_backref, node);
2373 ret = backref_comp(backref, entry);
2377 p = &(*p)->rb_right;
2380 rb_link_node(&backref->node, parent, p);
2381 rb_insert_color(&backref->node, root);
2385 * Note the backref might has changed, and in this case we just return 0.
2387 static noinline int record_one_backref(u64 inum, u64 offset, u64 root_id,
2390 struct btrfs_file_extent_item *extent;
2391 struct old_sa_defrag_extent *old = ctx;
2392 struct new_sa_defrag_extent *new = old->new;
2393 struct btrfs_path *path = new->path;
2394 struct btrfs_key key;
2395 struct btrfs_root *root;
2396 struct sa_defrag_extent_backref *backref;
2397 struct extent_buffer *leaf;
2398 struct inode *inode = new->inode;
2399 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2405 if (BTRFS_I(inode)->root->root_key.objectid == root_id &&
2406 inum == btrfs_ino(BTRFS_I(inode)))
2409 key.objectid = root_id;
2410 key.type = BTRFS_ROOT_ITEM_KEY;
2411 key.offset = (u64)-1;
2413 root = btrfs_read_fs_root_no_name(fs_info, &key);
2415 if (PTR_ERR(root) == -ENOENT)
2418 btrfs_debug(fs_info, "inum=%llu, offset=%llu, root_id=%llu",
2419 inum, offset, root_id);
2420 return PTR_ERR(root);
2423 key.objectid = inum;
2424 key.type = BTRFS_EXTENT_DATA_KEY;
2425 if (offset > (u64)-1 << 32)
2428 key.offset = offset;
2430 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2431 if (WARN_ON(ret < 0))
2438 leaf = path->nodes[0];
2439 slot = path->slots[0];
2441 if (slot >= btrfs_header_nritems(leaf)) {
2442 ret = btrfs_next_leaf(root, path);
2445 } else if (ret > 0) {
2454 btrfs_item_key_to_cpu(leaf, &key, slot);
2456 if (key.objectid > inum)
2459 if (key.objectid < inum || key.type != BTRFS_EXTENT_DATA_KEY)
2462 extent = btrfs_item_ptr(leaf, slot,
2463 struct btrfs_file_extent_item);
2465 if (btrfs_file_extent_disk_bytenr(leaf, extent) != old->bytenr)
2469 * 'offset' refers to the exact key.offset,
2470 * NOT the 'offset' field in btrfs_extent_data_ref, ie.
2471 * (key.offset - extent_offset).
2473 if (key.offset != offset)
2476 extent_offset = btrfs_file_extent_offset(leaf, extent);
2477 num_bytes = btrfs_file_extent_num_bytes(leaf, extent);
2479 if (extent_offset >= old->extent_offset + old->offset +
2480 old->len || extent_offset + num_bytes <=
2481 old->extent_offset + old->offset)
2486 backref = kmalloc(sizeof(*backref), GFP_NOFS);
2492 backref->root_id = root_id;
2493 backref->inum = inum;
2494 backref->file_pos = offset;
2495 backref->num_bytes = num_bytes;
2496 backref->extent_offset = extent_offset;
2497 backref->generation = btrfs_file_extent_generation(leaf, extent);
2499 backref_insert(&new->root, backref);
2502 btrfs_release_path(path);
2507 static noinline bool record_extent_backrefs(struct btrfs_path *path,
2508 struct new_sa_defrag_extent *new)
2510 struct btrfs_fs_info *fs_info = btrfs_sb(new->inode->i_sb);
2511 struct old_sa_defrag_extent *old, *tmp;
2516 list_for_each_entry_safe(old, tmp, &new->head, list) {
2517 ret = iterate_inodes_from_logical(old->bytenr +
2518 old->extent_offset, fs_info,
2519 path, record_one_backref,
2521 if (ret < 0 && ret != -ENOENT)
2524 /* no backref to be processed for this extent */
2526 list_del(&old->list);
2531 if (list_empty(&new->head))
2537 static int relink_is_mergable(struct extent_buffer *leaf,
2538 struct btrfs_file_extent_item *fi,
2539 struct new_sa_defrag_extent *new)
2541 if (btrfs_file_extent_disk_bytenr(leaf, fi) != new->bytenr)
2544 if (btrfs_file_extent_type(leaf, fi) != BTRFS_FILE_EXTENT_REG)
2547 if (btrfs_file_extent_compression(leaf, fi) != new->compress_type)
2550 if (btrfs_file_extent_encryption(leaf, fi) ||
2551 btrfs_file_extent_other_encoding(leaf, fi))
2558 * Note the backref might has changed, and in this case we just return 0.
2560 static noinline int relink_extent_backref(struct btrfs_path *path,
2561 struct sa_defrag_extent_backref *prev,
2562 struct sa_defrag_extent_backref *backref)
2564 struct btrfs_file_extent_item *extent;
2565 struct btrfs_file_extent_item *item;
2566 struct btrfs_ordered_extent *ordered;
2567 struct btrfs_trans_handle *trans;
2568 struct btrfs_ref ref = { 0 };
2569 struct btrfs_root *root;
2570 struct btrfs_key key;
2571 struct extent_buffer *leaf;
2572 struct old_sa_defrag_extent *old = backref->old;
2573 struct new_sa_defrag_extent *new = old->new;
2574 struct btrfs_fs_info *fs_info = btrfs_sb(new->inode->i_sb);
2575 struct inode *inode;
2576 struct extent_state *cached = NULL;
2585 if (prev && prev->root_id == backref->root_id &&
2586 prev->inum == backref->inum &&
2587 prev->file_pos + prev->num_bytes == backref->file_pos)
2590 /* step 1: get root */
2591 key.objectid = backref->root_id;
2592 key.type = BTRFS_ROOT_ITEM_KEY;
2593 key.offset = (u64)-1;
2595 index = srcu_read_lock(&fs_info->subvol_srcu);
2597 root = btrfs_read_fs_root_no_name(fs_info, &key);
2599 srcu_read_unlock(&fs_info->subvol_srcu, index);
2600 if (PTR_ERR(root) == -ENOENT)
2602 return PTR_ERR(root);
2605 if (btrfs_root_readonly(root)) {
2606 srcu_read_unlock(&fs_info->subvol_srcu, index);
2610 /* step 2: get inode */
2611 key.objectid = backref->inum;
2612 key.type = BTRFS_INODE_ITEM_KEY;
2615 inode = btrfs_iget(fs_info->sb, &key, root, NULL);
2616 if (IS_ERR(inode)) {
2617 srcu_read_unlock(&fs_info->subvol_srcu, index);
2621 srcu_read_unlock(&fs_info->subvol_srcu, index);
2623 /* step 3: relink backref */
2624 lock_start = backref->file_pos;
2625 lock_end = backref->file_pos + backref->num_bytes - 1;
2626 lock_extent_bits(&BTRFS_I(inode)->io_tree, lock_start, lock_end,
2629 ordered = btrfs_lookup_first_ordered_extent(inode, lock_end);
2631 btrfs_put_ordered_extent(ordered);
2635 trans = btrfs_join_transaction(root);
2636 if (IS_ERR(trans)) {
2637 ret = PTR_ERR(trans);
2641 key.objectid = backref->inum;
2642 key.type = BTRFS_EXTENT_DATA_KEY;
2643 key.offset = backref->file_pos;
2645 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2648 } else if (ret > 0) {
2653 extent = btrfs_item_ptr(path->nodes[0], path->slots[0],
2654 struct btrfs_file_extent_item);
2656 if (btrfs_file_extent_generation(path->nodes[0], extent) !=
2657 backref->generation)
2660 btrfs_release_path(path);
2662 start = backref->file_pos;
2663 if (backref->extent_offset < old->extent_offset + old->offset)
2664 start += old->extent_offset + old->offset -
2665 backref->extent_offset;
2667 len = min(backref->extent_offset + backref->num_bytes,
2668 old->extent_offset + old->offset + old->len);
2669 len -= max(backref->extent_offset, old->extent_offset + old->offset);
2671 ret = btrfs_drop_extents(trans, root, inode, start,
2676 key.objectid = btrfs_ino(BTRFS_I(inode));
2677 key.type = BTRFS_EXTENT_DATA_KEY;
2680 path->leave_spinning = 1;
2682 struct btrfs_file_extent_item *fi;
2684 struct btrfs_key found_key;
2686 ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
2691 leaf = path->nodes[0];
2692 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
2694 fi = btrfs_item_ptr(leaf, path->slots[0],
2695 struct btrfs_file_extent_item);
2696 extent_len = btrfs_file_extent_num_bytes(leaf, fi);
2698 if (extent_len + found_key.offset == start &&
2699 relink_is_mergable(leaf, fi, new)) {
2700 btrfs_set_file_extent_num_bytes(leaf, fi,
2702 btrfs_mark_buffer_dirty(leaf);
2703 inode_add_bytes(inode, len);
2709 btrfs_release_path(path);
2714 ret = btrfs_insert_empty_item(trans, root, path, &key,
2717 btrfs_abort_transaction(trans, ret);
2721 leaf = path->nodes[0];
2722 item = btrfs_item_ptr(leaf, path->slots[0],
2723 struct btrfs_file_extent_item);
2724 btrfs_set_file_extent_disk_bytenr(leaf, item, new->bytenr);
2725 btrfs_set_file_extent_disk_num_bytes(leaf, item, new->disk_len);
2726 btrfs_set_file_extent_offset(leaf, item, start - new->file_pos);
2727 btrfs_set_file_extent_num_bytes(leaf, item, len);
2728 btrfs_set_file_extent_ram_bytes(leaf, item, new->len);
2729 btrfs_set_file_extent_generation(leaf, item, trans->transid);
2730 btrfs_set_file_extent_type(leaf, item, BTRFS_FILE_EXTENT_REG);
2731 btrfs_set_file_extent_compression(leaf, item, new->compress_type);
2732 btrfs_set_file_extent_encryption(leaf, item, 0);
2733 btrfs_set_file_extent_other_encoding(leaf, item, 0);
2735 btrfs_mark_buffer_dirty(leaf);
2736 inode_add_bytes(inode, len);
2737 btrfs_release_path(path);
2739 btrfs_init_generic_ref(&ref, BTRFS_ADD_DELAYED_REF, new->bytenr,
2741 btrfs_init_data_ref(&ref, backref->root_id, backref->inum,
2742 new->file_pos); /* start - extent_offset */
2743 ret = btrfs_inc_extent_ref(trans, &ref);
2745 btrfs_abort_transaction(trans, ret);
2751 btrfs_release_path(path);
2752 path->leave_spinning = 0;
2753 btrfs_end_transaction(trans);
2755 unlock_extent_cached(&BTRFS_I(inode)->io_tree, lock_start, lock_end,
2761 static void free_sa_defrag_extent(struct new_sa_defrag_extent *new)
2763 struct old_sa_defrag_extent *old, *tmp;
2768 list_for_each_entry_safe(old, tmp, &new->head, list) {
2774 static void relink_file_extents(struct new_sa_defrag_extent *new)
2776 struct btrfs_fs_info *fs_info = btrfs_sb(new->inode->i_sb);
2777 struct btrfs_path *path;
2778 struct sa_defrag_extent_backref *backref;
2779 struct sa_defrag_extent_backref *prev = NULL;
2780 struct rb_node *node;
2783 path = btrfs_alloc_path();
2787 if (!record_extent_backrefs(path, new)) {
2788 btrfs_free_path(path);
2791 btrfs_release_path(path);
2794 node = rb_first(&new->root);
2797 rb_erase(node, &new->root);
2799 backref = rb_entry(node, struct sa_defrag_extent_backref, node);
2801 ret = relink_extent_backref(path, prev, backref);
2814 btrfs_free_path(path);
2816 free_sa_defrag_extent(new);
2818 atomic_dec(&fs_info->defrag_running);
2819 wake_up(&fs_info->transaction_wait);
2822 static struct new_sa_defrag_extent *
2823 record_old_file_extents(struct inode *inode,
2824 struct btrfs_ordered_extent *ordered)
2826 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2827 struct btrfs_root *root = BTRFS_I(inode)->root;
2828 struct btrfs_path *path;
2829 struct btrfs_key key;
2830 struct old_sa_defrag_extent *old;
2831 struct new_sa_defrag_extent *new;
2834 new = kmalloc(sizeof(*new), GFP_NOFS);
2839 new->file_pos = ordered->file_offset;
2840 new->len = ordered->len;
2841 new->bytenr = ordered->start;
2842 new->disk_len = ordered->disk_len;
2843 new->compress_type = ordered->compress_type;
2844 new->root = RB_ROOT;
2845 INIT_LIST_HEAD(&new->head);
2847 path = btrfs_alloc_path();
2851 key.objectid = btrfs_ino(BTRFS_I(inode));
2852 key.type = BTRFS_EXTENT_DATA_KEY;
2853 key.offset = new->file_pos;
2855 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2858 if (ret > 0 && path->slots[0] > 0)
2861 /* find out all the old extents for the file range */
2863 struct btrfs_file_extent_item *extent;
2864 struct extent_buffer *l;
2873 slot = path->slots[0];
2875 if (slot >= btrfs_header_nritems(l)) {
2876 ret = btrfs_next_leaf(root, path);
2884 btrfs_item_key_to_cpu(l, &key, slot);
2886 if (key.objectid != btrfs_ino(BTRFS_I(inode)))
2888 if (key.type != BTRFS_EXTENT_DATA_KEY)
2890 if (key.offset >= new->file_pos + new->len)
2893 extent = btrfs_item_ptr(l, slot, struct btrfs_file_extent_item);
2895 num_bytes = btrfs_file_extent_num_bytes(l, extent);
2896 if (key.offset + num_bytes < new->file_pos)
2899 disk_bytenr = btrfs_file_extent_disk_bytenr(l, extent);
2903 extent_offset = btrfs_file_extent_offset(l, extent);
2905 old = kmalloc(sizeof(*old), GFP_NOFS);
2909 offset = max(new->file_pos, key.offset);
2910 end = min(new->file_pos + new->len, key.offset + num_bytes);
2912 old->bytenr = disk_bytenr;
2913 old->extent_offset = extent_offset;
2914 old->offset = offset - key.offset;
2915 old->len = end - offset;
2918 list_add_tail(&old->list, &new->head);
2924 btrfs_free_path(path);
2925 atomic_inc(&fs_info->defrag_running);
2930 btrfs_free_path(path);
2932 free_sa_defrag_extent(new);
2936 static void btrfs_release_delalloc_bytes(struct btrfs_fs_info *fs_info,
2939 struct btrfs_block_group_cache *cache;
2941 cache = btrfs_lookup_block_group(fs_info, start);
2944 spin_lock(&cache->lock);
2945 cache->delalloc_bytes -= len;
2946 spin_unlock(&cache->lock);
2948 btrfs_put_block_group(cache);
2951 /* as ordered data IO finishes, this gets called so we can finish
2952 * an ordered extent if the range of bytes in the file it covers are
2955 static int btrfs_finish_ordered_io(struct btrfs_ordered_extent *ordered_extent)
2957 struct inode *inode = ordered_extent->inode;
2958 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2959 struct btrfs_root *root = BTRFS_I(inode)->root;
2960 struct btrfs_trans_handle *trans = NULL;
2961 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
2962 struct extent_state *cached_state = NULL;
2963 struct new_sa_defrag_extent *new = NULL;
2964 int compress_type = 0;
2966 u64 logical_len = ordered_extent->len;
2968 bool truncated = false;
2969 bool range_locked = false;
2970 bool clear_new_delalloc_bytes = false;
2971 bool clear_reserved_extent = true;
2973 if (!test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags) &&
2974 !test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags) &&
2975 !test_bit(BTRFS_ORDERED_DIRECT, &ordered_extent->flags))
2976 clear_new_delalloc_bytes = true;
2978 nolock = btrfs_is_free_space_inode(BTRFS_I(inode));
2980 if (test_bit(BTRFS_ORDERED_IOERR, &ordered_extent->flags)) {
2985 btrfs_free_io_failure_record(BTRFS_I(inode),
2986 ordered_extent->file_offset,
2987 ordered_extent->file_offset +
2988 ordered_extent->len - 1);
2990 if (test_bit(BTRFS_ORDERED_TRUNCATED, &ordered_extent->flags)) {
2992 logical_len = ordered_extent->truncated_len;
2993 /* Truncated the entire extent, don't bother adding */
2998 if (test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags)) {
2999 BUG_ON(!list_empty(&ordered_extent->list)); /* Logic error */
3002 * For mwrite(mmap + memset to write) case, we still reserve
3003 * space for NOCOW range.
3004 * As NOCOW won't cause a new delayed ref, just free the space
3006 btrfs_qgroup_free_data(inode, NULL, ordered_extent->file_offset,
3007 ordered_extent->len);
3008 btrfs_ordered_update_i_size(inode, 0, ordered_extent);
3010 trans = btrfs_join_transaction_nolock(root);
3012 trans = btrfs_join_transaction(root);
3013 if (IS_ERR(trans)) {
3014 ret = PTR_ERR(trans);
3018 trans->block_rsv = &BTRFS_I(inode)->block_rsv;
3019 ret = btrfs_update_inode_fallback(trans, root, inode);
3020 if (ret) /* -ENOMEM or corruption */
3021 btrfs_abort_transaction(trans, ret);
3025 range_locked = true;
3026 lock_extent_bits(io_tree, ordered_extent->file_offset,
3027 ordered_extent->file_offset + ordered_extent->len - 1,
3030 ret = test_range_bit(io_tree, ordered_extent->file_offset,
3031 ordered_extent->file_offset + ordered_extent->len - 1,
3032 EXTENT_DEFRAG, 0, cached_state);
3034 u64 last_snapshot = btrfs_root_last_snapshot(&root->root_item);
3035 if (0 && last_snapshot >= BTRFS_I(inode)->generation)
3036 /* the inode is shared */
3037 new = record_old_file_extents(inode, ordered_extent);
3039 clear_extent_bit(io_tree, ordered_extent->file_offset,
3040 ordered_extent->file_offset + ordered_extent->len - 1,
3041 EXTENT_DEFRAG, 0, 0, &cached_state);
3045 trans = btrfs_join_transaction_nolock(root);
3047 trans = btrfs_join_transaction(root);
3048 if (IS_ERR(trans)) {
3049 ret = PTR_ERR(trans);
3054 trans->block_rsv = &BTRFS_I(inode)->block_rsv;
3056 if (test_bit(BTRFS_ORDERED_COMPRESSED, &ordered_extent->flags))
3057 compress_type = ordered_extent->compress_type;
3058 if (test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags)) {
3059 BUG_ON(compress_type);
3060 btrfs_qgroup_free_data(inode, NULL, ordered_extent->file_offset,
3061 ordered_extent->len);
3062 ret = btrfs_mark_extent_written(trans, BTRFS_I(inode),
3063 ordered_extent->file_offset,
3064 ordered_extent->file_offset +
3067 BUG_ON(root == fs_info->tree_root);
3068 ret = insert_reserved_file_extent(trans, inode,
3069 ordered_extent->file_offset,
3070 ordered_extent->start,
3071 ordered_extent->disk_len,
3072 logical_len, logical_len,
3073 compress_type, 0, 0,
3074 BTRFS_FILE_EXTENT_REG);
3076 clear_reserved_extent = false;
3077 btrfs_release_delalloc_bytes(fs_info,
3078 ordered_extent->start,
3079 ordered_extent->disk_len);
3082 unpin_extent_cache(&BTRFS_I(inode)->extent_tree,
3083 ordered_extent->file_offset, ordered_extent->len,
3086 btrfs_abort_transaction(trans, ret);
3090 ret = add_pending_csums(trans, inode, &ordered_extent->list);
3092 btrfs_abort_transaction(trans, ret);
3096 btrfs_ordered_update_i_size(inode, 0, ordered_extent);
3097 ret = btrfs_update_inode_fallback(trans, root, inode);
3098 if (ret) { /* -ENOMEM or corruption */
3099 btrfs_abort_transaction(trans, ret);
3104 if (range_locked || clear_new_delalloc_bytes) {
3105 unsigned int clear_bits = 0;
3108 clear_bits |= EXTENT_LOCKED;
3109 if (clear_new_delalloc_bytes)
3110 clear_bits |= EXTENT_DELALLOC_NEW;
3111 clear_extent_bit(&BTRFS_I(inode)->io_tree,
3112 ordered_extent->file_offset,
3113 ordered_extent->file_offset +
3114 ordered_extent->len - 1,
3116 (clear_bits & EXTENT_LOCKED) ? 1 : 0,
3121 btrfs_end_transaction(trans);
3123 if (ret || truncated) {
3127 start = ordered_extent->file_offset + logical_len;
3129 start = ordered_extent->file_offset;
3130 end = ordered_extent->file_offset + ordered_extent->len - 1;
3131 clear_extent_uptodate(io_tree, start, end, NULL);
3133 /* Drop the cache for the part of the extent we didn't write. */
3134 btrfs_drop_extent_cache(BTRFS_I(inode), start, end, 0);
3137 * If the ordered extent had an IOERR or something else went
3138 * wrong we need to return the space for this ordered extent
3139 * back to the allocator. We only free the extent in the
3140 * truncated case if we didn't write out the extent at all.
3142 * If we made it past insert_reserved_file_extent before we
3143 * errored out then we don't need to do this as the accounting
3144 * has already been done.
3146 if ((ret || !logical_len) &&
3147 clear_reserved_extent &&
3148 !test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags) &&
3149 !test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags))
3150 btrfs_free_reserved_extent(fs_info,
3151 ordered_extent->start,
3152 ordered_extent->disk_len, 1);
3157 * This needs to be done to make sure anybody waiting knows we are done
3158 * updating everything for this ordered extent.
3160 btrfs_remove_ordered_extent(inode, ordered_extent);
3162 /* for snapshot-aware defrag */
3165 free_sa_defrag_extent(new);
3166 atomic_dec(&fs_info->defrag_running);
3168 relink_file_extents(new);
3173 btrfs_put_ordered_extent(ordered_extent);
3174 /* once for the tree */
3175 btrfs_put_ordered_extent(ordered_extent);
3180 static void finish_ordered_fn(struct btrfs_work *work)
3182 struct btrfs_ordered_extent *ordered_extent;
3183 ordered_extent = container_of(work, struct btrfs_ordered_extent, work);
3184 btrfs_finish_ordered_io(ordered_extent);
3187 void btrfs_writepage_endio_finish_ordered(struct page *page, u64 start,
3188 u64 end, int uptodate)
3190 struct inode *inode = page->mapping->host;
3191 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
3192 struct btrfs_ordered_extent *ordered_extent = NULL;
3193 struct btrfs_workqueue *wq;
3194 btrfs_work_func_t func;
3196 trace_btrfs_writepage_end_io_hook(page, start, end, uptodate);
3198 ClearPagePrivate2(page);
3199 if (!btrfs_dec_test_ordered_pending(inode, &ordered_extent, start,
3200 end - start + 1, uptodate))
3203 if (btrfs_is_free_space_inode(BTRFS_I(inode))) {
3204 wq = fs_info->endio_freespace_worker;
3205 func = btrfs_freespace_write_helper;
3207 wq = fs_info->endio_write_workers;
3208 func = btrfs_endio_write_helper;
3211 btrfs_init_work(&ordered_extent->work, func, finish_ordered_fn, NULL,
3213 btrfs_queue_work(wq, &ordered_extent->work);
3216 static int __readpage_endio_check(struct inode *inode,
3217 struct btrfs_io_bio *io_bio,
3218 int icsum, struct page *page,
3219 int pgoff, u64 start, size_t len)
3221 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
3222 SHASH_DESC_ON_STACK(shash, fs_info->csum_shash);
3224 u16 csum_size = btrfs_super_csum_size(fs_info->super_copy);
3226 u8 csum[BTRFS_CSUM_SIZE];
3228 csum_expected = ((u8 *)io_bio->csum) + icsum * csum_size;
3230 kaddr = kmap_atomic(page);
3231 shash->tfm = fs_info->csum_shash;
3233 crypto_shash_init(shash);
3234 crypto_shash_update(shash, kaddr + pgoff, len);
3235 crypto_shash_final(shash, csum);
3237 if (memcmp(csum, csum_expected, csum_size))
3240 kunmap_atomic(kaddr);
3243 btrfs_print_data_csum_error(BTRFS_I(inode), start, csum, csum_expected,
3244 io_bio->mirror_num);
3245 memset(kaddr + pgoff, 1, len);
3246 flush_dcache_page(page);
3247 kunmap_atomic(kaddr);
3252 * when reads are done, we need to check csums to verify the data is correct
3253 * if there's a match, we allow the bio to finish. If not, the code in
3254 * extent_io.c will try to find good copies for us.
3256 static int btrfs_readpage_end_io_hook(struct btrfs_io_bio *io_bio,
3257 u64 phy_offset, struct page *page,
3258 u64 start, u64 end, int mirror)
3260 size_t offset = start - page_offset(page);
3261 struct inode *inode = page->mapping->host;
3262 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
3263 struct btrfs_root *root = BTRFS_I(inode)->root;
3265 if (PageChecked(page)) {
3266 ClearPageChecked(page);
3270 if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)
3273 if (root->root_key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID &&
3274 test_range_bit(io_tree, start, end, EXTENT_NODATASUM, 1, NULL)) {
3275 clear_extent_bits(io_tree, start, end, EXTENT_NODATASUM);
3279 phy_offset >>= inode->i_sb->s_blocksize_bits;
3280 return __readpage_endio_check(inode, io_bio, phy_offset, page, offset,
3281 start, (size_t)(end - start + 1));
3285 * btrfs_add_delayed_iput - perform a delayed iput on @inode
3287 * @inode: The inode we want to perform iput on
3289 * This function uses the generic vfs_inode::i_count to track whether we should
3290 * just decrement it (in case it's > 1) or if this is the last iput then link
3291 * the inode to the delayed iput machinery. Delayed iputs are processed at
3292 * transaction commit time/superblock commit/cleaner kthread.
3294 void btrfs_add_delayed_iput(struct inode *inode)
3296 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
3297 struct btrfs_inode *binode = BTRFS_I(inode);
3299 if (atomic_add_unless(&inode->i_count, -1, 1))
3302 atomic_inc(&fs_info->nr_delayed_iputs);
3303 spin_lock(&fs_info->delayed_iput_lock);
3304 ASSERT(list_empty(&binode->delayed_iput));
3305 list_add_tail(&binode->delayed_iput, &fs_info->delayed_iputs);
3306 spin_unlock(&fs_info->delayed_iput_lock);
3307 if (!test_bit(BTRFS_FS_CLEANER_RUNNING, &fs_info->flags))
3308 wake_up_process(fs_info->cleaner_kthread);
3311 static void run_delayed_iput_locked(struct btrfs_fs_info *fs_info,
3312 struct btrfs_inode *inode)
3314 list_del_init(&inode->delayed_iput);
3315 spin_unlock(&fs_info->delayed_iput_lock);
3316 iput(&inode->vfs_inode);
3317 if (atomic_dec_and_test(&fs_info->nr_delayed_iputs))
3318 wake_up(&fs_info->delayed_iputs_wait);
3319 spin_lock(&fs_info->delayed_iput_lock);
3322 static void btrfs_run_delayed_iput(struct btrfs_fs_info *fs_info,
3323 struct btrfs_inode *inode)
3325 if (!list_empty(&inode->delayed_iput)) {
3326 spin_lock(&fs_info->delayed_iput_lock);
3327 if (!list_empty(&inode->delayed_iput))
3328 run_delayed_iput_locked(fs_info, inode);
3329 spin_unlock(&fs_info->delayed_iput_lock);
3333 void btrfs_run_delayed_iputs(struct btrfs_fs_info *fs_info)
3336 spin_lock(&fs_info->delayed_iput_lock);
3337 while (!list_empty(&fs_info->delayed_iputs)) {
3338 struct btrfs_inode *inode;
3340 inode = list_first_entry(&fs_info->delayed_iputs,
3341 struct btrfs_inode, delayed_iput);
3342 run_delayed_iput_locked(fs_info, inode);
3344 spin_unlock(&fs_info->delayed_iput_lock);
3348 * btrfs_wait_on_delayed_iputs - wait on the delayed iputs to be done running
3349 * @fs_info - the fs_info for this fs
3350 * @return - EINTR if we were killed, 0 if nothing's pending
3352 * This will wait on any delayed iputs that are currently running with KILLABLE
3353 * set. Once they are all done running we will return, unless we are killed in
3354 * which case we return EINTR. This helps in user operations like fallocate etc
3355 * that might get blocked on the iputs.
3357 int btrfs_wait_on_delayed_iputs(struct btrfs_fs_info *fs_info)
3359 int ret = wait_event_killable(fs_info->delayed_iputs_wait,
3360 atomic_read(&fs_info->nr_delayed_iputs) == 0);
3367 * This creates an orphan entry for the given inode in case something goes wrong
3368 * in the middle of an unlink.
3370 int btrfs_orphan_add(struct btrfs_trans_handle *trans,
3371 struct btrfs_inode *inode)
3375 ret = btrfs_insert_orphan_item(trans, inode->root, btrfs_ino(inode));
3376 if (ret && ret != -EEXIST) {
3377 btrfs_abort_transaction(trans, ret);
3385 * We have done the delete so we can go ahead and remove the orphan item for
3386 * this particular inode.
3388 static int btrfs_orphan_del(struct btrfs_trans_handle *trans,
3389 struct btrfs_inode *inode)
3391 return btrfs_del_orphan_item(trans, inode->root, btrfs_ino(inode));
3395 * this cleans up any orphans that may be left on the list from the last use
3398 int btrfs_orphan_cleanup(struct btrfs_root *root)
3400 struct btrfs_fs_info *fs_info = root->fs_info;
3401 struct btrfs_path *path;
3402 struct extent_buffer *leaf;
3403 struct btrfs_key key, found_key;
3404 struct btrfs_trans_handle *trans;
3405 struct inode *inode;
3406 u64 last_objectid = 0;
3407 int ret = 0, nr_unlink = 0;
3409 if (cmpxchg(&root->orphan_cleanup_state, 0, ORPHAN_CLEANUP_STARTED))
3412 path = btrfs_alloc_path();
3417 path->reada = READA_BACK;
3419 key.objectid = BTRFS_ORPHAN_OBJECTID;
3420 key.type = BTRFS_ORPHAN_ITEM_KEY;
3421 key.offset = (u64)-1;
3424 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
3429 * if ret == 0 means we found what we were searching for, which
3430 * is weird, but possible, so only screw with path if we didn't
3431 * find the key and see if we have stuff that matches
3435 if (path->slots[0] == 0)
3440 /* pull out the item */
3441 leaf = path->nodes[0];
3442 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
3444 /* make sure the item matches what we want */
3445 if (found_key.objectid != BTRFS_ORPHAN_OBJECTID)
3447 if (found_key.type != BTRFS_ORPHAN_ITEM_KEY)
3450 /* release the path since we're done with it */
3451 btrfs_release_path(path);
3454 * this is where we are basically btrfs_lookup, without the
3455 * crossing root thing. we store the inode number in the
3456 * offset of the orphan item.
3459 if (found_key.offset == last_objectid) {
3461 "Error removing orphan entry, stopping orphan cleanup");
3466 last_objectid = found_key.offset;
3468 found_key.objectid = found_key.offset;
3469 found_key.type = BTRFS_INODE_ITEM_KEY;
3470 found_key.offset = 0;
3471 inode = btrfs_iget(fs_info->sb, &found_key, root, NULL);
3472 ret = PTR_ERR_OR_ZERO(inode);
3473 if (ret && ret != -ENOENT)
3476 if (ret == -ENOENT && root == fs_info->tree_root) {
3477 struct btrfs_root *dead_root;
3478 struct btrfs_fs_info *fs_info = root->fs_info;
3479 int is_dead_root = 0;
3482 * this is an orphan in the tree root. Currently these
3483 * could come from 2 sources:
3484 * a) a snapshot deletion in progress
3485 * b) a free space cache inode
3486 * We need to distinguish those two, as the snapshot
3487 * orphan must not get deleted.
3488 * find_dead_roots already ran before us, so if this
3489 * is a snapshot deletion, we should find the root
3490 * in the dead_roots list
3492 spin_lock(&fs_info->trans_lock);
3493 list_for_each_entry(dead_root, &fs_info->dead_roots,
3495 if (dead_root->root_key.objectid ==
3496 found_key.objectid) {
3501 spin_unlock(&fs_info->trans_lock);
3503 /* prevent this orphan from being found again */
3504 key.offset = found_key.objectid - 1;
3511 * If we have an inode with links, there are a couple of
3512 * possibilities. Old kernels (before v3.12) used to create an
3513 * orphan item for truncate indicating that there were possibly
3514 * extent items past i_size that needed to be deleted. In v3.12,
3515 * truncate was changed to update i_size in sync with the extent
3516 * items, but the (useless) orphan item was still created. Since
3517 * v4.18, we don't create the orphan item for truncate at all.
3519 * So, this item could mean that we need to do a truncate, but
3520 * only if this filesystem was last used on a pre-v3.12 kernel
3521 * and was not cleanly unmounted. The odds of that are quite
3522 * slim, and it's a pain to do the truncate now, so just delete
3525 * It's also possible that this orphan item was supposed to be
3526 * deleted but wasn't. The inode number may have been reused,
3527 * but either way, we can delete the orphan item.
3529 if (ret == -ENOENT || inode->i_nlink) {
3532 trans = btrfs_start_transaction(root, 1);
3533 if (IS_ERR(trans)) {
3534 ret = PTR_ERR(trans);
3537 btrfs_debug(fs_info, "auto deleting %Lu",
3538 found_key.objectid);
3539 ret = btrfs_del_orphan_item(trans, root,
3540 found_key.objectid);
3541 btrfs_end_transaction(trans);
3549 /* this will do delete_inode and everything for us */
3552 /* release the path since we're done with it */
3553 btrfs_release_path(path);
3555 root->orphan_cleanup_state = ORPHAN_CLEANUP_DONE;
3557 if (test_bit(BTRFS_ROOT_ORPHAN_ITEM_INSERTED, &root->state)) {
3558 trans = btrfs_join_transaction(root);
3560 btrfs_end_transaction(trans);
3564 btrfs_debug(fs_info, "unlinked %d orphans", nr_unlink);
3568 btrfs_err(fs_info, "could not do orphan cleanup %d", ret);
3569 btrfs_free_path(path);
3574 * very simple check to peek ahead in the leaf looking for xattrs. If we
3575 * don't find any xattrs, we know there can't be any acls.
3577 * slot is the slot the inode is in, objectid is the objectid of the inode
3579 static noinline int acls_after_inode_item(struct extent_buffer *leaf,
3580 int slot, u64 objectid,
3581 int *first_xattr_slot)
3583 u32 nritems = btrfs_header_nritems(leaf);
3584 struct btrfs_key found_key;
3585 static u64 xattr_access = 0;
3586 static u64 xattr_default = 0;
3589 if (!xattr_access) {
3590 xattr_access = btrfs_name_hash(XATTR_NAME_POSIX_ACL_ACCESS,
3591 strlen(XATTR_NAME_POSIX_ACL_ACCESS));
3592 xattr_default = btrfs_name_hash(XATTR_NAME_POSIX_ACL_DEFAULT,
3593 strlen(XATTR_NAME_POSIX_ACL_DEFAULT));
3597 *first_xattr_slot = -1;
3598 while (slot < nritems) {
3599 btrfs_item_key_to_cpu(leaf, &found_key, slot);
3601 /* we found a different objectid, there must not be acls */
3602 if (found_key.objectid != objectid)
3605 /* we found an xattr, assume we've got an acl */
3606 if (found_key.type == BTRFS_XATTR_ITEM_KEY) {
3607 if (*first_xattr_slot == -1)
3608 *first_xattr_slot = slot;
3609 if (found_key.offset == xattr_access ||
3610 found_key.offset == xattr_default)
3615 * we found a key greater than an xattr key, there can't
3616 * be any acls later on
3618 if (found_key.type > BTRFS_XATTR_ITEM_KEY)
3625 * it goes inode, inode backrefs, xattrs, extents,
3626 * so if there are a ton of hard links to an inode there can
3627 * be a lot of backrefs. Don't waste time searching too hard,
3628 * this is just an optimization
3633 /* we hit the end of the leaf before we found an xattr or
3634 * something larger than an xattr. We have to assume the inode
3637 if (*first_xattr_slot == -1)
3638 *first_xattr_slot = slot;
3643 * read an inode from the btree into the in-memory inode
3645 static int btrfs_read_locked_inode(struct inode *inode,
3646 struct btrfs_path *in_path)
3648 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
3649 struct btrfs_path *path = in_path;
3650 struct extent_buffer *leaf;
3651 struct btrfs_inode_item *inode_item;
3652 struct btrfs_root *root = BTRFS_I(inode)->root;
3653 struct btrfs_key location;
3658 bool filled = false;
3659 int first_xattr_slot;
3661 ret = btrfs_fill_inode(inode, &rdev);
3666 path = btrfs_alloc_path();
3671 memcpy(&location, &BTRFS_I(inode)->location, sizeof(location));
3673 ret = btrfs_lookup_inode(NULL, root, path, &location, 0);
3675 if (path != in_path)
3676 btrfs_free_path(path);
3680 leaf = path->nodes[0];
3685 inode_item = btrfs_item_ptr(leaf, path->slots[0],
3686 struct btrfs_inode_item);
3687 inode->i_mode = btrfs_inode_mode(leaf, inode_item);
3688 set_nlink(inode, btrfs_inode_nlink(leaf, inode_item));
3689 i_uid_write(inode, btrfs_inode_uid(leaf, inode_item));
3690 i_gid_write(inode, btrfs_inode_gid(leaf, inode_item));
3691 btrfs_i_size_write(BTRFS_I(inode), btrfs_inode_size(leaf, inode_item));
3693 inode->i_atime.tv_sec = btrfs_timespec_sec(leaf, &inode_item->atime);
3694 inode->i_atime.tv_nsec = btrfs_timespec_nsec(leaf, &inode_item->atime);
3696 inode->i_mtime.tv_sec = btrfs_timespec_sec(leaf, &inode_item->mtime);
3697 inode->i_mtime.tv_nsec = btrfs_timespec_nsec(leaf, &inode_item->mtime);
3699 inode->i_ctime.tv_sec = btrfs_timespec_sec(leaf, &inode_item->ctime);
3700 inode->i_ctime.tv_nsec = btrfs_timespec_nsec(leaf, &inode_item->ctime);
3702 BTRFS_I(inode)->i_otime.tv_sec =
3703 btrfs_timespec_sec(leaf, &inode_item->otime);
3704 BTRFS_I(inode)->i_otime.tv_nsec =
3705 btrfs_timespec_nsec(leaf, &inode_item->otime);
3707 inode_set_bytes(inode, btrfs_inode_nbytes(leaf, inode_item));
3708 BTRFS_I(inode)->generation = btrfs_inode_generation(leaf, inode_item);
3709 BTRFS_I(inode)->last_trans = btrfs_inode_transid(leaf, inode_item);
3711 inode_set_iversion_queried(inode,
3712 btrfs_inode_sequence(leaf, inode_item));
3713 inode->i_generation = BTRFS_I(inode)->generation;
3715 rdev = btrfs_inode_rdev(leaf, inode_item);
3717 BTRFS_I(inode)->index_cnt = (u64)-1;
3718 BTRFS_I(inode)->flags = btrfs_inode_flags(leaf, inode_item);
3722 * If we were modified in the current generation and evicted from memory
3723 * and then re-read we need to do a full sync since we don't have any
3724 * idea about which extents were modified before we were evicted from
3727 * This is required for both inode re-read from disk and delayed inode
3728 * in delayed_nodes_tree.
3730 if (BTRFS_I(inode)->last_trans == fs_info->generation)
3731 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
3732 &BTRFS_I(inode)->runtime_flags);
3735 * We don't persist the id of the transaction where an unlink operation
3736 * against the inode was last made. So here we assume the inode might
3737 * have been evicted, and therefore the exact value of last_unlink_trans
3738 * lost, and set it to last_trans to avoid metadata inconsistencies
3739 * between the inode and its parent if the inode is fsync'ed and the log
3740 * replayed. For example, in the scenario:
3743 * ln mydir/foo mydir/bar
3746 * echo 2 > /proc/sys/vm/drop_caches # evicts inode
3747 * xfs_io -c fsync mydir/foo
3749 * mount fs, triggers fsync log replay
3751 * We must make sure that when we fsync our inode foo we also log its
3752 * parent inode, otherwise after log replay the parent still has the
3753 * dentry with the "bar" name but our inode foo has a link count of 1
3754 * and doesn't have an inode ref with the name "bar" anymore.
3756 * Setting last_unlink_trans to last_trans is a pessimistic approach,
3757 * but it guarantees correctness at the expense of occasional full
3758 * transaction commits on fsync if our inode is a directory, or if our
3759 * inode is not a directory, logging its parent unnecessarily.
3761 BTRFS_I(inode)->last_unlink_trans = BTRFS_I(inode)->last_trans;
3764 if (inode->i_nlink != 1 ||
3765 path->slots[0] >= btrfs_header_nritems(leaf))
3768 btrfs_item_key_to_cpu(leaf, &location, path->slots[0]);
3769 if (location.objectid != btrfs_ino(BTRFS_I(inode)))
3772 ptr = btrfs_item_ptr_offset(leaf, path->slots[0]);
3773 if (location.type == BTRFS_INODE_REF_KEY) {
3774 struct btrfs_inode_ref *ref;
3776 ref = (struct btrfs_inode_ref *)ptr;
3777 BTRFS_I(inode)->dir_index = btrfs_inode_ref_index(leaf, ref);
3778 } else if (location.type == BTRFS_INODE_EXTREF_KEY) {
3779 struct btrfs_inode_extref *extref;
3781 extref = (struct btrfs_inode_extref *)ptr;
3782 BTRFS_I(inode)->dir_index = btrfs_inode_extref_index(leaf,
3787 * try to precache a NULL acl entry for files that don't have
3788 * any xattrs or acls
3790 maybe_acls = acls_after_inode_item(leaf, path->slots[0],
3791 btrfs_ino(BTRFS_I(inode)), &first_xattr_slot);
3792 if (first_xattr_slot != -1) {
3793 path->slots[0] = first_xattr_slot;
3794 ret = btrfs_load_inode_props(inode, path);
3797 "error loading props for ino %llu (root %llu): %d",
3798 btrfs_ino(BTRFS_I(inode)),
3799 root->root_key.objectid, ret);
3801 if (path != in_path)
3802 btrfs_free_path(path);
3805 cache_no_acl(inode);
3807 switch (inode->i_mode & S_IFMT) {
3809 inode->i_mapping->a_ops = &btrfs_aops;
3810 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
3811 inode->i_fop = &btrfs_file_operations;
3812 inode->i_op = &btrfs_file_inode_operations;
3815 inode->i_fop = &btrfs_dir_file_operations;
3816 inode->i_op = &btrfs_dir_inode_operations;
3819 inode->i_op = &btrfs_symlink_inode_operations;
3820 inode_nohighmem(inode);
3821 inode->i_mapping->a_ops = &btrfs_aops;
3824 inode->i_op = &btrfs_special_inode_operations;
3825 init_special_inode(inode, inode->i_mode, rdev);
3829 btrfs_sync_inode_flags_to_i_flags(inode);
3834 * given a leaf and an inode, copy the inode fields into the leaf
3836 static void fill_inode_item(struct btrfs_trans_handle *trans,
3837 struct extent_buffer *leaf,
3838 struct btrfs_inode_item *item,
3839 struct inode *inode)
3841 struct btrfs_map_token token;
3843 btrfs_init_map_token(&token);
3845 btrfs_set_token_inode_uid(leaf, item, i_uid_read(inode), &token);
3846 btrfs_set_token_inode_gid(leaf, item, i_gid_read(inode), &token);
3847 btrfs_set_token_inode_size(leaf, item, BTRFS_I(inode)->disk_i_size,
3849 btrfs_set_token_inode_mode(leaf, item, inode->i_mode, &token);
3850 btrfs_set_token_inode_nlink(leaf, item, inode->i_nlink, &token);
3852 btrfs_set_token_timespec_sec(leaf, &item->atime,
3853 inode->i_atime.tv_sec, &token);
3854 btrfs_set_token_timespec_nsec(leaf, &item->atime,
3855 inode->i_atime.tv_nsec, &token);
3857 btrfs_set_token_timespec_sec(leaf, &item->mtime,
3858 inode->i_mtime.tv_sec, &token);
3859 btrfs_set_token_timespec_nsec(leaf, &item->mtime,
3860 inode->i_mtime.tv_nsec, &token);
3862 btrfs_set_token_timespec_sec(leaf, &item->ctime,
3863 inode->i_ctime.tv_sec, &token);
3864 btrfs_set_token_timespec_nsec(leaf, &item->ctime,
3865 inode->i_ctime.tv_nsec, &token);
3867 btrfs_set_token_timespec_sec(leaf, &item->otime,
3868 BTRFS_I(inode)->i_otime.tv_sec, &token);
3869 btrfs_set_token_timespec_nsec(leaf, &item->otime,
3870 BTRFS_I(inode)->i_otime.tv_nsec, &token);
3872 btrfs_set_token_inode_nbytes(leaf, item, inode_get_bytes(inode),
3874 btrfs_set_token_inode_generation(leaf, item, BTRFS_I(inode)->generation,
3876 btrfs_set_token_inode_sequence(leaf, item, inode_peek_iversion(inode),
3878 btrfs_set_token_inode_transid(leaf, item, trans->transid, &token);
3879 btrfs_set_token_inode_rdev(leaf, item, inode->i_rdev, &token);
3880 btrfs_set_token_inode_flags(leaf, item, BTRFS_I(inode)->flags, &token);
3881 btrfs_set_token_inode_block_group(leaf, item, 0, &token);
3885 * copy everything in the in-memory inode into the btree.
3887 static noinline int btrfs_update_inode_item(struct btrfs_trans_handle *trans,
3888 struct btrfs_root *root, struct inode *inode)
3890 struct btrfs_inode_item *inode_item;
3891 struct btrfs_path *path;
3892 struct extent_buffer *leaf;
3895 path = btrfs_alloc_path();
3899 path->leave_spinning = 1;
3900 ret = btrfs_lookup_inode(trans, root, path, &BTRFS_I(inode)->location,
3908 leaf = path->nodes[0];
3909 inode_item = btrfs_item_ptr(leaf, path->slots[0],
3910 struct btrfs_inode_item);
3912 fill_inode_item(trans, leaf, inode_item, inode);
3913 btrfs_mark_buffer_dirty(leaf);
3914 btrfs_set_inode_last_trans(trans, inode);
3917 btrfs_free_path(path);
3922 * copy everything in the in-memory inode into the btree.
3924 noinline int btrfs_update_inode(struct btrfs_trans_handle *trans,
3925 struct btrfs_root *root, struct inode *inode)
3927 struct btrfs_fs_info *fs_info = root->fs_info;
3931 * If the inode is a free space inode, we can deadlock during commit
3932 * if we put it into the delayed code.
3934 * The data relocation inode should also be directly updated
3937 if (!btrfs_is_free_space_inode(BTRFS_I(inode))
3938 && root->root_key.objectid != BTRFS_DATA_RELOC_TREE_OBJECTID
3939 && !test_bit(BTRFS_FS_LOG_RECOVERING, &fs_info->flags)) {
3940 btrfs_update_root_times(trans, root);
3942 ret = btrfs_delayed_update_inode(trans, root, inode);
3944 btrfs_set_inode_last_trans(trans, inode);
3948 return btrfs_update_inode_item(trans, root, inode);
3951 noinline int btrfs_update_inode_fallback(struct btrfs_trans_handle *trans,
3952 struct btrfs_root *root,
3953 struct inode *inode)
3957 ret = btrfs_update_inode(trans, root, inode);
3959 return btrfs_update_inode_item(trans, root, inode);
3964 * unlink helper that gets used here in inode.c and in the tree logging
3965 * recovery code. It remove a link in a directory with a given name, and
3966 * also drops the back refs in the inode to the directory
3968 static int __btrfs_unlink_inode(struct btrfs_trans_handle *trans,
3969 struct btrfs_root *root,
3970 struct btrfs_inode *dir,
3971 struct btrfs_inode *inode,
3972 const char *name, int name_len)
3974 struct btrfs_fs_info *fs_info = root->fs_info;
3975 struct btrfs_path *path;
3977 struct btrfs_dir_item *di;
3979 u64 ino = btrfs_ino(inode);
3980 u64 dir_ino = btrfs_ino(dir);
3982 path = btrfs_alloc_path();
3988 path->leave_spinning = 1;
3989 di = btrfs_lookup_dir_item(trans, root, path, dir_ino,
3990 name, name_len, -1);
3991 if (IS_ERR_OR_NULL(di)) {
3992 ret = di ? PTR_ERR(di) : -ENOENT;
3995 ret = btrfs_delete_one_dir_name(trans, root, path, di);
3998 btrfs_release_path(path);
4001 * If we don't have dir index, we have to get it by looking up
4002 * the inode ref, since we get the inode ref, remove it directly,
4003 * it is unnecessary to do delayed deletion.
4005 * But if we have dir index, needn't search inode ref to get it.
4006 * Since the inode ref is close to the inode item, it is better
4007 * that we delay to delete it, and just do this deletion when
4008 * we update the inode item.
4010 if (inode->dir_index) {
4011 ret = btrfs_delayed_delete_inode_ref(inode);
4013 index = inode->dir_index;
4018 ret = btrfs_del_inode_ref(trans, root, name, name_len, ino,
4022 "failed to delete reference to %.*s, inode %llu parent %llu",
4023 name_len, name, ino, dir_ino);
4024 btrfs_abort_transaction(trans, ret);
4028 ret = btrfs_delete_delayed_dir_index(trans, dir, index);
4030 btrfs_abort_transaction(trans, ret);
4034 ret = btrfs_del_inode_ref_in_log(trans, root, name, name_len, inode,
4036 if (ret != 0 && ret != -ENOENT) {
4037 btrfs_abort_transaction(trans, ret);
4041 ret = btrfs_del_dir_entries_in_log(trans, root, name, name_len, dir,
4046 btrfs_abort_transaction(trans, ret);
4049 * If we have a pending delayed iput we could end up with the final iput
4050 * being run in btrfs-cleaner context. If we have enough of these built
4051 * up we can end up burning a lot of time in btrfs-cleaner without any
4052 * way to throttle the unlinks. Since we're currently holding a ref on
4053 * the inode we can run the delayed iput here without any issues as the
4054 * final iput won't be done until after we drop the ref we're currently
4057 btrfs_run_delayed_iput(fs_info, inode);
4059 btrfs_free_path(path);
4063 btrfs_i_size_write(dir, dir->vfs_inode.i_size - name_len * 2);
4064 inode_inc_iversion(&inode->vfs_inode);
4065 inode_inc_iversion(&dir->vfs_inode);
4066 inode->vfs_inode.i_ctime = dir->vfs_inode.i_mtime =
4067 dir->vfs_inode.i_ctime = current_time(&inode->vfs_inode);
4068 ret = btrfs_update_inode(trans, root, &dir->vfs_inode);
4073 int btrfs_unlink_inode(struct btrfs_trans_handle *trans,
4074 struct btrfs_root *root,
4075 struct btrfs_inode *dir, struct btrfs_inode *inode,
4076 const char *name, int name_len)
4079 ret = __btrfs_unlink_inode(trans, root, dir, inode, name, name_len);
4081 drop_nlink(&inode->vfs_inode);
4082 ret = btrfs_update_inode(trans, root, &inode->vfs_inode);
4088 * helper to start transaction for unlink and rmdir.
4090 * unlink and rmdir are special in btrfs, they do not always free space, so
4091 * if we cannot make our reservations the normal way try and see if there is
4092 * plenty of slack room in the global reserve to migrate, otherwise we cannot
4093 * allow the unlink to occur.
4095 static struct btrfs_trans_handle *__unlink_start_trans(struct inode *dir)
4097 struct btrfs_root *root = BTRFS_I(dir)->root;
4100 * 1 for the possible orphan item
4101 * 1 for the dir item
4102 * 1 for the dir index
4103 * 1 for the inode ref
4106 return btrfs_start_transaction_fallback_global_rsv(root, 5, 5);
4109 static int btrfs_unlink(struct inode *dir, struct dentry *dentry)
4111 struct btrfs_root *root = BTRFS_I(dir)->root;
4112 struct btrfs_trans_handle *trans;
4113 struct inode *inode = d_inode(dentry);
4116 trans = __unlink_start_trans(dir);
4118 return PTR_ERR(trans);
4120 btrfs_record_unlink_dir(trans, BTRFS_I(dir), BTRFS_I(d_inode(dentry)),
4123 ret = btrfs_unlink_inode(trans, root, BTRFS_I(dir),
4124 BTRFS_I(d_inode(dentry)), dentry->d_name.name,
4125 dentry->d_name.len);
4129 if (inode->i_nlink == 0) {
4130 ret = btrfs_orphan_add(trans, BTRFS_I(inode));
4136 btrfs_end_transaction(trans);
4137 btrfs_btree_balance_dirty(root->fs_info);
4141 static int btrfs_unlink_subvol(struct btrfs_trans_handle *trans,
4142 struct inode *dir, u64 objectid,
4143 const char *name, int name_len)
4145 struct btrfs_root *root = BTRFS_I(dir)->root;
4146 struct btrfs_path *path;
4147 struct extent_buffer *leaf;
4148 struct btrfs_dir_item *di;
4149 struct btrfs_key key;
4152 u64 dir_ino = btrfs_ino(BTRFS_I(dir));
4154 path = btrfs_alloc_path();
4158 di = btrfs_lookup_dir_item(trans, root, path, dir_ino,
4159 name, name_len, -1);
4160 if (IS_ERR_OR_NULL(di)) {
4161 ret = di ? PTR_ERR(di) : -ENOENT;
4165 leaf = path->nodes[0];
4166 btrfs_dir_item_key_to_cpu(leaf, di, &key);
4167 WARN_ON(key.type != BTRFS_ROOT_ITEM_KEY || key.objectid != objectid);
4168 ret = btrfs_delete_one_dir_name(trans, root, path, di);
4170 btrfs_abort_transaction(trans, ret);
4173 btrfs_release_path(path);
4175 ret = btrfs_del_root_ref(trans, objectid, root->root_key.objectid,
4176 dir_ino, &index, name, name_len);
4178 if (ret != -ENOENT) {
4179 btrfs_abort_transaction(trans, ret);
4182 di = btrfs_search_dir_index_item(root, path, dir_ino,
4184 if (IS_ERR_OR_NULL(di)) {
4189 btrfs_abort_transaction(trans, ret);
4193 leaf = path->nodes[0];
4194 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
4197 btrfs_release_path(path);
4199 ret = btrfs_delete_delayed_dir_index(trans, BTRFS_I(dir), index);
4201 btrfs_abort_transaction(trans, ret);
4205 btrfs_i_size_write(BTRFS_I(dir), dir->i_size - name_len * 2);
4206 inode_inc_iversion(dir);
4207 dir->i_mtime = dir->i_ctime = current_time(dir);
4208 ret = btrfs_update_inode_fallback(trans, root, dir);
4210 btrfs_abort_transaction(trans, ret);
4212 btrfs_free_path(path);
4217 * Helper to check if the subvolume references other subvolumes or if it's
4220 static noinline int may_destroy_subvol(struct btrfs_root *root)
4222 struct btrfs_fs_info *fs_info = root->fs_info;
4223 struct btrfs_path *path;
4224 struct btrfs_dir_item *di;
4225 struct btrfs_key key;
4229 path = btrfs_alloc_path();
4233 /* Make sure this root isn't set as the default subvol */
4234 dir_id = btrfs_super_root_dir(fs_info->super_copy);
4235 di = btrfs_lookup_dir_item(NULL, fs_info->tree_root, path,
4236 dir_id, "default", 7, 0);
4237 if (di && !IS_ERR(di)) {
4238 btrfs_dir_item_key_to_cpu(path->nodes[0], di, &key);
4239 if (key.objectid == root->root_key.objectid) {
4242 "deleting default subvolume %llu is not allowed",
4246 btrfs_release_path(path);
4249 key.objectid = root->root_key.objectid;
4250 key.type = BTRFS_ROOT_REF_KEY;
4251 key.offset = (u64)-1;
4253 ret = btrfs_search_slot(NULL, fs_info->tree_root, &key, path, 0, 0);
4259 if (path->slots[0] > 0) {
4261 btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
4262 if (key.objectid == root->root_key.objectid &&
4263 key.type == BTRFS_ROOT_REF_KEY)
4267 btrfs_free_path(path);
4271 /* Delete all dentries for inodes belonging to the root */
4272 static void btrfs_prune_dentries(struct btrfs_root *root)
4274 struct btrfs_fs_info *fs_info = root->fs_info;
4275 struct rb_node *node;
4276 struct rb_node *prev;
4277 struct btrfs_inode *entry;
4278 struct inode *inode;
4281 if (!test_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state))
4282 WARN_ON(btrfs_root_refs(&root->root_item) != 0);
4284 spin_lock(&root->inode_lock);
4286 node = root->inode_tree.rb_node;
4290 entry = rb_entry(node, struct btrfs_inode, rb_node);
4292 if (objectid < btrfs_ino(entry))
4293 node = node->rb_left;
4294 else if (objectid > btrfs_ino(entry))
4295 node = node->rb_right;
4301 entry = rb_entry(prev, struct btrfs_inode, rb_node);
4302 if (objectid <= btrfs_ino(entry)) {
4306 prev = rb_next(prev);
4310 entry = rb_entry(node, struct btrfs_inode, rb_node);
4311 objectid = btrfs_ino(entry) + 1;
4312 inode = igrab(&entry->vfs_inode);
4314 spin_unlock(&root->inode_lock);
4315 if (atomic_read(&inode->i_count) > 1)
4316 d_prune_aliases(inode);
4318 * btrfs_drop_inode will have it removed from the inode
4319 * cache when its usage count hits zero.
4323 spin_lock(&root->inode_lock);
4327 if (cond_resched_lock(&root->inode_lock))
4330 node = rb_next(node);
4332 spin_unlock(&root->inode_lock);
4335 int btrfs_delete_subvolume(struct inode *dir, struct dentry *dentry)
4337 struct btrfs_fs_info *fs_info = btrfs_sb(dentry->d_sb);
4338 struct btrfs_root *root = BTRFS_I(dir)->root;
4339 struct inode *inode = d_inode(dentry);
4340 struct btrfs_root *dest = BTRFS_I(inode)->root;
4341 struct btrfs_trans_handle *trans;
4342 struct btrfs_block_rsv block_rsv;
4348 * Don't allow to delete a subvolume with send in progress. This is
4349 * inside the inode lock so the error handling that has to drop the bit
4350 * again is not run concurrently.
4352 spin_lock(&dest->root_item_lock);
4353 if (dest->send_in_progress) {
4354 spin_unlock(&dest->root_item_lock);
4356 "attempt to delete subvolume %llu during send",
4357 dest->root_key.objectid);
4360 root_flags = btrfs_root_flags(&dest->root_item);
4361 btrfs_set_root_flags(&dest->root_item,
4362 root_flags | BTRFS_ROOT_SUBVOL_DEAD);
4363 spin_unlock(&dest->root_item_lock);
4365 down_write(&fs_info->subvol_sem);
4367 err = may_destroy_subvol(dest);
4371 btrfs_init_block_rsv(&block_rsv, BTRFS_BLOCK_RSV_TEMP);
4373 * One for dir inode,
4374 * two for dir entries,
4375 * two for root ref/backref.
4377 err = btrfs_subvolume_reserve_metadata(root, &block_rsv, 5, true);
4381 trans = btrfs_start_transaction(root, 0);
4382 if (IS_ERR(trans)) {
4383 err = PTR_ERR(trans);
4386 trans->block_rsv = &block_rsv;
4387 trans->bytes_reserved = block_rsv.size;
4389 btrfs_record_snapshot_destroy(trans, BTRFS_I(dir));
4391 ret = btrfs_unlink_subvol(trans, dir, dest->root_key.objectid,
4392 dentry->d_name.name, dentry->d_name.len);
4395 btrfs_abort_transaction(trans, ret);
4399 btrfs_record_root_in_trans(trans, dest);
4401 memset(&dest->root_item.drop_progress, 0,
4402 sizeof(dest->root_item.drop_progress));
4403 dest->root_item.drop_level = 0;
4404 btrfs_set_root_refs(&dest->root_item, 0);
4406 if (!test_and_set_bit(BTRFS_ROOT_ORPHAN_ITEM_INSERTED, &dest->state)) {
4407 ret = btrfs_insert_orphan_item(trans,
4409 dest->root_key.objectid);
4411 btrfs_abort_transaction(trans, ret);
4417 ret = btrfs_uuid_tree_remove(trans, dest->root_item.uuid,
4418 BTRFS_UUID_KEY_SUBVOL,
4419 dest->root_key.objectid);
4420 if (ret && ret != -ENOENT) {
4421 btrfs_abort_transaction(trans, ret);
4425 if (!btrfs_is_empty_uuid(dest->root_item.received_uuid)) {
4426 ret = btrfs_uuid_tree_remove(trans,
4427 dest->root_item.received_uuid,
4428 BTRFS_UUID_KEY_RECEIVED_SUBVOL,
4429 dest->root_key.objectid);
4430 if (ret && ret != -ENOENT) {
4431 btrfs_abort_transaction(trans, ret);
4438 trans->block_rsv = NULL;
4439 trans->bytes_reserved = 0;
4440 ret = btrfs_end_transaction(trans);
4443 inode->i_flags |= S_DEAD;
4445 btrfs_subvolume_release_metadata(fs_info, &block_rsv);
4447 up_write(&fs_info->subvol_sem);
4449 spin_lock(&dest->root_item_lock);
4450 root_flags = btrfs_root_flags(&dest->root_item);
4451 btrfs_set_root_flags(&dest->root_item,
4452 root_flags & ~BTRFS_ROOT_SUBVOL_DEAD);
4453 spin_unlock(&dest->root_item_lock);
4455 d_invalidate(dentry);
4456 btrfs_prune_dentries(dest);
4457 ASSERT(dest->send_in_progress == 0);
4460 if (dest->ino_cache_inode) {
4461 iput(dest->ino_cache_inode);
4462 dest->ino_cache_inode = NULL;
4469 static int btrfs_rmdir(struct inode *dir, struct dentry *dentry)
4471 struct inode *inode = d_inode(dentry);
4473 struct btrfs_root *root = BTRFS_I(dir)->root;
4474 struct btrfs_trans_handle *trans;
4475 u64 last_unlink_trans;
4477 if (inode->i_size > BTRFS_EMPTY_DIR_SIZE)
4479 if (btrfs_ino(BTRFS_I(inode)) == BTRFS_FIRST_FREE_OBJECTID)
4480 return btrfs_delete_subvolume(dir, dentry);
4482 trans = __unlink_start_trans(dir);
4484 return PTR_ERR(trans);
4486 if (unlikely(btrfs_ino(BTRFS_I(inode)) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)) {
4487 err = btrfs_unlink_subvol(trans, dir,
4488 BTRFS_I(inode)->location.objectid,
4489 dentry->d_name.name,
4490 dentry->d_name.len);
4494 err = btrfs_orphan_add(trans, BTRFS_I(inode));
4498 last_unlink_trans = BTRFS_I(inode)->last_unlink_trans;
4500 /* now the directory is empty */
4501 err = btrfs_unlink_inode(trans, root, BTRFS_I(dir),
4502 BTRFS_I(d_inode(dentry)), dentry->d_name.name,
4503 dentry->d_name.len);
4505 btrfs_i_size_write(BTRFS_I(inode), 0);
4507 * Propagate the last_unlink_trans value of the deleted dir to
4508 * its parent directory. This is to prevent an unrecoverable
4509 * log tree in the case we do something like this:
4511 * 2) create snapshot under dir foo
4512 * 3) delete the snapshot
4515 * 6) fsync foo or some file inside foo
4517 if (last_unlink_trans >= trans->transid)
4518 BTRFS_I(dir)->last_unlink_trans = last_unlink_trans;
4521 btrfs_end_transaction(trans);
4522 btrfs_btree_balance_dirty(root->fs_info);
4528 * Return this if we need to call truncate_block for the last bit of the
4531 #define NEED_TRUNCATE_BLOCK 1
4534 * this can truncate away extent items, csum items and directory items.
4535 * It starts at a high offset and removes keys until it can't find
4536 * any higher than new_size
4538 * csum items that cross the new i_size are truncated to the new size
4541 * min_type is the minimum key type to truncate down to. If set to 0, this
4542 * will kill all the items on this inode, including the INODE_ITEM_KEY.
4544 int btrfs_truncate_inode_items(struct btrfs_trans_handle *trans,
4545 struct btrfs_root *root,
4546 struct inode *inode,
4547 u64 new_size, u32 min_type)
4549 struct btrfs_fs_info *fs_info = root->fs_info;
4550 struct btrfs_path *path;
4551 struct extent_buffer *leaf;
4552 struct btrfs_file_extent_item *fi;
4553 struct btrfs_key key;
4554 struct btrfs_key found_key;
4555 u64 extent_start = 0;
4556 u64 extent_num_bytes = 0;
4557 u64 extent_offset = 0;
4559 u64 last_size = new_size;
4560 u32 found_type = (u8)-1;
4563 int pending_del_nr = 0;
4564 int pending_del_slot = 0;
4565 int extent_type = -1;
4567 u64 ino = btrfs_ino(BTRFS_I(inode));
4568 u64 bytes_deleted = 0;
4569 bool be_nice = false;
4570 bool should_throttle = false;
4572 BUG_ON(new_size > 0 && min_type != BTRFS_EXTENT_DATA_KEY);
4575 * for non-free space inodes and ref cows, we want to back off from
4578 if (!btrfs_is_free_space_inode(BTRFS_I(inode)) &&
4579 test_bit(BTRFS_ROOT_REF_COWS, &root->state))
4582 path = btrfs_alloc_path();
4585 path->reada = READA_BACK;
4588 * We want to drop from the next block forward in case this new size is
4589 * not block aligned since we will be keeping the last block of the
4590 * extent just the way it is.
4592 if (test_bit(BTRFS_ROOT_REF_COWS, &root->state) ||
4593 root == fs_info->tree_root)
4594 btrfs_drop_extent_cache(BTRFS_I(inode), ALIGN(new_size,
4595 fs_info->sectorsize),
4599 * This function is also used to drop the items in the log tree before
4600 * we relog the inode, so if root != BTRFS_I(inode)->root, it means
4601 * it is used to drop the logged items. So we shouldn't kill the delayed
4604 if (min_type == 0 && root == BTRFS_I(inode)->root)
4605 btrfs_kill_delayed_inode_items(BTRFS_I(inode));
4608 key.offset = (u64)-1;
4613 * with a 16K leaf size and 128MB extents, you can actually queue
4614 * up a huge file in a single leaf. Most of the time that
4615 * bytes_deleted is > 0, it will be huge by the time we get here
4617 if (be_nice && bytes_deleted > SZ_32M &&
4618 btrfs_should_end_transaction(trans)) {
4623 path->leave_spinning = 1;
4624 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
4630 /* there are no items in the tree for us to truncate, we're
4633 if (path->slots[0] == 0)
4640 leaf = path->nodes[0];
4641 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
4642 found_type = found_key.type;
4644 if (found_key.objectid != ino)
4647 if (found_type < min_type)
4650 item_end = found_key.offset;
4651 if (found_type == BTRFS_EXTENT_DATA_KEY) {
4652 fi = btrfs_item_ptr(leaf, path->slots[0],
4653 struct btrfs_file_extent_item);
4654 extent_type = btrfs_file_extent_type(leaf, fi);
4655 if (extent_type != BTRFS_FILE_EXTENT_INLINE) {
4657 btrfs_file_extent_num_bytes(leaf, fi);
4659 trace_btrfs_truncate_show_fi_regular(
4660 BTRFS_I(inode), leaf, fi,
4662 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
4663 item_end += btrfs_file_extent_ram_bytes(leaf,
4666 trace_btrfs_truncate_show_fi_inline(
4667 BTRFS_I(inode), leaf, fi, path->slots[0],
4672 if (found_type > min_type) {
4675 if (item_end < new_size)
4677 if (found_key.offset >= new_size)
4683 /* FIXME, shrink the extent if the ref count is only 1 */
4684 if (found_type != BTRFS_EXTENT_DATA_KEY)
4687 if (extent_type != BTRFS_FILE_EXTENT_INLINE) {
4689 extent_start = btrfs_file_extent_disk_bytenr(leaf, fi);
4691 u64 orig_num_bytes =
4692 btrfs_file_extent_num_bytes(leaf, fi);
4693 extent_num_bytes = ALIGN(new_size -
4695 fs_info->sectorsize);
4696 btrfs_set_file_extent_num_bytes(leaf, fi,
4698 num_dec = (orig_num_bytes -
4700 if (test_bit(BTRFS_ROOT_REF_COWS,
4703 inode_sub_bytes(inode, num_dec);
4704 btrfs_mark_buffer_dirty(leaf);
4707 btrfs_file_extent_disk_num_bytes(leaf,
4709 extent_offset = found_key.offset -
4710 btrfs_file_extent_offset(leaf, fi);
4712 /* FIXME blocksize != 4096 */
4713 num_dec = btrfs_file_extent_num_bytes(leaf, fi);
4714 if (extent_start != 0) {
4716 if (test_bit(BTRFS_ROOT_REF_COWS,
4718 inode_sub_bytes(inode, num_dec);
4721 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
4723 * we can't truncate inline items that have had
4727 btrfs_file_extent_encryption(leaf, fi) == 0 &&
4728 btrfs_file_extent_other_encoding(leaf, fi) == 0 &&
4729 btrfs_file_extent_compression(leaf, fi) == 0) {
4730 u32 size = (u32)(new_size - found_key.offset);
4732 btrfs_set_file_extent_ram_bytes(leaf, fi, size);
4733 size = btrfs_file_extent_calc_inline_size(size);
4734 btrfs_truncate_item(path, size, 1);
4735 } else if (!del_item) {
4737 * We have to bail so the last_size is set to
4738 * just before this extent.
4740 ret = NEED_TRUNCATE_BLOCK;
4744 if (test_bit(BTRFS_ROOT_REF_COWS, &root->state))
4745 inode_sub_bytes(inode, item_end + 1 - new_size);
4749 last_size = found_key.offset;
4751 last_size = new_size;
4753 if (!pending_del_nr) {
4754 /* no pending yet, add ourselves */
4755 pending_del_slot = path->slots[0];
4757 } else if (pending_del_nr &&
4758 path->slots[0] + 1 == pending_del_slot) {
4759 /* hop on the pending chunk */
4761 pending_del_slot = path->slots[0];
4768 should_throttle = false;
4771 (test_bit(BTRFS_ROOT_REF_COWS, &root->state) ||
4772 root == fs_info->tree_root)) {
4773 struct btrfs_ref ref = { 0 };
4775 btrfs_set_path_blocking(path);
4776 bytes_deleted += extent_num_bytes;
4778 btrfs_init_generic_ref(&ref, BTRFS_DROP_DELAYED_REF,
4779 extent_start, extent_num_bytes, 0);
4780 ref.real_root = root->root_key.objectid;
4781 btrfs_init_data_ref(&ref, btrfs_header_owner(leaf),
4782 ino, extent_offset);
4783 ret = btrfs_free_extent(trans, &ref);
4785 btrfs_abort_transaction(trans, ret);
4789 if (btrfs_should_throttle_delayed_refs(trans))
4790 should_throttle = true;
4794 if (found_type == BTRFS_INODE_ITEM_KEY)
4797 if (path->slots[0] == 0 ||
4798 path->slots[0] != pending_del_slot ||
4800 if (pending_del_nr) {
4801 ret = btrfs_del_items(trans, root, path,
4805 btrfs_abort_transaction(trans, ret);
4810 btrfs_release_path(path);
4813 * We can generate a lot of delayed refs, so we need to
4814 * throttle every once and a while and make sure we're
4815 * adding enough space to keep up with the work we are
4816 * generating. Since we hold a transaction here we
4817 * can't flush, and we don't want to FLUSH_LIMIT because
4818 * we could have generated too many delayed refs to
4819 * actually allocate, so just bail if we're short and
4820 * let the normal reservation dance happen higher up.
4822 if (should_throttle) {
4823 ret = btrfs_delayed_refs_rsv_refill(fs_info,
4824 BTRFS_RESERVE_NO_FLUSH);
4836 if (ret >= 0 && pending_del_nr) {
4839 err = btrfs_del_items(trans, root, path, pending_del_slot,
4842 btrfs_abort_transaction(trans, err);
4846 if (root->root_key.objectid != BTRFS_TREE_LOG_OBJECTID) {
4847 ASSERT(last_size >= new_size);
4848 if (!ret && last_size > new_size)
4849 last_size = new_size;
4850 btrfs_ordered_update_i_size(inode, last_size, NULL);
4853 btrfs_free_path(path);
4858 * btrfs_truncate_block - read, zero a chunk and write a block
4859 * @inode - inode that we're zeroing
4860 * @from - the offset to start zeroing
4861 * @len - the length to zero, 0 to zero the entire range respective to the
4863 * @front - zero up to the offset instead of from the offset on
4865 * This will find the block for the "from" offset and cow the block and zero the
4866 * part we want to zero. This is used with truncate and hole punching.
4868 int btrfs_truncate_block(struct inode *inode, loff_t from, loff_t len,
4871 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
4872 struct address_space *mapping = inode->i_mapping;
4873 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
4874 struct btrfs_ordered_extent *ordered;
4875 struct extent_state *cached_state = NULL;
4876 struct extent_changeset *data_reserved = NULL;
4878 u32 blocksize = fs_info->sectorsize;
4879 pgoff_t index = from >> PAGE_SHIFT;
4880 unsigned offset = from & (blocksize - 1);
4882 gfp_t mask = btrfs_alloc_write_mask(mapping);
4887 if (IS_ALIGNED(offset, blocksize) &&
4888 (!len || IS_ALIGNED(len, blocksize)))
4891 block_start = round_down(from, blocksize);
4892 block_end = block_start + blocksize - 1;
4894 ret = btrfs_delalloc_reserve_space(inode, &data_reserved,
4895 block_start, blocksize);
4900 page = find_or_create_page(mapping, index, mask);
4902 btrfs_delalloc_release_space(inode, data_reserved,
4903 block_start, blocksize, true);
4904 btrfs_delalloc_release_extents(BTRFS_I(inode), blocksize, true);
4909 if (!PageUptodate(page)) {
4910 ret = btrfs_readpage(NULL, page);
4912 if (page->mapping != mapping) {
4917 if (!PageUptodate(page)) {
4922 wait_on_page_writeback(page);
4924 lock_extent_bits(io_tree, block_start, block_end, &cached_state);
4925 set_page_extent_mapped(page);
4927 ordered = btrfs_lookup_ordered_extent(inode, block_start);
4929 unlock_extent_cached(io_tree, block_start, block_end,
4933 btrfs_start_ordered_extent(inode, ordered, 1);
4934 btrfs_put_ordered_extent(ordered);
4938 clear_extent_bit(&BTRFS_I(inode)->io_tree, block_start, block_end,
4939 EXTENT_DIRTY | EXTENT_DELALLOC |
4940 EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG,
4941 0, 0, &cached_state);
4943 ret = btrfs_set_extent_delalloc(inode, block_start, block_end, 0,
4946 unlock_extent_cached(io_tree, block_start, block_end,
4951 if (offset != blocksize) {
4953 len = blocksize - offset;
4956 memset(kaddr + (block_start - page_offset(page)),
4959 memset(kaddr + (block_start - page_offset(page)) + offset,
4961 flush_dcache_page(page);
4964 ClearPageChecked(page);
4965 set_page_dirty(page);
4966 unlock_extent_cached(io_tree, block_start, block_end, &cached_state);
4970 btrfs_delalloc_release_space(inode, data_reserved, block_start,
4972 btrfs_delalloc_release_extents(BTRFS_I(inode), blocksize, (ret != 0));
4976 extent_changeset_free(data_reserved);
4980 static int maybe_insert_hole(struct btrfs_root *root, struct inode *inode,
4981 u64 offset, u64 len)
4983 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
4984 struct btrfs_trans_handle *trans;
4988 * Still need to make sure the inode looks like it's been updated so
4989 * that any holes get logged if we fsync.
4991 if (btrfs_fs_incompat(fs_info, NO_HOLES)) {
4992 BTRFS_I(inode)->last_trans = fs_info->generation;
4993 BTRFS_I(inode)->last_sub_trans = root->log_transid;
4994 BTRFS_I(inode)->last_log_commit = root->last_log_commit;
4999 * 1 - for the one we're dropping
5000 * 1 - for the one we're adding
5001 * 1 - for updating the inode.
5003 trans = btrfs_start_transaction(root, 3);
5005 return PTR_ERR(trans);
5007 ret = btrfs_drop_extents(trans, root, inode, offset, offset + len, 1);
5009 btrfs_abort_transaction(trans, ret);
5010 btrfs_end_transaction(trans);
5014 ret = btrfs_insert_file_extent(trans, root, btrfs_ino(BTRFS_I(inode)),
5015 offset, 0, 0, len, 0, len, 0, 0, 0);
5017 btrfs_abort_transaction(trans, ret);
5019 btrfs_update_inode(trans, root, inode);
5020 btrfs_end_transaction(trans);
5025 * This function puts in dummy file extents for the area we're creating a hole
5026 * for. So if we are truncating this file to a larger size we need to insert
5027 * these file extents so that btrfs_get_extent will return a EXTENT_MAP_HOLE for
5028 * the range between oldsize and size
5030 int btrfs_cont_expand(struct inode *inode, loff_t oldsize, loff_t size)
5032 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
5033 struct btrfs_root *root = BTRFS_I(inode)->root;
5034 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
5035 struct extent_map *em = NULL;
5036 struct extent_state *cached_state = NULL;
5037 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
5038 u64 hole_start = ALIGN(oldsize, fs_info->sectorsize);
5039 u64 block_end = ALIGN(size, fs_info->sectorsize);
5046 * If our size started in the middle of a block we need to zero out the
5047 * rest of the block before we expand the i_size, otherwise we could
5048 * expose stale data.
5050 err = btrfs_truncate_block(inode, oldsize, 0, 0);
5054 if (size <= hole_start)
5057 btrfs_lock_and_flush_ordered_range(io_tree, BTRFS_I(inode), hole_start,
5058 block_end - 1, &cached_state);
5059 cur_offset = hole_start;
5061 em = btrfs_get_extent(BTRFS_I(inode), NULL, 0, cur_offset,
5062 block_end - cur_offset, 0);
5068 last_byte = min(extent_map_end(em), block_end);
5069 last_byte = ALIGN(last_byte, fs_info->sectorsize);
5070 if (!test_bit(EXTENT_FLAG_PREALLOC, &em->flags)) {
5071 struct extent_map *hole_em;
5072 hole_size = last_byte - cur_offset;
5074 err = maybe_insert_hole(root, inode, cur_offset,
5078 btrfs_drop_extent_cache(BTRFS_I(inode), cur_offset,
5079 cur_offset + hole_size - 1, 0);
5080 hole_em = alloc_extent_map();
5082 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
5083 &BTRFS_I(inode)->runtime_flags);
5086 hole_em->start = cur_offset;
5087 hole_em->len = hole_size;
5088 hole_em->orig_start = cur_offset;
5090 hole_em->block_start = EXTENT_MAP_HOLE;
5091 hole_em->block_len = 0;
5092 hole_em->orig_block_len = 0;
5093 hole_em->ram_bytes = hole_size;
5094 hole_em->bdev = fs_info->fs_devices->latest_bdev;
5095 hole_em->compress_type = BTRFS_COMPRESS_NONE;
5096 hole_em->generation = fs_info->generation;
5099 write_lock(&em_tree->lock);
5100 err = add_extent_mapping(em_tree, hole_em, 1);
5101 write_unlock(&em_tree->lock);
5104 btrfs_drop_extent_cache(BTRFS_I(inode),
5109 free_extent_map(hole_em);
5112 free_extent_map(em);
5114 cur_offset = last_byte;
5115 if (cur_offset >= block_end)
5118 free_extent_map(em);
5119 unlock_extent_cached(io_tree, hole_start, block_end - 1, &cached_state);
5123 static int btrfs_setsize(struct inode *inode, struct iattr *attr)
5125 struct btrfs_root *root = BTRFS_I(inode)->root;
5126 struct btrfs_trans_handle *trans;
5127 loff_t oldsize = i_size_read(inode);
5128 loff_t newsize = attr->ia_size;
5129 int mask = attr->ia_valid;
5133 * The regular truncate() case without ATTR_CTIME and ATTR_MTIME is a
5134 * special case where we need to update the times despite not having
5135 * these flags set. For all other operations the VFS set these flags
5136 * explicitly if it wants a timestamp update.
5138 if (newsize != oldsize) {
5139 inode_inc_iversion(inode);
5140 if (!(mask & (ATTR_CTIME | ATTR_MTIME)))
5141 inode->i_ctime = inode->i_mtime =
5142 current_time(inode);
5145 if (newsize > oldsize) {
5147 * Don't do an expanding truncate while snapshotting is ongoing.
5148 * This is to ensure the snapshot captures a fully consistent
5149 * state of this file - if the snapshot captures this expanding
5150 * truncation, it must capture all writes that happened before
5153 btrfs_wait_for_snapshot_creation(root);
5154 ret = btrfs_cont_expand(inode, oldsize, newsize);
5156 btrfs_end_write_no_snapshotting(root);
5160 trans = btrfs_start_transaction(root, 1);
5161 if (IS_ERR(trans)) {
5162 btrfs_end_write_no_snapshotting(root);
5163 return PTR_ERR(trans);
5166 i_size_write(inode, newsize);
5167 btrfs_ordered_update_i_size(inode, i_size_read(inode), NULL);
5168 pagecache_isize_extended(inode, oldsize, newsize);
5169 ret = btrfs_update_inode(trans, root, inode);
5170 btrfs_end_write_no_snapshotting(root);
5171 btrfs_end_transaction(trans);
5175 * We're truncating a file that used to have good data down to
5176 * zero. Make sure it gets into the ordered flush list so that
5177 * any new writes get down to disk quickly.
5180 set_bit(BTRFS_INODE_ORDERED_DATA_CLOSE,
5181 &BTRFS_I(inode)->runtime_flags);
5183 truncate_setsize(inode, newsize);
5185 /* Disable nonlocked read DIO to avoid the endless truncate */
5186 btrfs_inode_block_unlocked_dio(BTRFS_I(inode));
5187 inode_dio_wait(inode);
5188 btrfs_inode_resume_unlocked_dio(BTRFS_I(inode));
5190 ret = btrfs_truncate(inode, newsize == oldsize);
5191 if (ret && inode->i_nlink) {
5195 * Truncate failed, so fix up the in-memory size. We
5196 * adjusted disk_i_size down as we removed extents, so
5197 * wait for disk_i_size to be stable and then update the
5198 * in-memory size to match.
5200 err = btrfs_wait_ordered_range(inode, 0, (u64)-1);
5203 i_size_write(inode, BTRFS_I(inode)->disk_i_size);
5210 static int btrfs_setattr(struct dentry *dentry, struct iattr *attr)
5212 struct inode *inode = d_inode(dentry);
5213 struct btrfs_root *root = BTRFS_I(inode)->root;
5216 if (btrfs_root_readonly(root))
5219 err = setattr_prepare(dentry, attr);
5223 if (S_ISREG(inode->i_mode) && (attr->ia_valid & ATTR_SIZE)) {
5224 err = btrfs_setsize(inode, attr);
5229 if (attr->ia_valid) {
5230 setattr_copy(inode, attr);
5231 inode_inc_iversion(inode);
5232 err = btrfs_dirty_inode(inode);
5234 if (!err && attr->ia_valid & ATTR_MODE)
5235 err = posix_acl_chmod(inode, inode->i_mode);
5242 * While truncating the inode pages during eviction, we get the VFS calling
5243 * btrfs_invalidatepage() against each page of the inode. This is slow because
5244 * the calls to btrfs_invalidatepage() result in a huge amount of calls to
5245 * lock_extent_bits() and clear_extent_bit(), which keep merging and splitting
5246 * extent_state structures over and over, wasting lots of time.
5248 * Therefore if the inode is being evicted, let btrfs_invalidatepage() skip all
5249 * those expensive operations on a per page basis and do only the ordered io
5250 * finishing, while we release here the extent_map and extent_state structures,
5251 * without the excessive merging and splitting.
5253 static void evict_inode_truncate_pages(struct inode *inode)
5255 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
5256 struct extent_map_tree *map_tree = &BTRFS_I(inode)->extent_tree;
5257 struct rb_node *node;
5259 ASSERT(inode->i_state & I_FREEING);
5260 truncate_inode_pages_final(&inode->i_data);
5262 write_lock(&map_tree->lock);
5263 while (!RB_EMPTY_ROOT(&map_tree->map.rb_root)) {
5264 struct extent_map *em;
5266 node = rb_first_cached(&map_tree->map);
5267 em = rb_entry(node, struct extent_map, rb_node);
5268 clear_bit(EXTENT_FLAG_PINNED, &em->flags);
5269 clear_bit(EXTENT_FLAG_LOGGING, &em->flags);
5270 remove_extent_mapping(map_tree, em);
5271 free_extent_map(em);
5272 if (need_resched()) {
5273 write_unlock(&map_tree->lock);
5275 write_lock(&map_tree->lock);
5278 write_unlock(&map_tree->lock);
5281 * Keep looping until we have no more ranges in the io tree.
5282 * We can have ongoing bios started by readpages (called from readahead)
5283 * that have their endio callback (extent_io.c:end_bio_extent_readpage)
5284 * still in progress (unlocked the pages in the bio but did not yet
5285 * unlocked the ranges in the io tree). Therefore this means some
5286 * ranges can still be locked and eviction started because before
5287 * submitting those bios, which are executed by a separate task (work
5288 * queue kthread), inode references (inode->i_count) were not taken
5289 * (which would be dropped in the end io callback of each bio).
5290 * Therefore here we effectively end up waiting for those bios and
5291 * anyone else holding locked ranges without having bumped the inode's
5292 * reference count - if we don't do it, when they access the inode's
5293 * io_tree to unlock a range it may be too late, leading to an
5294 * use-after-free issue.
5296 spin_lock(&io_tree->lock);
5297 while (!RB_EMPTY_ROOT(&io_tree->state)) {
5298 struct extent_state *state;
5299 struct extent_state *cached_state = NULL;
5302 unsigned state_flags;
5304 node = rb_first(&io_tree->state);
5305 state = rb_entry(node, struct extent_state, rb_node);
5306 start = state->start;
5308 state_flags = state->state;
5309 spin_unlock(&io_tree->lock);
5311 lock_extent_bits(io_tree, start, end, &cached_state);
5314 * If still has DELALLOC flag, the extent didn't reach disk,
5315 * and its reserved space won't be freed by delayed_ref.
5316 * So we need to free its reserved space here.
5317 * (Refer to comment in btrfs_invalidatepage, case 2)
5319 * Note, end is the bytenr of last byte, so we need + 1 here.
5321 if (state_flags & EXTENT_DELALLOC)
5322 btrfs_qgroup_free_data(inode, NULL, start, end - start + 1);
5324 clear_extent_bit(io_tree, start, end,
5325 EXTENT_LOCKED | EXTENT_DIRTY |
5326 EXTENT_DELALLOC | EXTENT_DO_ACCOUNTING |
5327 EXTENT_DEFRAG, 1, 1, &cached_state);
5330 spin_lock(&io_tree->lock);
5332 spin_unlock(&io_tree->lock);
5335 static struct btrfs_trans_handle *evict_refill_and_join(struct btrfs_root *root,
5336 struct btrfs_block_rsv *rsv)
5338 struct btrfs_fs_info *fs_info = root->fs_info;
5339 struct btrfs_block_rsv *global_rsv = &fs_info->global_block_rsv;
5340 u64 delayed_refs_extra = btrfs_calc_trans_metadata_size(fs_info, 1);
5344 struct btrfs_trans_handle *trans;
5347 ret = btrfs_block_rsv_refill(root, rsv,
5348 rsv->size + delayed_refs_extra,
5349 BTRFS_RESERVE_FLUSH_LIMIT);
5351 if (ret && ++failures > 2) {
5353 "could not allocate space for a delete; will truncate on mount");
5354 return ERR_PTR(-ENOSPC);
5358 * Evict can generate a large amount of delayed refs without
5359 * having a way to add space back since we exhaust our temporary
5360 * block rsv. We aren't allowed to do FLUSH_ALL in this case
5361 * because we could deadlock with so many things in the flushing
5362 * code, so we have to try and hold some extra space to
5363 * compensate for our delayed ref generation. If we can't get
5364 * that space then we need see if we can steal our minimum from
5365 * the global reserve. We will be ratelimited by the amount of
5366 * space we have for the delayed refs rsv, so we'll end up
5367 * committing and trying again.
5369 trans = btrfs_join_transaction(root);
5370 if (IS_ERR(trans) || !ret) {
5371 if (!IS_ERR(trans)) {
5372 trans->block_rsv = &fs_info->trans_block_rsv;
5373 trans->bytes_reserved = delayed_refs_extra;
5374 btrfs_block_rsv_migrate(rsv, trans->block_rsv,
5375 delayed_refs_extra, 1);
5381 * Try to steal from the global reserve if there is space for
5384 if (!btrfs_check_space_for_delayed_refs(fs_info) &&
5385 !btrfs_block_rsv_migrate(global_rsv, rsv, rsv->size, 0))
5388 /* If not, commit and try again. */
5389 ret = btrfs_commit_transaction(trans);
5391 return ERR_PTR(ret);
5395 void btrfs_evict_inode(struct inode *inode)
5397 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
5398 struct btrfs_trans_handle *trans;
5399 struct btrfs_root *root = BTRFS_I(inode)->root;
5400 struct btrfs_block_rsv *rsv;
5403 trace_btrfs_inode_evict(inode);
5410 evict_inode_truncate_pages(inode);
5412 if (inode->i_nlink &&
5413 ((btrfs_root_refs(&root->root_item) != 0 &&
5414 root->root_key.objectid != BTRFS_ROOT_TREE_OBJECTID) ||
5415 btrfs_is_free_space_inode(BTRFS_I(inode))))
5418 if (is_bad_inode(inode))
5421 btrfs_free_io_failure_record(BTRFS_I(inode), 0, (u64)-1);
5423 if (test_bit(BTRFS_FS_LOG_RECOVERING, &fs_info->flags))
5426 if (inode->i_nlink > 0) {
5427 BUG_ON(btrfs_root_refs(&root->root_item) != 0 &&
5428 root->root_key.objectid != BTRFS_ROOT_TREE_OBJECTID);
5432 ret = btrfs_commit_inode_delayed_inode(BTRFS_I(inode));
5436 rsv = btrfs_alloc_block_rsv(fs_info, BTRFS_BLOCK_RSV_TEMP);
5439 rsv->size = btrfs_calc_trunc_metadata_size(fs_info, 1);
5442 btrfs_i_size_write(BTRFS_I(inode), 0);
5445 trans = evict_refill_and_join(root, rsv);
5449 trans->block_rsv = rsv;
5451 ret = btrfs_truncate_inode_items(trans, root, inode, 0, 0);
5452 trans->block_rsv = &fs_info->trans_block_rsv;
5453 btrfs_end_transaction(trans);
5454 btrfs_btree_balance_dirty(fs_info);
5455 if (ret && ret != -ENOSPC && ret != -EAGAIN)
5462 * Errors here aren't a big deal, it just means we leave orphan items in
5463 * the tree. They will be cleaned up on the next mount. If the inode
5464 * number gets reused, cleanup deletes the orphan item without doing
5465 * anything, and unlink reuses the existing orphan item.
5467 * If it turns out that we are dropping too many of these, we might want
5468 * to add a mechanism for retrying these after a commit.
5470 trans = evict_refill_and_join(root, rsv);
5471 if (!IS_ERR(trans)) {
5472 trans->block_rsv = rsv;
5473 btrfs_orphan_del(trans, BTRFS_I(inode));
5474 trans->block_rsv = &fs_info->trans_block_rsv;
5475 btrfs_end_transaction(trans);
5478 if (!(root == fs_info->tree_root ||
5479 root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID))
5480 btrfs_return_ino(root, btrfs_ino(BTRFS_I(inode)));
5483 btrfs_free_block_rsv(fs_info, rsv);
5486 * If we didn't successfully delete, the orphan item will still be in
5487 * the tree and we'll retry on the next mount. Again, we might also want
5488 * to retry these periodically in the future.
5490 btrfs_remove_delayed_node(BTRFS_I(inode));
5495 * Return the key found in the dir entry in the location pointer, fill @type
5496 * with BTRFS_FT_*, and return 0.
5498 * If no dir entries were found, returns -ENOENT.
5499 * If found a corrupted location in dir entry, returns -EUCLEAN.
5501 static int btrfs_inode_by_name(struct inode *dir, struct dentry *dentry,
5502 struct btrfs_key *location, u8 *type)
5504 const char *name = dentry->d_name.name;
5505 int namelen = dentry->d_name.len;
5506 struct btrfs_dir_item *di;
5507 struct btrfs_path *path;
5508 struct btrfs_root *root = BTRFS_I(dir)->root;
5511 path = btrfs_alloc_path();
5515 di = btrfs_lookup_dir_item(NULL, root, path, btrfs_ino(BTRFS_I(dir)),
5517 if (IS_ERR_OR_NULL(di)) {
5518 ret = di ? PTR_ERR(di) : -ENOENT;
5522 btrfs_dir_item_key_to_cpu(path->nodes[0], di, location);
5523 if (location->type != BTRFS_INODE_ITEM_KEY &&
5524 location->type != BTRFS_ROOT_ITEM_KEY) {
5526 btrfs_warn(root->fs_info,
5527 "%s gets something invalid in DIR_ITEM (name %s, directory ino %llu, location(%llu %u %llu))",
5528 __func__, name, btrfs_ino(BTRFS_I(dir)),
5529 location->objectid, location->type, location->offset);
5532 *type = btrfs_dir_type(path->nodes[0], di);
5534 btrfs_free_path(path);
5539 * when we hit a tree root in a directory, the btrfs part of the inode
5540 * needs to be changed to reflect the root directory of the tree root. This
5541 * is kind of like crossing a mount point.
5543 static int fixup_tree_root_location(struct btrfs_fs_info *fs_info,
5545 struct dentry *dentry,
5546 struct btrfs_key *location,
5547 struct btrfs_root **sub_root)
5549 struct btrfs_path *path;
5550 struct btrfs_root *new_root;
5551 struct btrfs_root_ref *ref;
5552 struct extent_buffer *leaf;
5553 struct btrfs_key key;
5557 path = btrfs_alloc_path();
5564 key.objectid = BTRFS_I(dir)->root->root_key.objectid;
5565 key.type = BTRFS_ROOT_REF_KEY;
5566 key.offset = location->objectid;
5568 ret = btrfs_search_slot(NULL, fs_info->tree_root, &key, path, 0, 0);
5575 leaf = path->nodes[0];
5576 ref = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_root_ref);
5577 if (btrfs_root_ref_dirid(leaf, ref) != btrfs_ino(BTRFS_I(dir)) ||
5578 btrfs_root_ref_name_len(leaf, ref) != dentry->d_name.len)
5581 ret = memcmp_extent_buffer(leaf, dentry->d_name.name,
5582 (unsigned long)(ref + 1),
5583 dentry->d_name.len);
5587 btrfs_release_path(path);
5589 new_root = btrfs_read_fs_root_no_name(fs_info, location);
5590 if (IS_ERR(new_root)) {
5591 err = PTR_ERR(new_root);
5595 *sub_root = new_root;
5596 location->objectid = btrfs_root_dirid(&new_root->root_item);
5597 location->type = BTRFS_INODE_ITEM_KEY;
5598 location->offset = 0;
5601 btrfs_free_path(path);
5605 static void inode_tree_add(struct inode *inode)
5607 struct btrfs_root *root = BTRFS_I(inode)->root;
5608 struct btrfs_inode *entry;
5610 struct rb_node *parent;
5611 struct rb_node *new = &BTRFS_I(inode)->rb_node;
5612 u64 ino = btrfs_ino(BTRFS_I(inode));
5614 if (inode_unhashed(inode))
5617 spin_lock(&root->inode_lock);
5618 p = &root->inode_tree.rb_node;
5621 entry = rb_entry(parent, struct btrfs_inode, rb_node);
5623 if (ino < btrfs_ino(entry))
5624 p = &parent->rb_left;
5625 else if (ino > btrfs_ino(entry))
5626 p = &parent->rb_right;
5628 WARN_ON(!(entry->vfs_inode.i_state &
5629 (I_WILL_FREE | I_FREEING)));
5630 rb_replace_node(parent, new, &root->inode_tree);
5631 RB_CLEAR_NODE(parent);
5632 spin_unlock(&root->inode_lock);
5636 rb_link_node(new, parent, p);
5637 rb_insert_color(new, &root->inode_tree);
5638 spin_unlock(&root->inode_lock);
5641 static void inode_tree_del(struct inode *inode)
5643 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
5644 struct btrfs_root *root = BTRFS_I(inode)->root;
5647 spin_lock(&root->inode_lock);
5648 if (!RB_EMPTY_NODE(&BTRFS_I(inode)->rb_node)) {
5649 rb_erase(&BTRFS_I(inode)->rb_node, &root->inode_tree);
5650 RB_CLEAR_NODE(&BTRFS_I(inode)->rb_node);
5651 empty = RB_EMPTY_ROOT(&root->inode_tree);
5653 spin_unlock(&root->inode_lock);
5655 if (empty && btrfs_root_refs(&root->root_item) == 0) {
5656 synchronize_srcu(&fs_info->subvol_srcu);
5657 spin_lock(&root->inode_lock);
5658 empty = RB_EMPTY_ROOT(&root->inode_tree);
5659 spin_unlock(&root->inode_lock);
5661 btrfs_add_dead_root(root);
5666 static int btrfs_init_locked_inode(struct inode *inode, void *p)
5668 struct btrfs_iget_args *args = p;
5669 inode->i_ino = args->location->objectid;
5670 memcpy(&BTRFS_I(inode)->location, args->location,
5671 sizeof(*args->location));
5672 BTRFS_I(inode)->root = args->root;
5676 static int btrfs_find_actor(struct inode *inode, void *opaque)
5678 struct btrfs_iget_args *args = opaque;
5679 return args->location->objectid == BTRFS_I(inode)->location.objectid &&
5680 args->root == BTRFS_I(inode)->root;
5683 static struct inode *btrfs_iget_locked(struct super_block *s,
5684 struct btrfs_key *location,
5685 struct btrfs_root *root)
5687 struct inode *inode;
5688 struct btrfs_iget_args args;
5689 unsigned long hashval = btrfs_inode_hash(location->objectid, root);
5691 args.location = location;
5694 inode = iget5_locked(s, hashval, btrfs_find_actor,
5695 btrfs_init_locked_inode,
5700 /* Get an inode object given its location and corresponding root.
5701 * Returns in *is_new if the inode was read from disk
5703 struct inode *btrfs_iget_path(struct super_block *s, struct btrfs_key *location,
5704 struct btrfs_root *root, int *new,
5705 struct btrfs_path *path)
5707 struct inode *inode;
5709 inode = btrfs_iget_locked(s, location, root);
5711 return ERR_PTR(-ENOMEM);
5713 if (inode->i_state & I_NEW) {
5716 ret = btrfs_read_locked_inode(inode, path);
5718 inode_tree_add(inode);
5719 unlock_new_inode(inode);
5725 * ret > 0 can come from btrfs_search_slot called by
5726 * btrfs_read_locked_inode, this means the inode item
5731 inode = ERR_PTR(ret);
5738 struct inode *btrfs_iget(struct super_block *s, struct btrfs_key *location,
5739 struct btrfs_root *root, int *new)
5741 return btrfs_iget_path(s, location, root, new, NULL);
5744 static struct inode *new_simple_dir(struct super_block *s,
5745 struct btrfs_key *key,
5746 struct btrfs_root *root)
5748 struct inode *inode = new_inode(s);
5751 return ERR_PTR(-ENOMEM);
5753 BTRFS_I(inode)->root = root;
5754 memcpy(&BTRFS_I(inode)->location, key, sizeof(*key));
5755 set_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags);
5757 inode->i_ino = BTRFS_EMPTY_SUBVOL_DIR_OBJECTID;
5758 inode->i_op = &btrfs_dir_ro_inode_operations;
5759 inode->i_opflags &= ~IOP_XATTR;
5760 inode->i_fop = &simple_dir_operations;
5761 inode->i_mode = S_IFDIR | S_IRUGO | S_IWUSR | S_IXUGO;
5762 inode->i_mtime = current_time(inode);
5763 inode->i_atime = inode->i_mtime;
5764 inode->i_ctime = inode->i_mtime;
5765 BTRFS_I(inode)->i_otime = inode->i_mtime;
5770 static inline u8 btrfs_inode_type(struct inode *inode)
5773 * Compile-time asserts that generic FT_* types still match
5776 BUILD_BUG_ON(BTRFS_FT_UNKNOWN != FT_UNKNOWN);
5777 BUILD_BUG_ON(BTRFS_FT_REG_FILE != FT_REG_FILE);
5778 BUILD_BUG_ON(BTRFS_FT_DIR != FT_DIR);
5779 BUILD_BUG_ON(BTRFS_FT_CHRDEV != FT_CHRDEV);
5780 BUILD_BUG_ON(BTRFS_FT_BLKDEV != FT_BLKDEV);
5781 BUILD_BUG_ON(BTRFS_FT_FIFO != FT_FIFO);
5782 BUILD_BUG_ON(BTRFS_FT_SOCK != FT_SOCK);
5783 BUILD_BUG_ON(BTRFS_FT_SYMLINK != FT_SYMLINK);
5785 return fs_umode_to_ftype(inode->i_mode);
5788 struct inode *btrfs_lookup_dentry(struct inode *dir, struct dentry *dentry)
5790 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
5791 struct inode *inode;
5792 struct btrfs_root *root = BTRFS_I(dir)->root;
5793 struct btrfs_root *sub_root = root;
5794 struct btrfs_key location;
5799 if (dentry->d_name.len > BTRFS_NAME_LEN)
5800 return ERR_PTR(-ENAMETOOLONG);
5802 ret = btrfs_inode_by_name(dir, dentry, &location, &di_type);
5804 return ERR_PTR(ret);
5806 if (location.type == BTRFS_INODE_ITEM_KEY) {
5807 inode = btrfs_iget(dir->i_sb, &location, root, NULL);
5811 /* Do extra check against inode mode with di_type */
5812 if (btrfs_inode_type(inode) != di_type) {
5814 "inode mode mismatch with dir: inode mode=0%o btrfs type=%u dir type=%u",
5815 inode->i_mode, btrfs_inode_type(inode),
5818 return ERR_PTR(-EUCLEAN);
5823 index = srcu_read_lock(&fs_info->subvol_srcu);
5824 ret = fixup_tree_root_location(fs_info, dir, dentry,
5825 &location, &sub_root);
5828 inode = ERR_PTR(ret);
5830 inode = new_simple_dir(dir->i_sb, &location, sub_root);
5832 inode = btrfs_iget(dir->i_sb, &location, sub_root, NULL);
5834 srcu_read_unlock(&fs_info->subvol_srcu, index);
5836 if (!IS_ERR(inode) && root != sub_root) {
5837 down_read(&fs_info->cleanup_work_sem);
5838 if (!sb_rdonly(inode->i_sb))
5839 ret = btrfs_orphan_cleanup(sub_root);
5840 up_read(&fs_info->cleanup_work_sem);
5843 inode = ERR_PTR(ret);
5850 static int btrfs_dentry_delete(const struct dentry *dentry)
5852 struct btrfs_root *root;
5853 struct inode *inode = d_inode(dentry);
5855 if (!inode && !IS_ROOT(dentry))
5856 inode = d_inode(dentry->d_parent);
5859 root = BTRFS_I(inode)->root;
5860 if (btrfs_root_refs(&root->root_item) == 0)
5863 if (btrfs_ino(BTRFS_I(inode)) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)
5869 static struct dentry *btrfs_lookup(struct inode *dir, struct dentry *dentry,
5872 struct inode *inode = btrfs_lookup_dentry(dir, dentry);
5874 if (inode == ERR_PTR(-ENOENT))
5876 return d_splice_alias(inode, dentry);
5880 * All this infrastructure exists because dir_emit can fault, and we are holding
5881 * the tree lock when doing readdir. For now just allocate a buffer and copy
5882 * our information into that, and then dir_emit from the buffer. This is
5883 * similar to what NFS does, only we don't keep the buffer around in pagecache
5884 * because I'm afraid I'll mess that up. Long term we need to make filldir do
5885 * copy_to_user_inatomic so we don't have to worry about page faulting under the
5888 static int btrfs_opendir(struct inode *inode, struct file *file)
5890 struct btrfs_file_private *private;
5892 private = kzalloc(sizeof(struct btrfs_file_private), GFP_KERNEL);
5895 private->filldir_buf = kzalloc(PAGE_SIZE, GFP_KERNEL);
5896 if (!private->filldir_buf) {
5900 file->private_data = private;
5911 static int btrfs_filldir(void *addr, int entries, struct dir_context *ctx)
5914 struct dir_entry *entry = addr;
5915 char *name = (char *)(entry + 1);
5917 ctx->pos = get_unaligned(&entry->offset);
5918 if (!dir_emit(ctx, name, get_unaligned(&entry->name_len),
5919 get_unaligned(&entry->ino),
5920 get_unaligned(&entry->type)))
5922 addr += sizeof(struct dir_entry) +
5923 get_unaligned(&entry->name_len);
5929 static int btrfs_real_readdir(struct file *file, struct dir_context *ctx)
5931 struct inode *inode = file_inode(file);
5932 struct btrfs_root *root = BTRFS_I(inode)->root;
5933 struct btrfs_file_private *private = file->private_data;
5934 struct btrfs_dir_item *di;
5935 struct btrfs_key key;
5936 struct btrfs_key found_key;
5937 struct btrfs_path *path;
5939 struct list_head ins_list;
5940 struct list_head del_list;
5942 struct extent_buffer *leaf;
5949 struct btrfs_key location;
5951 if (!dir_emit_dots(file, ctx))
5954 path = btrfs_alloc_path();
5958 addr = private->filldir_buf;
5959 path->reada = READA_FORWARD;
5961 INIT_LIST_HEAD(&ins_list);
5962 INIT_LIST_HEAD(&del_list);
5963 put = btrfs_readdir_get_delayed_items(inode, &ins_list, &del_list);
5966 key.type = BTRFS_DIR_INDEX_KEY;
5967 key.offset = ctx->pos;
5968 key.objectid = btrfs_ino(BTRFS_I(inode));
5970 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
5975 struct dir_entry *entry;
5977 leaf = path->nodes[0];
5978 slot = path->slots[0];
5979 if (slot >= btrfs_header_nritems(leaf)) {
5980 ret = btrfs_next_leaf(root, path);
5988 btrfs_item_key_to_cpu(leaf, &found_key, slot);
5990 if (found_key.objectid != key.objectid)
5992 if (found_key.type != BTRFS_DIR_INDEX_KEY)
5994 if (found_key.offset < ctx->pos)
5996 if (btrfs_should_delete_dir_index(&del_list, found_key.offset))
5998 di = btrfs_item_ptr(leaf, slot, struct btrfs_dir_item);
5999 name_len = btrfs_dir_name_len(leaf, di);
6000 if ((total_len + sizeof(struct dir_entry) + name_len) >=
6002 btrfs_release_path(path);
6003 ret = btrfs_filldir(private->filldir_buf, entries, ctx);
6006 addr = private->filldir_buf;
6013 put_unaligned(name_len, &entry->name_len);
6014 name_ptr = (char *)(entry + 1);
6015 read_extent_buffer(leaf, name_ptr, (unsigned long)(di + 1),
6017 put_unaligned(fs_ftype_to_dtype(btrfs_dir_type(leaf, di)),
6019 btrfs_dir_item_key_to_cpu(leaf, di, &location);
6020 put_unaligned(location.objectid, &entry->ino);
6021 put_unaligned(found_key.offset, &entry->offset);
6023 addr += sizeof(struct dir_entry) + name_len;
6024 total_len += sizeof(struct dir_entry) + name_len;
6028 btrfs_release_path(path);
6030 ret = btrfs_filldir(private->filldir_buf, entries, ctx);
6034 ret = btrfs_readdir_delayed_dir_index(ctx, &ins_list);
6039 * Stop new entries from being returned after we return the last
6042 * New directory entries are assigned a strictly increasing
6043 * offset. This means that new entries created during readdir
6044 * are *guaranteed* to be seen in the future by that readdir.
6045 * This has broken buggy programs which operate on names as
6046 * they're returned by readdir. Until we re-use freed offsets
6047 * we have this hack to stop new entries from being returned
6048 * under the assumption that they'll never reach this huge
6051 * This is being careful not to overflow 32bit loff_t unless the
6052 * last entry requires it because doing so has broken 32bit apps
6055 if (ctx->pos >= INT_MAX)
6056 ctx->pos = LLONG_MAX;
6063 btrfs_readdir_put_delayed_items(inode, &ins_list, &del_list);
6064 btrfs_free_path(path);
6069 * This is somewhat expensive, updating the tree every time the
6070 * inode changes. But, it is most likely to find the inode in cache.
6071 * FIXME, needs more benchmarking...there are no reasons other than performance
6072 * to keep or drop this code.
6074 static int btrfs_dirty_inode(struct inode *inode)
6076 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
6077 struct btrfs_root *root = BTRFS_I(inode)->root;
6078 struct btrfs_trans_handle *trans;
6081 if (test_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags))
6084 trans = btrfs_join_transaction(root);
6086 return PTR_ERR(trans);
6088 ret = btrfs_update_inode(trans, root, inode);
6089 if (ret && ret == -ENOSPC) {
6090 /* whoops, lets try again with the full transaction */
6091 btrfs_end_transaction(trans);
6092 trans = btrfs_start_transaction(root, 1);
6094 return PTR_ERR(trans);
6096 ret = btrfs_update_inode(trans, root, inode);
6098 btrfs_end_transaction(trans);
6099 if (BTRFS_I(inode)->delayed_node)
6100 btrfs_balance_delayed_items(fs_info);
6106 * This is a copy of file_update_time. We need this so we can return error on
6107 * ENOSPC for updating the inode in the case of file write and mmap writes.
6109 static int btrfs_update_time(struct inode *inode, struct timespec64 *now,
6112 struct btrfs_root *root = BTRFS_I(inode)->root;
6113 bool dirty = flags & ~S_VERSION;
6115 if (btrfs_root_readonly(root))
6118 if (flags & S_VERSION)
6119 dirty |= inode_maybe_inc_iversion(inode, dirty);
6120 if (flags & S_CTIME)
6121 inode->i_ctime = *now;
6122 if (flags & S_MTIME)
6123 inode->i_mtime = *now;
6124 if (flags & S_ATIME)
6125 inode->i_atime = *now;
6126 return dirty ? btrfs_dirty_inode(inode) : 0;
6130 * find the highest existing sequence number in a directory
6131 * and then set the in-memory index_cnt variable to reflect
6132 * free sequence numbers
6134 static int btrfs_set_inode_index_count(struct btrfs_inode *inode)
6136 struct btrfs_root *root = inode->root;
6137 struct btrfs_key key, found_key;
6138 struct btrfs_path *path;
6139 struct extent_buffer *leaf;
6142 key.objectid = btrfs_ino(inode);
6143 key.type = BTRFS_DIR_INDEX_KEY;
6144 key.offset = (u64)-1;
6146 path = btrfs_alloc_path();
6150 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
6153 /* FIXME: we should be able to handle this */
6159 * MAGIC NUMBER EXPLANATION:
6160 * since we search a directory based on f_pos we have to start at 2
6161 * since '.' and '..' have f_pos of 0 and 1 respectively, so everybody
6162 * else has to start at 2
6164 if (path->slots[0] == 0) {
6165 inode->index_cnt = 2;
6171 leaf = path->nodes[0];
6172 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
6174 if (found_key.objectid != btrfs_ino(inode) ||
6175 found_key.type != BTRFS_DIR_INDEX_KEY) {
6176 inode->index_cnt = 2;
6180 inode->index_cnt = found_key.offset + 1;
6182 btrfs_free_path(path);
6187 * helper to find a free sequence number in a given directory. This current
6188 * code is very simple, later versions will do smarter things in the btree
6190 int btrfs_set_inode_index(struct btrfs_inode *dir, u64 *index)
6194 if (dir->index_cnt == (u64)-1) {
6195 ret = btrfs_inode_delayed_dir_index_count(dir);
6197 ret = btrfs_set_inode_index_count(dir);
6203 *index = dir->index_cnt;
6209 static int btrfs_insert_inode_locked(struct inode *inode)
6211 struct btrfs_iget_args args;
6212 args.location = &BTRFS_I(inode)->location;
6213 args.root = BTRFS_I(inode)->root;
6215 return insert_inode_locked4(inode,
6216 btrfs_inode_hash(inode->i_ino, BTRFS_I(inode)->root),
6217 btrfs_find_actor, &args);
6221 * Inherit flags from the parent inode.
6223 * Currently only the compression flags and the cow flags are inherited.
6225 static void btrfs_inherit_iflags(struct inode *inode, struct inode *dir)
6232 flags = BTRFS_I(dir)->flags;
6234 if (flags & BTRFS_INODE_NOCOMPRESS) {
6235 BTRFS_I(inode)->flags &= ~BTRFS_INODE_COMPRESS;
6236 BTRFS_I(inode)->flags |= BTRFS_INODE_NOCOMPRESS;
6237 } else if (flags & BTRFS_INODE_COMPRESS) {
6238 BTRFS_I(inode)->flags &= ~BTRFS_INODE_NOCOMPRESS;
6239 BTRFS_I(inode)->flags |= BTRFS_INODE_COMPRESS;
6242 if (flags & BTRFS_INODE_NODATACOW) {
6243 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATACOW;
6244 if (S_ISREG(inode->i_mode))
6245 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATASUM;
6248 btrfs_sync_inode_flags_to_i_flags(inode);
6251 static struct inode *btrfs_new_inode(struct btrfs_trans_handle *trans,
6252 struct btrfs_root *root,
6254 const char *name, int name_len,
6255 u64 ref_objectid, u64 objectid,
6256 umode_t mode, u64 *index)
6258 struct btrfs_fs_info *fs_info = root->fs_info;
6259 struct inode *inode;
6260 struct btrfs_inode_item *inode_item;
6261 struct btrfs_key *location;
6262 struct btrfs_path *path;
6263 struct btrfs_inode_ref *ref;
6264 struct btrfs_key key[2];
6266 int nitems = name ? 2 : 1;
6270 path = btrfs_alloc_path();
6272 return ERR_PTR(-ENOMEM);
6274 inode = new_inode(fs_info->sb);
6276 btrfs_free_path(path);
6277 return ERR_PTR(-ENOMEM);
6281 * O_TMPFILE, set link count to 0, so that after this point,
6282 * we fill in an inode item with the correct link count.
6285 set_nlink(inode, 0);
6288 * we have to initialize this early, so we can reclaim the inode
6289 * number if we fail afterwards in this function.
6291 inode->i_ino = objectid;
6294 trace_btrfs_inode_request(dir);
6296 ret = btrfs_set_inode_index(BTRFS_I(dir), index);
6298 btrfs_free_path(path);
6300 return ERR_PTR(ret);
6306 * index_cnt is ignored for everything but a dir,
6307 * btrfs_set_inode_index_count has an explanation for the magic
6310 BTRFS_I(inode)->index_cnt = 2;
6311 BTRFS_I(inode)->dir_index = *index;
6312 BTRFS_I(inode)->root = root;
6313 BTRFS_I(inode)->generation = trans->transid;
6314 inode->i_generation = BTRFS_I(inode)->generation;
6317 * We could have gotten an inode number from somebody who was fsynced
6318 * and then removed in this same transaction, so let's just set full
6319 * sync since it will be a full sync anyway and this will blow away the
6320 * old info in the log.
6322 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &BTRFS_I(inode)->runtime_flags);
6324 key[0].objectid = objectid;
6325 key[0].type = BTRFS_INODE_ITEM_KEY;
6328 sizes[0] = sizeof(struct btrfs_inode_item);
6332 * Start new inodes with an inode_ref. This is slightly more
6333 * efficient for small numbers of hard links since they will
6334 * be packed into one item. Extended refs will kick in if we
6335 * add more hard links than can fit in the ref item.
6337 key[1].objectid = objectid;
6338 key[1].type = BTRFS_INODE_REF_KEY;
6339 key[1].offset = ref_objectid;
6341 sizes[1] = name_len + sizeof(*ref);
6344 location = &BTRFS_I(inode)->location;
6345 location->objectid = objectid;
6346 location->offset = 0;
6347 location->type = BTRFS_INODE_ITEM_KEY;
6349 ret = btrfs_insert_inode_locked(inode);
6355 path->leave_spinning = 1;
6356 ret = btrfs_insert_empty_items(trans, root, path, key, sizes, nitems);
6360 inode_init_owner(inode, dir, mode);
6361 inode_set_bytes(inode, 0);
6363 inode->i_mtime = current_time(inode);
6364 inode->i_atime = inode->i_mtime;
6365 inode->i_ctime = inode->i_mtime;
6366 BTRFS_I(inode)->i_otime = inode->i_mtime;
6368 inode_item = btrfs_item_ptr(path->nodes[0], path->slots[0],
6369 struct btrfs_inode_item);
6370 memzero_extent_buffer(path->nodes[0], (unsigned long)inode_item,
6371 sizeof(*inode_item));
6372 fill_inode_item(trans, path->nodes[0], inode_item, inode);
6375 ref = btrfs_item_ptr(path->nodes[0], path->slots[0] + 1,
6376 struct btrfs_inode_ref);
6377 btrfs_set_inode_ref_name_len(path->nodes[0], ref, name_len);
6378 btrfs_set_inode_ref_index(path->nodes[0], ref, *index);
6379 ptr = (unsigned long)(ref + 1);
6380 write_extent_buffer(path->nodes[0], name, ptr, name_len);
6383 btrfs_mark_buffer_dirty(path->nodes[0]);
6384 btrfs_free_path(path);
6386 btrfs_inherit_iflags(inode, dir);
6388 if (S_ISREG(mode)) {
6389 if (btrfs_test_opt(fs_info, NODATASUM))
6390 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATASUM;
6391 if (btrfs_test_opt(fs_info, NODATACOW))
6392 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATACOW |
6393 BTRFS_INODE_NODATASUM;
6396 inode_tree_add(inode);
6398 trace_btrfs_inode_new(inode);
6399 btrfs_set_inode_last_trans(trans, inode);
6401 btrfs_update_root_times(trans, root);
6403 ret = btrfs_inode_inherit_props(trans, inode, dir);
6406 "error inheriting props for ino %llu (root %llu): %d",
6407 btrfs_ino(BTRFS_I(inode)), root->root_key.objectid, ret);
6412 discard_new_inode(inode);
6415 BTRFS_I(dir)->index_cnt--;
6416 btrfs_free_path(path);
6417 return ERR_PTR(ret);
6421 * utility function to add 'inode' into 'parent_inode' with
6422 * a give name and a given sequence number.
6423 * if 'add_backref' is true, also insert a backref from the
6424 * inode to the parent directory.
6426 int btrfs_add_link(struct btrfs_trans_handle *trans,
6427 struct btrfs_inode *parent_inode, struct btrfs_inode *inode,
6428 const char *name, int name_len, int add_backref, u64 index)
6431 struct btrfs_key key;
6432 struct btrfs_root *root = parent_inode->root;
6433 u64 ino = btrfs_ino(inode);
6434 u64 parent_ino = btrfs_ino(parent_inode);
6436 if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
6437 memcpy(&key, &inode->root->root_key, sizeof(key));
6440 key.type = BTRFS_INODE_ITEM_KEY;
6444 if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
6445 ret = btrfs_add_root_ref(trans, key.objectid,
6446 root->root_key.objectid, parent_ino,
6447 index, name, name_len);
6448 } else if (add_backref) {
6449 ret = btrfs_insert_inode_ref(trans, root, name, name_len, ino,
6453 /* Nothing to clean up yet */
6457 ret = btrfs_insert_dir_item(trans, name, name_len, parent_inode, &key,
6458 btrfs_inode_type(&inode->vfs_inode), index);
6459 if (ret == -EEXIST || ret == -EOVERFLOW)
6462 btrfs_abort_transaction(trans, ret);
6466 btrfs_i_size_write(parent_inode, parent_inode->vfs_inode.i_size +
6468 inode_inc_iversion(&parent_inode->vfs_inode);
6470 * If we are replaying a log tree, we do not want to update the mtime
6471 * and ctime of the parent directory with the current time, since the
6472 * log replay procedure is responsible for setting them to their correct
6473 * values (the ones it had when the fsync was done).
6475 if (!test_bit(BTRFS_FS_LOG_RECOVERING, &root->fs_info->flags)) {
6476 struct timespec64 now = current_time(&parent_inode->vfs_inode);
6478 parent_inode->vfs_inode.i_mtime = now;
6479 parent_inode->vfs_inode.i_ctime = now;
6481 ret = btrfs_update_inode(trans, root, &parent_inode->vfs_inode);
6483 btrfs_abort_transaction(trans, ret);
6487 if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
6490 err = btrfs_del_root_ref(trans, key.objectid,
6491 root->root_key.objectid, parent_ino,
6492 &local_index, name, name_len);
6494 btrfs_abort_transaction(trans, err);
6495 } else if (add_backref) {
6499 err = btrfs_del_inode_ref(trans, root, name, name_len,
6500 ino, parent_ino, &local_index);
6502 btrfs_abort_transaction(trans, err);
6505 /* Return the original error code */
6509 static int btrfs_add_nondir(struct btrfs_trans_handle *trans,
6510 struct btrfs_inode *dir, struct dentry *dentry,
6511 struct btrfs_inode *inode, int backref, u64 index)
6513 int err = btrfs_add_link(trans, dir, inode,
6514 dentry->d_name.name, dentry->d_name.len,
6521 static int btrfs_mknod(struct inode *dir, struct dentry *dentry,
6522 umode_t mode, dev_t rdev)
6524 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
6525 struct btrfs_trans_handle *trans;
6526 struct btrfs_root *root = BTRFS_I(dir)->root;
6527 struct inode *inode = NULL;
6533 * 2 for inode item and ref
6535 * 1 for xattr if selinux is on
6537 trans = btrfs_start_transaction(root, 5);
6539 return PTR_ERR(trans);
6541 err = btrfs_find_free_ino(root, &objectid);
6545 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
6546 dentry->d_name.len, btrfs_ino(BTRFS_I(dir)), objectid,
6548 if (IS_ERR(inode)) {
6549 err = PTR_ERR(inode);
6555 * If the active LSM wants to access the inode during
6556 * d_instantiate it needs these. Smack checks to see
6557 * if the filesystem supports xattrs by looking at the
6560 inode->i_op = &btrfs_special_inode_operations;
6561 init_special_inode(inode, inode->i_mode, rdev);
6563 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
6567 err = btrfs_add_nondir(trans, BTRFS_I(dir), dentry, BTRFS_I(inode),
6572 btrfs_update_inode(trans, root, inode);
6573 d_instantiate_new(dentry, inode);
6576 btrfs_end_transaction(trans);
6577 btrfs_btree_balance_dirty(fs_info);
6579 inode_dec_link_count(inode);
6580 discard_new_inode(inode);
6585 static int btrfs_create(struct inode *dir, struct dentry *dentry,
6586 umode_t mode, bool excl)
6588 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
6589 struct btrfs_trans_handle *trans;
6590 struct btrfs_root *root = BTRFS_I(dir)->root;
6591 struct inode *inode = NULL;
6597 * 2 for inode item and ref
6599 * 1 for xattr if selinux is on
6601 trans = btrfs_start_transaction(root, 5);
6603 return PTR_ERR(trans);
6605 err = btrfs_find_free_ino(root, &objectid);
6609 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
6610 dentry->d_name.len, btrfs_ino(BTRFS_I(dir)), objectid,
6612 if (IS_ERR(inode)) {
6613 err = PTR_ERR(inode);
6618 * If the active LSM wants to access the inode during
6619 * d_instantiate it needs these. Smack checks to see
6620 * if the filesystem supports xattrs by looking at the
6623 inode->i_fop = &btrfs_file_operations;
6624 inode->i_op = &btrfs_file_inode_operations;
6625 inode->i_mapping->a_ops = &btrfs_aops;
6627 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
6631 err = btrfs_update_inode(trans, root, inode);
6635 err = btrfs_add_nondir(trans, BTRFS_I(dir), dentry, BTRFS_I(inode),
6640 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
6641 d_instantiate_new(dentry, inode);
6644 btrfs_end_transaction(trans);
6646 inode_dec_link_count(inode);
6647 discard_new_inode(inode);
6649 btrfs_btree_balance_dirty(fs_info);
6653 static int btrfs_link(struct dentry *old_dentry, struct inode *dir,
6654 struct dentry *dentry)
6656 struct btrfs_trans_handle *trans = NULL;
6657 struct btrfs_root *root = BTRFS_I(dir)->root;
6658 struct inode *inode = d_inode(old_dentry);
6659 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
6664 /* do not allow sys_link's with other subvols of the same device */
6665 if (root->root_key.objectid != BTRFS_I(inode)->root->root_key.objectid)
6668 if (inode->i_nlink >= BTRFS_LINK_MAX)
6671 err = btrfs_set_inode_index(BTRFS_I(dir), &index);
6676 * 2 items for inode and inode ref
6677 * 2 items for dir items
6678 * 1 item for parent inode
6679 * 1 item for orphan item deletion if O_TMPFILE
6681 trans = btrfs_start_transaction(root, inode->i_nlink ? 5 : 6);
6682 if (IS_ERR(trans)) {
6683 err = PTR_ERR(trans);
6688 /* There are several dir indexes for this inode, clear the cache. */
6689 BTRFS_I(inode)->dir_index = 0ULL;
6691 inode_inc_iversion(inode);
6692 inode->i_ctime = current_time(inode);
6694 set_bit(BTRFS_INODE_COPY_EVERYTHING, &BTRFS_I(inode)->runtime_flags);
6696 err = btrfs_add_nondir(trans, BTRFS_I(dir), dentry, BTRFS_I(inode),
6702 struct dentry *parent = dentry->d_parent;
6705 err = btrfs_update_inode(trans, root, inode);
6708 if (inode->i_nlink == 1) {
6710 * If new hard link count is 1, it's a file created
6711 * with open(2) O_TMPFILE flag.
6713 err = btrfs_orphan_del(trans, BTRFS_I(inode));
6717 d_instantiate(dentry, inode);
6718 ret = btrfs_log_new_name(trans, BTRFS_I(inode), NULL, parent,
6720 if (ret == BTRFS_NEED_TRANS_COMMIT) {
6721 err = btrfs_commit_transaction(trans);
6728 btrfs_end_transaction(trans);
6730 inode_dec_link_count(inode);
6733 btrfs_btree_balance_dirty(fs_info);
6737 static int btrfs_mkdir(struct inode *dir, struct dentry *dentry, umode_t mode)
6739 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
6740 struct inode *inode = NULL;
6741 struct btrfs_trans_handle *trans;
6742 struct btrfs_root *root = BTRFS_I(dir)->root;
6748 * 2 items for inode and ref
6749 * 2 items for dir items
6750 * 1 for xattr if selinux is on
6752 trans = btrfs_start_transaction(root, 5);
6754 return PTR_ERR(trans);
6756 err = btrfs_find_free_ino(root, &objectid);
6760 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
6761 dentry->d_name.len, btrfs_ino(BTRFS_I(dir)), objectid,
6762 S_IFDIR | mode, &index);
6763 if (IS_ERR(inode)) {
6764 err = PTR_ERR(inode);
6769 /* these must be set before we unlock the inode */
6770 inode->i_op = &btrfs_dir_inode_operations;
6771 inode->i_fop = &btrfs_dir_file_operations;
6773 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
6777 btrfs_i_size_write(BTRFS_I(inode), 0);
6778 err = btrfs_update_inode(trans, root, inode);
6782 err = btrfs_add_link(trans, BTRFS_I(dir), BTRFS_I(inode),
6783 dentry->d_name.name,
6784 dentry->d_name.len, 0, index);
6788 d_instantiate_new(dentry, inode);
6791 btrfs_end_transaction(trans);
6793 inode_dec_link_count(inode);
6794 discard_new_inode(inode);
6796 btrfs_btree_balance_dirty(fs_info);
6800 static noinline int uncompress_inline(struct btrfs_path *path,
6802 size_t pg_offset, u64 extent_offset,
6803 struct btrfs_file_extent_item *item)
6806 struct extent_buffer *leaf = path->nodes[0];
6809 unsigned long inline_size;
6813 WARN_ON(pg_offset != 0);
6814 compress_type = btrfs_file_extent_compression(leaf, item);
6815 max_size = btrfs_file_extent_ram_bytes(leaf, item);
6816 inline_size = btrfs_file_extent_inline_item_len(leaf,
6817 btrfs_item_nr(path->slots[0]));
6818 tmp = kmalloc(inline_size, GFP_NOFS);
6821 ptr = btrfs_file_extent_inline_start(item);
6823 read_extent_buffer(leaf, tmp, ptr, inline_size);
6825 max_size = min_t(unsigned long, PAGE_SIZE, max_size);
6826 ret = btrfs_decompress(compress_type, tmp, page,
6827 extent_offset, inline_size, max_size);
6830 * decompression code contains a memset to fill in any space between the end
6831 * of the uncompressed data and the end of max_size in case the decompressed
6832 * data ends up shorter than ram_bytes. That doesn't cover the hole between
6833 * the end of an inline extent and the beginning of the next block, so we
6834 * cover that region here.
6837 if (max_size + pg_offset < PAGE_SIZE) {
6838 char *map = kmap(page);
6839 memset(map + pg_offset + max_size, 0, PAGE_SIZE - max_size - pg_offset);
6847 * a bit scary, this does extent mapping from logical file offset to the disk.
6848 * the ugly parts come from merging extents from the disk with the in-ram
6849 * representation. This gets more complex because of the data=ordered code,
6850 * where the in-ram extents might be locked pending data=ordered completion.
6852 * This also copies inline extents directly into the page.
6854 struct extent_map *btrfs_get_extent(struct btrfs_inode *inode,
6856 size_t pg_offset, u64 start, u64 len,
6859 struct btrfs_fs_info *fs_info = inode->root->fs_info;
6862 u64 extent_start = 0;
6864 u64 objectid = btrfs_ino(inode);
6865 int extent_type = -1;
6866 struct btrfs_path *path = NULL;
6867 struct btrfs_root *root = inode->root;
6868 struct btrfs_file_extent_item *item;
6869 struct extent_buffer *leaf;
6870 struct btrfs_key found_key;
6871 struct extent_map *em = NULL;
6872 struct extent_map_tree *em_tree = &inode->extent_tree;
6873 struct extent_io_tree *io_tree = &inode->io_tree;
6874 const bool new_inline = !page || create;
6876 read_lock(&em_tree->lock);
6877 em = lookup_extent_mapping(em_tree, start, len);
6879 em->bdev = fs_info->fs_devices->latest_bdev;
6880 read_unlock(&em_tree->lock);
6883 if (em->start > start || em->start + em->len <= start)
6884 free_extent_map(em);
6885 else if (em->block_start == EXTENT_MAP_INLINE && page)
6886 free_extent_map(em);
6890 em = alloc_extent_map();
6895 em->bdev = fs_info->fs_devices->latest_bdev;
6896 em->start = EXTENT_MAP_HOLE;
6897 em->orig_start = EXTENT_MAP_HOLE;
6899 em->block_len = (u64)-1;
6901 path = btrfs_alloc_path();
6907 /* Chances are we'll be called again, so go ahead and do readahead */
6908 path->reada = READA_FORWARD;
6911 * Unless we're going to uncompress the inline extent, no sleep would
6914 path->leave_spinning = 1;
6916 ret = btrfs_lookup_file_extent(NULL, root, path, objectid, start, 0);
6920 } else if (ret > 0) {
6921 if (path->slots[0] == 0)
6926 leaf = path->nodes[0];
6927 item = btrfs_item_ptr(leaf, path->slots[0],
6928 struct btrfs_file_extent_item);
6929 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
6930 if (found_key.objectid != objectid ||
6931 found_key.type != BTRFS_EXTENT_DATA_KEY) {
6933 * If we backup past the first extent we want to move forward
6934 * and see if there is an extent in front of us, otherwise we'll
6935 * say there is a hole for our whole search range which can
6942 extent_type = btrfs_file_extent_type(leaf, item);
6943 extent_start = found_key.offset;
6944 if (extent_type == BTRFS_FILE_EXTENT_REG ||
6945 extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
6946 /* Only regular file could have regular/prealloc extent */
6947 if (!S_ISREG(inode->vfs_inode.i_mode)) {
6950 "regular/prealloc extent found for non-regular inode %llu",
6954 extent_end = extent_start +
6955 btrfs_file_extent_num_bytes(leaf, item);
6957 trace_btrfs_get_extent_show_fi_regular(inode, leaf, item,
6959 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
6962 size = btrfs_file_extent_ram_bytes(leaf, item);
6963 extent_end = ALIGN(extent_start + size,
6964 fs_info->sectorsize);
6966 trace_btrfs_get_extent_show_fi_inline(inode, leaf, item,
6971 if (start >= extent_end) {
6973 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
6974 ret = btrfs_next_leaf(root, path);
6978 } else if (ret > 0) {
6981 leaf = path->nodes[0];
6983 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
6984 if (found_key.objectid != objectid ||
6985 found_key.type != BTRFS_EXTENT_DATA_KEY)
6987 if (start + len <= found_key.offset)
6989 if (start > found_key.offset)
6992 /* New extent overlaps with existing one */
6994 em->orig_start = start;
6995 em->len = found_key.offset - start;
6996 em->block_start = EXTENT_MAP_HOLE;
7000 btrfs_extent_item_to_extent_map(inode, path, item,
7003 if (extent_type == BTRFS_FILE_EXTENT_REG ||
7004 extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
7006 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
7010 size_t extent_offset;
7016 size = btrfs_file_extent_ram_bytes(leaf, item);
7017 extent_offset = page_offset(page) + pg_offset - extent_start;
7018 copy_size = min_t(u64, PAGE_SIZE - pg_offset,
7019 size - extent_offset);
7020 em->start = extent_start + extent_offset;
7021 em->len = ALIGN(copy_size, fs_info->sectorsize);
7022 em->orig_block_len = em->len;
7023 em->orig_start = em->start;
7024 ptr = btrfs_file_extent_inline_start(item) + extent_offset;
7026 btrfs_set_path_blocking(path);
7027 if (!PageUptodate(page)) {
7028 if (btrfs_file_extent_compression(leaf, item) !=
7029 BTRFS_COMPRESS_NONE) {
7030 ret = uncompress_inline(path, page, pg_offset,
7031 extent_offset, item);
7038 read_extent_buffer(leaf, map + pg_offset, ptr,
7040 if (pg_offset + copy_size < PAGE_SIZE) {
7041 memset(map + pg_offset + copy_size, 0,
7042 PAGE_SIZE - pg_offset -
7047 flush_dcache_page(page);
7049 set_extent_uptodate(io_tree, em->start,
7050 extent_map_end(em) - 1, NULL, GFP_NOFS);
7055 em->orig_start = start;
7057 em->block_start = EXTENT_MAP_HOLE;
7059 btrfs_release_path(path);
7060 if (em->start > start || extent_map_end(em) <= start) {
7062 "bad extent! em: [%llu %llu] passed [%llu %llu]",
7063 em->start, em->len, start, len);
7069 write_lock(&em_tree->lock);
7070 err = btrfs_add_extent_mapping(fs_info, em_tree, &em, start, len);
7071 write_unlock(&em_tree->lock);
7073 btrfs_free_path(path);
7075 trace_btrfs_get_extent(root, inode, em);
7078 free_extent_map(em);
7079 return ERR_PTR(err);
7081 BUG_ON(!em); /* Error is always set */
7085 struct extent_map *btrfs_get_extent_fiemap(struct btrfs_inode *inode,
7088 struct extent_map *em;
7089 struct extent_map *hole_em = NULL;
7090 u64 delalloc_start = start;
7096 em = btrfs_get_extent(inode, NULL, 0, start, len, 0);
7100 * If our em maps to:
7102 * - a pre-alloc extent,
7103 * there might actually be delalloc bytes behind it.
7105 if (em->block_start != EXTENT_MAP_HOLE &&
7106 !test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
7111 /* check to see if we've wrapped (len == -1 or similar) */
7120 /* ok, we didn't find anything, lets look for delalloc */
7121 delalloc_len = count_range_bits(&inode->io_tree, &delalloc_start,
7122 end, len, EXTENT_DELALLOC, 1);
7123 delalloc_end = delalloc_start + delalloc_len;
7124 if (delalloc_end < delalloc_start)
7125 delalloc_end = (u64)-1;
7128 * We didn't find anything useful, return the original results from
7131 if (delalloc_start > end || delalloc_end <= start) {
7138 * Adjust the delalloc_start to make sure it doesn't go backwards from
7139 * the start they passed in
7141 delalloc_start = max(start, delalloc_start);
7142 delalloc_len = delalloc_end - delalloc_start;
7144 if (delalloc_len > 0) {
7147 const u64 hole_end = extent_map_end(hole_em);
7149 em = alloc_extent_map();
7158 * When btrfs_get_extent can't find anything it returns one
7161 * Make sure what it found really fits our range, and adjust to
7162 * make sure it is based on the start from the caller
7164 if (hole_end <= start || hole_em->start > end) {
7165 free_extent_map(hole_em);
7168 hole_start = max(hole_em->start, start);
7169 hole_len = hole_end - hole_start;
7172 if (hole_em && delalloc_start > hole_start) {
7174 * Our hole starts before our delalloc, so we have to
7175 * return just the parts of the hole that go until the
7178 em->len = min(hole_len, delalloc_start - hole_start);
7179 em->start = hole_start;
7180 em->orig_start = hole_start;
7182 * Don't adjust block start at all, it is fixed at
7185 em->block_start = hole_em->block_start;
7186 em->block_len = hole_len;
7187 if (test_bit(EXTENT_FLAG_PREALLOC, &hole_em->flags))
7188 set_bit(EXTENT_FLAG_PREALLOC, &em->flags);
7191 * Hole is out of passed range or it starts after
7194 em->start = delalloc_start;
7195 em->len = delalloc_len;
7196 em->orig_start = delalloc_start;
7197 em->block_start = EXTENT_MAP_DELALLOC;
7198 em->block_len = delalloc_len;
7205 free_extent_map(hole_em);
7207 free_extent_map(em);
7208 return ERR_PTR(err);
7213 static struct extent_map *btrfs_create_dio_extent(struct inode *inode,
7216 const u64 orig_start,
7217 const u64 block_start,
7218 const u64 block_len,
7219 const u64 orig_block_len,
7220 const u64 ram_bytes,
7223 struct extent_map *em = NULL;
7226 if (type != BTRFS_ORDERED_NOCOW) {
7227 em = create_io_em(inode, start, len, orig_start,
7228 block_start, block_len, orig_block_len,
7230 BTRFS_COMPRESS_NONE, /* compress_type */
7235 ret = btrfs_add_ordered_extent_dio(inode, start, block_start,
7236 len, block_len, type);
7239 free_extent_map(em);
7240 btrfs_drop_extent_cache(BTRFS_I(inode), start,
7241 start + len - 1, 0);
7250 static struct extent_map *btrfs_new_extent_direct(struct inode *inode,
7253 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7254 struct btrfs_root *root = BTRFS_I(inode)->root;
7255 struct extent_map *em;
7256 struct btrfs_key ins;
7260 alloc_hint = get_extent_allocation_hint(inode, start, len);
7261 ret = btrfs_reserve_extent(root, len, len, fs_info->sectorsize,
7262 0, alloc_hint, &ins, 1, 1);
7264 return ERR_PTR(ret);
7266 em = btrfs_create_dio_extent(inode, start, ins.offset, start,
7267 ins.objectid, ins.offset, ins.offset,
7268 ins.offset, BTRFS_ORDERED_REGULAR);
7269 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
7271 btrfs_free_reserved_extent(fs_info, ins.objectid,
7278 * returns 1 when the nocow is safe, < 1 on error, 0 if the
7279 * block must be cow'd
7281 noinline int can_nocow_extent(struct inode *inode, u64 offset, u64 *len,
7282 u64 *orig_start, u64 *orig_block_len,
7285 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7286 struct btrfs_path *path;
7288 struct extent_buffer *leaf;
7289 struct btrfs_root *root = BTRFS_I(inode)->root;
7290 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
7291 struct btrfs_file_extent_item *fi;
7292 struct btrfs_key key;
7299 bool nocow = (BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW);
7301 path = btrfs_alloc_path();
7305 ret = btrfs_lookup_file_extent(NULL, root, path,
7306 btrfs_ino(BTRFS_I(inode)), offset, 0);
7310 slot = path->slots[0];
7313 /* can't find the item, must cow */
7320 leaf = path->nodes[0];
7321 btrfs_item_key_to_cpu(leaf, &key, slot);
7322 if (key.objectid != btrfs_ino(BTRFS_I(inode)) ||
7323 key.type != BTRFS_EXTENT_DATA_KEY) {
7324 /* not our file or wrong item type, must cow */
7328 if (key.offset > offset) {
7329 /* Wrong offset, must cow */
7333 fi = btrfs_item_ptr(leaf, slot, struct btrfs_file_extent_item);
7334 found_type = btrfs_file_extent_type(leaf, fi);
7335 if (found_type != BTRFS_FILE_EXTENT_REG &&
7336 found_type != BTRFS_FILE_EXTENT_PREALLOC) {
7337 /* not a regular extent, must cow */
7341 if (!nocow && found_type == BTRFS_FILE_EXTENT_REG)
7344 extent_end = key.offset + btrfs_file_extent_num_bytes(leaf, fi);
7345 if (extent_end <= offset)
7348 disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
7349 if (disk_bytenr == 0)
7352 if (btrfs_file_extent_compression(leaf, fi) ||
7353 btrfs_file_extent_encryption(leaf, fi) ||
7354 btrfs_file_extent_other_encoding(leaf, fi))
7358 * Do the same check as in btrfs_cross_ref_exist but without the
7359 * unnecessary search.
7361 if (btrfs_file_extent_generation(leaf, fi) <=
7362 btrfs_root_last_snapshot(&root->root_item))
7365 backref_offset = btrfs_file_extent_offset(leaf, fi);
7368 *orig_start = key.offset - backref_offset;
7369 *orig_block_len = btrfs_file_extent_disk_num_bytes(leaf, fi);
7370 *ram_bytes = btrfs_file_extent_ram_bytes(leaf, fi);
7373 if (btrfs_extent_readonly(fs_info, disk_bytenr))
7376 num_bytes = min(offset + *len, extent_end) - offset;
7377 if (!nocow && found_type == BTRFS_FILE_EXTENT_PREALLOC) {
7380 range_end = round_up(offset + num_bytes,
7381 root->fs_info->sectorsize) - 1;
7382 ret = test_range_bit(io_tree, offset, range_end,
7383 EXTENT_DELALLOC, 0, NULL);
7390 btrfs_release_path(path);
7393 * look for other files referencing this extent, if we
7394 * find any we must cow
7397 ret = btrfs_cross_ref_exist(root, btrfs_ino(BTRFS_I(inode)),
7398 key.offset - backref_offset, disk_bytenr);
7405 * adjust disk_bytenr and num_bytes to cover just the bytes
7406 * in this extent we are about to write. If there
7407 * are any csums in that range we have to cow in order
7408 * to keep the csums correct
7410 disk_bytenr += backref_offset;
7411 disk_bytenr += offset - key.offset;
7412 if (csum_exist_in_range(fs_info, disk_bytenr, num_bytes))
7415 * all of the above have passed, it is safe to overwrite this extent
7421 btrfs_free_path(path);
7425 static int lock_extent_direct(struct inode *inode, u64 lockstart, u64 lockend,
7426 struct extent_state **cached_state, int writing)
7428 struct btrfs_ordered_extent *ordered;
7432 lock_extent_bits(&BTRFS_I(inode)->io_tree, lockstart, lockend,
7435 * We're concerned with the entire range that we're going to be
7436 * doing DIO to, so we need to make sure there's no ordered
7437 * extents in this range.
7439 ordered = btrfs_lookup_ordered_range(BTRFS_I(inode), lockstart,
7440 lockend - lockstart + 1);
7443 * We need to make sure there are no buffered pages in this
7444 * range either, we could have raced between the invalidate in
7445 * generic_file_direct_write and locking the extent. The
7446 * invalidate needs to happen so that reads after a write do not
7450 (!writing || !filemap_range_has_page(inode->i_mapping,
7451 lockstart, lockend)))
7454 unlock_extent_cached(&BTRFS_I(inode)->io_tree, lockstart, lockend,
7459 * If we are doing a DIO read and the ordered extent we
7460 * found is for a buffered write, we can not wait for it
7461 * to complete and retry, because if we do so we can
7462 * deadlock with concurrent buffered writes on page
7463 * locks. This happens only if our DIO read covers more
7464 * than one extent map, if at this point has already
7465 * created an ordered extent for a previous extent map
7466 * and locked its range in the inode's io tree, and a
7467 * concurrent write against that previous extent map's
7468 * range and this range started (we unlock the ranges
7469 * in the io tree only when the bios complete and
7470 * buffered writes always lock pages before attempting
7471 * to lock range in the io tree).
7474 test_bit(BTRFS_ORDERED_DIRECT, &ordered->flags))
7475 btrfs_start_ordered_extent(inode, ordered, 1);
7478 btrfs_put_ordered_extent(ordered);
7481 * We could trigger writeback for this range (and wait
7482 * for it to complete) and then invalidate the pages for
7483 * this range (through invalidate_inode_pages2_range()),
7484 * but that can lead us to a deadlock with a concurrent
7485 * call to readpages() (a buffered read or a defrag call
7486 * triggered a readahead) on a page lock due to an
7487 * ordered dio extent we created before but did not have
7488 * yet a corresponding bio submitted (whence it can not
7489 * complete), which makes readpages() wait for that
7490 * ordered extent to complete while holding a lock on
7505 /* The callers of this must take lock_extent() */
7506 static struct extent_map *create_io_em(struct inode *inode, u64 start, u64 len,
7507 u64 orig_start, u64 block_start,
7508 u64 block_len, u64 orig_block_len,
7509 u64 ram_bytes, int compress_type,
7512 struct extent_map_tree *em_tree;
7513 struct extent_map *em;
7514 struct btrfs_root *root = BTRFS_I(inode)->root;
7517 ASSERT(type == BTRFS_ORDERED_PREALLOC ||
7518 type == BTRFS_ORDERED_COMPRESSED ||
7519 type == BTRFS_ORDERED_NOCOW ||
7520 type == BTRFS_ORDERED_REGULAR);
7522 em_tree = &BTRFS_I(inode)->extent_tree;
7523 em = alloc_extent_map();
7525 return ERR_PTR(-ENOMEM);
7528 em->orig_start = orig_start;
7530 em->block_len = block_len;
7531 em->block_start = block_start;
7532 em->bdev = root->fs_info->fs_devices->latest_bdev;
7533 em->orig_block_len = orig_block_len;
7534 em->ram_bytes = ram_bytes;
7535 em->generation = -1;
7536 set_bit(EXTENT_FLAG_PINNED, &em->flags);
7537 if (type == BTRFS_ORDERED_PREALLOC) {
7538 set_bit(EXTENT_FLAG_FILLING, &em->flags);
7539 } else if (type == BTRFS_ORDERED_COMPRESSED) {
7540 set_bit(EXTENT_FLAG_COMPRESSED, &em->flags);
7541 em->compress_type = compress_type;
7545 btrfs_drop_extent_cache(BTRFS_I(inode), em->start,
7546 em->start + em->len - 1, 0);
7547 write_lock(&em_tree->lock);
7548 ret = add_extent_mapping(em_tree, em, 1);
7549 write_unlock(&em_tree->lock);
7551 * The caller has taken lock_extent(), who could race with us
7554 } while (ret == -EEXIST);
7557 free_extent_map(em);
7558 return ERR_PTR(ret);
7561 /* em got 2 refs now, callers needs to do free_extent_map once. */
7566 static int btrfs_get_blocks_direct_read(struct extent_map *em,
7567 struct buffer_head *bh_result,
7568 struct inode *inode,
7571 if (em->block_start == EXTENT_MAP_HOLE ||
7572 test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
7575 len = min(len, em->len - (start - em->start));
7577 bh_result->b_blocknr = (em->block_start + (start - em->start)) >>
7579 bh_result->b_size = len;
7580 bh_result->b_bdev = em->bdev;
7581 set_buffer_mapped(bh_result);
7586 static int btrfs_get_blocks_direct_write(struct extent_map **map,
7587 struct buffer_head *bh_result,
7588 struct inode *inode,
7589 struct btrfs_dio_data *dio_data,
7592 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7593 struct extent_map *em = *map;
7597 * We don't allocate a new extent in the following cases
7599 * 1) The inode is marked as NODATACOW. In this case we'll just use the
7601 * 2) The extent is marked as PREALLOC. We're good to go here and can
7602 * just use the extent.
7605 if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags) ||
7606 ((BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW) &&
7607 em->block_start != EXTENT_MAP_HOLE)) {
7609 u64 block_start, orig_start, orig_block_len, ram_bytes;
7611 if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
7612 type = BTRFS_ORDERED_PREALLOC;
7614 type = BTRFS_ORDERED_NOCOW;
7615 len = min(len, em->len - (start - em->start));
7616 block_start = em->block_start + (start - em->start);
7618 if (can_nocow_extent(inode, start, &len, &orig_start,
7619 &orig_block_len, &ram_bytes) == 1 &&
7620 btrfs_inc_nocow_writers(fs_info, block_start)) {
7621 struct extent_map *em2;
7623 em2 = btrfs_create_dio_extent(inode, start, len,
7624 orig_start, block_start,
7625 len, orig_block_len,
7627 btrfs_dec_nocow_writers(fs_info, block_start);
7628 if (type == BTRFS_ORDERED_PREALLOC) {
7629 free_extent_map(em);
7633 if (em2 && IS_ERR(em2)) {
7638 * For inode marked NODATACOW or extent marked PREALLOC,
7639 * use the existing or preallocated extent, so does not
7640 * need to adjust btrfs_space_info's bytes_may_use.
7642 btrfs_free_reserved_data_space_noquota(inode, start,
7648 /* this will cow the extent */
7649 len = bh_result->b_size;
7650 free_extent_map(em);
7651 *map = em = btrfs_new_extent_direct(inode, start, len);
7657 len = min(len, em->len - (start - em->start));
7660 bh_result->b_blocknr = (em->block_start + (start - em->start)) >>
7662 bh_result->b_size = len;
7663 bh_result->b_bdev = em->bdev;
7664 set_buffer_mapped(bh_result);
7666 if (!test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
7667 set_buffer_new(bh_result);
7670 * Need to update the i_size under the extent lock so buffered
7671 * readers will get the updated i_size when we unlock.
7673 if (!dio_data->overwrite && start + len > i_size_read(inode))
7674 i_size_write(inode, start + len);
7676 WARN_ON(dio_data->reserve < len);
7677 dio_data->reserve -= len;
7678 dio_data->unsubmitted_oe_range_end = start + len;
7679 current->journal_info = dio_data;
7684 static int btrfs_get_blocks_direct(struct inode *inode, sector_t iblock,
7685 struct buffer_head *bh_result, int create)
7687 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7688 struct extent_map *em;
7689 struct extent_state *cached_state = NULL;
7690 struct btrfs_dio_data *dio_data = NULL;
7691 u64 start = iblock << inode->i_blkbits;
7692 u64 lockstart, lockend;
7693 u64 len = bh_result->b_size;
7694 int unlock_bits = EXTENT_LOCKED;
7698 unlock_bits |= EXTENT_DIRTY;
7700 len = min_t(u64, len, fs_info->sectorsize);
7703 lockend = start + len - 1;
7705 if (current->journal_info) {
7707 * Need to pull our outstanding extents and set journal_info to NULL so
7708 * that anything that needs to check if there's a transaction doesn't get
7711 dio_data = current->journal_info;
7712 current->journal_info = NULL;
7716 * If this errors out it's because we couldn't invalidate pagecache for
7717 * this range and we need to fallback to buffered.
7719 if (lock_extent_direct(inode, lockstart, lockend, &cached_state,
7725 em = btrfs_get_extent(BTRFS_I(inode), NULL, 0, start, len, 0);
7732 * Ok for INLINE and COMPRESSED extents we need to fallback on buffered
7733 * io. INLINE is special, and we could probably kludge it in here, but
7734 * it's still buffered so for safety lets just fall back to the generic
7737 * For COMPRESSED we _have_ to read the entire extent in so we can
7738 * decompress it, so there will be buffering required no matter what we
7739 * do, so go ahead and fallback to buffered.
7741 * We return -ENOTBLK because that's what makes DIO go ahead and go back
7742 * to buffered IO. Don't blame me, this is the price we pay for using
7745 if (test_bit(EXTENT_FLAG_COMPRESSED, &em->flags) ||
7746 em->block_start == EXTENT_MAP_INLINE) {
7747 free_extent_map(em);
7753 ret = btrfs_get_blocks_direct_write(&em, bh_result, inode,
7754 dio_data, start, len);
7758 /* clear and unlock the entire range */
7759 clear_extent_bit(&BTRFS_I(inode)->io_tree, lockstart, lockend,
7760 unlock_bits, 1, 0, &cached_state);
7762 ret = btrfs_get_blocks_direct_read(em, bh_result, inode,
7764 /* Can be negative only if we read from a hole */
7767 free_extent_map(em);
7771 * We need to unlock only the end area that we aren't using.
7772 * The rest is going to be unlocked by the endio routine.
7774 lockstart = start + bh_result->b_size;
7775 if (lockstart < lockend) {
7776 clear_extent_bit(&BTRFS_I(inode)->io_tree, lockstart,
7777 lockend, unlock_bits, 1, 0,
7780 free_extent_state(cached_state);
7784 free_extent_map(em);
7789 clear_extent_bit(&BTRFS_I(inode)->io_tree, lockstart, lockend,
7790 unlock_bits, 1, 0, &cached_state);
7793 current->journal_info = dio_data;
7797 static inline blk_status_t submit_dio_repair_bio(struct inode *inode,
7801 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7804 BUG_ON(bio_op(bio) == REQ_OP_WRITE);
7806 ret = btrfs_bio_wq_end_io(fs_info, bio, BTRFS_WQ_ENDIO_DIO_REPAIR);
7810 ret = btrfs_map_bio(fs_info, bio, mirror_num, 0);
7815 static int btrfs_check_dio_repairable(struct inode *inode,
7816 struct bio *failed_bio,
7817 struct io_failure_record *failrec,
7820 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7823 num_copies = btrfs_num_copies(fs_info, failrec->logical, failrec->len);
7824 if (num_copies == 1) {
7826 * we only have a single copy of the data, so don't bother with
7827 * all the retry and error correction code that follows. no
7828 * matter what the error is, it is very likely to persist.
7830 btrfs_debug(fs_info,
7831 "Check DIO Repairable: cannot repair, num_copies=%d, next_mirror %d, failed_mirror %d",
7832 num_copies, failrec->this_mirror, failed_mirror);
7836 failrec->failed_mirror = failed_mirror;
7837 failrec->this_mirror++;
7838 if (failrec->this_mirror == failed_mirror)
7839 failrec->this_mirror++;
7841 if (failrec->this_mirror > num_copies) {
7842 btrfs_debug(fs_info,
7843 "Check DIO Repairable: (fail) num_copies=%d, next_mirror %d, failed_mirror %d",
7844 num_copies, failrec->this_mirror, failed_mirror);
7851 static blk_status_t dio_read_error(struct inode *inode, struct bio *failed_bio,
7852 struct page *page, unsigned int pgoff,
7853 u64 start, u64 end, int failed_mirror,
7854 bio_end_io_t *repair_endio, void *repair_arg)
7856 struct io_failure_record *failrec;
7857 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
7858 struct extent_io_tree *failure_tree = &BTRFS_I(inode)->io_failure_tree;
7861 unsigned int read_mode = 0;
7864 blk_status_t status;
7865 struct bio_vec bvec;
7867 BUG_ON(bio_op(failed_bio) == REQ_OP_WRITE);
7869 ret = btrfs_get_io_failure_record(inode, start, end, &failrec);
7871 return errno_to_blk_status(ret);
7873 ret = btrfs_check_dio_repairable(inode, failed_bio, failrec,
7876 free_io_failure(failure_tree, io_tree, failrec);
7877 return BLK_STS_IOERR;
7880 segs = bio_segments(failed_bio);
7881 bio_get_first_bvec(failed_bio, &bvec);
7883 (bvec.bv_len > btrfs_inode_sectorsize(inode)))
7884 read_mode |= REQ_FAILFAST_DEV;
7886 isector = start - btrfs_io_bio(failed_bio)->logical;
7887 isector >>= inode->i_sb->s_blocksize_bits;
7888 bio = btrfs_create_repair_bio(inode, failed_bio, failrec, page,
7889 pgoff, isector, repair_endio, repair_arg);
7890 bio->bi_opf = REQ_OP_READ | read_mode;
7892 btrfs_debug(BTRFS_I(inode)->root->fs_info,
7893 "repair DIO read error: submitting new dio read[%#x] to this_mirror=%d, in_validation=%d",
7894 read_mode, failrec->this_mirror, failrec->in_validation);
7896 status = submit_dio_repair_bio(inode, bio, failrec->this_mirror);
7898 free_io_failure(failure_tree, io_tree, failrec);
7905 struct btrfs_retry_complete {
7906 struct completion done;
7907 struct inode *inode;
7912 static void btrfs_retry_endio_nocsum(struct bio *bio)
7914 struct btrfs_retry_complete *done = bio->bi_private;
7915 struct inode *inode = done->inode;
7916 struct bio_vec *bvec;
7917 struct extent_io_tree *io_tree, *failure_tree;
7918 struct bvec_iter_all iter_all;
7923 ASSERT(bio->bi_vcnt == 1);
7924 io_tree = &BTRFS_I(inode)->io_tree;
7925 failure_tree = &BTRFS_I(inode)->io_failure_tree;
7926 ASSERT(bio_first_bvec_all(bio)->bv_len == btrfs_inode_sectorsize(inode));
7929 ASSERT(!bio_flagged(bio, BIO_CLONED));
7930 bio_for_each_segment_all(bvec, bio, iter_all)
7931 clean_io_failure(BTRFS_I(inode)->root->fs_info, failure_tree,
7932 io_tree, done->start, bvec->bv_page,
7933 btrfs_ino(BTRFS_I(inode)), 0);
7935 complete(&done->done);
7939 static blk_status_t __btrfs_correct_data_nocsum(struct inode *inode,
7940 struct btrfs_io_bio *io_bio)
7942 struct btrfs_fs_info *fs_info;
7943 struct bio_vec bvec;
7944 struct bvec_iter iter;
7945 struct btrfs_retry_complete done;
7951 blk_status_t err = BLK_STS_OK;
7953 fs_info = BTRFS_I(inode)->root->fs_info;
7954 sectorsize = fs_info->sectorsize;
7956 start = io_bio->logical;
7958 io_bio->bio.bi_iter = io_bio->iter;
7960 bio_for_each_segment(bvec, &io_bio->bio, iter) {
7961 nr_sectors = BTRFS_BYTES_TO_BLKS(fs_info, bvec.bv_len);
7962 pgoff = bvec.bv_offset;
7964 next_block_or_try_again:
7967 init_completion(&done.done);
7969 ret = dio_read_error(inode, &io_bio->bio, bvec.bv_page,
7970 pgoff, start, start + sectorsize - 1,
7972 btrfs_retry_endio_nocsum, &done);
7978 wait_for_completion_io(&done.done);
7980 if (!done.uptodate) {
7981 /* We might have another mirror, so try again */
7982 goto next_block_or_try_again;
7986 start += sectorsize;
7990 pgoff += sectorsize;
7991 ASSERT(pgoff < PAGE_SIZE);
7992 goto next_block_or_try_again;
7999 static void btrfs_retry_endio(struct bio *bio)
8001 struct btrfs_retry_complete *done = bio->bi_private;
8002 struct btrfs_io_bio *io_bio = btrfs_io_bio(bio);
8003 struct extent_io_tree *io_tree, *failure_tree;
8004 struct inode *inode = done->inode;
8005 struct bio_vec *bvec;
8009 struct bvec_iter_all iter_all;
8016 ASSERT(bio->bi_vcnt == 1);
8017 ASSERT(bio_first_bvec_all(bio)->bv_len == btrfs_inode_sectorsize(done->inode));
8019 io_tree = &BTRFS_I(inode)->io_tree;
8020 failure_tree = &BTRFS_I(inode)->io_failure_tree;
8022 ASSERT(!bio_flagged(bio, BIO_CLONED));
8023 bio_for_each_segment_all(bvec, bio, iter_all) {
8024 ret = __readpage_endio_check(inode, io_bio, i, bvec->bv_page,
8025 bvec->bv_offset, done->start,
8028 clean_io_failure(BTRFS_I(inode)->root->fs_info,
8029 failure_tree, io_tree, done->start,
8031 btrfs_ino(BTRFS_I(inode)),
8038 done->uptodate = uptodate;
8040 complete(&done->done);
8044 static blk_status_t __btrfs_subio_endio_read(struct inode *inode,
8045 struct btrfs_io_bio *io_bio, blk_status_t err)
8047 struct btrfs_fs_info *fs_info;
8048 struct bio_vec bvec;
8049 struct bvec_iter iter;
8050 struct btrfs_retry_complete done;
8057 bool uptodate = (err == 0);
8059 blk_status_t status;
8061 fs_info = BTRFS_I(inode)->root->fs_info;
8062 sectorsize = fs_info->sectorsize;
8065 start = io_bio->logical;
8067 io_bio->bio.bi_iter = io_bio->iter;
8069 bio_for_each_segment(bvec, &io_bio->bio, iter) {
8070 nr_sectors = BTRFS_BYTES_TO_BLKS(fs_info, bvec.bv_len);
8072 pgoff = bvec.bv_offset;
8075 csum_pos = BTRFS_BYTES_TO_BLKS(fs_info, offset);
8076 ret = __readpage_endio_check(inode, io_bio, csum_pos,
8077 bvec.bv_page, pgoff, start, sectorsize);
8084 init_completion(&done.done);
8086 status = dio_read_error(inode, &io_bio->bio, bvec.bv_page,
8087 pgoff, start, start + sectorsize - 1,
8088 io_bio->mirror_num, btrfs_retry_endio,
8095 wait_for_completion_io(&done.done);
8097 if (!done.uptodate) {
8098 /* We might have another mirror, so try again */
8102 offset += sectorsize;
8103 start += sectorsize;
8109 pgoff += sectorsize;
8110 ASSERT(pgoff < PAGE_SIZE);
8118 static blk_status_t btrfs_subio_endio_read(struct inode *inode,
8119 struct btrfs_io_bio *io_bio, blk_status_t err)
8121 bool skip_csum = BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM;
8125 return __btrfs_correct_data_nocsum(inode, io_bio);
8129 return __btrfs_subio_endio_read(inode, io_bio, err);
8133 static void btrfs_endio_direct_read(struct bio *bio)
8135 struct btrfs_dio_private *dip = bio->bi_private;
8136 struct inode *inode = dip->inode;
8137 struct bio *dio_bio;
8138 struct btrfs_io_bio *io_bio = btrfs_io_bio(bio);
8139 blk_status_t err = bio->bi_status;
8141 if (dip->flags & BTRFS_DIO_ORIG_BIO_SUBMITTED)
8142 err = btrfs_subio_endio_read(inode, io_bio, err);
8144 unlock_extent(&BTRFS_I(inode)->io_tree, dip->logical_offset,
8145 dip->logical_offset + dip->bytes - 1);
8146 dio_bio = dip->dio_bio;
8150 dio_bio->bi_status = err;
8151 dio_end_io(dio_bio);
8152 btrfs_io_bio_free_csum(io_bio);
8156 static void __endio_write_update_ordered(struct inode *inode,
8157 const u64 offset, const u64 bytes,
8158 const bool uptodate)
8160 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
8161 struct btrfs_ordered_extent *ordered = NULL;
8162 struct btrfs_workqueue *wq;
8163 btrfs_work_func_t func;
8164 u64 ordered_offset = offset;
8165 u64 ordered_bytes = bytes;
8168 if (btrfs_is_free_space_inode(BTRFS_I(inode))) {
8169 wq = fs_info->endio_freespace_worker;
8170 func = btrfs_freespace_write_helper;
8172 wq = fs_info->endio_write_workers;
8173 func = btrfs_endio_write_helper;
8176 while (ordered_offset < offset + bytes) {
8177 last_offset = ordered_offset;
8178 if (btrfs_dec_test_first_ordered_pending(inode, &ordered,
8182 btrfs_init_work(&ordered->work, func,
8185 btrfs_queue_work(wq, &ordered->work);
8188 * If btrfs_dec_test_ordered_pending does not find any ordered
8189 * extent in the range, we can exit.
8191 if (ordered_offset == last_offset)
8194 * Our bio might span multiple ordered extents. In this case
8195 * we keep going until we have accounted the whole dio.
8197 if (ordered_offset < offset + bytes) {
8198 ordered_bytes = offset + bytes - ordered_offset;
8204 static void btrfs_endio_direct_write(struct bio *bio)
8206 struct btrfs_dio_private *dip = bio->bi_private;
8207 struct bio *dio_bio = dip->dio_bio;
8209 __endio_write_update_ordered(dip->inode, dip->logical_offset,
8210 dip->bytes, !bio->bi_status);
8214 dio_bio->bi_status = bio->bi_status;
8215 dio_end_io(dio_bio);
8219 static blk_status_t btrfs_submit_bio_start_direct_io(void *private_data,
8220 struct bio *bio, u64 offset)
8222 struct inode *inode = private_data;
8224 ret = btrfs_csum_one_bio(inode, bio, offset, 1);
8225 BUG_ON(ret); /* -ENOMEM */
8229 static void btrfs_end_dio_bio(struct bio *bio)
8231 struct btrfs_dio_private *dip = bio->bi_private;
8232 blk_status_t err = bio->bi_status;
8235 btrfs_warn(BTRFS_I(dip->inode)->root->fs_info,
8236 "direct IO failed ino %llu rw %d,%u sector %#Lx len %u err no %d",
8237 btrfs_ino(BTRFS_I(dip->inode)), bio_op(bio),
8239 (unsigned long long)bio->bi_iter.bi_sector,
8240 bio->bi_iter.bi_size, err);
8242 if (dip->subio_endio)
8243 err = dip->subio_endio(dip->inode, btrfs_io_bio(bio), err);
8247 * We want to perceive the errors flag being set before
8248 * decrementing the reference count. We don't need a barrier
8249 * since atomic operations with a return value are fully
8250 * ordered as per atomic_t.txt
8255 /* if there are more bios still pending for this dio, just exit */
8256 if (!atomic_dec_and_test(&dip->pending_bios))
8260 bio_io_error(dip->orig_bio);
8262 dip->dio_bio->bi_status = BLK_STS_OK;
8263 bio_endio(dip->orig_bio);
8269 static inline blk_status_t btrfs_lookup_and_bind_dio_csum(struct inode *inode,
8270 struct btrfs_dio_private *dip,
8274 struct btrfs_io_bio *io_bio = btrfs_io_bio(bio);
8275 struct btrfs_io_bio *orig_io_bio = btrfs_io_bio(dip->orig_bio);
8279 * We load all the csum data we need when we submit
8280 * the first bio to reduce the csum tree search and
8283 if (dip->logical_offset == file_offset) {
8284 ret = btrfs_lookup_bio_sums_dio(inode, dip->orig_bio,
8290 if (bio == dip->orig_bio)
8293 file_offset -= dip->logical_offset;
8294 file_offset >>= inode->i_sb->s_blocksize_bits;
8295 io_bio->csum = (u8 *)(((u32 *)orig_io_bio->csum) + file_offset);
8300 static inline blk_status_t btrfs_submit_dio_bio(struct bio *bio,
8301 struct inode *inode, u64 file_offset, int async_submit)
8303 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
8304 struct btrfs_dio_private *dip = bio->bi_private;
8305 bool write = bio_op(bio) == REQ_OP_WRITE;
8308 /* Check btrfs_submit_bio_hook() for rules about async submit. */
8310 async_submit = !atomic_read(&BTRFS_I(inode)->sync_writers);
8313 ret = btrfs_bio_wq_end_io(fs_info, bio, BTRFS_WQ_ENDIO_DATA);
8318 if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)
8321 if (write && async_submit) {
8322 ret = btrfs_wq_submit_bio(fs_info, bio, 0, 0,
8324 btrfs_submit_bio_start_direct_io);
8328 * If we aren't doing async submit, calculate the csum of the
8331 ret = btrfs_csum_one_bio(inode, bio, file_offset, 1);
8335 ret = btrfs_lookup_and_bind_dio_csum(inode, dip, bio,
8341 ret = btrfs_map_bio(fs_info, bio, 0, 0);
8346 static int btrfs_submit_direct_hook(struct btrfs_dio_private *dip)
8348 struct inode *inode = dip->inode;
8349 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
8351 struct bio *orig_bio = dip->orig_bio;
8352 u64 start_sector = orig_bio->bi_iter.bi_sector;
8353 u64 file_offset = dip->logical_offset;
8354 int async_submit = 0;
8356 int clone_offset = 0;
8359 blk_status_t status;
8360 struct btrfs_io_geometry geom;
8362 submit_len = orig_bio->bi_iter.bi_size;
8363 ret = btrfs_get_io_geometry(fs_info, btrfs_op(orig_bio),
8364 start_sector << 9, submit_len, &geom);
8368 if (geom.len >= submit_len) {
8370 dip->flags |= BTRFS_DIO_ORIG_BIO_SUBMITTED;
8374 /* async crcs make it difficult to collect full stripe writes. */
8375 if (btrfs_data_alloc_profile(fs_info) & BTRFS_BLOCK_GROUP_RAID56_MASK)
8381 ASSERT(geom.len <= INT_MAX);
8382 atomic_inc(&dip->pending_bios);
8384 clone_len = min_t(int, submit_len, geom.len);
8387 * This will never fail as it's passing GPF_NOFS and
8388 * the allocation is backed by btrfs_bioset.
8390 bio = btrfs_bio_clone_partial(orig_bio, clone_offset,
8392 bio->bi_private = dip;
8393 bio->bi_end_io = btrfs_end_dio_bio;
8394 btrfs_io_bio(bio)->logical = file_offset;
8396 ASSERT(submit_len >= clone_len);
8397 submit_len -= clone_len;
8398 if (submit_len == 0)
8402 * Increase the count before we submit the bio so we know
8403 * the end IO handler won't happen before we increase the
8404 * count. Otherwise, the dip might get freed before we're
8405 * done setting it up.
8407 atomic_inc(&dip->pending_bios);
8409 status = btrfs_submit_dio_bio(bio, inode, file_offset,
8413 atomic_dec(&dip->pending_bios);
8417 clone_offset += clone_len;
8418 start_sector += clone_len >> 9;
8419 file_offset += clone_len;
8421 ret = btrfs_get_io_geometry(fs_info, btrfs_op(orig_bio),
8422 start_sector << 9, submit_len, &geom);
8425 } while (submit_len > 0);
8428 status = btrfs_submit_dio_bio(bio, inode, file_offset, async_submit);
8436 * Before atomic variable goto zero, we must make sure dip->errors is
8437 * perceived to be set. This ordering is ensured by the fact that an
8438 * atomic operations with a return value are fully ordered as per
8441 if (atomic_dec_and_test(&dip->pending_bios))
8442 bio_io_error(dip->orig_bio);
8444 /* bio_end_io() will handle error, so we needn't return it */
8448 static void btrfs_submit_direct(struct bio *dio_bio, struct inode *inode,
8451 struct btrfs_dio_private *dip = NULL;
8452 struct bio *bio = NULL;
8453 struct btrfs_io_bio *io_bio;
8454 bool write = (bio_op(dio_bio) == REQ_OP_WRITE);
8457 bio = btrfs_bio_clone(dio_bio);
8459 dip = kzalloc(sizeof(*dip), GFP_NOFS);
8465 dip->private = dio_bio->bi_private;
8467 dip->logical_offset = file_offset;
8468 dip->bytes = dio_bio->bi_iter.bi_size;
8469 dip->disk_bytenr = (u64)dio_bio->bi_iter.bi_sector << 9;
8470 bio->bi_private = dip;
8471 dip->orig_bio = bio;
8472 dip->dio_bio = dio_bio;
8473 atomic_set(&dip->pending_bios, 0);
8474 io_bio = btrfs_io_bio(bio);
8475 io_bio->logical = file_offset;
8478 bio->bi_end_io = btrfs_endio_direct_write;
8480 bio->bi_end_io = btrfs_endio_direct_read;
8481 dip->subio_endio = btrfs_subio_endio_read;
8485 * Reset the range for unsubmitted ordered extents (to a 0 length range)
8486 * even if we fail to submit a bio, because in such case we do the
8487 * corresponding error handling below and it must not be done a second
8488 * time by btrfs_direct_IO().
8491 struct btrfs_dio_data *dio_data = current->journal_info;
8493 dio_data->unsubmitted_oe_range_end = dip->logical_offset +
8495 dio_data->unsubmitted_oe_range_start =
8496 dio_data->unsubmitted_oe_range_end;
8499 ret = btrfs_submit_direct_hook(dip);
8503 btrfs_io_bio_free_csum(io_bio);
8507 * If we arrived here it means either we failed to submit the dip
8508 * or we either failed to clone the dio_bio or failed to allocate the
8509 * dip. If we cloned the dio_bio and allocated the dip, we can just
8510 * call bio_endio against our io_bio so that we get proper resource
8511 * cleanup if we fail to submit the dip, otherwise, we must do the
8512 * same as btrfs_endio_direct_[write|read] because we can't call these
8513 * callbacks - they require an allocated dip and a clone of dio_bio.
8518 * The end io callbacks free our dip, do the final put on bio
8519 * and all the cleanup and final put for dio_bio (through
8526 __endio_write_update_ordered(inode,
8528 dio_bio->bi_iter.bi_size,
8531 unlock_extent(&BTRFS_I(inode)->io_tree, file_offset,
8532 file_offset + dio_bio->bi_iter.bi_size - 1);
8534 dio_bio->bi_status = BLK_STS_IOERR;
8536 * Releases and cleans up our dio_bio, no need to bio_put()
8537 * nor bio_endio()/bio_io_error() against dio_bio.
8539 dio_end_io(dio_bio);
8546 static ssize_t check_direct_IO(struct btrfs_fs_info *fs_info,
8547 const struct iov_iter *iter, loff_t offset)
8551 unsigned int blocksize_mask = fs_info->sectorsize - 1;
8552 ssize_t retval = -EINVAL;
8554 if (offset & blocksize_mask)
8557 if (iov_iter_alignment(iter) & blocksize_mask)
8560 /* If this is a write we don't need to check anymore */
8561 if (iov_iter_rw(iter) != READ || !iter_is_iovec(iter))
8564 * Check to make sure we don't have duplicate iov_base's in this
8565 * iovec, if so return EINVAL, otherwise we'll get csum errors
8566 * when reading back.
8568 for (seg = 0; seg < iter->nr_segs; seg++) {
8569 for (i = seg + 1; i < iter->nr_segs; i++) {
8570 if (iter->iov[seg].iov_base == iter->iov[i].iov_base)
8579 static ssize_t btrfs_direct_IO(struct kiocb *iocb, struct iov_iter *iter)
8581 struct file *file = iocb->ki_filp;
8582 struct inode *inode = file->f_mapping->host;
8583 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
8584 struct btrfs_dio_data dio_data = { 0 };
8585 struct extent_changeset *data_reserved = NULL;
8586 loff_t offset = iocb->ki_pos;
8590 bool relock = false;
8593 if (check_direct_IO(fs_info, iter, offset))
8596 inode_dio_begin(inode);
8599 * The generic stuff only does filemap_write_and_wait_range, which
8600 * isn't enough if we've written compressed pages to this area, so
8601 * we need to flush the dirty pages again to make absolutely sure
8602 * that any outstanding dirty pages are on disk.
8604 count = iov_iter_count(iter);
8605 if (test_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
8606 &BTRFS_I(inode)->runtime_flags))
8607 filemap_fdatawrite_range(inode->i_mapping, offset,
8608 offset + count - 1);
8610 if (iov_iter_rw(iter) == WRITE) {
8612 * If the write DIO is beyond the EOF, we need update
8613 * the isize, but it is protected by i_mutex. So we can
8614 * not unlock the i_mutex at this case.
8616 if (offset + count <= inode->i_size) {
8617 dio_data.overwrite = 1;
8618 inode_unlock(inode);
8620 } else if (iocb->ki_flags & IOCB_NOWAIT) {
8624 ret = btrfs_delalloc_reserve_space(inode, &data_reserved,
8630 * We need to know how many extents we reserved so that we can
8631 * do the accounting properly if we go over the number we
8632 * originally calculated. Abuse current->journal_info for this.
8634 dio_data.reserve = round_up(count,
8635 fs_info->sectorsize);
8636 dio_data.unsubmitted_oe_range_start = (u64)offset;
8637 dio_data.unsubmitted_oe_range_end = (u64)offset;
8638 current->journal_info = &dio_data;
8639 down_read(&BTRFS_I(inode)->dio_sem);
8640 } else if (test_bit(BTRFS_INODE_READDIO_NEED_LOCK,
8641 &BTRFS_I(inode)->runtime_flags)) {
8642 inode_dio_end(inode);
8643 flags = DIO_LOCKING | DIO_SKIP_HOLES;
8647 ret = __blockdev_direct_IO(iocb, inode,
8648 fs_info->fs_devices->latest_bdev,
8649 iter, btrfs_get_blocks_direct, NULL,
8650 btrfs_submit_direct, flags);
8651 if (iov_iter_rw(iter) == WRITE) {
8652 up_read(&BTRFS_I(inode)->dio_sem);
8653 current->journal_info = NULL;
8654 if (ret < 0 && ret != -EIOCBQUEUED) {
8655 if (dio_data.reserve)
8656 btrfs_delalloc_release_space(inode, data_reserved,
8657 offset, dio_data.reserve, true);
8659 * On error we might have left some ordered extents
8660 * without submitting corresponding bios for them, so
8661 * cleanup them up to avoid other tasks getting them
8662 * and waiting for them to complete forever.
8664 if (dio_data.unsubmitted_oe_range_start <
8665 dio_data.unsubmitted_oe_range_end)
8666 __endio_write_update_ordered(inode,
8667 dio_data.unsubmitted_oe_range_start,
8668 dio_data.unsubmitted_oe_range_end -
8669 dio_data.unsubmitted_oe_range_start,
8671 } else if (ret >= 0 && (size_t)ret < count)
8672 btrfs_delalloc_release_space(inode, data_reserved,
8673 offset, count - (size_t)ret, true);
8674 btrfs_delalloc_release_extents(BTRFS_I(inode), count, false);
8678 inode_dio_end(inode);
8682 extent_changeset_free(data_reserved);
8686 #define BTRFS_FIEMAP_FLAGS (FIEMAP_FLAG_SYNC)
8688 static int btrfs_fiemap(struct inode *inode, struct fiemap_extent_info *fieinfo,
8689 __u64 start, __u64 len)
8693 ret = fiemap_check_flags(fieinfo, BTRFS_FIEMAP_FLAGS);
8697 return extent_fiemap(inode, fieinfo, start, len);
8700 int btrfs_readpage(struct file *file, struct page *page)
8702 struct extent_io_tree *tree;
8703 tree = &BTRFS_I(page->mapping->host)->io_tree;
8704 return extent_read_full_page(tree, page, btrfs_get_extent, 0);
8707 static int btrfs_writepage(struct page *page, struct writeback_control *wbc)
8709 struct inode *inode = page->mapping->host;
8712 if (current->flags & PF_MEMALLOC) {
8713 redirty_page_for_writepage(wbc, page);
8719 * If we are under memory pressure we will call this directly from the
8720 * VM, we need to make sure we have the inode referenced for the ordered
8721 * extent. If not just return like we didn't do anything.
8723 if (!igrab(inode)) {
8724 redirty_page_for_writepage(wbc, page);
8725 return AOP_WRITEPAGE_ACTIVATE;
8727 ret = extent_write_full_page(page, wbc);
8728 btrfs_add_delayed_iput(inode);
8732 static int btrfs_writepages(struct address_space *mapping,
8733 struct writeback_control *wbc)
8735 return extent_writepages(mapping, wbc);
8739 btrfs_readpages(struct file *file, struct address_space *mapping,
8740 struct list_head *pages, unsigned nr_pages)
8742 return extent_readpages(mapping, pages, nr_pages);
8745 static int __btrfs_releasepage(struct page *page, gfp_t gfp_flags)
8747 int ret = try_release_extent_mapping(page, gfp_flags);
8749 ClearPagePrivate(page);
8750 set_page_private(page, 0);
8756 static int btrfs_releasepage(struct page *page, gfp_t gfp_flags)
8758 if (PageWriteback(page) || PageDirty(page))
8760 return __btrfs_releasepage(page, gfp_flags);
8763 static void btrfs_invalidatepage(struct page *page, unsigned int offset,
8764 unsigned int length)
8766 struct inode *inode = page->mapping->host;
8767 struct extent_io_tree *tree;
8768 struct btrfs_ordered_extent *ordered;
8769 struct extent_state *cached_state = NULL;
8770 u64 page_start = page_offset(page);
8771 u64 page_end = page_start + PAGE_SIZE - 1;
8774 int inode_evicting = inode->i_state & I_FREEING;
8777 * we have the page locked, so new writeback can't start,
8778 * and the dirty bit won't be cleared while we are here.
8780 * Wait for IO on this page so that we can safely clear
8781 * the PagePrivate2 bit and do ordered accounting
8783 wait_on_page_writeback(page);
8785 tree = &BTRFS_I(inode)->io_tree;
8787 btrfs_releasepage(page, GFP_NOFS);
8791 if (!inode_evicting)
8792 lock_extent_bits(tree, page_start, page_end, &cached_state);
8795 ordered = btrfs_lookup_ordered_range(BTRFS_I(inode), start,
8796 page_end - start + 1);
8798 end = min(page_end, ordered->file_offset + ordered->len - 1);
8800 * IO on this page will never be started, so we need
8801 * to account for any ordered extents now
8803 if (!inode_evicting)
8804 clear_extent_bit(tree, start, end,
8805 EXTENT_DIRTY | EXTENT_DELALLOC |
8806 EXTENT_DELALLOC_NEW |
8807 EXTENT_LOCKED | EXTENT_DO_ACCOUNTING |
8808 EXTENT_DEFRAG, 1, 0, &cached_state);
8810 * whoever cleared the private bit is responsible
8811 * for the finish_ordered_io
8813 if (TestClearPagePrivate2(page)) {
8814 struct btrfs_ordered_inode_tree *tree;
8817 tree = &BTRFS_I(inode)->ordered_tree;
8819 spin_lock_irq(&tree->lock);
8820 set_bit(BTRFS_ORDERED_TRUNCATED, &ordered->flags);
8821 new_len = start - ordered->file_offset;
8822 if (new_len < ordered->truncated_len)
8823 ordered->truncated_len = new_len;
8824 spin_unlock_irq(&tree->lock);
8826 if (btrfs_dec_test_ordered_pending(inode, &ordered,
8828 end - start + 1, 1))
8829 btrfs_finish_ordered_io(ordered);
8831 btrfs_put_ordered_extent(ordered);
8832 if (!inode_evicting) {
8833 cached_state = NULL;
8834 lock_extent_bits(tree, start, end,
8839 if (start < page_end)
8844 * Qgroup reserved space handler
8845 * Page here will be either
8846 * 1) Already written to disk
8847 * In this case, its reserved space is released from data rsv map
8848 * and will be freed by delayed_ref handler finally.
8849 * So even we call qgroup_free_data(), it won't decrease reserved
8851 * 2) Not written to disk
8852 * This means the reserved space should be freed here. However,
8853 * if a truncate invalidates the page (by clearing PageDirty)
8854 * and the page is accounted for while allocating extent
8855 * in btrfs_check_data_free_space() we let delayed_ref to
8856 * free the entire extent.
8858 if (PageDirty(page))
8859 btrfs_qgroup_free_data(inode, NULL, page_start, PAGE_SIZE);
8860 if (!inode_evicting) {
8861 clear_extent_bit(tree, page_start, page_end,
8862 EXTENT_LOCKED | EXTENT_DIRTY |
8863 EXTENT_DELALLOC | EXTENT_DELALLOC_NEW |
8864 EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG, 1, 1,
8867 __btrfs_releasepage(page, GFP_NOFS);
8870 ClearPageChecked(page);
8871 if (PagePrivate(page)) {
8872 ClearPagePrivate(page);
8873 set_page_private(page, 0);
8879 * btrfs_page_mkwrite() is not allowed to change the file size as it gets
8880 * called from a page fault handler when a page is first dirtied. Hence we must
8881 * be careful to check for EOF conditions here. We set the page up correctly
8882 * for a written page which means we get ENOSPC checking when writing into
8883 * holes and correct delalloc and unwritten extent mapping on filesystems that
8884 * support these features.
8886 * We are not allowed to take the i_mutex here so we have to play games to
8887 * protect against truncate races as the page could now be beyond EOF. Because
8888 * truncate_setsize() writes the inode size before removing pages, once we have
8889 * the page lock we can determine safely if the page is beyond EOF. If it is not
8890 * beyond EOF, then the page is guaranteed safe against truncation until we
8893 vm_fault_t btrfs_page_mkwrite(struct vm_fault *vmf)
8895 struct page *page = vmf->page;
8896 struct inode *inode = file_inode(vmf->vma->vm_file);
8897 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
8898 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
8899 struct btrfs_ordered_extent *ordered;
8900 struct extent_state *cached_state = NULL;
8901 struct extent_changeset *data_reserved = NULL;
8903 unsigned long zero_start;
8913 reserved_space = PAGE_SIZE;
8915 sb_start_pagefault(inode->i_sb);
8916 page_start = page_offset(page);
8917 page_end = page_start + PAGE_SIZE - 1;
8921 * Reserving delalloc space after obtaining the page lock can lead to
8922 * deadlock. For example, if a dirty page is locked by this function
8923 * and the call to btrfs_delalloc_reserve_space() ends up triggering
8924 * dirty page write out, then the btrfs_writepage() function could
8925 * end up waiting indefinitely to get a lock on the page currently
8926 * being processed by btrfs_page_mkwrite() function.
8928 ret2 = btrfs_delalloc_reserve_space(inode, &data_reserved, page_start,
8931 ret2 = file_update_time(vmf->vma->vm_file);
8935 ret = vmf_error(ret2);
8941 ret = VM_FAULT_NOPAGE; /* make the VM retry the fault */
8944 size = i_size_read(inode);
8946 if ((page->mapping != inode->i_mapping) ||
8947 (page_start >= size)) {
8948 /* page got truncated out from underneath us */
8951 wait_on_page_writeback(page);
8953 lock_extent_bits(io_tree, page_start, page_end, &cached_state);
8954 set_page_extent_mapped(page);
8957 * we can't set the delalloc bits if there are pending ordered
8958 * extents. Drop our locks and wait for them to finish
8960 ordered = btrfs_lookup_ordered_range(BTRFS_I(inode), page_start,
8963 unlock_extent_cached(io_tree, page_start, page_end,
8966 btrfs_start_ordered_extent(inode, ordered, 1);
8967 btrfs_put_ordered_extent(ordered);
8971 if (page->index == ((size - 1) >> PAGE_SHIFT)) {
8972 reserved_space = round_up(size - page_start,
8973 fs_info->sectorsize);
8974 if (reserved_space < PAGE_SIZE) {
8975 end = page_start + reserved_space - 1;
8976 btrfs_delalloc_release_space(inode, data_reserved,
8977 page_start, PAGE_SIZE - reserved_space,
8983 * page_mkwrite gets called when the page is firstly dirtied after it's
8984 * faulted in, but write(2) could also dirty a page and set delalloc
8985 * bits, thus in this case for space account reason, we still need to
8986 * clear any delalloc bits within this page range since we have to
8987 * reserve data&meta space before lock_page() (see above comments).
8989 clear_extent_bit(&BTRFS_I(inode)->io_tree, page_start, end,
8990 EXTENT_DIRTY | EXTENT_DELALLOC |
8991 EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG,
8992 0, 0, &cached_state);
8994 ret2 = btrfs_set_extent_delalloc(inode, page_start, end, 0,
8997 unlock_extent_cached(io_tree, page_start, page_end,
8999 ret = VM_FAULT_SIGBUS;
9004 /* page is wholly or partially inside EOF */
9005 if (page_start + PAGE_SIZE > size)
9006 zero_start = offset_in_page(size);
9008 zero_start = PAGE_SIZE;
9010 if (zero_start != PAGE_SIZE) {
9012 memset(kaddr + zero_start, 0, PAGE_SIZE - zero_start);
9013 flush_dcache_page(page);
9016 ClearPageChecked(page);
9017 set_page_dirty(page);
9018 SetPageUptodate(page);
9020 BTRFS_I(inode)->last_trans = fs_info->generation;
9021 BTRFS_I(inode)->last_sub_trans = BTRFS_I(inode)->root->log_transid;
9022 BTRFS_I(inode)->last_log_commit = BTRFS_I(inode)->root->last_log_commit;
9024 unlock_extent_cached(io_tree, page_start, page_end, &cached_state);
9027 btrfs_delalloc_release_extents(BTRFS_I(inode), PAGE_SIZE, true);
9028 sb_end_pagefault(inode->i_sb);
9029 extent_changeset_free(data_reserved);
9030 return VM_FAULT_LOCKED;
9036 btrfs_delalloc_release_extents(BTRFS_I(inode), PAGE_SIZE, (ret != 0));
9037 btrfs_delalloc_release_space(inode, data_reserved, page_start,
9038 reserved_space, (ret != 0));
9040 sb_end_pagefault(inode->i_sb);
9041 extent_changeset_free(data_reserved);
9045 static int btrfs_truncate(struct inode *inode, bool skip_writeback)
9047 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
9048 struct btrfs_root *root = BTRFS_I(inode)->root;
9049 struct btrfs_block_rsv *rsv;
9051 struct btrfs_trans_handle *trans;
9052 u64 mask = fs_info->sectorsize - 1;
9053 u64 min_size = btrfs_calc_trunc_metadata_size(fs_info, 1);
9055 if (!skip_writeback) {
9056 ret = btrfs_wait_ordered_range(inode, inode->i_size & (~mask),
9063 * Yes ladies and gentlemen, this is indeed ugly. We have a couple of
9064 * things going on here:
9066 * 1) We need to reserve space to update our inode.
9068 * 2) We need to have something to cache all the space that is going to
9069 * be free'd up by the truncate operation, but also have some slack
9070 * space reserved in case it uses space during the truncate (thank you
9071 * very much snapshotting).
9073 * And we need these to be separate. The fact is we can use a lot of
9074 * space doing the truncate, and we have no earthly idea how much space
9075 * we will use, so we need the truncate reservation to be separate so it
9076 * doesn't end up using space reserved for updating the inode. We also
9077 * need to be able to stop the transaction and start a new one, which
9078 * means we need to be able to update the inode several times, and we
9079 * have no idea of knowing how many times that will be, so we can't just
9080 * reserve 1 item for the entirety of the operation, so that has to be
9081 * done separately as well.
9083 * So that leaves us with
9085 * 1) rsv - for the truncate reservation, which we will steal from the
9086 * transaction reservation.
9087 * 2) fs_info->trans_block_rsv - this will have 1 items worth left for
9088 * updating the inode.
9090 rsv = btrfs_alloc_block_rsv(fs_info, BTRFS_BLOCK_RSV_TEMP);
9093 rsv->size = min_size;
9097 * 1 for the truncate slack space
9098 * 1 for updating the inode.
9100 trans = btrfs_start_transaction(root, 2);
9101 if (IS_ERR(trans)) {
9102 ret = PTR_ERR(trans);
9106 /* Migrate the slack space for the truncate to our reserve */
9107 ret = btrfs_block_rsv_migrate(&fs_info->trans_block_rsv, rsv,
9112 * So if we truncate and then write and fsync we normally would just
9113 * write the extents that changed, which is a problem if we need to
9114 * first truncate that entire inode. So set this flag so we write out
9115 * all of the extents in the inode to the sync log so we're completely
9118 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &BTRFS_I(inode)->runtime_flags);
9119 trans->block_rsv = rsv;
9122 ret = btrfs_truncate_inode_items(trans, root, inode,
9124 BTRFS_EXTENT_DATA_KEY);
9125 trans->block_rsv = &fs_info->trans_block_rsv;
9126 if (ret != -ENOSPC && ret != -EAGAIN)
9129 ret = btrfs_update_inode(trans, root, inode);
9133 btrfs_end_transaction(trans);
9134 btrfs_btree_balance_dirty(fs_info);
9136 trans = btrfs_start_transaction(root, 2);
9137 if (IS_ERR(trans)) {
9138 ret = PTR_ERR(trans);
9143 btrfs_block_rsv_release(fs_info, rsv, -1);
9144 ret = btrfs_block_rsv_migrate(&fs_info->trans_block_rsv,
9145 rsv, min_size, false);
9146 BUG_ON(ret); /* shouldn't happen */
9147 trans->block_rsv = rsv;
9151 * We can't call btrfs_truncate_block inside a trans handle as we could
9152 * deadlock with freeze, if we got NEED_TRUNCATE_BLOCK then we know
9153 * we've truncated everything except the last little bit, and can do
9154 * btrfs_truncate_block and then update the disk_i_size.
9156 if (ret == NEED_TRUNCATE_BLOCK) {
9157 btrfs_end_transaction(trans);
9158 btrfs_btree_balance_dirty(fs_info);
9160 ret = btrfs_truncate_block(inode, inode->i_size, 0, 0);
9163 trans = btrfs_start_transaction(root, 1);
9164 if (IS_ERR(trans)) {
9165 ret = PTR_ERR(trans);
9168 btrfs_ordered_update_i_size(inode, inode->i_size, NULL);
9174 trans->block_rsv = &fs_info->trans_block_rsv;
9175 ret2 = btrfs_update_inode(trans, root, inode);
9179 ret2 = btrfs_end_transaction(trans);
9182 btrfs_btree_balance_dirty(fs_info);
9185 btrfs_free_block_rsv(fs_info, rsv);
9191 * create a new subvolume directory/inode (helper for the ioctl).
9193 int btrfs_create_subvol_root(struct btrfs_trans_handle *trans,
9194 struct btrfs_root *new_root,
9195 struct btrfs_root *parent_root,
9198 struct inode *inode;
9202 inode = btrfs_new_inode(trans, new_root, NULL, "..", 2,
9203 new_dirid, new_dirid,
9204 S_IFDIR | (~current_umask() & S_IRWXUGO),
9207 return PTR_ERR(inode);
9208 inode->i_op = &btrfs_dir_inode_operations;
9209 inode->i_fop = &btrfs_dir_file_operations;
9211 set_nlink(inode, 1);
9212 btrfs_i_size_write(BTRFS_I(inode), 0);
9213 unlock_new_inode(inode);
9215 err = btrfs_subvol_inherit_props(trans, new_root, parent_root);
9217 btrfs_err(new_root->fs_info,
9218 "error inheriting subvolume %llu properties: %d",
9219 new_root->root_key.objectid, err);
9221 err = btrfs_update_inode(trans, new_root, inode);
9227 struct inode *btrfs_alloc_inode(struct super_block *sb)
9229 struct btrfs_fs_info *fs_info = btrfs_sb(sb);
9230 struct btrfs_inode *ei;
9231 struct inode *inode;
9233 ei = kmem_cache_alloc(btrfs_inode_cachep, GFP_KERNEL);
9240 ei->last_sub_trans = 0;
9241 ei->logged_trans = 0;
9242 ei->delalloc_bytes = 0;
9243 ei->new_delalloc_bytes = 0;
9244 ei->defrag_bytes = 0;
9245 ei->disk_i_size = 0;
9248 ei->index_cnt = (u64)-1;
9250 ei->last_unlink_trans = 0;
9251 ei->last_log_commit = 0;
9253 spin_lock_init(&ei->lock);
9254 ei->outstanding_extents = 0;
9255 if (sb->s_magic != BTRFS_TEST_MAGIC)
9256 btrfs_init_metadata_block_rsv(fs_info, &ei->block_rsv,
9257 BTRFS_BLOCK_RSV_DELALLOC);
9258 ei->runtime_flags = 0;
9259 ei->prop_compress = BTRFS_COMPRESS_NONE;
9260 ei->defrag_compress = BTRFS_COMPRESS_NONE;
9262 ei->delayed_node = NULL;
9264 ei->i_otime.tv_sec = 0;
9265 ei->i_otime.tv_nsec = 0;
9267 inode = &ei->vfs_inode;
9268 extent_map_tree_init(&ei->extent_tree);
9269 extent_io_tree_init(fs_info, &ei->io_tree, IO_TREE_INODE_IO, inode);
9270 extent_io_tree_init(fs_info, &ei->io_failure_tree,
9271 IO_TREE_INODE_IO_FAILURE, inode);
9272 ei->io_tree.track_uptodate = true;
9273 ei->io_failure_tree.track_uptodate = true;
9274 atomic_set(&ei->sync_writers, 0);
9275 mutex_init(&ei->log_mutex);
9276 mutex_init(&ei->delalloc_mutex);
9277 btrfs_ordered_inode_tree_init(&ei->ordered_tree);
9278 INIT_LIST_HEAD(&ei->delalloc_inodes);
9279 INIT_LIST_HEAD(&ei->delayed_iput);
9280 RB_CLEAR_NODE(&ei->rb_node);
9281 init_rwsem(&ei->dio_sem);
9286 #ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
9287 void btrfs_test_destroy_inode(struct inode *inode)
9289 btrfs_drop_extent_cache(BTRFS_I(inode), 0, (u64)-1, 0);
9290 kmem_cache_free(btrfs_inode_cachep, BTRFS_I(inode));
9294 void btrfs_free_inode(struct inode *inode)
9296 kmem_cache_free(btrfs_inode_cachep, BTRFS_I(inode));
9299 void btrfs_destroy_inode(struct inode *inode)
9301 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
9302 struct btrfs_ordered_extent *ordered;
9303 struct btrfs_root *root = BTRFS_I(inode)->root;
9305 WARN_ON(!hlist_empty(&inode->i_dentry));
9306 WARN_ON(inode->i_data.nrpages);
9307 WARN_ON(BTRFS_I(inode)->block_rsv.reserved);
9308 WARN_ON(BTRFS_I(inode)->block_rsv.size);
9309 WARN_ON(BTRFS_I(inode)->outstanding_extents);
9310 WARN_ON(BTRFS_I(inode)->delalloc_bytes);
9311 WARN_ON(BTRFS_I(inode)->new_delalloc_bytes);
9312 WARN_ON(BTRFS_I(inode)->csum_bytes);
9313 WARN_ON(BTRFS_I(inode)->defrag_bytes);
9316 * This can happen where we create an inode, but somebody else also
9317 * created the same inode and we need to destroy the one we already
9324 ordered = btrfs_lookup_first_ordered_extent(inode, (u64)-1);
9329 "found ordered extent %llu %llu on inode cleanup",
9330 ordered->file_offset, ordered->len);
9331 btrfs_remove_ordered_extent(inode, ordered);
9332 btrfs_put_ordered_extent(ordered);
9333 btrfs_put_ordered_extent(ordered);
9336 btrfs_qgroup_check_reserved_leak(inode);
9337 inode_tree_del(inode);
9338 btrfs_drop_extent_cache(BTRFS_I(inode), 0, (u64)-1, 0);
9341 int btrfs_drop_inode(struct inode *inode)
9343 struct btrfs_root *root = BTRFS_I(inode)->root;
9348 /* the snap/subvol tree is on deleting */
9349 if (btrfs_root_refs(&root->root_item) == 0)
9352 return generic_drop_inode(inode);
9355 static void init_once(void *foo)
9357 struct btrfs_inode *ei = (struct btrfs_inode *) foo;
9359 inode_init_once(&ei->vfs_inode);
9362 void __cold btrfs_destroy_cachep(void)
9365 * Make sure all delayed rcu free inodes are flushed before we
9369 kmem_cache_destroy(btrfs_inode_cachep);
9370 kmem_cache_destroy(btrfs_trans_handle_cachep);
9371 kmem_cache_destroy(btrfs_path_cachep);
9372 kmem_cache_destroy(btrfs_free_space_cachep);
9375 int __init btrfs_init_cachep(void)
9377 btrfs_inode_cachep = kmem_cache_create("btrfs_inode",
9378 sizeof(struct btrfs_inode), 0,
9379 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD | SLAB_ACCOUNT,
9381 if (!btrfs_inode_cachep)
9384 btrfs_trans_handle_cachep = kmem_cache_create("btrfs_trans_handle",
9385 sizeof(struct btrfs_trans_handle), 0,
9386 SLAB_TEMPORARY | SLAB_MEM_SPREAD, NULL);
9387 if (!btrfs_trans_handle_cachep)
9390 btrfs_path_cachep = kmem_cache_create("btrfs_path",
9391 sizeof(struct btrfs_path), 0,
9392 SLAB_MEM_SPREAD, NULL);
9393 if (!btrfs_path_cachep)
9396 btrfs_free_space_cachep = kmem_cache_create("btrfs_free_space",
9397 sizeof(struct btrfs_free_space), 0,
9398 SLAB_MEM_SPREAD, NULL);
9399 if (!btrfs_free_space_cachep)
9404 btrfs_destroy_cachep();
9408 static int btrfs_getattr(const struct path *path, struct kstat *stat,
9409 u32 request_mask, unsigned int flags)
9412 struct inode *inode = d_inode(path->dentry);
9413 u32 blocksize = inode->i_sb->s_blocksize;
9414 u32 bi_flags = BTRFS_I(inode)->flags;
9416 stat->result_mask |= STATX_BTIME;
9417 stat->btime.tv_sec = BTRFS_I(inode)->i_otime.tv_sec;
9418 stat->btime.tv_nsec = BTRFS_I(inode)->i_otime.tv_nsec;
9419 if (bi_flags & BTRFS_INODE_APPEND)
9420 stat->attributes |= STATX_ATTR_APPEND;
9421 if (bi_flags & BTRFS_INODE_COMPRESS)
9422 stat->attributes |= STATX_ATTR_COMPRESSED;
9423 if (bi_flags & BTRFS_INODE_IMMUTABLE)
9424 stat->attributes |= STATX_ATTR_IMMUTABLE;
9425 if (bi_flags & BTRFS_INODE_NODUMP)
9426 stat->attributes |= STATX_ATTR_NODUMP;
9428 stat->attributes_mask |= (STATX_ATTR_APPEND |
9429 STATX_ATTR_COMPRESSED |
9430 STATX_ATTR_IMMUTABLE |
9433 generic_fillattr(inode, stat);
9434 stat->dev = BTRFS_I(inode)->root->anon_dev;
9436 spin_lock(&BTRFS_I(inode)->lock);
9437 delalloc_bytes = BTRFS_I(inode)->new_delalloc_bytes;
9438 spin_unlock(&BTRFS_I(inode)->lock);
9439 stat->blocks = (ALIGN(inode_get_bytes(inode), blocksize) +
9440 ALIGN(delalloc_bytes, blocksize)) >> 9;
9444 static int btrfs_rename_exchange(struct inode *old_dir,
9445 struct dentry *old_dentry,
9446 struct inode *new_dir,
9447 struct dentry *new_dentry)
9449 struct btrfs_fs_info *fs_info = btrfs_sb(old_dir->i_sb);
9450 struct btrfs_trans_handle *trans;
9451 struct btrfs_root *root = BTRFS_I(old_dir)->root;
9452 struct btrfs_root *dest = BTRFS_I(new_dir)->root;
9453 struct inode *new_inode = new_dentry->d_inode;
9454 struct inode *old_inode = old_dentry->d_inode;
9455 struct timespec64 ctime = current_time(old_inode);
9456 struct dentry *parent;
9457 u64 old_ino = btrfs_ino(BTRFS_I(old_inode));
9458 u64 new_ino = btrfs_ino(BTRFS_I(new_inode));
9463 bool root_log_pinned = false;
9464 bool dest_log_pinned = false;
9465 struct btrfs_log_ctx ctx_root;
9466 struct btrfs_log_ctx ctx_dest;
9467 bool sync_log_root = false;
9468 bool sync_log_dest = false;
9469 bool commit_transaction = false;
9471 /* we only allow rename subvolume link between subvolumes */
9472 if (old_ino != BTRFS_FIRST_FREE_OBJECTID && root != dest)
9475 btrfs_init_log_ctx(&ctx_root, old_inode);
9476 btrfs_init_log_ctx(&ctx_dest, new_inode);
9478 /* close the race window with snapshot create/destroy ioctl */
9479 if (old_ino == BTRFS_FIRST_FREE_OBJECTID)
9480 down_read(&fs_info->subvol_sem);
9481 if (new_ino == BTRFS_FIRST_FREE_OBJECTID)
9482 down_read(&fs_info->subvol_sem);
9485 * We want to reserve the absolute worst case amount of items. So if
9486 * both inodes are subvols and we need to unlink them then that would
9487 * require 4 item modifications, but if they are both normal inodes it
9488 * would require 5 item modifications, so we'll assume their normal
9489 * inodes. So 5 * 2 is 10, plus 2 for the new links, so 12 total items
9490 * should cover the worst case number of items we'll modify.
9492 trans = btrfs_start_transaction(root, 12);
9493 if (IS_ERR(trans)) {
9494 ret = PTR_ERR(trans);
9499 * We need to find a free sequence number both in the source and
9500 * in the destination directory for the exchange.
9502 ret = btrfs_set_inode_index(BTRFS_I(new_dir), &old_idx);
9505 ret = btrfs_set_inode_index(BTRFS_I(old_dir), &new_idx);
9509 BTRFS_I(old_inode)->dir_index = 0ULL;
9510 BTRFS_I(new_inode)->dir_index = 0ULL;
9512 /* Reference for the source. */
9513 if (old_ino == BTRFS_FIRST_FREE_OBJECTID) {
9514 /* force full log commit if subvolume involved. */
9515 btrfs_set_log_full_commit(trans);
9517 btrfs_pin_log_trans(root);
9518 root_log_pinned = true;
9519 ret = btrfs_insert_inode_ref(trans, dest,
9520 new_dentry->d_name.name,
9521 new_dentry->d_name.len,
9523 btrfs_ino(BTRFS_I(new_dir)),
9529 /* And now for the dest. */
9530 if (new_ino == BTRFS_FIRST_FREE_OBJECTID) {
9531 /* force full log commit if subvolume involved. */
9532 btrfs_set_log_full_commit(trans);
9534 btrfs_pin_log_trans(dest);
9535 dest_log_pinned = true;
9536 ret = btrfs_insert_inode_ref(trans, root,
9537 old_dentry->d_name.name,
9538 old_dentry->d_name.len,
9540 btrfs_ino(BTRFS_I(old_dir)),
9546 /* Update inode version and ctime/mtime. */
9547 inode_inc_iversion(old_dir);
9548 inode_inc_iversion(new_dir);
9549 inode_inc_iversion(old_inode);
9550 inode_inc_iversion(new_inode);
9551 old_dir->i_ctime = old_dir->i_mtime = ctime;
9552 new_dir->i_ctime = new_dir->i_mtime = ctime;
9553 old_inode->i_ctime = ctime;
9554 new_inode->i_ctime = ctime;
9556 if (old_dentry->d_parent != new_dentry->d_parent) {
9557 btrfs_record_unlink_dir(trans, BTRFS_I(old_dir),
9558 BTRFS_I(old_inode), 1);
9559 btrfs_record_unlink_dir(trans, BTRFS_I(new_dir),
9560 BTRFS_I(new_inode), 1);
9563 /* src is a subvolume */
9564 if (old_ino == BTRFS_FIRST_FREE_OBJECTID) {
9565 root_objectid = BTRFS_I(old_inode)->root->root_key.objectid;
9566 ret = btrfs_unlink_subvol(trans, old_dir, root_objectid,
9567 old_dentry->d_name.name,
9568 old_dentry->d_name.len);
9569 } else { /* src is an inode */
9570 ret = __btrfs_unlink_inode(trans, root, BTRFS_I(old_dir),
9571 BTRFS_I(old_dentry->d_inode),
9572 old_dentry->d_name.name,
9573 old_dentry->d_name.len);
9575 ret = btrfs_update_inode(trans, root, old_inode);
9578 btrfs_abort_transaction(trans, ret);
9582 /* dest is a subvolume */
9583 if (new_ino == BTRFS_FIRST_FREE_OBJECTID) {
9584 root_objectid = BTRFS_I(new_inode)->root->root_key.objectid;
9585 ret = btrfs_unlink_subvol(trans, new_dir, root_objectid,
9586 new_dentry->d_name.name,
9587 new_dentry->d_name.len);
9588 } else { /* dest is an inode */
9589 ret = __btrfs_unlink_inode(trans, dest, BTRFS_I(new_dir),
9590 BTRFS_I(new_dentry->d_inode),
9591 new_dentry->d_name.name,
9592 new_dentry->d_name.len);
9594 ret = btrfs_update_inode(trans, dest, new_inode);
9597 btrfs_abort_transaction(trans, ret);
9601 ret = btrfs_add_link(trans, BTRFS_I(new_dir), BTRFS_I(old_inode),
9602 new_dentry->d_name.name,
9603 new_dentry->d_name.len, 0, old_idx);
9605 btrfs_abort_transaction(trans, ret);
9609 ret = btrfs_add_link(trans, BTRFS_I(old_dir), BTRFS_I(new_inode),
9610 old_dentry->d_name.name,
9611 old_dentry->d_name.len, 0, new_idx);
9613 btrfs_abort_transaction(trans, ret);
9617 if (old_inode->i_nlink == 1)
9618 BTRFS_I(old_inode)->dir_index = old_idx;
9619 if (new_inode->i_nlink == 1)
9620 BTRFS_I(new_inode)->dir_index = new_idx;
9622 if (root_log_pinned) {
9623 parent = new_dentry->d_parent;
9624 ret = btrfs_log_new_name(trans, BTRFS_I(old_inode),
9625 BTRFS_I(old_dir), parent,
9627 if (ret == BTRFS_NEED_LOG_SYNC)
9628 sync_log_root = true;
9629 else if (ret == BTRFS_NEED_TRANS_COMMIT)
9630 commit_transaction = true;
9632 btrfs_end_log_trans(root);
9633 root_log_pinned = false;
9635 if (dest_log_pinned) {
9636 if (!commit_transaction) {
9637 parent = old_dentry->d_parent;
9638 ret = btrfs_log_new_name(trans, BTRFS_I(new_inode),
9639 BTRFS_I(new_dir), parent,
9641 if (ret == BTRFS_NEED_LOG_SYNC)
9642 sync_log_dest = true;
9643 else if (ret == BTRFS_NEED_TRANS_COMMIT)
9644 commit_transaction = true;
9647 btrfs_end_log_trans(dest);
9648 dest_log_pinned = false;
9652 * If we have pinned a log and an error happened, we unpin tasks
9653 * trying to sync the log and force them to fallback to a transaction
9654 * commit if the log currently contains any of the inodes involved in
9655 * this rename operation (to ensure we do not persist a log with an
9656 * inconsistent state for any of these inodes or leading to any
9657 * inconsistencies when replayed). If the transaction was aborted, the
9658 * abortion reason is propagated to userspace when attempting to commit
9659 * the transaction. If the log does not contain any of these inodes, we
9660 * allow the tasks to sync it.
9662 if (ret && (root_log_pinned || dest_log_pinned)) {
9663 if (btrfs_inode_in_log(BTRFS_I(old_dir), fs_info->generation) ||
9664 btrfs_inode_in_log(BTRFS_I(new_dir), fs_info->generation) ||
9665 btrfs_inode_in_log(BTRFS_I(old_inode), fs_info->generation) ||
9667 btrfs_inode_in_log(BTRFS_I(new_inode), fs_info->generation)))
9668 btrfs_set_log_full_commit(trans);
9670 if (root_log_pinned) {
9671 btrfs_end_log_trans(root);
9672 root_log_pinned = false;
9674 if (dest_log_pinned) {
9675 btrfs_end_log_trans(dest);
9676 dest_log_pinned = false;
9679 if (!ret && sync_log_root && !commit_transaction) {
9680 ret = btrfs_sync_log(trans, BTRFS_I(old_inode)->root,
9683 commit_transaction = true;
9685 if (!ret && sync_log_dest && !commit_transaction) {
9686 ret = btrfs_sync_log(trans, BTRFS_I(new_inode)->root,
9689 commit_transaction = true;
9691 if (commit_transaction) {
9692 ret = btrfs_commit_transaction(trans);
9696 ret2 = btrfs_end_transaction(trans);
9697 ret = ret ? ret : ret2;
9700 if (new_ino == BTRFS_FIRST_FREE_OBJECTID)
9701 up_read(&fs_info->subvol_sem);
9702 if (old_ino == BTRFS_FIRST_FREE_OBJECTID)
9703 up_read(&fs_info->subvol_sem);
9708 static int btrfs_whiteout_for_rename(struct btrfs_trans_handle *trans,
9709 struct btrfs_root *root,
9711 struct dentry *dentry)
9714 struct inode *inode;
9718 ret = btrfs_find_free_ino(root, &objectid);
9722 inode = btrfs_new_inode(trans, root, dir,
9723 dentry->d_name.name,
9725 btrfs_ino(BTRFS_I(dir)),
9727 S_IFCHR | WHITEOUT_MODE,
9730 if (IS_ERR(inode)) {
9731 ret = PTR_ERR(inode);
9735 inode->i_op = &btrfs_special_inode_operations;
9736 init_special_inode(inode, inode->i_mode,
9739 ret = btrfs_init_inode_security(trans, inode, dir,
9744 ret = btrfs_add_nondir(trans, BTRFS_I(dir), dentry,
9745 BTRFS_I(inode), 0, index);
9749 ret = btrfs_update_inode(trans, root, inode);
9751 unlock_new_inode(inode);
9753 inode_dec_link_count(inode);
9759 static int btrfs_rename(struct inode *old_dir, struct dentry *old_dentry,
9760 struct inode *new_dir, struct dentry *new_dentry,
9763 struct btrfs_fs_info *fs_info = btrfs_sb(old_dir->i_sb);
9764 struct btrfs_trans_handle *trans;
9765 unsigned int trans_num_items;
9766 struct btrfs_root *root = BTRFS_I(old_dir)->root;
9767 struct btrfs_root *dest = BTRFS_I(new_dir)->root;
9768 struct inode *new_inode = d_inode(new_dentry);
9769 struct inode *old_inode = d_inode(old_dentry);
9773 u64 old_ino = btrfs_ino(BTRFS_I(old_inode));
9774 bool log_pinned = false;
9775 struct btrfs_log_ctx ctx;
9776 bool sync_log = false;
9777 bool commit_transaction = false;
9779 if (btrfs_ino(BTRFS_I(new_dir)) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)
9782 /* we only allow rename subvolume link between subvolumes */
9783 if (old_ino != BTRFS_FIRST_FREE_OBJECTID && root != dest)
9786 if (old_ino == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID ||
9787 (new_inode && btrfs_ino(BTRFS_I(new_inode)) == BTRFS_FIRST_FREE_OBJECTID))
9790 if (S_ISDIR(old_inode->i_mode) && new_inode &&
9791 new_inode->i_size > BTRFS_EMPTY_DIR_SIZE)
9795 /* check for collisions, even if the name isn't there */
9796 ret = btrfs_check_dir_item_collision(dest, new_dir->i_ino,
9797 new_dentry->d_name.name,
9798 new_dentry->d_name.len);
9801 if (ret == -EEXIST) {
9803 * eexist without a new_inode */
9804 if (WARN_ON(!new_inode)) {
9808 /* maybe -EOVERFLOW */
9815 * we're using rename to replace one file with another. Start IO on it
9816 * now so we don't add too much work to the end of the transaction
9818 if (new_inode && S_ISREG(old_inode->i_mode) && new_inode->i_size)
9819 filemap_flush(old_inode->i_mapping);
9821 /* close the racy window with snapshot create/destroy ioctl */
9822 if (old_ino == BTRFS_FIRST_FREE_OBJECTID)
9823 down_read(&fs_info->subvol_sem);
9825 * We want to reserve the absolute worst case amount of items. So if
9826 * both inodes are subvols and we need to unlink them then that would
9827 * require 4 item modifications, but if they are both normal inodes it
9828 * would require 5 item modifications, so we'll assume they are normal
9829 * inodes. So 5 * 2 is 10, plus 1 for the new link, so 11 total items
9830 * should cover the worst case number of items we'll modify.
9831 * If our rename has the whiteout flag, we need more 5 units for the
9832 * new inode (1 inode item, 1 inode ref, 2 dir items and 1 xattr item
9833 * when selinux is enabled).
9835 trans_num_items = 11;
9836 if (flags & RENAME_WHITEOUT)
9837 trans_num_items += 5;
9838 trans = btrfs_start_transaction(root, trans_num_items);
9839 if (IS_ERR(trans)) {
9840 ret = PTR_ERR(trans);
9845 btrfs_record_root_in_trans(trans, dest);
9847 ret = btrfs_set_inode_index(BTRFS_I(new_dir), &index);
9851 BTRFS_I(old_inode)->dir_index = 0ULL;
9852 if (unlikely(old_ino == BTRFS_FIRST_FREE_OBJECTID)) {
9853 /* force full log commit if subvolume involved. */
9854 btrfs_set_log_full_commit(trans);
9856 btrfs_pin_log_trans(root);
9858 ret = btrfs_insert_inode_ref(trans, dest,
9859 new_dentry->d_name.name,
9860 new_dentry->d_name.len,
9862 btrfs_ino(BTRFS_I(new_dir)), index);
9867 inode_inc_iversion(old_dir);
9868 inode_inc_iversion(new_dir);
9869 inode_inc_iversion(old_inode);
9870 old_dir->i_ctime = old_dir->i_mtime =
9871 new_dir->i_ctime = new_dir->i_mtime =
9872 old_inode->i_ctime = current_time(old_dir);
9874 if (old_dentry->d_parent != new_dentry->d_parent)
9875 btrfs_record_unlink_dir(trans, BTRFS_I(old_dir),
9876 BTRFS_I(old_inode), 1);
9878 if (unlikely(old_ino == BTRFS_FIRST_FREE_OBJECTID)) {
9879 root_objectid = BTRFS_I(old_inode)->root->root_key.objectid;
9880 ret = btrfs_unlink_subvol(trans, old_dir, root_objectid,
9881 old_dentry->d_name.name,
9882 old_dentry->d_name.len);
9884 ret = __btrfs_unlink_inode(trans, root, BTRFS_I(old_dir),
9885 BTRFS_I(d_inode(old_dentry)),
9886 old_dentry->d_name.name,
9887 old_dentry->d_name.len);
9889 ret = btrfs_update_inode(trans, root, old_inode);
9892 btrfs_abort_transaction(trans, ret);
9897 inode_inc_iversion(new_inode);
9898 new_inode->i_ctime = current_time(new_inode);
9899 if (unlikely(btrfs_ino(BTRFS_I(new_inode)) ==
9900 BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)) {
9901 root_objectid = BTRFS_I(new_inode)->location.objectid;
9902 ret = btrfs_unlink_subvol(trans, new_dir, root_objectid,
9903 new_dentry->d_name.name,
9904 new_dentry->d_name.len);
9905 BUG_ON(new_inode->i_nlink == 0);
9907 ret = btrfs_unlink_inode(trans, dest, BTRFS_I(new_dir),
9908 BTRFS_I(d_inode(new_dentry)),
9909 new_dentry->d_name.name,
9910 new_dentry->d_name.len);
9912 if (!ret && new_inode->i_nlink == 0)
9913 ret = btrfs_orphan_add(trans,
9914 BTRFS_I(d_inode(new_dentry)));
9916 btrfs_abort_transaction(trans, ret);
9921 ret = btrfs_add_link(trans, BTRFS_I(new_dir), BTRFS_I(old_inode),
9922 new_dentry->d_name.name,
9923 new_dentry->d_name.len, 0, index);
9925 btrfs_abort_transaction(trans, ret);
9929 if (old_inode->i_nlink == 1)
9930 BTRFS_I(old_inode)->dir_index = index;
9933 struct dentry *parent = new_dentry->d_parent;
9935 btrfs_init_log_ctx(&ctx, old_inode);
9936 ret = btrfs_log_new_name(trans, BTRFS_I(old_inode),
9937 BTRFS_I(old_dir), parent,
9939 if (ret == BTRFS_NEED_LOG_SYNC)
9941 else if (ret == BTRFS_NEED_TRANS_COMMIT)
9942 commit_transaction = true;
9944 btrfs_end_log_trans(root);
9948 if (flags & RENAME_WHITEOUT) {
9949 ret = btrfs_whiteout_for_rename(trans, root, old_dir,
9953 btrfs_abort_transaction(trans, ret);
9959 * If we have pinned the log and an error happened, we unpin tasks
9960 * trying to sync the log and force them to fallback to a transaction
9961 * commit if the log currently contains any of the inodes involved in
9962 * this rename operation (to ensure we do not persist a log with an
9963 * inconsistent state for any of these inodes or leading to any
9964 * inconsistencies when replayed). If the transaction was aborted, the
9965 * abortion reason is propagated to userspace when attempting to commit
9966 * the transaction. If the log does not contain any of these inodes, we
9967 * allow the tasks to sync it.
9969 if (ret && log_pinned) {
9970 if (btrfs_inode_in_log(BTRFS_I(old_dir), fs_info->generation) ||
9971 btrfs_inode_in_log(BTRFS_I(new_dir), fs_info->generation) ||
9972 btrfs_inode_in_log(BTRFS_I(old_inode), fs_info->generation) ||
9974 btrfs_inode_in_log(BTRFS_I(new_inode), fs_info->generation)))
9975 btrfs_set_log_full_commit(trans);
9977 btrfs_end_log_trans(root);
9980 if (!ret && sync_log) {
9981 ret = btrfs_sync_log(trans, BTRFS_I(old_inode)->root, &ctx);
9983 commit_transaction = true;
9985 if (commit_transaction) {
9986 ret = btrfs_commit_transaction(trans);
9990 ret2 = btrfs_end_transaction(trans);
9991 ret = ret ? ret : ret2;
9994 if (old_ino == BTRFS_FIRST_FREE_OBJECTID)
9995 up_read(&fs_info->subvol_sem);
10000 static int btrfs_rename2(struct inode *old_dir, struct dentry *old_dentry,
10001 struct inode *new_dir, struct dentry *new_dentry,
10002 unsigned int flags)
10004 if (flags & ~(RENAME_NOREPLACE | RENAME_EXCHANGE | RENAME_WHITEOUT))
10007 if (flags & RENAME_EXCHANGE)
10008 return btrfs_rename_exchange(old_dir, old_dentry, new_dir,
10011 return btrfs_rename(old_dir, old_dentry, new_dir, new_dentry, flags);
10014 struct btrfs_delalloc_work {
10015 struct inode *inode;
10016 struct completion completion;
10017 struct list_head list;
10018 struct btrfs_work work;
10021 static void btrfs_run_delalloc_work(struct btrfs_work *work)
10023 struct btrfs_delalloc_work *delalloc_work;
10024 struct inode *inode;
10026 delalloc_work = container_of(work, struct btrfs_delalloc_work,
10028 inode = delalloc_work->inode;
10029 filemap_flush(inode->i_mapping);
10030 if (test_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
10031 &BTRFS_I(inode)->runtime_flags))
10032 filemap_flush(inode->i_mapping);
10035 complete(&delalloc_work->completion);
10038 static struct btrfs_delalloc_work *btrfs_alloc_delalloc_work(struct inode *inode)
10040 struct btrfs_delalloc_work *work;
10042 work = kmalloc(sizeof(*work), GFP_NOFS);
10046 init_completion(&work->completion);
10047 INIT_LIST_HEAD(&work->list);
10048 work->inode = inode;
10049 btrfs_init_work(&work->work, btrfs_flush_delalloc_helper,
10050 btrfs_run_delalloc_work, NULL, NULL);
10056 * some fairly slow code that needs optimization. This walks the list
10057 * of all the inodes with pending delalloc and forces them to disk.
10059 static int start_delalloc_inodes(struct btrfs_root *root, int nr, bool snapshot)
10061 struct btrfs_inode *binode;
10062 struct inode *inode;
10063 struct btrfs_delalloc_work *work, *next;
10064 struct list_head works;
10065 struct list_head splice;
10068 INIT_LIST_HEAD(&works);
10069 INIT_LIST_HEAD(&splice);
10071 mutex_lock(&root->delalloc_mutex);
10072 spin_lock(&root->delalloc_lock);
10073 list_splice_init(&root->delalloc_inodes, &splice);
10074 while (!list_empty(&splice)) {
10075 binode = list_entry(splice.next, struct btrfs_inode,
10078 list_move_tail(&binode->delalloc_inodes,
10079 &root->delalloc_inodes);
10080 inode = igrab(&binode->vfs_inode);
10082 cond_resched_lock(&root->delalloc_lock);
10085 spin_unlock(&root->delalloc_lock);
10088 set_bit(BTRFS_INODE_SNAPSHOT_FLUSH,
10089 &binode->runtime_flags);
10090 work = btrfs_alloc_delalloc_work(inode);
10096 list_add_tail(&work->list, &works);
10097 btrfs_queue_work(root->fs_info->flush_workers,
10100 if (nr != -1 && ret >= nr)
10103 spin_lock(&root->delalloc_lock);
10105 spin_unlock(&root->delalloc_lock);
10108 list_for_each_entry_safe(work, next, &works, list) {
10109 list_del_init(&work->list);
10110 wait_for_completion(&work->completion);
10114 if (!list_empty(&splice)) {
10115 spin_lock(&root->delalloc_lock);
10116 list_splice_tail(&splice, &root->delalloc_inodes);
10117 spin_unlock(&root->delalloc_lock);
10119 mutex_unlock(&root->delalloc_mutex);
10123 int btrfs_start_delalloc_snapshot(struct btrfs_root *root)
10125 struct btrfs_fs_info *fs_info = root->fs_info;
10128 if (test_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state))
10131 ret = start_delalloc_inodes(root, -1, true);
10137 int btrfs_start_delalloc_roots(struct btrfs_fs_info *fs_info, int nr)
10139 struct btrfs_root *root;
10140 struct list_head splice;
10143 if (test_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state))
10146 INIT_LIST_HEAD(&splice);
10148 mutex_lock(&fs_info->delalloc_root_mutex);
10149 spin_lock(&fs_info->delalloc_root_lock);
10150 list_splice_init(&fs_info->delalloc_roots, &splice);
10151 while (!list_empty(&splice) && nr) {
10152 root = list_first_entry(&splice, struct btrfs_root,
10154 root = btrfs_grab_fs_root(root);
10156 list_move_tail(&root->delalloc_root,
10157 &fs_info->delalloc_roots);
10158 spin_unlock(&fs_info->delalloc_root_lock);
10160 ret = start_delalloc_inodes(root, nr, false);
10161 btrfs_put_fs_root(root);
10169 spin_lock(&fs_info->delalloc_root_lock);
10171 spin_unlock(&fs_info->delalloc_root_lock);
10175 if (!list_empty(&splice)) {
10176 spin_lock(&fs_info->delalloc_root_lock);
10177 list_splice_tail(&splice, &fs_info->delalloc_roots);
10178 spin_unlock(&fs_info->delalloc_root_lock);
10180 mutex_unlock(&fs_info->delalloc_root_mutex);
10184 static int btrfs_symlink(struct inode *dir, struct dentry *dentry,
10185 const char *symname)
10187 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
10188 struct btrfs_trans_handle *trans;
10189 struct btrfs_root *root = BTRFS_I(dir)->root;
10190 struct btrfs_path *path;
10191 struct btrfs_key key;
10192 struct inode *inode = NULL;
10199 struct btrfs_file_extent_item *ei;
10200 struct extent_buffer *leaf;
10202 name_len = strlen(symname);
10203 if (name_len > BTRFS_MAX_INLINE_DATA_SIZE(fs_info))
10204 return -ENAMETOOLONG;
10207 * 2 items for inode item and ref
10208 * 2 items for dir items
10209 * 1 item for updating parent inode item
10210 * 1 item for the inline extent item
10211 * 1 item for xattr if selinux is on
10213 trans = btrfs_start_transaction(root, 7);
10215 return PTR_ERR(trans);
10217 err = btrfs_find_free_ino(root, &objectid);
10221 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
10222 dentry->d_name.len, btrfs_ino(BTRFS_I(dir)),
10223 objectid, S_IFLNK|S_IRWXUGO, &index);
10224 if (IS_ERR(inode)) {
10225 err = PTR_ERR(inode);
10231 * If the active LSM wants to access the inode during
10232 * d_instantiate it needs these. Smack checks to see
10233 * if the filesystem supports xattrs by looking at the
10236 inode->i_fop = &btrfs_file_operations;
10237 inode->i_op = &btrfs_file_inode_operations;
10238 inode->i_mapping->a_ops = &btrfs_aops;
10239 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
10241 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
10245 path = btrfs_alloc_path();
10250 key.objectid = btrfs_ino(BTRFS_I(inode));
10252 key.type = BTRFS_EXTENT_DATA_KEY;
10253 datasize = btrfs_file_extent_calc_inline_size(name_len);
10254 err = btrfs_insert_empty_item(trans, root, path, &key,
10257 btrfs_free_path(path);
10260 leaf = path->nodes[0];
10261 ei = btrfs_item_ptr(leaf, path->slots[0],
10262 struct btrfs_file_extent_item);
10263 btrfs_set_file_extent_generation(leaf, ei, trans->transid);
10264 btrfs_set_file_extent_type(leaf, ei,
10265 BTRFS_FILE_EXTENT_INLINE);
10266 btrfs_set_file_extent_encryption(leaf, ei, 0);
10267 btrfs_set_file_extent_compression(leaf, ei, 0);
10268 btrfs_set_file_extent_other_encoding(leaf, ei, 0);
10269 btrfs_set_file_extent_ram_bytes(leaf, ei, name_len);
10271 ptr = btrfs_file_extent_inline_start(ei);
10272 write_extent_buffer(leaf, symname, ptr, name_len);
10273 btrfs_mark_buffer_dirty(leaf);
10274 btrfs_free_path(path);
10276 inode->i_op = &btrfs_symlink_inode_operations;
10277 inode_nohighmem(inode);
10278 inode_set_bytes(inode, name_len);
10279 btrfs_i_size_write(BTRFS_I(inode), name_len);
10280 err = btrfs_update_inode(trans, root, inode);
10282 * Last step, add directory indexes for our symlink inode. This is the
10283 * last step to avoid extra cleanup of these indexes if an error happens
10287 err = btrfs_add_nondir(trans, BTRFS_I(dir), dentry,
10288 BTRFS_I(inode), 0, index);
10292 d_instantiate_new(dentry, inode);
10295 btrfs_end_transaction(trans);
10296 if (err && inode) {
10297 inode_dec_link_count(inode);
10298 discard_new_inode(inode);
10300 btrfs_btree_balance_dirty(fs_info);
10304 static int __btrfs_prealloc_file_range(struct inode *inode, int mode,
10305 u64 start, u64 num_bytes, u64 min_size,
10306 loff_t actual_len, u64 *alloc_hint,
10307 struct btrfs_trans_handle *trans)
10309 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
10310 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
10311 struct extent_map *em;
10312 struct btrfs_root *root = BTRFS_I(inode)->root;
10313 struct btrfs_key ins;
10314 u64 cur_offset = start;
10317 u64 last_alloc = (u64)-1;
10319 bool own_trans = true;
10320 u64 end = start + num_bytes - 1;
10324 while (num_bytes > 0) {
10326 trans = btrfs_start_transaction(root, 3);
10327 if (IS_ERR(trans)) {
10328 ret = PTR_ERR(trans);
10333 cur_bytes = min_t(u64, num_bytes, SZ_256M);
10334 cur_bytes = max(cur_bytes, min_size);
10336 * If we are severely fragmented we could end up with really
10337 * small allocations, so if the allocator is returning small
10338 * chunks lets make its job easier by only searching for those
10341 cur_bytes = min(cur_bytes, last_alloc);
10342 ret = btrfs_reserve_extent(root, cur_bytes, cur_bytes,
10343 min_size, 0, *alloc_hint, &ins, 1, 0);
10346 btrfs_end_transaction(trans);
10349 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
10351 last_alloc = ins.offset;
10352 ret = insert_reserved_file_extent(trans, inode,
10353 cur_offset, ins.objectid,
10354 ins.offset, ins.offset,
10355 ins.offset, 0, 0, 0,
10356 BTRFS_FILE_EXTENT_PREALLOC);
10358 btrfs_free_reserved_extent(fs_info, ins.objectid,
10360 btrfs_abort_transaction(trans, ret);
10362 btrfs_end_transaction(trans);
10366 btrfs_drop_extent_cache(BTRFS_I(inode), cur_offset,
10367 cur_offset + ins.offset -1, 0);
10369 em = alloc_extent_map();
10371 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
10372 &BTRFS_I(inode)->runtime_flags);
10376 em->start = cur_offset;
10377 em->orig_start = cur_offset;
10378 em->len = ins.offset;
10379 em->block_start = ins.objectid;
10380 em->block_len = ins.offset;
10381 em->orig_block_len = ins.offset;
10382 em->ram_bytes = ins.offset;
10383 em->bdev = fs_info->fs_devices->latest_bdev;
10384 set_bit(EXTENT_FLAG_PREALLOC, &em->flags);
10385 em->generation = trans->transid;
10388 write_lock(&em_tree->lock);
10389 ret = add_extent_mapping(em_tree, em, 1);
10390 write_unlock(&em_tree->lock);
10391 if (ret != -EEXIST)
10393 btrfs_drop_extent_cache(BTRFS_I(inode), cur_offset,
10394 cur_offset + ins.offset - 1,
10397 free_extent_map(em);
10399 num_bytes -= ins.offset;
10400 cur_offset += ins.offset;
10401 *alloc_hint = ins.objectid + ins.offset;
10403 inode_inc_iversion(inode);
10404 inode->i_ctime = current_time(inode);
10405 BTRFS_I(inode)->flags |= BTRFS_INODE_PREALLOC;
10406 if (!(mode & FALLOC_FL_KEEP_SIZE) &&
10407 (actual_len > inode->i_size) &&
10408 (cur_offset > inode->i_size)) {
10409 if (cur_offset > actual_len)
10410 i_size = actual_len;
10412 i_size = cur_offset;
10413 i_size_write(inode, i_size);
10414 btrfs_ordered_update_i_size(inode, i_size, NULL);
10417 ret = btrfs_update_inode(trans, root, inode);
10420 btrfs_abort_transaction(trans, ret);
10422 btrfs_end_transaction(trans);
10427 btrfs_end_transaction(trans);
10429 if (cur_offset < end)
10430 btrfs_free_reserved_data_space(inode, NULL, cur_offset,
10431 end - cur_offset + 1);
10435 int btrfs_prealloc_file_range(struct inode *inode, int mode,
10436 u64 start, u64 num_bytes, u64 min_size,
10437 loff_t actual_len, u64 *alloc_hint)
10439 return __btrfs_prealloc_file_range(inode, mode, start, num_bytes,
10440 min_size, actual_len, alloc_hint,
10444 int btrfs_prealloc_file_range_trans(struct inode *inode,
10445 struct btrfs_trans_handle *trans, int mode,
10446 u64 start, u64 num_bytes, u64 min_size,
10447 loff_t actual_len, u64 *alloc_hint)
10449 return __btrfs_prealloc_file_range(inode, mode, start, num_bytes,
10450 min_size, actual_len, alloc_hint, trans);
10453 static int btrfs_set_page_dirty(struct page *page)
10455 return __set_page_dirty_nobuffers(page);
10458 static int btrfs_permission(struct inode *inode, int mask)
10460 struct btrfs_root *root = BTRFS_I(inode)->root;
10461 umode_t mode = inode->i_mode;
10463 if (mask & MAY_WRITE &&
10464 (S_ISREG(mode) || S_ISDIR(mode) || S_ISLNK(mode))) {
10465 if (btrfs_root_readonly(root))
10467 if (BTRFS_I(inode)->flags & BTRFS_INODE_READONLY)
10470 return generic_permission(inode, mask);
10473 static int btrfs_tmpfile(struct inode *dir, struct dentry *dentry, umode_t mode)
10475 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
10476 struct btrfs_trans_handle *trans;
10477 struct btrfs_root *root = BTRFS_I(dir)->root;
10478 struct inode *inode = NULL;
10484 * 5 units required for adding orphan entry
10486 trans = btrfs_start_transaction(root, 5);
10488 return PTR_ERR(trans);
10490 ret = btrfs_find_free_ino(root, &objectid);
10494 inode = btrfs_new_inode(trans, root, dir, NULL, 0,
10495 btrfs_ino(BTRFS_I(dir)), objectid, mode, &index);
10496 if (IS_ERR(inode)) {
10497 ret = PTR_ERR(inode);
10502 inode->i_fop = &btrfs_file_operations;
10503 inode->i_op = &btrfs_file_inode_operations;
10505 inode->i_mapping->a_ops = &btrfs_aops;
10506 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
10508 ret = btrfs_init_inode_security(trans, inode, dir, NULL);
10512 ret = btrfs_update_inode(trans, root, inode);
10515 ret = btrfs_orphan_add(trans, BTRFS_I(inode));
10520 * We set number of links to 0 in btrfs_new_inode(), and here we set
10521 * it to 1 because d_tmpfile() will issue a warning if the count is 0,
10524 * d_tmpfile() -> inode_dec_link_count() -> drop_nlink()
10526 set_nlink(inode, 1);
10527 d_tmpfile(dentry, inode);
10528 unlock_new_inode(inode);
10529 mark_inode_dirty(inode);
10531 btrfs_end_transaction(trans);
10533 discard_new_inode(inode);
10534 btrfs_btree_balance_dirty(fs_info);
10538 void btrfs_set_range_writeback(struct extent_io_tree *tree, u64 start, u64 end)
10540 struct inode *inode = tree->private_data;
10541 unsigned long index = start >> PAGE_SHIFT;
10542 unsigned long end_index = end >> PAGE_SHIFT;
10545 while (index <= end_index) {
10546 page = find_get_page(inode->i_mapping, index);
10547 ASSERT(page); /* Pages should be in the extent_io_tree */
10548 set_page_writeback(page);
10556 * Add an entry indicating a block group or device which is pinned by a
10557 * swapfile. Returns 0 on success, 1 if there is already an entry for it, or a
10558 * negative errno on failure.
10560 static int btrfs_add_swapfile_pin(struct inode *inode, void *ptr,
10561 bool is_block_group)
10563 struct btrfs_fs_info *fs_info = BTRFS_I(inode)->root->fs_info;
10564 struct btrfs_swapfile_pin *sp, *entry;
10565 struct rb_node **p;
10566 struct rb_node *parent = NULL;
10568 sp = kmalloc(sizeof(*sp), GFP_NOFS);
10573 sp->is_block_group = is_block_group;
10575 spin_lock(&fs_info->swapfile_pins_lock);
10576 p = &fs_info->swapfile_pins.rb_node;
10579 entry = rb_entry(parent, struct btrfs_swapfile_pin, node);
10580 if (sp->ptr < entry->ptr ||
10581 (sp->ptr == entry->ptr && sp->inode < entry->inode)) {
10582 p = &(*p)->rb_left;
10583 } else if (sp->ptr > entry->ptr ||
10584 (sp->ptr == entry->ptr && sp->inode > entry->inode)) {
10585 p = &(*p)->rb_right;
10587 spin_unlock(&fs_info->swapfile_pins_lock);
10592 rb_link_node(&sp->node, parent, p);
10593 rb_insert_color(&sp->node, &fs_info->swapfile_pins);
10594 spin_unlock(&fs_info->swapfile_pins_lock);
10598 /* Free all of the entries pinned by this swapfile. */
10599 static void btrfs_free_swapfile_pins(struct inode *inode)
10601 struct btrfs_fs_info *fs_info = BTRFS_I(inode)->root->fs_info;
10602 struct btrfs_swapfile_pin *sp;
10603 struct rb_node *node, *next;
10605 spin_lock(&fs_info->swapfile_pins_lock);
10606 node = rb_first(&fs_info->swapfile_pins);
10608 next = rb_next(node);
10609 sp = rb_entry(node, struct btrfs_swapfile_pin, node);
10610 if (sp->inode == inode) {
10611 rb_erase(&sp->node, &fs_info->swapfile_pins);
10612 if (sp->is_block_group)
10613 btrfs_put_block_group(sp->ptr);
10618 spin_unlock(&fs_info->swapfile_pins_lock);
10621 struct btrfs_swap_info {
10627 unsigned long nr_pages;
10631 static int btrfs_add_swap_extent(struct swap_info_struct *sis,
10632 struct btrfs_swap_info *bsi)
10634 unsigned long nr_pages;
10635 u64 first_ppage, first_ppage_reported, next_ppage;
10638 first_ppage = ALIGN(bsi->block_start, PAGE_SIZE) >> PAGE_SHIFT;
10639 next_ppage = ALIGN_DOWN(bsi->block_start + bsi->block_len,
10640 PAGE_SIZE) >> PAGE_SHIFT;
10642 if (first_ppage >= next_ppage)
10644 nr_pages = next_ppage - first_ppage;
10646 first_ppage_reported = first_ppage;
10647 if (bsi->start == 0)
10648 first_ppage_reported++;
10649 if (bsi->lowest_ppage > first_ppage_reported)
10650 bsi->lowest_ppage = first_ppage_reported;
10651 if (bsi->highest_ppage < (next_ppage - 1))
10652 bsi->highest_ppage = next_ppage - 1;
10654 ret = add_swap_extent(sis, bsi->nr_pages, nr_pages, first_ppage);
10657 bsi->nr_extents += ret;
10658 bsi->nr_pages += nr_pages;
10662 static void btrfs_swap_deactivate(struct file *file)
10664 struct inode *inode = file_inode(file);
10666 btrfs_free_swapfile_pins(inode);
10667 atomic_dec(&BTRFS_I(inode)->root->nr_swapfiles);
10670 static int btrfs_swap_activate(struct swap_info_struct *sis, struct file *file,
10673 struct inode *inode = file_inode(file);
10674 struct btrfs_fs_info *fs_info = BTRFS_I(inode)->root->fs_info;
10675 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
10676 struct extent_state *cached_state = NULL;
10677 struct extent_map *em = NULL;
10678 struct btrfs_device *device = NULL;
10679 struct btrfs_swap_info bsi = {
10680 .lowest_ppage = (sector_t)-1ULL,
10687 * If the swap file was just created, make sure delalloc is done. If the
10688 * file changes again after this, the user is doing something stupid and
10689 * we don't really care.
10691 ret = btrfs_wait_ordered_range(inode, 0, (u64)-1);
10696 * The inode is locked, so these flags won't change after we check them.
10698 if (BTRFS_I(inode)->flags & BTRFS_INODE_COMPRESS) {
10699 btrfs_warn(fs_info, "swapfile must not be compressed");
10702 if (!(BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW)) {
10703 btrfs_warn(fs_info, "swapfile must not be copy-on-write");
10706 if (!(BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)) {
10707 btrfs_warn(fs_info, "swapfile must not be checksummed");
10712 * Balance or device remove/replace/resize can move stuff around from
10713 * under us. The EXCL_OP flag makes sure they aren't running/won't run
10714 * concurrently while we are mapping the swap extents, and
10715 * fs_info->swapfile_pins prevents them from running while the swap file
10716 * is active and moving the extents. Note that this also prevents a
10717 * concurrent device add which isn't actually necessary, but it's not
10718 * really worth the trouble to allow it.
10720 if (test_and_set_bit(BTRFS_FS_EXCL_OP, &fs_info->flags)) {
10721 btrfs_warn(fs_info,
10722 "cannot activate swapfile while exclusive operation is running");
10726 * Snapshots can create extents which require COW even if NODATACOW is
10727 * set. We use this counter to prevent snapshots. We must increment it
10728 * before walking the extents because we don't want a concurrent
10729 * snapshot to run after we've already checked the extents.
10731 atomic_inc(&BTRFS_I(inode)->root->nr_swapfiles);
10733 isize = ALIGN_DOWN(inode->i_size, fs_info->sectorsize);
10735 lock_extent_bits(io_tree, 0, isize - 1, &cached_state);
10737 while (start < isize) {
10738 u64 logical_block_start, physical_block_start;
10739 struct btrfs_block_group_cache *bg;
10740 u64 len = isize - start;
10742 em = btrfs_get_extent(BTRFS_I(inode), NULL, 0, start, len, 0);
10748 if (em->block_start == EXTENT_MAP_HOLE) {
10749 btrfs_warn(fs_info, "swapfile must not have holes");
10753 if (em->block_start == EXTENT_MAP_INLINE) {
10755 * It's unlikely we'll ever actually find ourselves
10756 * here, as a file small enough to fit inline won't be
10757 * big enough to store more than the swap header, but in
10758 * case something changes in the future, let's catch it
10759 * here rather than later.
10761 btrfs_warn(fs_info, "swapfile must not be inline");
10765 if (test_bit(EXTENT_FLAG_COMPRESSED, &em->flags)) {
10766 btrfs_warn(fs_info, "swapfile must not be compressed");
10771 logical_block_start = em->block_start + (start - em->start);
10772 len = min(len, em->len - (start - em->start));
10773 free_extent_map(em);
10776 ret = can_nocow_extent(inode, start, &len, NULL, NULL, NULL);
10782 btrfs_warn(fs_info,
10783 "swapfile must not be copy-on-write");
10788 em = btrfs_get_chunk_map(fs_info, logical_block_start, len);
10794 if (em->map_lookup->type & BTRFS_BLOCK_GROUP_PROFILE_MASK) {
10795 btrfs_warn(fs_info,
10796 "swapfile must have single data profile");
10801 if (device == NULL) {
10802 device = em->map_lookup->stripes[0].dev;
10803 ret = btrfs_add_swapfile_pin(inode, device, false);
10808 } else if (device != em->map_lookup->stripes[0].dev) {
10809 btrfs_warn(fs_info, "swapfile must be on one device");
10814 physical_block_start = (em->map_lookup->stripes[0].physical +
10815 (logical_block_start - em->start));
10816 len = min(len, em->len - (logical_block_start - em->start));
10817 free_extent_map(em);
10820 bg = btrfs_lookup_block_group(fs_info, logical_block_start);
10822 btrfs_warn(fs_info,
10823 "could not find block group containing swapfile");
10828 ret = btrfs_add_swapfile_pin(inode, bg, true);
10830 btrfs_put_block_group(bg);
10837 if (bsi.block_len &&
10838 bsi.block_start + bsi.block_len == physical_block_start) {
10839 bsi.block_len += len;
10841 if (bsi.block_len) {
10842 ret = btrfs_add_swap_extent(sis, &bsi);
10847 bsi.block_start = physical_block_start;
10848 bsi.block_len = len;
10855 ret = btrfs_add_swap_extent(sis, &bsi);
10858 if (!IS_ERR_OR_NULL(em))
10859 free_extent_map(em);
10861 unlock_extent_cached(io_tree, 0, isize - 1, &cached_state);
10864 btrfs_swap_deactivate(file);
10866 clear_bit(BTRFS_FS_EXCL_OP, &fs_info->flags);
10872 sis->bdev = device->bdev;
10873 *span = bsi.highest_ppage - bsi.lowest_ppage + 1;
10874 sis->max = bsi.nr_pages;
10875 sis->pages = bsi.nr_pages - 1;
10876 sis->highest_bit = bsi.nr_pages - 1;
10877 return bsi.nr_extents;
10880 static void btrfs_swap_deactivate(struct file *file)
10884 static int btrfs_swap_activate(struct swap_info_struct *sis, struct file *file,
10887 return -EOPNOTSUPP;
10891 static const struct inode_operations btrfs_dir_inode_operations = {
10892 .getattr = btrfs_getattr,
10893 .lookup = btrfs_lookup,
10894 .create = btrfs_create,
10895 .unlink = btrfs_unlink,
10896 .link = btrfs_link,
10897 .mkdir = btrfs_mkdir,
10898 .rmdir = btrfs_rmdir,
10899 .rename = btrfs_rename2,
10900 .symlink = btrfs_symlink,
10901 .setattr = btrfs_setattr,
10902 .mknod = btrfs_mknod,
10903 .listxattr = btrfs_listxattr,
10904 .permission = btrfs_permission,
10905 .get_acl = btrfs_get_acl,
10906 .set_acl = btrfs_set_acl,
10907 .update_time = btrfs_update_time,
10908 .tmpfile = btrfs_tmpfile,
10910 static const struct inode_operations btrfs_dir_ro_inode_operations = {
10911 .lookup = btrfs_lookup,
10912 .permission = btrfs_permission,
10913 .update_time = btrfs_update_time,
10916 static const struct file_operations btrfs_dir_file_operations = {
10917 .llseek = generic_file_llseek,
10918 .read = generic_read_dir,
10919 .iterate_shared = btrfs_real_readdir,
10920 .open = btrfs_opendir,
10921 .unlocked_ioctl = btrfs_ioctl,
10922 #ifdef CONFIG_COMPAT
10923 .compat_ioctl = btrfs_compat_ioctl,
10925 .release = btrfs_release_file,
10926 .fsync = btrfs_sync_file,
10929 static const struct extent_io_ops btrfs_extent_io_ops = {
10930 /* mandatory callbacks */
10931 .submit_bio_hook = btrfs_submit_bio_hook,
10932 .readpage_end_io_hook = btrfs_readpage_end_io_hook,
10936 * btrfs doesn't support the bmap operation because swapfiles
10937 * use bmap to make a mapping of extents in the file. They assume
10938 * these extents won't change over the life of the file and they
10939 * use the bmap result to do IO directly to the drive.
10941 * the btrfs bmap call would return logical addresses that aren't
10942 * suitable for IO and they also will change frequently as COW
10943 * operations happen. So, swapfile + btrfs == corruption.
10945 * For now we're avoiding this by dropping bmap.
10947 static const struct address_space_operations btrfs_aops = {
10948 .readpage = btrfs_readpage,
10949 .writepage = btrfs_writepage,
10950 .writepages = btrfs_writepages,
10951 .readpages = btrfs_readpages,
10952 .direct_IO = btrfs_direct_IO,
10953 .invalidatepage = btrfs_invalidatepage,
10954 .releasepage = btrfs_releasepage,
10955 .set_page_dirty = btrfs_set_page_dirty,
10956 .error_remove_page = generic_error_remove_page,
10957 .swap_activate = btrfs_swap_activate,
10958 .swap_deactivate = btrfs_swap_deactivate,
10961 static const struct inode_operations btrfs_file_inode_operations = {
10962 .getattr = btrfs_getattr,
10963 .setattr = btrfs_setattr,
10964 .listxattr = btrfs_listxattr,
10965 .permission = btrfs_permission,
10966 .fiemap = btrfs_fiemap,
10967 .get_acl = btrfs_get_acl,
10968 .set_acl = btrfs_set_acl,
10969 .update_time = btrfs_update_time,
10971 static const struct inode_operations btrfs_special_inode_operations = {
10972 .getattr = btrfs_getattr,
10973 .setattr = btrfs_setattr,
10974 .permission = btrfs_permission,
10975 .listxattr = btrfs_listxattr,
10976 .get_acl = btrfs_get_acl,
10977 .set_acl = btrfs_set_acl,
10978 .update_time = btrfs_update_time,
10980 static const struct inode_operations btrfs_symlink_inode_operations = {
10981 .get_link = page_get_link,
10982 .getattr = btrfs_getattr,
10983 .setattr = btrfs_setattr,
10984 .permission = btrfs_permission,
10985 .listxattr = btrfs_listxattr,
10986 .update_time = btrfs_update_time,
10989 const struct dentry_operations btrfs_dentry_operations = {
10990 .d_delete = btrfs_dentry_delete,