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"
51 struct btrfs_iget_args {
52 struct btrfs_key *location;
53 struct btrfs_root *root;
56 struct btrfs_dio_data {
58 u64 unsubmitted_oe_range_start;
59 u64 unsubmitted_oe_range_end;
63 static const struct inode_operations btrfs_dir_inode_operations;
64 static const struct inode_operations btrfs_symlink_inode_operations;
65 static const struct inode_operations btrfs_dir_ro_inode_operations;
66 static const struct inode_operations btrfs_special_inode_operations;
67 static const struct inode_operations btrfs_file_inode_operations;
68 static const struct address_space_operations btrfs_aops;
69 static const struct file_operations btrfs_dir_file_operations;
70 static const struct extent_io_ops btrfs_extent_io_ops;
72 static struct kmem_cache *btrfs_inode_cachep;
73 struct kmem_cache *btrfs_trans_handle_cachep;
74 struct kmem_cache *btrfs_path_cachep;
75 struct kmem_cache *btrfs_free_space_cachep;
77 static int btrfs_setsize(struct inode *inode, struct iattr *attr);
78 static int btrfs_truncate(struct inode *inode, bool skip_writeback);
79 static int btrfs_finish_ordered_io(struct btrfs_ordered_extent *ordered_extent);
80 static noinline int cow_file_range(struct inode *inode,
81 struct page *locked_page,
82 u64 start, u64 end, u64 delalloc_end,
83 int *page_started, unsigned long *nr_written,
84 int unlock, struct btrfs_dedupe_hash *hash);
85 static struct extent_map *create_io_em(struct inode *inode, u64 start, u64 len,
86 u64 orig_start, u64 block_start,
87 u64 block_len, u64 orig_block_len,
88 u64 ram_bytes, int compress_type,
91 static void __endio_write_update_ordered(struct inode *inode,
92 const u64 offset, const u64 bytes,
96 * Cleanup all submitted ordered extents in specified range to handle errors
97 * from the btrfs_run_delalloc_range() callback.
99 * NOTE: caller must ensure that when an error happens, it can not call
100 * extent_clear_unlock_delalloc() to clear both the bits EXTENT_DO_ACCOUNTING
101 * and EXTENT_DELALLOC simultaneously, because that causes the reserved metadata
102 * to be released, which we want to happen only when finishing the ordered
103 * extent (btrfs_finish_ordered_io()).
105 static inline void btrfs_cleanup_ordered_extents(struct inode *inode,
106 struct page *locked_page,
107 u64 offset, u64 bytes)
109 unsigned long index = offset >> PAGE_SHIFT;
110 unsigned long end_index = (offset + bytes - 1) >> PAGE_SHIFT;
111 u64 page_start = page_offset(locked_page);
112 u64 page_end = page_start + PAGE_SIZE - 1;
116 while (index <= end_index) {
117 page = find_get_page(inode->i_mapping, index);
121 ClearPagePrivate2(page);
126 * In case this page belongs to the delalloc range being instantiated
127 * then skip it, since the first page of a range is going to be
128 * properly cleaned up by the caller of run_delalloc_range
130 if (page_start >= offset && page_end <= (offset + bytes - 1)) {
135 return __endio_write_update_ordered(inode, offset, bytes, false);
138 static int btrfs_dirty_inode(struct inode *inode);
140 #ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
141 void btrfs_test_inode_set_ops(struct inode *inode)
143 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
147 static int btrfs_init_inode_security(struct btrfs_trans_handle *trans,
148 struct inode *inode, struct inode *dir,
149 const struct qstr *qstr)
153 err = btrfs_init_acl(trans, inode, dir);
155 err = btrfs_xattr_security_init(trans, inode, dir, qstr);
160 * this does all the hard work for inserting an inline extent into
161 * the btree. The caller should have done a btrfs_drop_extents so that
162 * no overlapping inline items exist in the btree
164 static int insert_inline_extent(struct btrfs_trans_handle *trans,
165 struct btrfs_path *path, int extent_inserted,
166 struct btrfs_root *root, struct inode *inode,
167 u64 start, size_t size, size_t compressed_size,
169 struct page **compressed_pages)
171 struct extent_buffer *leaf;
172 struct page *page = NULL;
175 struct btrfs_file_extent_item *ei;
177 size_t cur_size = size;
178 unsigned long offset;
180 if (compressed_size && compressed_pages)
181 cur_size = compressed_size;
183 inode_add_bytes(inode, size);
185 if (!extent_inserted) {
186 struct btrfs_key key;
189 key.objectid = btrfs_ino(BTRFS_I(inode));
191 key.type = BTRFS_EXTENT_DATA_KEY;
193 datasize = btrfs_file_extent_calc_inline_size(cur_size);
194 path->leave_spinning = 1;
195 ret = btrfs_insert_empty_item(trans, root, path, &key,
200 leaf = path->nodes[0];
201 ei = btrfs_item_ptr(leaf, path->slots[0],
202 struct btrfs_file_extent_item);
203 btrfs_set_file_extent_generation(leaf, ei, trans->transid);
204 btrfs_set_file_extent_type(leaf, ei, BTRFS_FILE_EXTENT_INLINE);
205 btrfs_set_file_extent_encryption(leaf, ei, 0);
206 btrfs_set_file_extent_other_encoding(leaf, ei, 0);
207 btrfs_set_file_extent_ram_bytes(leaf, ei, size);
208 ptr = btrfs_file_extent_inline_start(ei);
210 if (compress_type != BTRFS_COMPRESS_NONE) {
213 while (compressed_size > 0) {
214 cpage = compressed_pages[i];
215 cur_size = min_t(unsigned long, compressed_size,
218 kaddr = kmap_atomic(cpage);
219 write_extent_buffer(leaf, kaddr, ptr, cur_size);
220 kunmap_atomic(kaddr);
224 compressed_size -= cur_size;
226 btrfs_set_file_extent_compression(leaf, ei,
229 page = find_get_page(inode->i_mapping,
230 start >> PAGE_SHIFT);
231 btrfs_set_file_extent_compression(leaf, ei, 0);
232 kaddr = kmap_atomic(page);
233 offset = offset_in_page(start);
234 write_extent_buffer(leaf, kaddr + offset, ptr, size);
235 kunmap_atomic(kaddr);
238 btrfs_mark_buffer_dirty(leaf);
239 btrfs_release_path(path);
242 * we're an inline extent, so nobody can
243 * extend the file past i_size without locking
244 * a page we already have locked.
246 * We must do any isize and inode updates
247 * before we unlock the pages. Otherwise we
248 * could end up racing with unlink.
250 BTRFS_I(inode)->disk_i_size = inode->i_size;
251 ret = btrfs_update_inode(trans, root, inode);
259 * conditionally insert an inline extent into the file. This
260 * does the checks required to make sure the data is small enough
261 * to fit as an inline extent.
263 static noinline int cow_file_range_inline(struct inode *inode, u64 start,
264 u64 end, size_t compressed_size,
266 struct page **compressed_pages)
268 struct btrfs_root *root = BTRFS_I(inode)->root;
269 struct btrfs_fs_info *fs_info = root->fs_info;
270 struct btrfs_trans_handle *trans;
271 u64 isize = i_size_read(inode);
272 u64 actual_end = min(end + 1, isize);
273 u64 inline_len = actual_end - start;
274 u64 aligned_end = ALIGN(end, fs_info->sectorsize);
275 u64 data_len = inline_len;
277 struct btrfs_path *path;
278 int extent_inserted = 0;
279 u32 extent_item_size;
282 data_len = compressed_size;
285 actual_end > fs_info->sectorsize ||
286 data_len > BTRFS_MAX_INLINE_DATA_SIZE(fs_info) ||
288 (actual_end & (fs_info->sectorsize - 1)) == 0) ||
290 data_len > fs_info->max_inline) {
294 path = btrfs_alloc_path();
298 trans = btrfs_join_transaction(root);
300 btrfs_free_path(path);
301 return PTR_ERR(trans);
303 trans->block_rsv = &BTRFS_I(inode)->block_rsv;
305 if (compressed_size && compressed_pages)
306 extent_item_size = btrfs_file_extent_calc_inline_size(
309 extent_item_size = btrfs_file_extent_calc_inline_size(
312 ret = __btrfs_drop_extents(trans, root, inode, path,
313 start, aligned_end, NULL,
314 1, 1, extent_item_size, &extent_inserted);
316 btrfs_abort_transaction(trans, ret);
320 if (isize > actual_end)
321 inline_len = min_t(u64, isize, actual_end);
322 ret = insert_inline_extent(trans, path, extent_inserted,
324 inline_len, compressed_size,
325 compress_type, compressed_pages);
326 if (ret && ret != -ENOSPC) {
327 btrfs_abort_transaction(trans, ret);
329 } else if (ret == -ENOSPC) {
334 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &BTRFS_I(inode)->runtime_flags);
335 btrfs_drop_extent_cache(BTRFS_I(inode), start, aligned_end - 1, 0);
338 * Don't forget to free the reserved space, as for inlined extent
339 * it won't count as data extent, free them directly here.
340 * And at reserve time, it's always aligned to page size, so
341 * just free one page here.
343 btrfs_qgroup_free_data(inode, NULL, 0, PAGE_SIZE);
344 btrfs_free_path(path);
345 btrfs_end_transaction(trans);
349 struct async_extent {
354 unsigned long nr_pages;
356 struct list_head list;
361 struct page *locked_page;
364 unsigned int write_flags;
365 struct list_head extents;
366 struct btrfs_work work;
371 /* Number of chunks in flight; must be first in the structure */
373 struct async_chunk chunks[];
376 static noinline int add_async_extent(struct async_chunk *cow,
377 u64 start, u64 ram_size,
380 unsigned long nr_pages,
383 struct async_extent *async_extent;
385 async_extent = kmalloc(sizeof(*async_extent), GFP_NOFS);
386 BUG_ON(!async_extent); /* -ENOMEM */
387 async_extent->start = start;
388 async_extent->ram_size = ram_size;
389 async_extent->compressed_size = compressed_size;
390 async_extent->pages = pages;
391 async_extent->nr_pages = nr_pages;
392 async_extent->compress_type = compress_type;
393 list_add_tail(&async_extent->list, &cow->extents);
397 static inline int inode_need_compress(struct inode *inode, u64 start, u64 end)
399 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
402 if (btrfs_test_opt(fs_info, FORCE_COMPRESS))
405 if (BTRFS_I(inode)->defrag_compress)
407 /* bad compression ratios */
408 if (BTRFS_I(inode)->flags & BTRFS_INODE_NOCOMPRESS)
410 if (btrfs_test_opt(fs_info, COMPRESS) ||
411 BTRFS_I(inode)->flags & BTRFS_INODE_COMPRESS ||
412 BTRFS_I(inode)->prop_compress)
413 return btrfs_compress_heuristic(inode, start, end);
417 static inline void inode_should_defrag(struct btrfs_inode *inode,
418 u64 start, u64 end, u64 num_bytes, u64 small_write)
420 /* If this is a small write inside eof, kick off a defrag */
421 if (num_bytes < small_write &&
422 (start > 0 || end + 1 < inode->disk_i_size))
423 btrfs_add_inode_defrag(NULL, inode);
427 * we create compressed extents in two phases. The first
428 * phase compresses a range of pages that have already been
429 * locked (both pages and state bits are locked).
431 * This is done inside an ordered work queue, and the compression
432 * is spread across many cpus. The actual IO submission is step
433 * two, and the ordered work queue takes care of making sure that
434 * happens in the same order things were put onto the queue by
435 * writepages and friends.
437 * If this code finds it can't get good compression, it puts an
438 * entry onto the work queue to write the uncompressed bytes. This
439 * makes sure that both compressed inodes and uncompressed inodes
440 * are written in the same order that the flusher thread sent them
443 static noinline void compress_file_range(struct async_chunk *async_chunk,
446 struct inode *inode = async_chunk->inode;
447 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
448 u64 blocksize = fs_info->sectorsize;
449 u64 start = async_chunk->start;
450 u64 end = async_chunk->end;
453 struct page **pages = NULL;
454 unsigned long nr_pages;
455 unsigned long total_compressed = 0;
456 unsigned long total_in = 0;
459 int compress_type = fs_info->compress_type;
462 inode_should_defrag(BTRFS_I(inode), start, end, end - start + 1,
465 actual_end = min_t(u64, i_size_read(inode), end + 1);
468 nr_pages = (end >> PAGE_SHIFT) - (start >> PAGE_SHIFT) + 1;
469 BUILD_BUG_ON((BTRFS_MAX_COMPRESSED % PAGE_SIZE) != 0);
470 nr_pages = min_t(unsigned long, nr_pages,
471 BTRFS_MAX_COMPRESSED / PAGE_SIZE);
474 * we don't want to send crud past the end of i_size through
475 * compression, that's just a waste of CPU time. So, if the
476 * end of the file is before the start of our current
477 * requested range of bytes, we bail out to the uncompressed
478 * cleanup code that can deal with all of this.
480 * It isn't really the fastest way to fix things, but this is a
481 * very uncommon corner.
483 if (actual_end <= start)
484 goto cleanup_and_bail_uncompressed;
486 total_compressed = actual_end - start;
489 * skip compression for a small file range(<=blocksize) that
490 * isn't an inline extent, since it doesn't save disk space at all.
492 if (total_compressed <= blocksize &&
493 (start > 0 || end + 1 < BTRFS_I(inode)->disk_i_size))
494 goto cleanup_and_bail_uncompressed;
496 total_compressed = min_t(unsigned long, total_compressed,
497 BTRFS_MAX_UNCOMPRESSED);
502 * we do compression for mount -o compress and when the
503 * inode has not been flagged as nocompress. This flag can
504 * change at any time if we discover bad compression ratios.
506 if (inode_need_compress(inode, start, end)) {
508 pages = kcalloc(nr_pages, sizeof(struct page *), GFP_NOFS);
510 /* just bail out to the uncompressed code */
515 if (BTRFS_I(inode)->defrag_compress)
516 compress_type = BTRFS_I(inode)->defrag_compress;
517 else if (BTRFS_I(inode)->prop_compress)
518 compress_type = BTRFS_I(inode)->prop_compress;
521 * we need to call clear_page_dirty_for_io on each
522 * page in the range. Otherwise applications with the file
523 * mmap'd can wander in and change the page contents while
524 * we are compressing them.
526 * If the compression fails for any reason, we set the pages
527 * dirty again later on.
529 * Note that the remaining part is redirtied, the start pointer
530 * has moved, the end is the original one.
533 extent_range_clear_dirty_for_io(inode, start, end);
537 /* Compression level is applied here and only here */
538 ret = btrfs_compress_pages(
539 compress_type | (fs_info->compress_level << 4),
540 inode->i_mapping, start,
547 unsigned long offset = offset_in_page(total_compressed);
548 struct page *page = pages[nr_pages - 1];
551 /* zero the tail end of the last page, we might be
552 * sending it down to disk
555 kaddr = kmap_atomic(page);
556 memset(kaddr + offset, 0,
558 kunmap_atomic(kaddr);
565 /* lets try to make an inline extent */
566 if (ret || total_in < actual_end) {
567 /* we didn't compress the entire range, try
568 * to make an uncompressed inline extent.
570 ret = cow_file_range_inline(inode, start, end, 0,
571 BTRFS_COMPRESS_NONE, NULL);
573 /* try making a compressed inline extent */
574 ret = cow_file_range_inline(inode, start, end,
576 compress_type, pages);
579 unsigned long clear_flags = EXTENT_DELALLOC |
580 EXTENT_DELALLOC_NEW | EXTENT_DEFRAG |
581 EXTENT_DO_ACCOUNTING;
582 unsigned long page_error_op;
584 page_error_op = ret < 0 ? PAGE_SET_ERROR : 0;
587 * inline extent creation worked or returned error,
588 * we don't need to create any more async work items.
589 * Unlock and free up our temp pages.
591 * We use DO_ACCOUNTING here because we need the
592 * delalloc_release_metadata to be done _after_ we drop
593 * our outstanding extent for clearing delalloc for this
596 extent_clear_unlock_delalloc(inode, start, end, end,
609 * we aren't doing an inline extent round the compressed size
610 * up to a block size boundary so the allocator does sane
613 total_compressed = ALIGN(total_compressed, blocksize);
616 * one last check to make sure the compression is really a
617 * win, compare the page count read with the blocks on disk,
618 * compression must free at least one sector size
620 total_in = ALIGN(total_in, PAGE_SIZE);
621 if (total_compressed + blocksize <= total_in) {
625 * The async work queues will take care of doing actual
626 * allocation on disk for these compressed pages, and
627 * will submit them to the elevator.
629 add_async_extent(async_chunk, start, total_in,
630 total_compressed, pages, nr_pages,
633 if (start + total_in < end) {
644 * the compression code ran but failed to make things smaller,
645 * free any pages it allocated and our page pointer array
647 for (i = 0; i < nr_pages; i++) {
648 WARN_ON(pages[i]->mapping);
653 total_compressed = 0;
656 /* flag the file so we don't compress in the future */
657 if (!btrfs_test_opt(fs_info, FORCE_COMPRESS) &&
658 !(BTRFS_I(inode)->prop_compress)) {
659 BTRFS_I(inode)->flags |= BTRFS_INODE_NOCOMPRESS;
662 cleanup_and_bail_uncompressed:
664 * No compression, but we still need to write the pages in the file
665 * we've been given so far. redirty the locked page if it corresponds
666 * to our extent and set things up for the async work queue to run
667 * cow_file_range to do the normal delalloc dance.
669 if (page_offset(async_chunk->locked_page) >= start &&
670 page_offset(async_chunk->locked_page) <= end)
671 __set_page_dirty_nobuffers(async_chunk->locked_page);
672 /* unlocked later on in the async handlers */
675 extent_range_redirty_for_io(inode, start, end);
676 add_async_extent(async_chunk, start, end - start + 1, 0, NULL, 0,
677 BTRFS_COMPRESS_NONE);
683 for (i = 0; i < nr_pages; i++) {
684 WARN_ON(pages[i]->mapping);
690 static void free_async_extent_pages(struct async_extent *async_extent)
694 if (!async_extent->pages)
697 for (i = 0; i < async_extent->nr_pages; i++) {
698 WARN_ON(async_extent->pages[i]->mapping);
699 put_page(async_extent->pages[i]);
701 kfree(async_extent->pages);
702 async_extent->nr_pages = 0;
703 async_extent->pages = NULL;
707 * phase two of compressed writeback. This is the ordered portion
708 * of the code, which only gets called in the order the work was
709 * queued. We walk all the async extents created by compress_file_range
710 * and send them down to the disk.
712 static noinline void submit_compressed_extents(struct async_chunk *async_chunk)
714 struct inode *inode = async_chunk->inode;
715 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
716 struct async_extent *async_extent;
718 struct btrfs_key ins;
719 struct extent_map *em;
720 struct btrfs_root *root = BTRFS_I(inode)->root;
721 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
725 while (!list_empty(&async_chunk->extents)) {
726 async_extent = list_entry(async_chunk->extents.next,
727 struct async_extent, list);
728 list_del(&async_extent->list);
731 lock_extent(io_tree, async_extent->start,
732 async_extent->start + async_extent->ram_size - 1);
733 /* did the compression code fall back to uncompressed IO? */
734 if (!async_extent->pages) {
735 int page_started = 0;
736 unsigned long nr_written = 0;
738 /* allocate blocks */
739 ret = cow_file_range(inode, async_chunk->locked_page,
741 async_extent->start +
742 async_extent->ram_size - 1,
743 async_extent->start +
744 async_extent->ram_size - 1,
745 &page_started, &nr_written, 0,
751 * if page_started, cow_file_range inserted an
752 * inline extent and took care of all the unlocking
753 * and IO for us. Otherwise, we need to submit
754 * all those pages down to the drive.
756 if (!page_started && !ret)
757 extent_write_locked_range(inode,
759 async_extent->start +
760 async_extent->ram_size - 1,
763 unlock_page(async_chunk->locked_page);
769 ret = btrfs_reserve_extent(root, async_extent->ram_size,
770 async_extent->compressed_size,
771 async_extent->compressed_size,
772 0, alloc_hint, &ins, 1, 1);
774 free_async_extent_pages(async_extent);
776 if (ret == -ENOSPC) {
777 unlock_extent(io_tree, async_extent->start,
778 async_extent->start +
779 async_extent->ram_size - 1);
782 * we need to redirty the pages if we decide to
783 * fallback to uncompressed IO, otherwise we
784 * will not submit these pages down to lower
787 extent_range_redirty_for_io(inode,
789 async_extent->start +
790 async_extent->ram_size - 1);
797 * here we're doing allocation and writeback of the
800 em = create_io_em(inode, async_extent->start,
801 async_extent->ram_size, /* len */
802 async_extent->start, /* orig_start */
803 ins.objectid, /* block_start */
804 ins.offset, /* block_len */
805 ins.offset, /* orig_block_len */
806 async_extent->ram_size, /* ram_bytes */
807 async_extent->compress_type,
808 BTRFS_ORDERED_COMPRESSED);
810 /* ret value is not necessary due to void function */
811 goto out_free_reserve;
814 ret = btrfs_add_ordered_extent_compress(inode,
817 async_extent->ram_size,
819 BTRFS_ORDERED_COMPRESSED,
820 async_extent->compress_type);
822 btrfs_drop_extent_cache(BTRFS_I(inode),
824 async_extent->start +
825 async_extent->ram_size - 1, 0);
826 goto out_free_reserve;
828 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
831 * clear dirty, set writeback and unlock the pages.
833 extent_clear_unlock_delalloc(inode, async_extent->start,
834 async_extent->start +
835 async_extent->ram_size - 1,
836 async_extent->start +
837 async_extent->ram_size - 1,
838 NULL, EXTENT_LOCKED | EXTENT_DELALLOC,
839 PAGE_UNLOCK | PAGE_CLEAR_DIRTY |
841 if (btrfs_submit_compressed_write(inode,
843 async_extent->ram_size,
845 ins.offset, async_extent->pages,
846 async_extent->nr_pages,
847 async_chunk->write_flags)) {
848 struct page *p = async_extent->pages[0];
849 const u64 start = async_extent->start;
850 const u64 end = start + async_extent->ram_size - 1;
852 p->mapping = inode->i_mapping;
853 btrfs_writepage_endio_finish_ordered(p, start, end, 0);
856 extent_clear_unlock_delalloc(inode, start, end, end,
860 free_async_extent_pages(async_extent);
862 alloc_hint = ins.objectid + ins.offset;
868 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
869 btrfs_free_reserved_extent(fs_info, ins.objectid, ins.offset, 1);
871 extent_clear_unlock_delalloc(inode, async_extent->start,
872 async_extent->start +
873 async_extent->ram_size - 1,
874 async_extent->start +
875 async_extent->ram_size - 1,
876 NULL, EXTENT_LOCKED | EXTENT_DELALLOC |
877 EXTENT_DELALLOC_NEW |
878 EXTENT_DEFRAG | EXTENT_DO_ACCOUNTING,
879 PAGE_UNLOCK | PAGE_CLEAR_DIRTY |
880 PAGE_SET_WRITEBACK | PAGE_END_WRITEBACK |
882 free_async_extent_pages(async_extent);
887 static u64 get_extent_allocation_hint(struct inode *inode, u64 start,
890 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
891 struct extent_map *em;
894 read_lock(&em_tree->lock);
895 em = search_extent_mapping(em_tree, start, num_bytes);
898 * if block start isn't an actual block number then find the
899 * first block in this inode and use that as a hint. If that
900 * block is also bogus then just don't worry about it.
902 if (em->block_start >= EXTENT_MAP_LAST_BYTE) {
904 em = search_extent_mapping(em_tree, 0, 0);
905 if (em && em->block_start < EXTENT_MAP_LAST_BYTE)
906 alloc_hint = em->block_start;
910 alloc_hint = em->block_start;
914 read_unlock(&em_tree->lock);
920 * when extent_io.c finds a delayed allocation range in the file,
921 * the call backs end up in this code. The basic idea is to
922 * allocate extents on disk for the range, and create ordered data structs
923 * in ram to track those extents.
925 * locked_page is the page that writepage had locked already. We use
926 * it to make sure we don't do extra locks or unlocks.
928 * *page_started is set to one if we unlock locked_page and do everything
929 * required to start IO on it. It may be clean and already done with
932 static noinline int cow_file_range(struct inode *inode,
933 struct page *locked_page,
934 u64 start, u64 end, u64 delalloc_end,
935 int *page_started, unsigned long *nr_written,
936 int unlock, struct btrfs_dedupe_hash *hash)
938 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
939 struct btrfs_root *root = BTRFS_I(inode)->root;
942 unsigned long ram_size;
943 u64 cur_alloc_size = 0;
944 u64 blocksize = fs_info->sectorsize;
945 struct btrfs_key ins;
946 struct extent_map *em;
948 unsigned long page_ops;
949 bool extent_reserved = false;
952 if (btrfs_is_free_space_inode(BTRFS_I(inode))) {
958 num_bytes = ALIGN(end - start + 1, blocksize);
959 num_bytes = max(blocksize, num_bytes);
960 ASSERT(num_bytes <= btrfs_super_total_bytes(fs_info->super_copy));
962 inode_should_defrag(BTRFS_I(inode), start, end, num_bytes, SZ_64K);
965 /* lets try to make an inline extent */
966 ret = cow_file_range_inline(inode, start, end, 0,
967 BTRFS_COMPRESS_NONE, NULL);
970 * We use DO_ACCOUNTING here because we need the
971 * delalloc_release_metadata to be run _after_ we drop
972 * our outstanding extent for clearing delalloc for this
975 extent_clear_unlock_delalloc(inode, start, end,
977 EXTENT_LOCKED | EXTENT_DELALLOC |
978 EXTENT_DELALLOC_NEW | EXTENT_DEFRAG |
979 EXTENT_DO_ACCOUNTING, PAGE_UNLOCK |
980 PAGE_CLEAR_DIRTY | PAGE_SET_WRITEBACK |
982 *nr_written = *nr_written +
983 (end - start + PAGE_SIZE) / PAGE_SIZE;
986 } else if (ret < 0) {
991 alloc_hint = get_extent_allocation_hint(inode, start, num_bytes);
992 btrfs_drop_extent_cache(BTRFS_I(inode), start,
993 start + num_bytes - 1, 0);
995 while (num_bytes > 0) {
996 cur_alloc_size = num_bytes;
997 ret = btrfs_reserve_extent(root, cur_alloc_size, cur_alloc_size,
998 fs_info->sectorsize, 0, alloc_hint,
1002 cur_alloc_size = ins.offset;
1003 extent_reserved = true;
1005 ram_size = ins.offset;
1006 em = create_io_em(inode, start, ins.offset, /* len */
1007 start, /* orig_start */
1008 ins.objectid, /* block_start */
1009 ins.offset, /* block_len */
1010 ins.offset, /* orig_block_len */
1011 ram_size, /* ram_bytes */
1012 BTRFS_COMPRESS_NONE, /* compress_type */
1013 BTRFS_ORDERED_REGULAR /* type */);
1018 free_extent_map(em);
1020 ret = btrfs_add_ordered_extent(inode, start, ins.objectid,
1021 ram_size, cur_alloc_size, 0);
1023 goto out_drop_extent_cache;
1025 if (root->root_key.objectid ==
1026 BTRFS_DATA_RELOC_TREE_OBJECTID) {
1027 ret = btrfs_reloc_clone_csums(inode, start,
1030 * Only drop cache here, and process as normal.
1032 * We must not allow extent_clear_unlock_delalloc()
1033 * at out_unlock label to free meta of this ordered
1034 * extent, as its meta should be freed by
1035 * btrfs_finish_ordered_io().
1037 * So we must continue until @start is increased to
1038 * skip current ordered extent.
1041 btrfs_drop_extent_cache(BTRFS_I(inode), start,
1042 start + ram_size - 1, 0);
1045 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
1047 /* we're not doing compressed IO, don't unlock the first
1048 * page (which the caller expects to stay locked), don't
1049 * clear any dirty bits and don't set any writeback bits
1051 * Do set the Private2 bit so we know this page was properly
1052 * setup for writepage
1054 page_ops = unlock ? PAGE_UNLOCK : 0;
1055 page_ops |= PAGE_SET_PRIVATE2;
1057 extent_clear_unlock_delalloc(inode, start,
1058 start + ram_size - 1,
1059 delalloc_end, locked_page,
1060 EXTENT_LOCKED | EXTENT_DELALLOC,
1062 if (num_bytes < cur_alloc_size)
1065 num_bytes -= cur_alloc_size;
1066 alloc_hint = ins.objectid + ins.offset;
1067 start += cur_alloc_size;
1068 extent_reserved = false;
1071 * btrfs_reloc_clone_csums() error, since start is increased
1072 * extent_clear_unlock_delalloc() at out_unlock label won't
1073 * free metadata of current ordered extent, we're OK to exit.
1081 out_drop_extent_cache:
1082 btrfs_drop_extent_cache(BTRFS_I(inode), start, start + ram_size - 1, 0);
1084 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
1085 btrfs_free_reserved_extent(fs_info, ins.objectid, ins.offset, 1);
1087 clear_bits = EXTENT_LOCKED | EXTENT_DELALLOC | EXTENT_DELALLOC_NEW |
1088 EXTENT_DEFRAG | EXTENT_CLEAR_META_RESV;
1089 page_ops = PAGE_UNLOCK | PAGE_CLEAR_DIRTY | PAGE_SET_WRITEBACK |
1092 * If we reserved an extent for our delalloc range (or a subrange) and
1093 * failed to create the respective ordered extent, then it means that
1094 * when we reserved the extent we decremented the extent's size from
1095 * the data space_info's bytes_may_use counter and incremented the
1096 * space_info's bytes_reserved counter by the same amount. We must make
1097 * sure extent_clear_unlock_delalloc() does not try to decrement again
1098 * the data space_info's bytes_may_use counter, therefore we do not pass
1099 * it the flag EXTENT_CLEAR_DATA_RESV.
1101 if (extent_reserved) {
1102 extent_clear_unlock_delalloc(inode, start,
1103 start + cur_alloc_size,
1104 start + cur_alloc_size,
1108 start += cur_alloc_size;
1112 extent_clear_unlock_delalloc(inode, start, end, delalloc_end,
1114 clear_bits | EXTENT_CLEAR_DATA_RESV,
1120 * work queue call back to started compression on a file and pages
1122 static noinline void async_cow_start(struct btrfs_work *work)
1124 struct async_chunk *async_chunk;
1127 async_chunk = container_of(work, struct async_chunk, work);
1129 compress_file_range(async_chunk, &num_added);
1130 if (num_added == 0) {
1131 btrfs_add_delayed_iput(async_chunk->inode);
1132 async_chunk->inode = NULL;
1137 * work queue call back to submit previously compressed pages
1139 static noinline void async_cow_submit(struct btrfs_work *work)
1141 struct async_chunk *async_chunk = container_of(work, struct async_chunk,
1143 struct btrfs_fs_info *fs_info = btrfs_work_owner(work);
1144 unsigned long nr_pages;
1146 nr_pages = (async_chunk->end - async_chunk->start + PAGE_SIZE) >>
1149 /* atomic_sub_return implies a barrier */
1150 if (atomic_sub_return(nr_pages, &fs_info->async_delalloc_pages) <
1152 cond_wake_up_nomb(&fs_info->async_submit_wait);
1155 * ->inode could be NULL if async_chunk_start has failed to compress,
1156 * in which case we don't have anything to submit, yet we need to
1157 * always adjust ->async_delalloc_pages as its paired with the init
1158 * happening in cow_file_range_async
1160 if (async_chunk->inode)
1161 submit_compressed_extents(async_chunk);
1164 static noinline void async_cow_free(struct btrfs_work *work)
1166 struct async_chunk *async_chunk;
1168 async_chunk = container_of(work, struct async_chunk, work);
1169 if (async_chunk->inode)
1170 btrfs_add_delayed_iput(async_chunk->inode);
1172 * Since the pointer to 'pending' is at the beginning of the array of
1173 * async_chunk's, freeing it ensures the whole array has been freed.
1175 if (atomic_dec_and_test(async_chunk->pending))
1176 kvfree(async_chunk->pending);
1179 static int cow_file_range_async(struct inode *inode, struct page *locked_page,
1180 u64 start, u64 end, int *page_started,
1181 unsigned long *nr_written,
1182 unsigned int write_flags)
1184 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1185 struct async_cow *ctx;
1186 struct async_chunk *async_chunk;
1187 unsigned long nr_pages;
1189 u64 num_chunks = DIV_ROUND_UP(end - start, SZ_512K);
1191 bool should_compress;
1194 unlock_extent(&BTRFS_I(inode)->io_tree, start, end);
1196 if (BTRFS_I(inode)->flags & BTRFS_INODE_NOCOMPRESS &&
1197 !btrfs_test_opt(fs_info, FORCE_COMPRESS)) {
1199 should_compress = false;
1201 should_compress = true;
1204 nofs_flag = memalloc_nofs_save();
1205 ctx = kvmalloc(struct_size(ctx, chunks, num_chunks), GFP_KERNEL);
1206 memalloc_nofs_restore(nofs_flag);
1209 unsigned clear_bits = EXTENT_LOCKED | EXTENT_DELALLOC |
1210 EXTENT_DELALLOC_NEW | EXTENT_DEFRAG |
1211 EXTENT_DO_ACCOUNTING;
1212 unsigned long page_ops = PAGE_UNLOCK | PAGE_CLEAR_DIRTY |
1213 PAGE_SET_WRITEBACK | PAGE_END_WRITEBACK |
1216 extent_clear_unlock_delalloc(inode, start, end, 0, locked_page,
1217 clear_bits, page_ops);
1221 async_chunk = ctx->chunks;
1222 atomic_set(&ctx->num_chunks, num_chunks);
1224 for (i = 0; i < num_chunks; i++) {
1225 if (should_compress)
1226 cur_end = min(end, start + SZ_512K - 1);
1231 * igrab is called higher up in the call chain, take only the
1232 * lightweight reference for the callback lifetime
1235 async_chunk[i].pending = &ctx->num_chunks;
1236 async_chunk[i].inode = inode;
1237 async_chunk[i].start = start;
1238 async_chunk[i].end = cur_end;
1239 async_chunk[i].locked_page = locked_page;
1240 async_chunk[i].write_flags = write_flags;
1241 INIT_LIST_HEAD(&async_chunk[i].extents);
1243 btrfs_init_work(&async_chunk[i].work,
1244 btrfs_delalloc_helper,
1245 async_cow_start, async_cow_submit,
1248 nr_pages = DIV_ROUND_UP(cur_end - start, PAGE_SIZE);
1249 atomic_add(nr_pages, &fs_info->async_delalloc_pages);
1251 btrfs_queue_work(fs_info->delalloc_workers, &async_chunk[i].work);
1253 *nr_written += nr_pages;
1254 start = cur_end + 1;
1260 static noinline int csum_exist_in_range(struct btrfs_fs_info *fs_info,
1261 u64 bytenr, u64 num_bytes)
1264 struct btrfs_ordered_sum *sums;
1267 ret = btrfs_lookup_csums_range(fs_info->csum_root, bytenr,
1268 bytenr + num_bytes - 1, &list, 0);
1269 if (ret == 0 && list_empty(&list))
1272 while (!list_empty(&list)) {
1273 sums = list_entry(list.next, struct btrfs_ordered_sum, list);
1274 list_del(&sums->list);
1283 * when nowcow writeback call back. This checks for snapshots or COW copies
1284 * of the extents that exist in the file, and COWs the file as required.
1286 * If no cow copies or snapshots exist, we write directly to the existing
1289 static noinline int run_delalloc_nocow(struct inode *inode,
1290 struct page *locked_page,
1291 u64 start, u64 end, int *page_started, int force,
1292 unsigned long *nr_written)
1294 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1295 struct btrfs_root *root = BTRFS_I(inode)->root;
1296 struct extent_buffer *leaf;
1297 struct btrfs_path *path;
1298 struct btrfs_file_extent_item *fi;
1299 struct btrfs_key found_key;
1300 struct extent_map *em;
1315 u64 ino = btrfs_ino(BTRFS_I(inode));
1317 path = btrfs_alloc_path();
1319 extent_clear_unlock_delalloc(inode, start, end, end,
1321 EXTENT_LOCKED | EXTENT_DELALLOC |
1322 EXTENT_DO_ACCOUNTING |
1323 EXTENT_DEFRAG, PAGE_UNLOCK |
1325 PAGE_SET_WRITEBACK |
1326 PAGE_END_WRITEBACK);
1330 nolock = btrfs_is_free_space_inode(BTRFS_I(inode));
1332 cow_start = (u64)-1;
1335 ret = btrfs_lookup_file_extent(NULL, root, path, ino,
1339 if (ret > 0 && path->slots[0] > 0 && check_prev) {
1340 leaf = path->nodes[0];
1341 btrfs_item_key_to_cpu(leaf, &found_key,
1342 path->slots[0] - 1);
1343 if (found_key.objectid == ino &&
1344 found_key.type == BTRFS_EXTENT_DATA_KEY)
1349 leaf = path->nodes[0];
1350 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
1351 ret = btrfs_next_leaf(root, path);
1353 if (cow_start != (u64)-1)
1354 cur_offset = cow_start;
1359 leaf = path->nodes[0];
1365 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
1367 if (found_key.objectid > ino)
1369 if (WARN_ON_ONCE(found_key.objectid < ino) ||
1370 found_key.type < BTRFS_EXTENT_DATA_KEY) {
1374 if (found_key.type > BTRFS_EXTENT_DATA_KEY ||
1375 found_key.offset > end)
1378 if (found_key.offset > cur_offset) {
1379 extent_end = found_key.offset;
1384 fi = btrfs_item_ptr(leaf, path->slots[0],
1385 struct btrfs_file_extent_item);
1386 extent_type = btrfs_file_extent_type(leaf, fi);
1388 ram_bytes = btrfs_file_extent_ram_bytes(leaf, fi);
1389 if (extent_type == BTRFS_FILE_EXTENT_REG ||
1390 extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
1391 disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
1392 extent_offset = btrfs_file_extent_offset(leaf, fi);
1393 extent_end = found_key.offset +
1394 btrfs_file_extent_num_bytes(leaf, fi);
1396 btrfs_file_extent_disk_num_bytes(leaf, fi);
1397 if (extent_end <= start) {
1401 if (disk_bytenr == 0)
1403 if (btrfs_file_extent_compression(leaf, fi) ||
1404 btrfs_file_extent_encryption(leaf, fi) ||
1405 btrfs_file_extent_other_encoding(leaf, fi))
1408 * Do the same check as in btrfs_cross_ref_exist but
1409 * without the unnecessary search.
1412 btrfs_file_extent_generation(leaf, fi) <=
1413 btrfs_root_last_snapshot(&root->root_item))
1415 if (extent_type == BTRFS_FILE_EXTENT_REG && !force)
1417 if (btrfs_extent_readonly(fs_info, disk_bytenr))
1419 ret = btrfs_cross_ref_exist(root, ino,
1421 extent_offset, disk_bytenr);
1424 * ret could be -EIO if the above fails to read
1428 if (cow_start != (u64)-1)
1429 cur_offset = cow_start;
1433 WARN_ON_ONCE(nolock);
1436 disk_bytenr += extent_offset;
1437 disk_bytenr += cur_offset - found_key.offset;
1438 num_bytes = min(end + 1, extent_end) - cur_offset;
1440 * if there are pending snapshots for this root,
1441 * we fall into common COW way.
1443 if (!nolock && atomic_read(&root->snapshot_force_cow))
1446 * force cow if csum exists in the range.
1447 * this ensure that csum for a given extent are
1448 * either valid or do not exist.
1450 ret = csum_exist_in_range(fs_info, disk_bytenr,
1454 * ret could be -EIO if the above fails to read
1458 if (cow_start != (u64)-1)
1459 cur_offset = cow_start;
1462 WARN_ON_ONCE(nolock);
1465 if (!btrfs_inc_nocow_writers(fs_info, disk_bytenr))
1468 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
1469 extent_end = found_key.offset +
1470 btrfs_file_extent_ram_bytes(leaf, fi);
1471 extent_end = ALIGN(extent_end,
1472 fs_info->sectorsize);
1477 if (extent_end <= start) {
1480 btrfs_dec_nocow_writers(fs_info, disk_bytenr);
1484 if (cow_start == (u64)-1)
1485 cow_start = cur_offset;
1486 cur_offset = extent_end;
1487 if (cur_offset > end)
1493 btrfs_release_path(path);
1494 if (cow_start != (u64)-1) {
1495 ret = cow_file_range(inode, locked_page,
1496 cow_start, found_key.offset - 1,
1497 end, page_started, nr_written, 1,
1501 btrfs_dec_nocow_writers(fs_info,
1505 cow_start = (u64)-1;
1508 if (extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
1509 u64 orig_start = found_key.offset - extent_offset;
1511 em = create_io_em(inode, cur_offset, num_bytes,
1513 disk_bytenr, /* block_start */
1514 num_bytes, /* block_len */
1515 disk_num_bytes, /* orig_block_len */
1516 ram_bytes, BTRFS_COMPRESS_NONE,
1517 BTRFS_ORDERED_PREALLOC);
1520 btrfs_dec_nocow_writers(fs_info,
1525 free_extent_map(em);
1528 if (extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
1529 type = BTRFS_ORDERED_PREALLOC;
1531 type = BTRFS_ORDERED_NOCOW;
1534 ret = btrfs_add_ordered_extent(inode, cur_offset, disk_bytenr,
1535 num_bytes, num_bytes, type);
1537 btrfs_dec_nocow_writers(fs_info, disk_bytenr);
1538 BUG_ON(ret); /* -ENOMEM */
1540 if (root->root_key.objectid ==
1541 BTRFS_DATA_RELOC_TREE_OBJECTID)
1543 * Error handled later, as we must prevent
1544 * extent_clear_unlock_delalloc() in error handler
1545 * from freeing metadata of created ordered extent.
1547 ret = btrfs_reloc_clone_csums(inode, cur_offset,
1550 extent_clear_unlock_delalloc(inode, cur_offset,
1551 cur_offset + num_bytes - 1, end,
1552 locked_page, EXTENT_LOCKED |
1554 EXTENT_CLEAR_DATA_RESV,
1555 PAGE_UNLOCK | PAGE_SET_PRIVATE2);
1557 cur_offset = extent_end;
1560 * btrfs_reloc_clone_csums() error, now we're OK to call error
1561 * handler, as metadata for created ordered extent will only
1562 * be freed by btrfs_finish_ordered_io().
1566 if (cur_offset > end)
1569 btrfs_release_path(path);
1571 if (cur_offset <= end && cow_start == (u64)-1)
1572 cow_start = cur_offset;
1574 if (cow_start != (u64)-1) {
1576 ret = cow_file_range(inode, locked_page, cow_start, end, end,
1577 page_started, nr_written, 1, NULL);
1583 if (ret && cur_offset < end)
1584 extent_clear_unlock_delalloc(inode, cur_offset, end, end,
1585 locked_page, EXTENT_LOCKED |
1586 EXTENT_DELALLOC | EXTENT_DEFRAG |
1587 EXTENT_DO_ACCOUNTING, PAGE_UNLOCK |
1589 PAGE_SET_WRITEBACK |
1590 PAGE_END_WRITEBACK);
1591 btrfs_free_path(path);
1595 static inline int need_force_cow(struct inode *inode, u64 start, u64 end)
1598 if (!(BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW) &&
1599 !(BTRFS_I(inode)->flags & BTRFS_INODE_PREALLOC))
1603 * @defrag_bytes is a hint value, no spinlock held here,
1604 * if is not zero, it means the file is defragging.
1605 * Force cow if given extent needs to be defragged.
1607 if (BTRFS_I(inode)->defrag_bytes &&
1608 test_range_bit(&BTRFS_I(inode)->io_tree, start, end,
1609 EXTENT_DEFRAG, 0, NULL))
1616 * Function to process delayed allocation (create CoW) for ranges which are
1617 * being touched for the first time.
1619 int btrfs_run_delalloc_range(struct inode *inode, struct page *locked_page,
1620 u64 start, u64 end, int *page_started, unsigned long *nr_written,
1621 struct writeback_control *wbc)
1624 int force_cow = need_force_cow(inode, start, end);
1625 unsigned int write_flags = wbc_to_write_flags(wbc);
1627 if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW && !force_cow) {
1628 ret = run_delalloc_nocow(inode, locked_page, start, end,
1629 page_started, 1, nr_written);
1630 } else if (BTRFS_I(inode)->flags & BTRFS_INODE_PREALLOC && !force_cow) {
1631 ret = run_delalloc_nocow(inode, locked_page, start, end,
1632 page_started, 0, nr_written);
1633 } else if (!inode_need_compress(inode, start, end)) {
1634 ret = cow_file_range(inode, locked_page, start, end, end,
1635 page_started, nr_written, 1, NULL);
1637 set_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
1638 &BTRFS_I(inode)->runtime_flags);
1639 ret = cow_file_range_async(inode, locked_page, start, end,
1640 page_started, nr_written,
1644 btrfs_cleanup_ordered_extents(inode, locked_page, start,
1649 void btrfs_split_delalloc_extent(struct inode *inode,
1650 struct extent_state *orig, u64 split)
1654 /* not delalloc, ignore it */
1655 if (!(orig->state & EXTENT_DELALLOC))
1658 size = orig->end - orig->start + 1;
1659 if (size > BTRFS_MAX_EXTENT_SIZE) {
1664 * See the explanation in btrfs_merge_delalloc_extent, the same
1665 * applies here, just in reverse.
1667 new_size = orig->end - split + 1;
1668 num_extents = count_max_extents(new_size);
1669 new_size = split - orig->start;
1670 num_extents += count_max_extents(new_size);
1671 if (count_max_extents(size) >= num_extents)
1675 spin_lock(&BTRFS_I(inode)->lock);
1676 btrfs_mod_outstanding_extents(BTRFS_I(inode), 1);
1677 spin_unlock(&BTRFS_I(inode)->lock);
1681 * Handle merged delayed allocation extents so we can keep track of new extents
1682 * that are just merged onto old extents, such as when we are doing sequential
1683 * writes, so we can properly account for the metadata space we'll need.
1685 void btrfs_merge_delalloc_extent(struct inode *inode, struct extent_state *new,
1686 struct extent_state *other)
1688 u64 new_size, old_size;
1691 /* not delalloc, ignore it */
1692 if (!(other->state & EXTENT_DELALLOC))
1695 if (new->start > other->start)
1696 new_size = new->end - other->start + 1;
1698 new_size = other->end - new->start + 1;
1700 /* we're not bigger than the max, unreserve the space and go */
1701 if (new_size <= BTRFS_MAX_EXTENT_SIZE) {
1702 spin_lock(&BTRFS_I(inode)->lock);
1703 btrfs_mod_outstanding_extents(BTRFS_I(inode), -1);
1704 spin_unlock(&BTRFS_I(inode)->lock);
1709 * We have to add up either side to figure out how many extents were
1710 * accounted for before we merged into one big extent. If the number of
1711 * extents we accounted for is <= the amount we need for the new range
1712 * then we can return, otherwise drop. Think of it like this
1716 * So we've grown the extent by a MAX_SIZE extent, this would mean we
1717 * need 2 outstanding extents, on one side we have 1 and the other side
1718 * we have 1 so they are == and we can return. But in this case
1720 * [MAX_SIZE+4k][MAX_SIZE+4k]
1722 * Each range on their own accounts for 2 extents, but merged together
1723 * they are only 3 extents worth of accounting, so we need to drop in
1726 old_size = other->end - other->start + 1;
1727 num_extents = count_max_extents(old_size);
1728 old_size = new->end - new->start + 1;
1729 num_extents += count_max_extents(old_size);
1730 if (count_max_extents(new_size) >= num_extents)
1733 spin_lock(&BTRFS_I(inode)->lock);
1734 btrfs_mod_outstanding_extents(BTRFS_I(inode), -1);
1735 spin_unlock(&BTRFS_I(inode)->lock);
1738 static void btrfs_add_delalloc_inodes(struct btrfs_root *root,
1739 struct inode *inode)
1741 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1743 spin_lock(&root->delalloc_lock);
1744 if (list_empty(&BTRFS_I(inode)->delalloc_inodes)) {
1745 list_add_tail(&BTRFS_I(inode)->delalloc_inodes,
1746 &root->delalloc_inodes);
1747 set_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1748 &BTRFS_I(inode)->runtime_flags);
1749 root->nr_delalloc_inodes++;
1750 if (root->nr_delalloc_inodes == 1) {
1751 spin_lock(&fs_info->delalloc_root_lock);
1752 BUG_ON(!list_empty(&root->delalloc_root));
1753 list_add_tail(&root->delalloc_root,
1754 &fs_info->delalloc_roots);
1755 spin_unlock(&fs_info->delalloc_root_lock);
1758 spin_unlock(&root->delalloc_lock);
1762 void __btrfs_del_delalloc_inode(struct btrfs_root *root,
1763 struct btrfs_inode *inode)
1765 struct btrfs_fs_info *fs_info = root->fs_info;
1767 if (!list_empty(&inode->delalloc_inodes)) {
1768 list_del_init(&inode->delalloc_inodes);
1769 clear_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1770 &inode->runtime_flags);
1771 root->nr_delalloc_inodes--;
1772 if (!root->nr_delalloc_inodes) {
1773 ASSERT(list_empty(&root->delalloc_inodes));
1774 spin_lock(&fs_info->delalloc_root_lock);
1775 BUG_ON(list_empty(&root->delalloc_root));
1776 list_del_init(&root->delalloc_root);
1777 spin_unlock(&fs_info->delalloc_root_lock);
1782 static void btrfs_del_delalloc_inode(struct btrfs_root *root,
1783 struct btrfs_inode *inode)
1785 spin_lock(&root->delalloc_lock);
1786 __btrfs_del_delalloc_inode(root, inode);
1787 spin_unlock(&root->delalloc_lock);
1791 * Properly track delayed allocation bytes in the inode and to maintain the
1792 * list of inodes that have pending delalloc work to be done.
1794 void btrfs_set_delalloc_extent(struct inode *inode, struct extent_state *state,
1797 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1799 if ((*bits & EXTENT_DEFRAG) && !(*bits & EXTENT_DELALLOC))
1802 * set_bit and clear bit hooks normally require _irqsave/restore
1803 * but in this case, we are only testing for the DELALLOC
1804 * bit, which is only set or cleared with irqs on
1806 if (!(state->state & EXTENT_DELALLOC) && (*bits & EXTENT_DELALLOC)) {
1807 struct btrfs_root *root = BTRFS_I(inode)->root;
1808 u64 len = state->end + 1 - state->start;
1809 u32 num_extents = count_max_extents(len);
1810 bool do_list = !btrfs_is_free_space_inode(BTRFS_I(inode));
1812 spin_lock(&BTRFS_I(inode)->lock);
1813 btrfs_mod_outstanding_extents(BTRFS_I(inode), num_extents);
1814 spin_unlock(&BTRFS_I(inode)->lock);
1816 /* For sanity tests */
1817 if (btrfs_is_testing(fs_info))
1820 percpu_counter_add_batch(&fs_info->delalloc_bytes, len,
1821 fs_info->delalloc_batch);
1822 spin_lock(&BTRFS_I(inode)->lock);
1823 BTRFS_I(inode)->delalloc_bytes += len;
1824 if (*bits & EXTENT_DEFRAG)
1825 BTRFS_I(inode)->defrag_bytes += len;
1826 if (do_list && !test_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1827 &BTRFS_I(inode)->runtime_flags))
1828 btrfs_add_delalloc_inodes(root, inode);
1829 spin_unlock(&BTRFS_I(inode)->lock);
1832 if (!(state->state & EXTENT_DELALLOC_NEW) &&
1833 (*bits & EXTENT_DELALLOC_NEW)) {
1834 spin_lock(&BTRFS_I(inode)->lock);
1835 BTRFS_I(inode)->new_delalloc_bytes += state->end + 1 -
1837 spin_unlock(&BTRFS_I(inode)->lock);
1842 * Once a range is no longer delalloc this function ensures that proper
1843 * accounting happens.
1845 void btrfs_clear_delalloc_extent(struct inode *vfs_inode,
1846 struct extent_state *state, unsigned *bits)
1848 struct btrfs_inode *inode = BTRFS_I(vfs_inode);
1849 struct btrfs_fs_info *fs_info = btrfs_sb(vfs_inode->i_sb);
1850 u64 len = state->end + 1 - state->start;
1851 u32 num_extents = count_max_extents(len);
1853 if ((state->state & EXTENT_DEFRAG) && (*bits & EXTENT_DEFRAG)) {
1854 spin_lock(&inode->lock);
1855 inode->defrag_bytes -= len;
1856 spin_unlock(&inode->lock);
1860 * set_bit and clear bit hooks normally require _irqsave/restore
1861 * but in this case, we are only testing for the DELALLOC
1862 * bit, which is only set or cleared with irqs on
1864 if ((state->state & EXTENT_DELALLOC) && (*bits & EXTENT_DELALLOC)) {
1865 struct btrfs_root *root = inode->root;
1866 bool do_list = !btrfs_is_free_space_inode(inode);
1868 spin_lock(&inode->lock);
1869 btrfs_mod_outstanding_extents(inode, -num_extents);
1870 spin_unlock(&inode->lock);
1873 * We don't reserve metadata space for space cache inodes so we
1874 * don't need to call delalloc_release_metadata if there is an
1877 if (*bits & EXTENT_CLEAR_META_RESV &&
1878 root != fs_info->tree_root)
1879 btrfs_delalloc_release_metadata(inode, len, false);
1881 /* For sanity tests. */
1882 if (btrfs_is_testing(fs_info))
1885 if (root->root_key.objectid != BTRFS_DATA_RELOC_TREE_OBJECTID &&
1886 do_list && !(state->state & EXTENT_NORESERVE) &&
1887 (*bits & EXTENT_CLEAR_DATA_RESV))
1888 btrfs_free_reserved_data_space_noquota(
1892 percpu_counter_add_batch(&fs_info->delalloc_bytes, -len,
1893 fs_info->delalloc_batch);
1894 spin_lock(&inode->lock);
1895 inode->delalloc_bytes -= len;
1896 if (do_list && inode->delalloc_bytes == 0 &&
1897 test_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1898 &inode->runtime_flags))
1899 btrfs_del_delalloc_inode(root, inode);
1900 spin_unlock(&inode->lock);
1903 if ((state->state & EXTENT_DELALLOC_NEW) &&
1904 (*bits & EXTENT_DELALLOC_NEW)) {
1905 spin_lock(&inode->lock);
1906 ASSERT(inode->new_delalloc_bytes >= len);
1907 inode->new_delalloc_bytes -= len;
1908 spin_unlock(&inode->lock);
1913 * btrfs_bio_fits_in_stripe - Checks whether the size of the given bio will fit
1914 * in a chunk's stripe. This function ensures that bios do not span a
1917 * @page - The page we are about to add to the bio
1918 * @size - size we want to add to the bio
1919 * @bio - bio we want to ensure is smaller than a stripe
1920 * @bio_flags - flags of the bio
1922 * return 1 if page cannot be added to the bio
1923 * return 0 if page can be added to the bio
1924 * return error otherwise
1926 int btrfs_bio_fits_in_stripe(struct page *page, size_t size, struct bio *bio,
1927 unsigned long bio_flags)
1929 struct inode *inode = page->mapping->host;
1930 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1931 u64 logical = (u64)bio->bi_iter.bi_sector << 9;
1936 if (bio_flags & EXTENT_BIO_COMPRESSED)
1939 length = bio->bi_iter.bi_size;
1940 map_length = length;
1941 ret = btrfs_map_block(fs_info, btrfs_op(bio), logical, &map_length,
1945 if (map_length < length + size)
1951 * in order to insert checksums into the metadata in large chunks,
1952 * we wait until bio submission time. All the pages in the bio are
1953 * checksummed and sums are attached onto the ordered extent record.
1955 * At IO completion time the cums attached on the ordered extent record
1956 * are inserted into the btree
1958 static blk_status_t btrfs_submit_bio_start(void *private_data, struct bio *bio,
1961 struct inode *inode = private_data;
1962 blk_status_t ret = 0;
1964 ret = btrfs_csum_one_bio(inode, bio, 0, 0);
1965 BUG_ON(ret); /* -ENOMEM */
1970 * extent_io.c submission hook. This does the right thing for csum calculation
1971 * on write, or reading the csums from the tree before a read.
1973 * Rules about async/sync submit,
1974 * a) read: sync submit
1976 * b) write without checksum: sync submit
1978 * c) write with checksum:
1979 * c-1) if bio is issued by fsync: sync submit
1980 * (sync_writers != 0)
1982 * c-2) if root is reloc root: sync submit
1983 * (only in case of buffered IO)
1985 * c-3) otherwise: async submit
1987 static blk_status_t btrfs_submit_bio_hook(struct inode *inode, struct bio *bio,
1989 unsigned long bio_flags)
1992 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1993 struct btrfs_root *root = BTRFS_I(inode)->root;
1994 enum btrfs_wq_endio_type metadata = BTRFS_WQ_ENDIO_DATA;
1995 blk_status_t ret = 0;
1997 int async = !atomic_read(&BTRFS_I(inode)->sync_writers);
1999 skip_sum = BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM;
2001 if (btrfs_is_free_space_inode(BTRFS_I(inode)))
2002 metadata = BTRFS_WQ_ENDIO_FREE_SPACE;
2004 if (bio_op(bio) != REQ_OP_WRITE) {
2005 ret = btrfs_bio_wq_end_io(fs_info, bio, metadata);
2009 if (bio_flags & EXTENT_BIO_COMPRESSED) {
2010 ret = btrfs_submit_compressed_read(inode, bio,
2014 } else if (!skip_sum) {
2015 ret = btrfs_lookup_bio_sums(inode, bio, NULL);
2020 } else if (async && !skip_sum) {
2021 /* csum items have already been cloned */
2022 if (root->root_key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID)
2024 /* we're doing a write, do the async checksumming */
2025 ret = btrfs_wq_submit_bio(fs_info, bio, mirror_num, bio_flags,
2026 0, inode, btrfs_submit_bio_start);
2028 } else if (!skip_sum) {
2029 ret = btrfs_csum_one_bio(inode, bio, 0, 0);
2035 ret = btrfs_map_bio(fs_info, bio, mirror_num, 0);
2039 bio->bi_status = ret;
2046 * given a list of ordered sums record them in the inode. This happens
2047 * at IO completion time based on sums calculated at bio submission time.
2049 static noinline int add_pending_csums(struct btrfs_trans_handle *trans,
2050 struct inode *inode, struct list_head *list)
2052 struct btrfs_ordered_sum *sum;
2055 list_for_each_entry(sum, list, list) {
2056 trans->adding_csums = true;
2057 ret = btrfs_csum_file_blocks(trans,
2058 BTRFS_I(inode)->root->fs_info->csum_root, sum);
2059 trans->adding_csums = false;
2066 int btrfs_set_extent_delalloc(struct inode *inode, u64 start, u64 end,
2067 unsigned int extra_bits,
2068 struct extent_state **cached_state, int dedupe)
2070 WARN_ON(PAGE_ALIGNED(end));
2071 return set_extent_delalloc(&BTRFS_I(inode)->io_tree, start, end,
2072 extra_bits, cached_state);
2075 /* see btrfs_writepage_start_hook for details on why this is required */
2076 struct btrfs_writepage_fixup {
2078 struct btrfs_work work;
2081 static void btrfs_writepage_fixup_worker(struct btrfs_work *work)
2083 struct btrfs_writepage_fixup *fixup;
2084 struct btrfs_ordered_extent *ordered;
2085 struct extent_state *cached_state = NULL;
2086 struct extent_changeset *data_reserved = NULL;
2088 struct inode *inode;
2093 fixup = container_of(work, struct btrfs_writepage_fixup, work);
2097 if (!page->mapping || !PageDirty(page) || !PageChecked(page)) {
2098 ClearPageChecked(page);
2102 inode = page->mapping->host;
2103 page_start = page_offset(page);
2104 page_end = page_offset(page) + PAGE_SIZE - 1;
2106 lock_extent_bits(&BTRFS_I(inode)->io_tree, page_start, page_end,
2109 /* already ordered? We're done */
2110 if (PagePrivate2(page))
2113 ordered = btrfs_lookup_ordered_range(BTRFS_I(inode), page_start,
2116 unlock_extent_cached(&BTRFS_I(inode)->io_tree, page_start,
2117 page_end, &cached_state);
2119 btrfs_start_ordered_extent(inode, ordered, 1);
2120 btrfs_put_ordered_extent(ordered);
2124 ret = btrfs_delalloc_reserve_space(inode, &data_reserved, page_start,
2127 mapping_set_error(page->mapping, ret);
2128 end_extent_writepage(page, ret, page_start, page_end);
2129 ClearPageChecked(page);
2133 ret = btrfs_set_extent_delalloc(inode, page_start, page_end, 0,
2136 mapping_set_error(page->mapping, ret);
2137 end_extent_writepage(page, ret, page_start, page_end);
2138 ClearPageChecked(page);
2142 ClearPageChecked(page);
2143 set_page_dirty(page);
2144 btrfs_delalloc_release_extents(BTRFS_I(inode), PAGE_SIZE, false);
2146 unlock_extent_cached(&BTRFS_I(inode)->io_tree, page_start, page_end,
2152 extent_changeset_free(data_reserved);
2156 * There are a few paths in the higher layers of the kernel that directly
2157 * set the page dirty bit without asking the filesystem if it is a
2158 * good idea. This causes problems because we want to make sure COW
2159 * properly happens and the data=ordered rules are followed.
2161 * In our case any range that doesn't have the ORDERED bit set
2162 * hasn't been properly setup for IO. We kick off an async process
2163 * to fix it up. The async helper will wait for ordered extents, set
2164 * the delalloc bit and make it safe to write the page.
2166 int btrfs_writepage_cow_fixup(struct page *page, u64 start, u64 end)
2168 struct inode *inode = page->mapping->host;
2169 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2170 struct btrfs_writepage_fixup *fixup;
2172 /* this page is properly in the ordered list */
2173 if (TestClearPagePrivate2(page))
2176 if (PageChecked(page))
2179 fixup = kzalloc(sizeof(*fixup), GFP_NOFS);
2183 SetPageChecked(page);
2185 btrfs_init_work(&fixup->work, btrfs_fixup_helper,
2186 btrfs_writepage_fixup_worker, NULL, NULL);
2188 btrfs_queue_work(fs_info->fixup_workers, &fixup->work);
2192 static int insert_reserved_file_extent(struct btrfs_trans_handle *trans,
2193 struct inode *inode, u64 file_pos,
2194 u64 disk_bytenr, u64 disk_num_bytes,
2195 u64 num_bytes, u64 ram_bytes,
2196 u8 compression, u8 encryption,
2197 u16 other_encoding, int extent_type)
2199 struct btrfs_root *root = BTRFS_I(inode)->root;
2200 struct btrfs_file_extent_item *fi;
2201 struct btrfs_path *path;
2202 struct extent_buffer *leaf;
2203 struct btrfs_key ins;
2205 int extent_inserted = 0;
2208 path = btrfs_alloc_path();
2213 * we may be replacing one extent in the tree with another.
2214 * The new extent is pinned in the extent map, and we don't want
2215 * to drop it from the cache until it is completely in the btree.
2217 * So, tell btrfs_drop_extents to leave this extent in the cache.
2218 * the caller is expected to unpin it and allow it to be merged
2221 ret = __btrfs_drop_extents(trans, root, inode, path, file_pos,
2222 file_pos + num_bytes, NULL, 0,
2223 1, sizeof(*fi), &extent_inserted);
2227 if (!extent_inserted) {
2228 ins.objectid = btrfs_ino(BTRFS_I(inode));
2229 ins.offset = file_pos;
2230 ins.type = BTRFS_EXTENT_DATA_KEY;
2232 path->leave_spinning = 1;
2233 ret = btrfs_insert_empty_item(trans, root, path, &ins,
2238 leaf = path->nodes[0];
2239 fi = btrfs_item_ptr(leaf, path->slots[0],
2240 struct btrfs_file_extent_item);
2241 btrfs_set_file_extent_generation(leaf, fi, trans->transid);
2242 btrfs_set_file_extent_type(leaf, fi, extent_type);
2243 btrfs_set_file_extent_disk_bytenr(leaf, fi, disk_bytenr);
2244 btrfs_set_file_extent_disk_num_bytes(leaf, fi, disk_num_bytes);
2245 btrfs_set_file_extent_offset(leaf, fi, 0);
2246 btrfs_set_file_extent_num_bytes(leaf, fi, num_bytes);
2247 btrfs_set_file_extent_ram_bytes(leaf, fi, ram_bytes);
2248 btrfs_set_file_extent_compression(leaf, fi, compression);
2249 btrfs_set_file_extent_encryption(leaf, fi, encryption);
2250 btrfs_set_file_extent_other_encoding(leaf, fi, other_encoding);
2252 btrfs_mark_buffer_dirty(leaf);
2253 btrfs_release_path(path);
2255 inode_add_bytes(inode, num_bytes);
2257 ins.objectid = disk_bytenr;
2258 ins.offset = disk_num_bytes;
2259 ins.type = BTRFS_EXTENT_ITEM_KEY;
2262 * Release the reserved range from inode dirty range map, as it is
2263 * already moved into delayed_ref_head
2265 ret = btrfs_qgroup_release_data(inode, file_pos, ram_bytes);
2269 ret = btrfs_alloc_reserved_file_extent(trans, root,
2270 btrfs_ino(BTRFS_I(inode)),
2271 file_pos, qg_released, &ins);
2273 btrfs_free_path(path);
2278 /* snapshot-aware defrag */
2279 struct sa_defrag_extent_backref {
2280 struct rb_node node;
2281 struct old_sa_defrag_extent *old;
2290 struct old_sa_defrag_extent {
2291 struct list_head list;
2292 struct new_sa_defrag_extent *new;
2301 struct new_sa_defrag_extent {
2302 struct rb_root root;
2303 struct list_head head;
2304 struct btrfs_path *path;
2305 struct inode *inode;
2313 static int backref_comp(struct sa_defrag_extent_backref *b1,
2314 struct sa_defrag_extent_backref *b2)
2316 if (b1->root_id < b2->root_id)
2318 else if (b1->root_id > b2->root_id)
2321 if (b1->inum < b2->inum)
2323 else if (b1->inum > b2->inum)
2326 if (b1->file_pos < b2->file_pos)
2328 else if (b1->file_pos > b2->file_pos)
2332 * [------------------------------] ===> (a range of space)
2333 * |<--->| |<---->| =============> (fs/file tree A)
2334 * |<---------------------------->| ===> (fs/file tree B)
2336 * A range of space can refer to two file extents in one tree while
2337 * refer to only one file extent in another tree.
2339 * So we may process a disk offset more than one time(two extents in A)
2340 * and locate at the same extent(one extent in B), then insert two same
2341 * backrefs(both refer to the extent in B).
2346 static void backref_insert(struct rb_root *root,
2347 struct sa_defrag_extent_backref *backref)
2349 struct rb_node **p = &root->rb_node;
2350 struct rb_node *parent = NULL;
2351 struct sa_defrag_extent_backref *entry;
2356 entry = rb_entry(parent, struct sa_defrag_extent_backref, node);
2358 ret = backref_comp(backref, entry);
2362 p = &(*p)->rb_right;
2365 rb_link_node(&backref->node, parent, p);
2366 rb_insert_color(&backref->node, root);
2370 * Note the backref might has changed, and in this case we just return 0.
2372 static noinline int record_one_backref(u64 inum, u64 offset, u64 root_id,
2375 struct btrfs_file_extent_item *extent;
2376 struct old_sa_defrag_extent *old = ctx;
2377 struct new_sa_defrag_extent *new = old->new;
2378 struct btrfs_path *path = new->path;
2379 struct btrfs_key key;
2380 struct btrfs_root *root;
2381 struct sa_defrag_extent_backref *backref;
2382 struct extent_buffer *leaf;
2383 struct inode *inode = new->inode;
2384 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2390 if (BTRFS_I(inode)->root->root_key.objectid == root_id &&
2391 inum == btrfs_ino(BTRFS_I(inode)))
2394 key.objectid = root_id;
2395 key.type = BTRFS_ROOT_ITEM_KEY;
2396 key.offset = (u64)-1;
2398 root = btrfs_read_fs_root_no_name(fs_info, &key);
2400 if (PTR_ERR(root) == -ENOENT)
2403 btrfs_debug(fs_info, "inum=%llu, offset=%llu, root_id=%llu",
2404 inum, offset, root_id);
2405 return PTR_ERR(root);
2408 key.objectid = inum;
2409 key.type = BTRFS_EXTENT_DATA_KEY;
2410 if (offset > (u64)-1 << 32)
2413 key.offset = offset;
2415 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2416 if (WARN_ON(ret < 0))
2423 leaf = path->nodes[0];
2424 slot = path->slots[0];
2426 if (slot >= btrfs_header_nritems(leaf)) {
2427 ret = btrfs_next_leaf(root, path);
2430 } else if (ret > 0) {
2439 btrfs_item_key_to_cpu(leaf, &key, slot);
2441 if (key.objectid > inum)
2444 if (key.objectid < inum || key.type != BTRFS_EXTENT_DATA_KEY)
2447 extent = btrfs_item_ptr(leaf, slot,
2448 struct btrfs_file_extent_item);
2450 if (btrfs_file_extent_disk_bytenr(leaf, extent) != old->bytenr)
2454 * 'offset' refers to the exact key.offset,
2455 * NOT the 'offset' field in btrfs_extent_data_ref, ie.
2456 * (key.offset - extent_offset).
2458 if (key.offset != offset)
2461 extent_offset = btrfs_file_extent_offset(leaf, extent);
2462 num_bytes = btrfs_file_extent_num_bytes(leaf, extent);
2464 if (extent_offset >= old->extent_offset + old->offset +
2465 old->len || extent_offset + num_bytes <=
2466 old->extent_offset + old->offset)
2471 backref = kmalloc(sizeof(*backref), GFP_NOFS);
2477 backref->root_id = root_id;
2478 backref->inum = inum;
2479 backref->file_pos = offset;
2480 backref->num_bytes = num_bytes;
2481 backref->extent_offset = extent_offset;
2482 backref->generation = btrfs_file_extent_generation(leaf, extent);
2484 backref_insert(&new->root, backref);
2487 btrfs_release_path(path);
2492 static noinline bool record_extent_backrefs(struct btrfs_path *path,
2493 struct new_sa_defrag_extent *new)
2495 struct btrfs_fs_info *fs_info = btrfs_sb(new->inode->i_sb);
2496 struct old_sa_defrag_extent *old, *tmp;
2501 list_for_each_entry_safe(old, tmp, &new->head, list) {
2502 ret = iterate_inodes_from_logical(old->bytenr +
2503 old->extent_offset, fs_info,
2504 path, record_one_backref,
2506 if (ret < 0 && ret != -ENOENT)
2509 /* no backref to be processed for this extent */
2511 list_del(&old->list);
2516 if (list_empty(&new->head))
2522 static int relink_is_mergable(struct extent_buffer *leaf,
2523 struct btrfs_file_extent_item *fi,
2524 struct new_sa_defrag_extent *new)
2526 if (btrfs_file_extent_disk_bytenr(leaf, fi) != new->bytenr)
2529 if (btrfs_file_extent_type(leaf, fi) != BTRFS_FILE_EXTENT_REG)
2532 if (btrfs_file_extent_compression(leaf, fi) != new->compress_type)
2535 if (btrfs_file_extent_encryption(leaf, fi) ||
2536 btrfs_file_extent_other_encoding(leaf, fi))
2543 * Note the backref might has changed, and in this case we just return 0.
2545 static noinline int relink_extent_backref(struct btrfs_path *path,
2546 struct sa_defrag_extent_backref *prev,
2547 struct sa_defrag_extent_backref *backref)
2549 struct btrfs_file_extent_item *extent;
2550 struct btrfs_file_extent_item *item;
2551 struct btrfs_ordered_extent *ordered;
2552 struct btrfs_trans_handle *trans;
2553 struct btrfs_ref ref = { 0 };
2554 struct btrfs_root *root;
2555 struct btrfs_key key;
2556 struct extent_buffer *leaf;
2557 struct old_sa_defrag_extent *old = backref->old;
2558 struct new_sa_defrag_extent *new = old->new;
2559 struct btrfs_fs_info *fs_info = btrfs_sb(new->inode->i_sb);
2560 struct inode *inode;
2561 struct extent_state *cached = NULL;
2570 if (prev && prev->root_id == backref->root_id &&
2571 prev->inum == backref->inum &&
2572 prev->file_pos + prev->num_bytes == backref->file_pos)
2575 /* step 1: get root */
2576 key.objectid = backref->root_id;
2577 key.type = BTRFS_ROOT_ITEM_KEY;
2578 key.offset = (u64)-1;
2580 index = srcu_read_lock(&fs_info->subvol_srcu);
2582 root = btrfs_read_fs_root_no_name(fs_info, &key);
2584 srcu_read_unlock(&fs_info->subvol_srcu, index);
2585 if (PTR_ERR(root) == -ENOENT)
2587 return PTR_ERR(root);
2590 if (btrfs_root_readonly(root)) {
2591 srcu_read_unlock(&fs_info->subvol_srcu, index);
2595 /* step 2: get inode */
2596 key.objectid = backref->inum;
2597 key.type = BTRFS_INODE_ITEM_KEY;
2600 inode = btrfs_iget(fs_info->sb, &key, root, NULL);
2601 if (IS_ERR(inode)) {
2602 srcu_read_unlock(&fs_info->subvol_srcu, index);
2606 srcu_read_unlock(&fs_info->subvol_srcu, index);
2608 /* step 3: relink backref */
2609 lock_start = backref->file_pos;
2610 lock_end = backref->file_pos + backref->num_bytes - 1;
2611 lock_extent_bits(&BTRFS_I(inode)->io_tree, lock_start, lock_end,
2614 ordered = btrfs_lookup_first_ordered_extent(inode, lock_end);
2616 btrfs_put_ordered_extent(ordered);
2620 trans = btrfs_join_transaction(root);
2621 if (IS_ERR(trans)) {
2622 ret = PTR_ERR(trans);
2626 key.objectid = backref->inum;
2627 key.type = BTRFS_EXTENT_DATA_KEY;
2628 key.offset = backref->file_pos;
2630 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2633 } else if (ret > 0) {
2638 extent = btrfs_item_ptr(path->nodes[0], path->slots[0],
2639 struct btrfs_file_extent_item);
2641 if (btrfs_file_extent_generation(path->nodes[0], extent) !=
2642 backref->generation)
2645 btrfs_release_path(path);
2647 start = backref->file_pos;
2648 if (backref->extent_offset < old->extent_offset + old->offset)
2649 start += old->extent_offset + old->offset -
2650 backref->extent_offset;
2652 len = min(backref->extent_offset + backref->num_bytes,
2653 old->extent_offset + old->offset + old->len);
2654 len -= max(backref->extent_offset, old->extent_offset + old->offset);
2656 ret = btrfs_drop_extents(trans, root, inode, start,
2661 key.objectid = btrfs_ino(BTRFS_I(inode));
2662 key.type = BTRFS_EXTENT_DATA_KEY;
2665 path->leave_spinning = 1;
2667 struct btrfs_file_extent_item *fi;
2669 struct btrfs_key found_key;
2671 ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
2676 leaf = path->nodes[0];
2677 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
2679 fi = btrfs_item_ptr(leaf, path->slots[0],
2680 struct btrfs_file_extent_item);
2681 extent_len = btrfs_file_extent_num_bytes(leaf, fi);
2683 if (extent_len + found_key.offset == start &&
2684 relink_is_mergable(leaf, fi, new)) {
2685 btrfs_set_file_extent_num_bytes(leaf, fi,
2687 btrfs_mark_buffer_dirty(leaf);
2688 inode_add_bytes(inode, len);
2694 btrfs_release_path(path);
2699 ret = btrfs_insert_empty_item(trans, root, path, &key,
2702 btrfs_abort_transaction(trans, ret);
2706 leaf = path->nodes[0];
2707 item = btrfs_item_ptr(leaf, path->slots[0],
2708 struct btrfs_file_extent_item);
2709 btrfs_set_file_extent_disk_bytenr(leaf, item, new->bytenr);
2710 btrfs_set_file_extent_disk_num_bytes(leaf, item, new->disk_len);
2711 btrfs_set_file_extent_offset(leaf, item, start - new->file_pos);
2712 btrfs_set_file_extent_num_bytes(leaf, item, len);
2713 btrfs_set_file_extent_ram_bytes(leaf, item, new->len);
2714 btrfs_set_file_extent_generation(leaf, item, trans->transid);
2715 btrfs_set_file_extent_type(leaf, item, BTRFS_FILE_EXTENT_REG);
2716 btrfs_set_file_extent_compression(leaf, item, new->compress_type);
2717 btrfs_set_file_extent_encryption(leaf, item, 0);
2718 btrfs_set_file_extent_other_encoding(leaf, item, 0);
2720 btrfs_mark_buffer_dirty(leaf);
2721 inode_add_bytes(inode, len);
2722 btrfs_release_path(path);
2724 btrfs_init_generic_ref(&ref, BTRFS_ADD_DELAYED_REF, new->bytenr,
2726 btrfs_init_data_ref(&ref, backref->root_id, backref->inum,
2727 new->file_pos); /* start - extent_offset */
2728 ret = btrfs_inc_extent_ref(trans, &ref);
2730 btrfs_abort_transaction(trans, ret);
2736 btrfs_release_path(path);
2737 path->leave_spinning = 0;
2738 btrfs_end_transaction(trans);
2740 unlock_extent_cached(&BTRFS_I(inode)->io_tree, lock_start, lock_end,
2746 static void free_sa_defrag_extent(struct new_sa_defrag_extent *new)
2748 struct old_sa_defrag_extent *old, *tmp;
2753 list_for_each_entry_safe(old, tmp, &new->head, list) {
2759 static void relink_file_extents(struct new_sa_defrag_extent *new)
2761 struct btrfs_fs_info *fs_info = btrfs_sb(new->inode->i_sb);
2762 struct btrfs_path *path;
2763 struct sa_defrag_extent_backref *backref;
2764 struct sa_defrag_extent_backref *prev = NULL;
2765 struct rb_node *node;
2768 path = btrfs_alloc_path();
2772 if (!record_extent_backrefs(path, new)) {
2773 btrfs_free_path(path);
2776 btrfs_release_path(path);
2779 node = rb_first(&new->root);
2782 rb_erase(node, &new->root);
2784 backref = rb_entry(node, struct sa_defrag_extent_backref, node);
2786 ret = relink_extent_backref(path, prev, backref);
2799 btrfs_free_path(path);
2801 free_sa_defrag_extent(new);
2803 atomic_dec(&fs_info->defrag_running);
2804 wake_up(&fs_info->transaction_wait);
2807 static struct new_sa_defrag_extent *
2808 record_old_file_extents(struct inode *inode,
2809 struct btrfs_ordered_extent *ordered)
2811 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2812 struct btrfs_root *root = BTRFS_I(inode)->root;
2813 struct btrfs_path *path;
2814 struct btrfs_key key;
2815 struct old_sa_defrag_extent *old;
2816 struct new_sa_defrag_extent *new;
2819 new = kmalloc(sizeof(*new), GFP_NOFS);
2824 new->file_pos = ordered->file_offset;
2825 new->len = ordered->len;
2826 new->bytenr = ordered->start;
2827 new->disk_len = ordered->disk_len;
2828 new->compress_type = ordered->compress_type;
2829 new->root = RB_ROOT;
2830 INIT_LIST_HEAD(&new->head);
2832 path = btrfs_alloc_path();
2836 key.objectid = btrfs_ino(BTRFS_I(inode));
2837 key.type = BTRFS_EXTENT_DATA_KEY;
2838 key.offset = new->file_pos;
2840 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2843 if (ret > 0 && path->slots[0] > 0)
2846 /* find out all the old extents for the file range */
2848 struct btrfs_file_extent_item *extent;
2849 struct extent_buffer *l;
2858 slot = path->slots[0];
2860 if (slot >= btrfs_header_nritems(l)) {
2861 ret = btrfs_next_leaf(root, path);
2869 btrfs_item_key_to_cpu(l, &key, slot);
2871 if (key.objectid != btrfs_ino(BTRFS_I(inode)))
2873 if (key.type != BTRFS_EXTENT_DATA_KEY)
2875 if (key.offset >= new->file_pos + new->len)
2878 extent = btrfs_item_ptr(l, slot, struct btrfs_file_extent_item);
2880 num_bytes = btrfs_file_extent_num_bytes(l, extent);
2881 if (key.offset + num_bytes < new->file_pos)
2884 disk_bytenr = btrfs_file_extent_disk_bytenr(l, extent);
2888 extent_offset = btrfs_file_extent_offset(l, extent);
2890 old = kmalloc(sizeof(*old), GFP_NOFS);
2894 offset = max(new->file_pos, key.offset);
2895 end = min(new->file_pos + new->len, key.offset + num_bytes);
2897 old->bytenr = disk_bytenr;
2898 old->extent_offset = extent_offset;
2899 old->offset = offset - key.offset;
2900 old->len = end - offset;
2903 list_add_tail(&old->list, &new->head);
2909 btrfs_free_path(path);
2910 atomic_inc(&fs_info->defrag_running);
2915 btrfs_free_path(path);
2917 free_sa_defrag_extent(new);
2921 static void btrfs_release_delalloc_bytes(struct btrfs_fs_info *fs_info,
2924 struct btrfs_block_group_cache *cache;
2926 cache = btrfs_lookup_block_group(fs_info, start);
2929 spin_lock(&cache->lock);
2930 cache->delalloc_bytes -= len;
2931 spin_unlock(&cache->lock);
2933 btrfs_put_block_group(cache);
2936 /* as ordered data IO finishes, this gets called so we can finish
2937 * an ordered extent if the range of bytes in the file it covers are
2940 static int btrfs_finish_ordered_io(struct btrfs_ordered_extent *ordered_extent)
2942 struct inode *inode = ordered_extent->inode;
2943 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2944 struct btrfs_root *root = BTRFS_I(inode)->root;
2945 struct btrfs_trans_handle *trans = NULL;
2946 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
2947 struct extent_state *cached_state = NULL;
2948 struct new_sa_defrag_extent *new = NULL;
2949 int compress_type = 0;
2951 u64 logical_len = ordered_extent->len;
2953 bool truncated = false;
2954 bool range_locked = false;
2955 bool clear_new_delalloc_bytes = false;
2956 bool clear_reserved_extent = true;
2958 if (!test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags) &&
2959 !test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags) &&
2960 !test_bit(BTRFS_ORDERED_DIRECT, &ordered_extent->flags))
2961 clear_new_delalloc_bytes = true;
2963 nolock = btrfs_is_free_space_inode(BTRFS_I(inode));
2965 if (test_bit(BTRFS_ORDERED_IOERR, &ordered_extent->flags)) {
2970 btrfs_free_io_failure_record(BTRFS_I(inode),
2971 ordered_extent->file_offset,
2972 ordered_extent->file_offset +
2973 ordered_extent->len - 1);
2975 if (test_bit(BTRFS_ORDERED_TRUNCATED, &ordered_extent->flags)) {
2977 logical_len = ordered_extent->truncated_len;
2978 /* Truncated the entire extent, don't bother adding */
2983 if (test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags)) {
2984 BUG_ON(!list_empty(&ordered_extent->list)); /* Logic error */
2987 * For mwrite(mmap + memset to write) case, we still reserve
2988 * space for NOCOW range.
2989 * As NOCOW won't cause a new delayed ref, just free the space
2991 btrfs_qgroup_free_data(inode, NULL, ordered_extent->file_offset,
2992 ordered_extent->len);
2993 btrfs_ordered_update_i_size(inode, 0, ordered_extent);
2995 trans = btrfs_join_transaction_nolock(root);
2997 trans = btrfs_join_transaction(root);
2998 if (IS_ERR(trans)) {
2999 ret = PTR_ERR(trans);
3003 trans->block_rsv = &BTRFS_I(inode)->block_rsv;
3004 ret = btrfs_update_inode_fallback(trans, root, inode);
3005 if (ret) /* -ENOMEM or corruption */
3006 btrfs_abort_transaction(trans, ret);
3010 range_locked = true;
3011 lock_extent_bits(io_tree, ordered_extent->file_offset,
3012 ordered_extent->file_offset + ordered_extent->len - 1,
3015 ret = test_range_bit(io_tree, ordered_extent->file_offset,
3016 ordered_extent->file_offset + ordered_extent->len - 1,
3017 EXTENT_DEFRAG, 0, cached_state);
3019 u64 last_snapshot = btrfs_root_last_snapshot(&root->root_item);
3020 if (0 && last_snapshot >= BTRFS_I(inode)->generation)
3021 /* the inode is shared */
3022 new = record_old_file_extents(inode, ordered_extent);
3024 clear_extent_bit(io_tree, ordered_extent->file_offset,
3025 ordered_extent->file_offset + ordered_extent->len - 1,
3026 EXTENT_DEFRAG, 0, 0, &cached_state);
3030 trans = btrfs_join_transaction_nolock(root);
3032 trans = btrfs_join_transaction(root);
3033 if (IS_ERR(trans)) {
3034 ret = PTR_ERR(trans);
3039 trans->block_rsv = &BTRFS_I(inode)->block_rsv;
3041 if (test_bit(BTRFS_ORDERED_COMPRESSED, &ordered_extent->flags))
3042 compress_type = ordered_extent->compress_type;
3043 if (test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags)) {
3044 BUG_ON(compress_type);
3045 btrfs_qgroup_free_data(inode, NULL, ordered_extent->file_offset,
3046 ordered_extent->len);
3047 ret = btrfs_mark_extent_written(trans, BTRFS_I(inode),
3048 ordered_extent->file_offset,
3049 ordered_extent->file_offset +
3052 BUG_ON(root == fs_info->tree_root);
3053 ret = insert_reserved_file_extent(trans, inode,
3054 ordered_extent->file_offset,
3055 ordered_extent->start,
3056 ordered_extent->disk_len,
3057 logical_len, logical_len,
3058 compress_type, 0, 0,
3059 BTRFS_FILE_EXTENT_REG);
3061 clear_reserved_extent = false;
3062 btrfs_release_delalloc_bytes(fs_info,
3063 ordered_extent->start,
3064 ordered_extent->disk_len);
3067 unpin_extent_cache(&BTRFS_I(inode)->extent_tree,
3068 ordered_extent->file_offset, ordered_extent->len,
3071 btrfs_abort_transaction(trans, ret);
3075 ret = add_pending_csums(trans, inode, &ordered_extent->list);
3077 btrfs_abort_transaction(trans, ret);
3081 btrfs_ordered_update_i_size(inode, 0, ordered_extent);
3082 ret = btrfs_update_inode_fallback(trans, root, inode);
3083 if (ret) { /* -ENOMEM or corruption */
3084 btrfs_abort_transaction(trans, ret);
3089 if (range_locked || clear_new_delalloc_bytes) {
3090 unsigned int clear_bits = 0;
3093 clear_bits |= EXTENT_LOCKED;
3094 if (clear_new_delalloc_bytes)
3095 clear_bits |= EXTENT_DELALLOC_NEW;
3096 clear_extent_bit(&BTRFS_I(inode)->io_tree,
3097 ordered_extent->file_offset,
3098 ordered_extent->file_offset +
3099 ordered_extent->len - 1,
3101 (clear_bits & EXTENT_LOCKED) ? 1 : 0,
3106 btrfs_end_transaction(trans);
3108 if (ret || truncated) {
3112 start = ordered_extent->file_offset + logical_len;
3114 start = ordered_extent->file_offset;
3115 end = ordered_extent->file_offset + ordered_extent->len - 1;
3116 clear_extent_uptodate(io_tree, start, end, NULL);
3118 /* Drop the cache for the part of the extent we didn't write. */
3119 btrfs_drop_extent_cache(BTRFS_I(inode), start, end, 0);
3122 * If the ordered extent had an IOERR or something else went
3123 * wrong we need to return the space for this ordered extent
3124 * back to the allocator. We only free the extent in the
3125 * truncated case if we didn't write out the extent at all.
3127 * If we made it past insert_reserved_file_extent before we
3128 * errored out then we don't need to do this as the accounting
3129 * has already been done.
3131 if ((ret || !logical_len) &&
3132 clear_reserved_extent &&
3133 !test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags) &&
3134 !test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags))
3135 btrfs_free_reserved_extent(fs_info,
3136 ordered_extent->start,
3137 ordered_extent->disk_len, 1);
3142 * This needs to be done to make sure anybody waiting knows we are done
3143 * updating everything for this ordered extent.
3145 btrfs_remove_ordered_extent(inode, ordered_extent);
3147 /* for snapshot-aware defrag */
3150 free_sa_defrag_extent(new);
3151 atomic_dec(&fs_info->defrag_running);
3153 relink_file_extents(new);
3158 btrfs_put_ordered_extent(ordered_extent);
3159 /* once for the tree */
3160 btrfs_put_ordered_extent(ordered_extent);
3165 static void finish_ordered_fn(struct btrfs_work *work)
3167 struct btrfs_ordered_extent *ordered_extent;
3168 ordered_extent = container_of(work, struct btrfs_ordered_extent, work);
3169 btrfs_finish_ordered_io(ordered_extent);
3172 void btrfs_writepage_endio_finish_ordered(struct page *page, u64 start,
3173 u64 end, int uptodate)
3175 struct inode *inode = page->mapping->host;
3176 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
3177 struct btrfs_ordered_extent *ordered_extent = NULL;
3178 struct btrfs_workqueue *wq;
3179 btrfs_work_func_t func;
3181 trace_btrfs_writepage_end_io_hook(page, start, end, uptodate);
3183 ClearPagePrivate2(page);
3184 if (!btrfs_dec_test_ordered_pending(inode, &ordered_extent, start,
3185 end - start + 1, uptodate))
3188 if (btrfs_is_free_space_inode(BTRFS_I(inode))) {
3189 wq = fs_info->endio_freespace_worker;
3190 func = btrfs_freespace_write_helper;
3192 wq = fs_info->endio_write_workers;
3193 func = btrfs_endio_write_helper;
3196 btrfs_init_work(&ordered_extent->work, func, finish_ordered_fn, NULL,
3198 btrfs_queue_work(wq, &ordered_extent->work);
3201 static int __readpage_endio_check(struct inode *inode,
3202 struct btrfs_io_bio *io_bio,
3203 int icsum, struct page *page,
3204 int pgoff, u64 start, size_t len)
3210 csum_expected = *(((u32 *)io_bio->csum) + icsum);
3212 kaddr = kmap_atomic(page);
3213 csum = btrfs_csum_data(kaddr + pgoff, csum, len);
3214 btrfs_csum_final(csum, (u8 *)&csum);
3215 if (csum != csum_expected)
3218 kunmap_atomic(kaddr);
3221 btrfs_print_data_csum_error(BTRFS_I(inode), start, csum, csum_expected,
3222 io_bio->mirror_num);
3223 memset(kaddr + pgoff, 1, len);
3224 flush_dcache_page(page);
3225 kunmap_atomic(kaddr);
3230 * when reads are done, we need to check csums to verify the data is correct
3231 * if there's a match, we allow the bio to finish. If not, the code in
3232 * extent_io.c will try to find good copies for us.
3234 static int btrfs_readpage_end_io_hook(struct btrfs_io_bio *io_bio,
3235 u64 phy_offset, struct page *page,
3236 u64 start, u64 end, int mirror)
3238 size_t offset = start - page_offset(page);
3239 struct inode *inode = page->mapping->host;
3240 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
3241 struct btrfs_root *root = BTRFS_I(inode)->root;
3243 if (PageChecked(page)) {
3244 ClearPageChecked(page);
3248 if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)
3251 if (root->root_key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID &&
3252 test_range_bit(io_tree, start, end, EXTENT_NODATASUM, 1, NULL)) {
3253 clear_extent_bits(io_tree, start, end, EXTENT_NODATASUM);
3257 phy_offset >>= inode->i_sb->s_blocksize_bits;
3258 return __readpage_endio_check(inode, io_bio, phy_offset, page, offset,
3259 start, (size_t)(end - start + 1));
3263 * btrfs_add_delayed_iput - perform a delayed iput on @inode
3265 * @inode: The inode we want to perform iput on
3267 * This function uses the generic vfs_inode::i_count to track whether we should
3268 * just decrement it (in case it's > 1) or if this is the last iput then link
3269 * the inode to the delayed iput machinery. Delayed iputs are processed at
3270 * transaction commit time/superblock commit/cleaner kthread.
3272 void btrfs_add_delayed_iput(struct inode *inode)
3274 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
3275 struct btrfs_inode *binode = BTRFS_I(inode);
3277 if (atomic_add_unless(&inode->i_count, -1, 1))
3280 atomic_inc(&fs_info->nr_delayed_iputs);
3281 spin_lock(&fs_info->delayed_iput_lock);
3282 ASSERT(list_empty(&binode->delayed_iput));
3283 list_add_tail(&binode->delayed_iput, &fs_info->delayed_iputs);
3284 spin_unlock(&fs_info->delayed_iput_lock);
3285 if (!test_bit(BTRFS_FS_CLEANER_RUNNING, &fs_info->flags))
3286 wake_up_process(fs_info->cleaner_kthread);
3289 void btrfs_run_delayed_iputs(struct btrfs_fs_info *fs_info)
3292 spin_lock(&fs_info->delayed_iput_lock);
3293 while (!list_empty(&fs_info->delayed_iputs)) {
3294 struct btrfs_inode *inode;
3296 inode = list_first_entry(&fs_info->delayed_iputs,
3297 struct btrfs_inode, delayed_iput);
3298 list_del_init(&inode->delayed_iput);
3299 spin_unlock(&fs_info->delayed_iput_lock);
3300 iput(&inode->vfs_inode);
3301 if (atomic_dec_and_test(&fs_info->nr_delayed_iputs))
3302 wake_up(&fs_info->delayed_iputs_wait);
3303 spin_lock(&fs_info->delayed_iput_lock);
3305 spin_unlock(&fs_info->delayed_iput_lock);
3309 * btrfs_wait_on_delayed_iputs - wait on the delayed iputs to be done running
3310 * @fs_info - the fs_info for this fs
3311 * @return - EINTR if we were killed, 0 if nothing's pending
3313 * This will wait on any delayed iputs that are currently running with KILLABLE
3314 * set. Once they are all done running we will return, unless we are killed in
3315 * which case we return EINTR. This helps in user operations like fallocate etc
3316 * that might get blocked on the iputs.
3318 int btrfs_wait_on_delayed_iputs(struct btrfs_fs_info *fs_info)
3320 int ret = wait_event_killable(fs_info->delayed_iputs_wait,
3321 atomic_read(&fs_info->nr_delayed_iputs) == 0);
3328 * This creates an orphan entry for the given inode in case something goes wrong
3329 * in the middle of an unlink.
3331 int btrfs_orphan_add(struct btrfs_trans_handle *trans,
3332 struct btrfs_inode *inode)
3336 ret = btrfs_insert_orphan_item(trans, inode->root, btrfs_ino(inode));
3337 if (ret && ret != -EEXIST) {
3338 btrfs_abort_transaction(trans, ret);
3346 * We have done the delete so we can go ahead and remove the orphan item for
3347 * this particular inode.
3349 static int btrfs_orphan_del(struct btrfs_trans_handle *trans,
3350 struct btrfs_inode *inode)
3352 return btrfs_del_orphan_item(trans, inode->root, btrfs_ino(inode));
3356 * this cleans up any orphans that may be left on the list from the last use
3359 int btrfs_orphan_cleanup(struct btrfs_root *root)
3361 struct btrfs_fs_info *fs_info = root->fs_info;
3362 struct btrfs_path *path;
3363 struct extent_buffer *leaf;
3364 struct btrfs_key key, found_key;
3365 struct btrfs_trans_handle *trans;
3366 struct inode *inode;
3367 u64 last_objectid = 0;
3368 int ret = 0, nr_unlink = 0;
3370 if (cmpxchg(&root->orphan_cleanup_state, 0, ORPHAN_CLEANUP_STARTED))
3373 path = btrfs_alloc_path();
3378 path->reada = READA_BACK;
3380 key.objectid = BTRFS_ORPHAN_OBJECTID;
3381 key.type = BTRFS_ORPHAN_ITEM_KEY;
3382 key.offset = (u64)-1;
3385 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
3390 * if ret == 0 means we found what we were searching for, which
3391 * is weird, but possible, so only screw with path if we didn't
3392 * find the key and see if we have stuff that matches
3396 if (path->slots[0] == 0)
3401 /* pull out the item */
3402 leaf = path->nodes[0];
3403 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
3405 /* make sure the item matches what we want */
3406 if (found_key.objectid != BTRFS_ORPHAN_OBJECTID)
3408 if (found_key.type != BTRFS_ORPHAN_ITEM_KEY)
3411 /* release the path since we're done with it */
3412 btrfs_release_path(path);
3415 * this is where we are basically btrfs_lookup, without the
3416 * crossing root thing. we store the inode number in the
3417 * offset of the orphan item.
3420 if (found_key.offset == last_objectid) {
3422 "Error removing orphan entry, stopping orphan cleanup");
3427 last_objectid = found_key.offset;
3429 found_key.objectid = found_key.offset;
3430 found_key.type = BTRFS_INODE_ITEM_KEY;
3431 found_key.offset = 0;
3432 inode = btrfs_iget(fs_info->sb, &found_key, root, NULL);
3433 ret = PTR_ERR_OR_ZERO(inode);
3434 if (ret && ret != -ENOENT)
3437 if (ret == -ENOENT && root == fs_info->tree_root) {
3438 struct btrfs_root *dead_root;
3439 struct btrfs_fs_info *fs_info = root->fs_info;
3440 int is_dead_root = 0;
3443 * this is an orphan in the tree root. Currently these
3444 * could come from 2 sources:
3445 * a) a snapshot deletion in progress
3446 * b) a free space cache inode
3447 * We need to distinguish those two, as the snapshot
3448 * orphan must not get deleted.
3449 * find_dead_roots already ran before us, so if this
3450 * is a snapshot deletion, we should find the root
3451 * in the dead_roots list
3453 spin_lock(&fs_info->trans_lock);
3454 list_for_each_entry(dead_root, &fs_info->dead_roots,
3456 if (dead_root->root_key.objectid ==
3457 found_key.objectid) {
3462 spin_unlock(&fs_info->trans_lock);
3464 /* prevent this orphan from being found again */
3465 key.offset = found_key.objectid - 1;
3472 * If we have an inode with links, there are a couple of
3473 * possibilities. Old kernels (before v3.12) used to create an
3474 * orphan item for truncate indicating that there were possibly
3475 * extent items past i_size that needed to be deleted. In v3.12,
3476 * truncate was changed to update i_size in sync with the extent
3477 * items, but the (useless) orphan item was still created. Since
3478 * v4.18, we don't create the orphan item for truncate at all.
3480 * So, this item could mean that we need to do a truncate, but
3481 * only if this filesystem was last used on a pre-v3.12 kernel
3482 * and was not cleanly unmounted. The odds of that are quite
3483 * slim, and it's a pain to do the truncate now, so just delete
3486 * It's also possible that this orphan item was supposed to be
3487 * deleted but wasn't. The inode number may have been reused,
3488 * but either way, we can delete the orphan item.
3490 if (ret == -ENOENT || inode->i_nlink) {
3493 trans = btrfs_start_transaction(root, 1);
3494 if (IS_ERR(trans)) {
3495 ret = PTR_ERR(trans);
3498 btrfs_debug(fs_info, "auto deleting %Lu",
3499 found_key.objectid);
3500 ret = btrfs_del_orphan_item(trans, root,
3501 found_key.objectid);
3502 btrfs_end_transaction(trans);
3510 /* this will do delete_inode and everything for us */
3513 /* release the path since we're done with it */
3514 btrfs_release_path(path);
3516 root->orphan_cleanup_state = ORPHAN_CLEANUP_DONE;
3518 if (test_bit(BTRFS_ROOT_ORPHAN_ITEM_INSERTED, &root->state)) {
3519 trans = btrfs_join_transaction(root);
3521 btrfs_end_transaction(trans);
3525 btrfs_debug(fs_info, "unlinked %d orphans", nr_unlink);
3529 btrfs_err(fs_info, "could not do orphan cleanup %d", ret);
3530 btrfs_free_path(path);
3535 * very simple check to peek ahead in the leaf looking for xattrs. If we
3536 * don't find any xattrs, we know there can't be any acls.
3538 * slot is the slot the inode is in, objectid is the objectid of the inode
3540 static noinline int acls_after_inode_item(struct extent_buffer *leaf,
3541 int slot, u64 objectid,
3542 int *first_xattr_slot)
3544 u32 nritems = btrfs_header_nritems(leaf);
3545 struct btrfs_key found_key;
3546 static u64 xattr_access = 0;
3547 static u64 xattr_default = 0;
3550 if (!xattr_access) {
3551 xattr_access = btrfs_name_hash(XATTR_NAME_POSIX_ACL_ACCESS,
3552 strlen(XATTR_NAME_POSIX_ACL_ACCESS));
3553 xattr_default = btrfs_name_hash(XATTR_NAME_POSIX_ACL_DEFAULT,
3554 strlen(XATTR_NAME_POSIX_ACL_DEFAULT));
3558 *first_xattr_slot = -1;
3559 while (slot < nritems) {
3560 btrfs_item_key_to_cpu(leaf, &found_key, slot);
3562 /* we found a different objectid, there must not be acls */
3563 if (found_key.objectid != objectid)
3566 /* we found an xattr, assume we've got an acl */
3567 if (found_key.type == BTRFS_XATTR_ITEM_KEY) {
3568 if (*first_xattr_slot == -1)
3569 *first_xattr_slot = slot;
3570 if (found_key.offset == xattr_access ||
3571 found_key.offset == xattr_default)
3576 * we found a key greater than an xattr key, there can't
3577 * be any acls later on
3579 if (found_key.type > BTRFS_XATTR_ITEM_KEY)
3586 * it goes inode, inode backrefs, xattrs, extents,
3587 * so if there are a ton of hard links to an inode there can
3588 * be a lot of backrefs. Don't waste time searching too hard,
3589 * this is just an optimization
3594 /* we hit the end of the leaf before we found an xattr or
3595 * something larger than an xattr. We have to assume the inode
3598 if (*first_xattr_slot == -1)
3599 *first_xattr_slot = slot;
3604 * read an inode from the btree into the in-memory inode
3606 static int btrfs_read_locked_inode(struct inode *inode,
3607 struct btrfs_path *in_path)
3609 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
3610 struct btrfs_path *path = in_path;
3611 struct extent_buffer *leaf;
3612 struct btrfs_inode_item *inode_item;
3613 struct btrfs_root *root = BTRFS_I(inode)->root;
3614 struct btrfs_key location;
3619 bool filled = false;
3620 int first_xattr_slot;
3622 ret = btrfs_fill_inode(inode, &rdev);
3627 path = btrfs_alloc_path();
3632 memcpy(&location, &BTRFS_I(inode)->location, sizeof(location));
3634 ret = btrfs_lookup_inode(NULL, root, path, &location, 0);
3636 if (path != in_path)
3637 btrfs_free_path(path);
3641 leaf = path->nodes[0];
3646 inode_item = btrfs_item_ptr(leaf, path->slots[0],
3647 struct btrfs_inode_item);
3648 inode->i_mode = btrfs_inode_mode(leaf, inode_item);
3649 set_nlink(inode, btrfs_inode_nlink(leaf, inode_item));
3650 i_uid_write(inode, btrfs_inode_uid(leaf, inode_item));
3651 i_gid_write(inode, btrfs_inode_gid(leaf, inode_item));
3652 btrfs_i_size_write(BTRFS_I(inode), btrfs_inode_size(leaf, inode_item));
3654 inode->i_atime.tv_sec = btrfs_timespec_sec(leaf, &inode_item->atime);
3655 inode->i_atime.tv_nsec = btrfs_timespec_nsec(leaf, &inode_item->atime);
3657 inode->i_mtime.tv_sec = btrfs_timespec_sec(leaf, &inode_item->mtime);
3658 inode->i_mtime.tv_nsec = btrfs_timespec_nsec(leaf, &inode_item->mtime);
3660 inode->i_ctime.tv_sec = btrfs_timespec_sec(leaf, &inode_item->ctime);
3661 inode->i_ctime.tv_nsec = btrfs_timespec_nsec(leaf, &inode_item->ctime);
3663 BTRFS_I(inode)->i_otime.tv_sec =
3664 btrfs_timespec_sec(leaf, &inode_item->otime);
3665 BTRFS_I(inode)->i_otime.tv_nsec =
3666 btrfs_timespec_nsec(leaf, &inode_item->otime);
3668 inode_set_bytes(inode, btrfs_inode_nbytes(leaf, inode_item));
3669 BTRFS_I(inode)->generation = btrfs_inode_generation(leaf, inode_item);
3670 BTRFS_I(inode)->last_trans = btrfs_inode_transid(leaf, inode_item);
3672 inode_set_iversion_queried(inode,
3673 btrfs_inode_sequence(leaf, inode_item));
3674 inode->i_generation = BTRFS_I(inode)->generation;
3676 rdev = btrfs_inode_rdev(leaf, inode_item);
3678 BTRFS_I(inode)->index_cnt = (u64)-1;
3679 BTRFS_I(inode)->flags = btrfs_inode_flags(leaf, inode_item);
3683 * If we were modified in the current generation and evicted from memory
3684 * and then re-read we need to do a full sync since we don't have any
3685 * idea about which extents were modified before we were evicted from
3688 * This is required for both inode re-read from disk and delayed inode
3689 * in delayed_nodes_tree.
3691 if (BTRFS_I(inode)->last_trans == fs_info->generation)
3692 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
3693 &BTRFS_I(inode)->runtime_flags);
3696 * We don't persist the id of the transaction where an unlink operation
3697 * against the inode was last made. So here we assume the inode might
3698 * have been evicted, and therefore the exact value of last_unlink_trans
3699 * lost, and set it to last_trans to avoid metadata inconsistencies
3700 * between the inode and its parent if the inode is fsync'ed and the log
3701 * replayed. For example, in the scenario:
3704 * ln mydir/foo mydir/bar
3707 * echo 2 > /proc/sys/vm/drop_caches # evicts inode
3708 * xfs_io -c fsync mydir/foo
3710 * mount fs, triggers fsync log replay
3712 * We must make sure that when we fsync our inode foo we also log its
3713 * parent inode, otherwise after log replay the parent still has the
3714 * dentry with the "bar" name but our inode foo has a link count of 1
3715 * and doesn't have an inode ref with the name "bar" anymore.
3717 * Setting last_unlink_trans to last_trans is a pessimistic approach,
3718 * but it guarantees correctness at the expense of occasional full
3719 * transaction commits on fsync if our inode is a directory, or if our
3720 * inode is not a directory, logging its parent unnecessarily.
3722 BTRFS_I(inode)->last_unlink_trans = BTRFS_I(inode)->last_trans;
3725 if (inode->i_nlink != 1 ||
3726 path->slots[0] >= btrfs_header_nritems(leaf))
3729 btrfs_item_key_to_cpu(leaf, &location, path->slots[0]);
3730 if (location.objectid != btrfs_ino(BTRFS_I(inode)))
3733 ptr = btrfs_item_ptr_offset(leaf, path->slots[0]);
3734 if (location.type == BTRFS_INODE_REF_KEY) {
3735 struct btrfs_inode_ref *ref;
3737 ref = (struct btrfs_inode_ref *)ptr;
3738 BTRFS_I(inode)->dir_index = btrfs_inode_ref_index(leaf, ref);
3739 } else if (location.type == BTRFS_INODE_EXTREF_KEY) {
3740 struct btrfs_inode_extref *extref;
3742 extref = (struct btrfs_inode_extref *)ptr;
3743 BTRFS_I(inode)->dir_index = btrfs_inode_extref_index(leaf,
3748 * try to precache a NULL acl entry for files that don't have
3749 * any xattrs or acls
3751 maybe_acls = acls_after_inode_item(leaf, path->slots[0],
3752 btrfs_ino(BTRFS_I(inode)), &first_xattr_slot);
3753 if (first_xattr_slot != -1) {
3754 path->slots[0] = first_xattr_slot;
3755 ret = btrfs_load_inode_props(inode, path);
3758 "error loading props for ino %llu (root %llu): %d",
3759 btrfs_ino(BTRFS_I(inode)),
3760 root->root_key.objectid, ret);
3762 if (path != in_path)
3763 btrfs_free_path(path);
3766 cache_no_acl(inode);
3768 switch (inode->i_mode & S_IFMT) {
3770 inode->i_mapping->a_ops = &btrfs_aops;
3771 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
3772 inode->i_fop = &btrfs_file_operations;
3773 inode->i_op = &btrfs_file_inode_operations;
3776 inode->i_fop = &btrfs_dir_file_operations;
3777 inode->i_op = &btrfs_dir_inode_operations;
3780 inode->i_op = &btrfs_symlink_inode_operations;
3781 inode_nohighmem(inode);
3782 inode->i_mapping->a_ops = &btrfs_aops;
3785 inode->i_op = &btrfs_special_inode_operations;
3786 init_special_inode(inode, inode->i_mode, rdev);
3790 btrfs_sync_inode_flags_to_i_flags(inode);
3795 * given a leaf and an inode, copy the inode fields into the leaf
3797 static void fill_inode_item(struct btrfs_trans_handle *trans,
3798 struct extent_buffer *leaf,
3799 struct btrfs_inode_item *item,
3800 struct inode *inode)
3802 struct btrfs_map_token token;
3804 btrfs_init_map_token(&token);
3806 btrfs_set_token_inode_uid(leaf, item, i_uid_read(inode), &token);
3807 btrfs_set_token_inode_gid(leaf, item, i_gid_read(inode), &token);
3808 btrfs_set_token_inode_size(leaf, item, BTRFS_I(inode)->disk_i_size,
3810 btrfs_set_token_inode_mode(leaf, item, inode->i_mode, &token);
3811 btrfs_set_token_inode_nlink(leaf, item, inode->i_nlink, &token);
3813 btrfs_set_token_timespec_sec(leaf, &item->atime,
3814 inode->i_atime.tv_sec, &token);
3815 btrfs_set_token_timespec_nsec(leaf, &item->atime,
3816 inode->i_atime.tv_nsec, &token);
3818 btrfs_set_token_timespec_sec(leaf, &item->mtime,
3819 inode->i_mtime.tv_sec, &token);
3820 btrfs_set_token_timespec_nsec(leaf, &item->mtime,
3821 inode->i_mtime.tv_nsec, &token);
3823 btrfs_set_token_timespec_sec(leaf, &item->ctime,
3824 inode->i_ctime.tv_sec, &token);
3825 btrfs_set_token_timespec_nsec(leaf, &item->ctime,
3826 inode->i_ctime.tv_nsec, &token);
3828 btrfs_set_token_timespec_sec(leaf, &item->otime,
3829 BTRFS_I(inode)->i_otime.tv_sec, &token);
3830 btrfs_set_token_timespec_nsec(leaf, &item->otime,
3831 BTRFS_I(inode)->i_otime.tv_nsec, &token);
3833 btrfs_set_token_inode_nbytes(leaf, item, inode_get_bytes(inode),
3835 btrfs_set_token_inode_generation(leaf, item, BTRFS_I(inode)->generation,
3837 btrfs_set_token_inode_sequence(leaf, item, inode_peek_iversion(inode),
3839 btrfs_set_token_inode_transid(leaf, item, trans->transid, &token);
3840 btrfs_set_token_inode_rdev(leaf, item, inode->i_rdev, &token);
3841 btrfs_set_token_inode_flags(leaf, item, BTRFS_I(inode)->flags, &token);
3842 btrfs_set_token_inode_block_group(leaf, item, 0, &token);
3846 * copy everything in the in-memory inode into the btree.
3848 static noinline int btrfs_update_inode_item(struct btrfs_trans_handle *trans,
3849 struct btrfs_root *root, struct inode *inode)
3851 struct btrfs_inode_item *inode_item;
3852 struct btrfs_path *path;
3853 struct extent_buffer *leaf;
3856 path = btrfs_alloc_path();
3860 path->leave_spinning = 1;
3861 ret = btrfs_lookup_inode(trans, root, path, &BTRFS_I(inode)->location,
3869 leaf = path->nodes[0];
3870 inode_item = btrfs_item_ptr(leaf, path->slots[0],
3871 struct btrfs_inode_item);
3873 fill_inode_item(trans, leaf, inode_item, inode);
3874 btrfs_mark_buffer_dirty(leaf);
3875 btrfs_set_inode_last_trans(trans, inode);
3878 btrfs_free_path(path);
3883 * copy everything in the in-memory inode into the btree.
3885 noinline int btrfs_update_inode(struct btrfs_trans_handle *trans,
3886 struct btrfs_root *root, struct inode *inode)
3888 struct btrfs_fs_info *fs_info = root->fs_info;
3892 * If the inode is a free space inode, we can deadlock during commit
3893 * if we put it into the delayed code.
3895 * The data relocation inode should also be directly updated
3898 if (!btrfs_is_free_space_inode(BTRFS_I(inode))
3899 && root->root_key.objectid != BTRFS_DATA_RELOC_TREE_OBJECTID
3900 && !test_bit(BTRFS_FS_LOG_RECOVERING, &fs_info->flags)) {
3901 btrfs_update_root_times(trans, root);
3903 ret = btrfs_delayed_update_inode(trans, root, inode);
3905 btrfs_set_inode_last_trans(trans, inode);
3909 return btrfs_update_inode_item(trans, root, inode);
3912 noinline int btrfs_update_inode_fallback(struct btrfs_trans_handle *trans,
3913 struct btrfs_root *root,
3914 struct inode *inode)
3918 ret = btrfs_update_inode(trans, root, inode);
3920 return btrfs_update_inode_item(trans, root, inode);
3925 * unlink helper that gets used here in inode.c and in the tree logging
3926 * recovery code. It remove a link in a directory with a given name, and
3927 * also drops the back refs in the inode to the directory
3929 static int __btrfs_unlink_inode(struct btrfs_trans_handle *trans,
3930 struct btrfs_root *root,
3931 struct btrfs_inode *dir,
3932 struct btrfs_inode *inode,
3933 const char *name, int name_len)
3935 struct btrfs_fs_info *fs_info = root->fs_info;
3936 struct btrfs_path *path;
3938 struct extent_buffer *leaf;
3939 struct btrfs_dir_item *di;
3940 struct btrfs_key key;
3942 u64 ino = btrfs_ino(inode);
3943 u64 dir_ino = btrfs_ino(dir);
3945 path = btrfs_alloc_path();
3951 path->leave_spinning = 1;
3952 di = btrfs_lookup_dir_item(trans, root, path, dir_ino,
3953 name, name_len, -1);
3954 if (IS_ERR_OR_NULL(di)) {
3955 ret = di ? PTR_ERR(di) : -ENOENT;
3958 leaf = path->nodes[0];
3959 btrfs_dir_item_key_to_cpu(leaf, di, &key);
3960 ret = btrfs_delete_one_dir_name(trans, root, path, di);
3963 btrfs_release_path(path);
3966 * If we don't have dir index, we have to get it by looking up
3967 * the inode ref, since we get the inode ref, remove it directly,
3968 * it is unnecessary to do delayed deletion.
3970 * But if we have dir index, needn't search inode ref to get it.
3971 * Since the inode ref is close to the inode item, it is better
3972 * that we delay to delete it, and just do this deletion when
3973 * we update the inode item.
3975 if (inode->dir_index) {
3976 ret = btrfs_delayed_delete_inode_ref(inode);
3978 index = inode->dir_index;
3983 ret = btrfs_del_inode_ref(trans, root, name, name_len, ino,
3987 "failed to delete reference to %.*s, inode %llu parent %llu",
3988 name_len, name, ino, dir_ino);
3989 btrfs_abort_transaction(trans, ret);
3993 ret = btrfs_delete_delayed_dir_index(trans, dir, index);
3995 btrfs_abort_transaction(trans, ret);
3999 ret = btrfs_del_inode_ref_in_log(trans, root, name, name_len, inode,
4001 if (ret != 0 && ret != -ENOENT) {
4002 btrfs_abort_transaction(trans, ret);
4006 ret = btrfs_del_dir_entries_in_log(trans, root, name, name_len, dir,
4011 btrfs_abort_transaction(trans, ret);
4013 btrfs_free_path(path);
4017 btrfs_i_size_write(dir, dir->vfs_inode.i_size - name_len * 2);
4018 inode_inc_iversion(&inode->vfs_inode);
4019 inode_inc_iversion(&dir->vfs_inode);
4020 inode->vfs_inode.i_ctime = dir->vfs_inode.i_mtime =
4021 dir->vfs_inode.i_ctime = current_time(&inode->vfs_inode);
4022 ret = btrfs_update_inode(trans, root, &dir->vfs_inode);
4027 int btrfs_unlink_inode(struct btrfs_trans_handle *trans,
4028 struct btrfs_root *root,
4029 struct btrfs_inode *dir, struct btrfs_inode *inode,
4030 const char *name, int name_len)
4033 ret = __btrfs_unlink_inode(trans, root, dir, inode, name, name_len);
4035 drop_nlink(&inode->vfs_inode);
4036 ret = btrfs_update_inode(trans, root, &inode->vfs_inode);
4042 * helper to start transaction for unlink and rmdir.
4044 * unlink and rmdir are special in btrfs, they do not always free space, so
4045 * if we cannot make our reservations the normal way try and see if there is
4046 * plenty of slack room in the global reserve to migrate, otherwise we cannot
4047 * allow the unlink to occur.
4049 static struct btrfs_trans_handle *__unlink_start_trans(struct inode *dir)
4051 struct btrfs_root *root = BTRFS_I(dir)->root;
4054 * 1 for the possible orphan item
4055 * 1 for the dir item
4056 * 1 for the dir index
4057 * 1 for the inode ref
4060 return btrfs_start_transaction_fallback_global_rsv(root, 5, 5);
4063 static int btrfs_unlink(struct inode *dir, struct dentry *dentry)
4065 struct btrfs_root *root = BTRFS_I(dir)->root;
4066 struct btrfs_trans_handle *trans;
4067 struct inode *inode = d_inode(dentry);
4070 trans = __unlink_start_trans(dir);
4072 return PTR_ERR(trans);
4074 btrfs_record_unlink_dir(trans, BTRFS_I(dir), BTRFS_I(d_inode(dentry)),
4077 ret = btrfs_unlink_inode(trans, root, BTRFS_I(dir),
4078 BTRFS_I(d_inode(dentry)), dentry->d_name.name,
4079 dentry->d_name.len);
4083 if (inode->i_nlink == 0) {
4084 ret = btrfs_orphan_add(trans, BTRFS_I(inode));
4090 btrfs_end_transaction(trans);
4091 btrfs_btree_balance_dirty(root->fs_info);
4095 static int btrfs_unlink_subvol(struct btrfs_trans_handle *trans,
4096 struct inode *dir, u64 objectid,
4097 const char *name, int name_len)
4099 struct btrfs_root *root = BTRFS_I(dir)->root;
4100 struct btrfs_path *path;
4101 struct extent_buffer *leaf;
4102 struct btrfs_dir_item *di;
4103 struct btrfs_key key;
4106 u64 dir_ino = btrfs_ino(BTRFS_I(dir));
4108 path = btrfs_alloc_path();
4112 di = btrfs_lookup_dir_item(trans, root, path, dir_ino,
4113 name, name_len, -1);
4114 if (IS_ERR_OR_NULL(di)) {
4115 ret = di ? PTR_ERR(di) : -ENOENT;
4119 leaf = path->nodes[0];
4120 btrfs_dir_item_key_to_cpu(leaf, di, &key);
4121 WARN_ON(key.type != BTRFS_ROOT_ITEM_KEY || key.objectid != objectid);
4122 ret = btrfs_delete_one_dir_name(trans, root, path, di);
4124 btrfs_abort_transaction(trans, ret);
4127 btrfs_release_path(path);
4129 ret = btrfs_del_root_ref(trans, objectid, root->root_key.objectid,
4130 dir_ino, &index, name, name_len);
4132 if (ret != -ENOENT) {
4133 btrfs_abort_transaction(trans, ret);
4136 di = btrfs_search_dir_index_item(root, path, dir_ino,
4138 if (IS_ERR_OR_NULL(di)) {
4143 btrfs_abort_transaction(trans, ret);
4147 leaf = path->nodes[0];
4148 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
4151 btrfs_release_path(path);
4153 ret = btrfs_delete_delayed_dir_index(trans, BTRFS_I(dir), index);
4155 btrfs_abort_transaction(trans, ret);
4159 btrfs_i_size_write(BTRFS_I(dir), dir->i_size - name_len * 2);
4160 inode_inc_iversion(dir);
4161 dir->i_mtime = dir->i_ctime = current_time(dir);
4162 ret = btrfs_update_inode_fallback(trans, root, dir);
4164 btrfs_abort_transaction(trans, ret);
4166 btrfs_free_path(path);
4171 * Helper to check if the subvolume references other subvolumes or if it's
4174 static noinline int may_destroy_subvol(struct btrfs_root *root)
4176 struct btrfs_fs_info *fs_info = root->fs_info;
4177 struct btrfs_path *path;
4178 struct btrfs_dir_item *di;
4179 struct btrfs_key key;
4183 path = btrfs_alloc_path();
4187 /* Make sure this root isn't set as the default subvol */
4188 dir_id = btrfs_super_root_dir(fs_info->super_copy);
4189 di = btrfs_lookup_dir_item(NULL, fs_info->tree_root, path,
4190 dir_id, "default", 7, 0);
4191 if (di && !IS_ERR(di)) {
4192 btrfs_dir_item_key_to_cpu(path->nodes[0], di, &key);
4193 if (key.objectid == root->root_key.objectid) {
4196 "deleting default subvolume %llu is not allowed",
4200 btrfs_release_path(path);
4203 key.objectid = root->root_key.objectid;
4204 key.type = BTRFS_ROOT_REF_KEY;
4205 key.offset = (u64)-1;
4207 ret = btrfs_search_slot(NULL, fs_info->tree_root, &key, path, 0, 0);
4213 if (path->slots[0] > 0) {
4215 btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
4216 if (key.objectid == root->root_key.objectid &&
4217 key.type == BTRFS_ROOT_REF_KEY)
4221 btrfs_free_path(path);
4225 /* Delete all dentries for inodes belonging to the root */
4226 static void btrfs_prune_dentries(struct btrfs_root *root)
4228 struct btrfs_fs_info *fs_info = root->fs_info;
4229 struct rb_node *node;
4230 struct rb_node *prev;
4231 struct btrfs_inode *entry;
4232 struct inode *inode;
4235 if (!test_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state))
4236 WARN_ON(btrfs_root_refs(&root->root_item) != 0);
4238 spin_lock(&root->inode_lock);
4240 node = root->inode_tree.rb_node;
4244 entry = rb_entry(node, struct btrfs_inode, rb_node);
4246 if (objectid < btrfs_ino(entry))
4247 node = node->rb_left;
4248 else if (objectid > btrfs_ino(entry))
4249 node = node->rb_right;
4255 entry = rb_entry(prev, struct btrfs_inode, rb_node);
4256 if (objectid <= btrfs_ino(entry)) {
4260 prev = rb_next(prev);
4264 entry = rb_entry(node, struct btrfs_inode, rb_node);
4265 objectid = btrfs_ino(entry) + 1;
4266 inode = igrab(&entry->vfs_inode);
4268 spin_unlock(&root->inode_lock);
4269 if (atomic_read(&inode->i_count) > 1)
4270 d_prune_aliases(inode);
4272 * btrfs_drop_inode will have it removed from the inode
4273 * cache when its usage count hits zero.
4277 spin_lock(&root->inode_lock);
4281 if (cond_resched_lock(&root->inode_lock))
4284 node = rb_next(node);
4286 spin_unlock(&root->inode_lock);
4289 int btrfs_delete_subvolume(struct inode *dir, struct dentry *dentry)
4291 struct btrfs_fs_info *fs_info = btrfs_sb(dentry->d_sb);
4292 struct btrfs_root *root = BTRFS_I(dir)->root;
4293 struct inode *inode = d_inode(dentry);
4294 struct btrfs_root *dest = BTRFS_I(inode)->root;
4295 struct btrfs_trans_handle *trans;
4296 struct btrfs_block_rsv block_rsv;
4302 * Don't allow to delete a subvolume with send in progress. This is
4303 * inside the inode lock so the error handling that has to drop the bit
4304 * again is not run concurrently.
4306 spin_lock(&dest->root_item_lock);
4307 if (dest->send_in_progress) {
4308 spin_unlock(&dest->root_item_lock);
4310 "attempt to delete subvolume %llu during send",
4311 dest->root_key.objectid);
4314 root_flags = btrfs_root_flags(&dest->root_item);
4315 btrfs_set_root_flags(&dest->root_item,
4316 root_flags | BTRFS_ROOT_SUBVOL_DEAD);
4317 spin_unlock(&dest->root_item_lock);
4319 down_write(&fs_info->subvol_sem);
4321 err = may_destroy_subvol(dest);
4325 btrfs_init_block_rsv(&block_rsv, BTRFS_BLOCK_RSV_TEMP);
4327 * One for dir inode,
4328 * two for dir entries,
4329 * two for root ref/backref.
4331 err = btrfs_subvolume_reserve_metadata(root, &block_rsv, 5, true);
4335 trans = btrfs_start_transaction(root, 0);
4336 if (IS_ERR(trans)) {
4337 err = PTR_ERR(trans);
4340 trans->block_rsv = &block_rsv;
4341 trans->bytes_reserved = block_rsv.size;
4343 btrfs_record_snapshot_destroy(trans, BTRFS_I(dir));
4345 ret = btrfs_unlink_subvol(trans, dir, dest->root_key.objectid,
4346 dentry->d_name.name, dentry->d_name.len);
4349 btrfs_abort_transaction(trans, ret);
4353 btrfs_record_root_in_trans(trans, dest);
4355 memset(&dest->root_item.drop_progress, 0,
4356 sizeof(dest->root_item.drop_progress));
4357 dest->root_item.drop_level = 0;
4358 btrfs_set_root_refs(&dest->root_item, 0);
4360 if (!test_and_set_bit(BTRFS_ROOT_ORPHAN_ITEM_INSERTED, &dest->state)) {
4361 ret = btrfs_insert_orphan_item(trans,
4363 dest->root_key.objectid);
4365 btrfs_abort_transaction(trans, ret);
4371 ret = btrfs_uuid_tree_remove(trans, dest->root_item.uuid,
4372 BTRFS_UUID_KEY_SUBVOL,
4373 dest->root_key.objectid);
4374 if (ret && ret != -ENOENT) {
4375 btrfs_abort_transaction(trans, ret);
4379 if (!btrfs_is_empty_uuid(dest->root_item.received_uuid)) {
4380 ret = btrfs_uuid_tree_remove(trans,
4381 dest->root_item.received_uuid,
4382 BTRFS_UUID_KEY_RECEIVED_SUBVOL,
4383 dest->root_key.objectid);
4384 if (ret && ret != -ENOENT) {
4385 btrfs_abort_transaction(trans, ret);
4392 trans->block_rsv = NULL;
4393 trans->bytes_reserved = 0;
4394 ret = btrfs_end_transaction(trans);
4397 inode->i_flags |= S_DEAD;
4399 btrfs_subvolume_release_metadata(fs_info, &block_rsv);
4401 up_write(&fs_info->subvol_sem);
4403 spin_lock(&dest->root_item_lock);
4404 root_flags = btrfs_root_flags(&dest->root_item);
4405 btrfs_set_root_flags(&dest->root_item,
4406 root_flags & ~BTRFS_ROOT_SUBVOL_DEAD);
4407 spin_unlock(&dest->root_item_lock);
4409 d_invalidate(dentry);
4410 btrfs_prune_dentries(dest);
4411 ASSERT(dest->send_in_progress == 0);
4414 if (dest->ino_cache_inode) {
4415 iput(dest->ino_cache_inode);
4416 dest->ino_cache_inode = NULL;
4423 static int btrfs_rmdir(struct inode *dir, struct dentry *dentry)
4425 struct inode *inode = d_inode(dentry);
4427 struct btrfs_root *root = BTRFS_I(dir)->root;
4428 struct btrfs_trans_handle *trans;
4429 u64 last_unlink_trans;
4431 if (inode->i_size > BTRFS_EMPTY_DIR_SIZE)
4433 if (btrfs_ino(BTRFS_I(inode)) == BTRFS_FIRST_FREE_OBJECTID)
4434 return btrfs_delete_subvolume(dir, dentry);
4436 trans = __unlink_start_trans(dir);
4438 return PTR_ERR(trans);
4440 if (unlikely(btrfs_ino(BTRFS_I(inode)) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)) {
4441 err = btrfs_unlink_subvol(trans, dir,
4442 BTRFS_I(inode)->location.objectid,
4443 dentry->d_name.name,
4444 dentry->d_name.len);
4448 err = btrfs_orphan_add(trans, BTRFS_I(inode));
4452 last_unlink_trans = BTRFS_I(inode)->last_unlink_trans;
4454 /* now the directory is empty */
4455 err = btrfs_unlink_inode(trans, root, BTRFS_I(dir),
4456 BTRFS_I(d_inode(dentry)), dentry->d_name.name,
4457 dentry->d_name.len);
4459 btrfs_i_size_write(BTRFS_I(inode), 0);
4461 * Propagate the last_unlink_trans value of the deleted dir to
4462 * its parent directory. This is to prevent an unrecoverable
4463 * log tree in the case we do something like this:
4465 * 2) create snapshot under dir foo
4466 * 3) delete the snapshot
4469 * 6) fsync foo or some file inside foo
4471 if (last_unlink_trans >= trans->transid)
4472 BTRFS_I(dir)->last_unlink_trans = last_unlink_trans;
4475 btrfs_end_transaction(trans);
4476 btrfs_btree_balance_dirty(root->fs_info);
4482 * Return this if we need to call truncate_block for the last bit of the
4485 #define NEED_TRUNCATE_BLOCK 1
4488 * this can truncate away extent items, csum items and directory items.
4489 * It starts at a high offset and removes keys until it can't find
4490 * any higher than new_size
4492 * csum items that cross the new i_size are truncated to the new size
4495 * min_type is the minimum key type to truncate down to. If set to 0, this
4496 * will kill all the items on this inode, including the INODE_ITEM_KEY.
4498 int btrfs_truncate_inode_items(struct btrfs_trans_handle *trans,
4499 struct btrfs_root *root,
4500 struct inode *inode,
4501 u64 new_size, u32 min_type)
4503 struct btrfs_fs_info *fs_info = root->fs_info;
4504 struct btrfs_path *path;
4505 struct extent_buffer *leaf;
4506 struct btrfs_file_extent_item *fi;
4507 struct btrfs_key key;
4508 struct btrfs_key found_key;
4509 u64 extent_start = 0;
4510 u64 extent_num_bytes = 0;
4511 u64 extent_offset = 0;
4513 u64 last_size = new_size;
4514 u32 found_type = (u8)-1;
4517 int pending_del_nr = 0;
4518 int pending_del_slot = 0;
4519 int extent_type = -1;
4521 u64 ino = btrfs_ino(BTRFS_I(inode));
4522 u64 bytes_deleted = 0;
4523 bool be_nice = false;
4524 bool should_throttle = false;
4526 BUG_ON(new_size > 0 && min_type != BTRFS_EXTENT_DATA_KEY);
4529 * for non-free space inodes and ref cows, we want to back off from
4532 if (!btrfs_is_free_space_inode(BTRFS_I(inode)) &&
4533 test_bit(BTRFS_ROOT_REF_COWS, &root->state))
4536 path = btrfs_alloc_path();
4539 path->reada = READA_BACK;
4542 * We want to drop from the next block forward in case this new size is
4543 * not block aligned since we will be keeping the last block of the
4544 * extent just the way it is.
4546 if (test_bit(BTRFS_ROOT_REF_COWS, &root->state) ||
4547 root == fs_info->tree_root)
4548 btrfs_drop_extent_cache(BTRFS_I(inode), ALIGN(new_size,
4549 fs_info->sectorsize),
4553 * This function is also used to drop the items in the log tree before
4554 * we relog the inode, so if root != BTRFS_I(inode)->root, it means
4555 * it is used to drop the logged items. So we shouldn't kill the delayed
4558 if (min_type == 0 && root == BTRFS_I(inode)->root)
4559 btrfs_kill_delayed_inode_items(BTRFS_I(inode));
4562 key.offset = (u64)-1;
4567 * with a 16K leaf size and 128MB extents, you can actually queue
4568 * up a huge file in a single leaf. Most of the time that
4569 * bytes_deleted is > 0, it will be huge by the time we get here
4571 if (be_nice && bytes_deleted > SZ_32M &&
4572 btrfs_should_end_transaction(trans)) {
4577 path->leave_spinning = 1;
4578 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
4584 /* there are no items in the tree for us to truncate, we're
4587 if (path->slots[0] == 0)
4594 leaf = path->nodes[0];
4595 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
4596 found_type = found_key.type;
4598 if (found_key.objectid != ino)
4601 if (found_type < min_type)
4604 item_end = found_key.offset;
4605 if (found_type == BTRFS_EXTENT_DATA_KEY) {
4606 fi = btrfs_item_ptr(leaf, path->slots[0],
4607 struct btrfs_file_extent_item);
4608 extent_type = btrfs_file_extent_type(leaf, fi);
4609 if (extent_type != BTRFS_FILE_EXTENT_INLINE) {
4611 btrfs_file_extent_num_bytes(leaf, fi);
4613 trace_btrfs_truncate_show_fi_regular(
4614 BTRFS_I(inode), leaf, fi,
4616 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
4617 item_end += btrfs_file_extent_ram_bytes(leaf,
4620 trace_btrfs_truncate_show_fi_inline(
4621 BTRFS_I(inode), leaf, fi, path->slots[0],
4626 if (found_type > min_type) {
4629 if (item_end < new_size)
4631 if (found_key.offset >= new_size)
4637 /* FIXME, shrink the extent if the ref count is only 1 */
4638 if (found_type != BTRFS_EXTENT_DATA_KEY)
4641 if (extent_type != BTRFS_FILE_EXTENT_INLINE) {
4643 extent_start = btrfs_file_extent_disk_bytenr(leaf, fi);
4645 u64 orig_num_bytes =
4646 btrfs_file_extent_num_bytes(leaf, fi);
4647 extent_num_bytes = ALIGN(new_size -
4649 fs_info->sectorsize);
4650 btrfs_set_file_extent_num_bytes(leaf, fi,
4652 num_dec = (orig_num_bytes -
4654 if (test_bit(BTRFS_ROOT_REF_COWS,
4657 inode_sub_bytes(inode, num_dec);
4658 btrfs_mark_buffer_dirty(leaf);
4661 btrfs_file_extent_disk_num_bytes(leaf,
4663 extent_offset = found_key.offset -
4664 btrfs_file_extent_offset(leaf, fi);
4666 /* FIXME blocksize != 4096 */
4667 num_dec = btrfs_file_extent_num_bytes(leaf, fi);
4668 if (extent_start != 0) {
4670 if (test_bit(BTRFS_ROOT_REF_COWS,
4672 inode_sub_bytes(inode, num_dec);
4675 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
4677 * we can't truncate inline items that have had
4681 btrfs_file_extent_encryption(leaf, fi) == 0 &&
4682 btrfs_file_extent_other_encoding(leaf, fi) == 0 &&
4683 btrfs_file_extent_compression(leaf, fi) == 0) {
4684 u32 size = (u32)(new_size - found_key.offset);
4686 btrfs_set_file_extent_ram_bytes(leaf, fi, size);
4687 size = btrfs_file_extent_calc_inline_size(size);
4688 btrfs_truncate_item(path, size, 1);
4689 } else if (!del_item) {
4691 * We have to bail so the last_size is set to
4692 * just before this extent.
4694 ret = NEED_TRUNCATE_BLOCK;
4698 if (test_bit(BTRFS_ROOT_REF_COWS, &root->state))
4699 inode_sub_bytes(inode, item_end + 1 - new_size);
4703 last_size = found_key.offset;
4705 last_size = new_size;
4707 if (!pending_del_nr) {
4708 /* no pending yet, add ourselves */
4709 pending_del_slot = path->slots[0];
4711 } else if (pending_del_nr &&
4712 path->slots[0] + 1 == pending_del_slot) {
4713 /* hop on the pending chunk */
4715 pending_del_slot = path->slots[0];
4722 should_throttle = false;
4725 (test_bit(BTRFS_ROOT_REF_COWS, &root->state) ||
4726 root == fs_info->tree_root)) {
4727 struct btrfs_ref ref = { 0 };
4729 btrfs_set_path_blocking(path);
4730 bytes_deleted += extent_num_bytes;
4732 btrfs_init_generic_ref(&ref, BTRFS_DROP_DELAYED_REF,
4733 extent_start, extent_num_bytes, 0);
4734 ref.real_root = root->root_key.objectid;
4735 btrfs_init_data_ref(&ref, btrfs_header_owner(leaf),
4736 ino, extent_offset);
4737 ret = btrfs_free_extent(trans, &ref);
4739 btrfs_abort_transaction(trans, ret);
4743 if (btrfs_should_throttle_delayed_refs(trans))
4744 should_throttle = true;
4748 if (found_type == BTRFS_INODE_ITEM_KEY)
4751 if (path->slots[0] == 0 ||
4752 path->slots[0] != pending_del_slot ||
4754 if (pending_del_nr) {
4755 ret = btrfs_del_items(trans, root, path,
4759 btrfs_abort_transaction(trans, ret);
4764 btrfs_release_path(path);
4767 * We can generate a lot of delayed refs, so we need to
4768 * throttle every once and a while and make sure we're
4769 * adding enough space to keep up with the work we are
4770 * generating. Since we hold a transaction here we
4771 * can't flush, and we don't want to FLUSH_LIMIT because
4772 * we could have generated too many delayed refs to
4773 * actually allocate, so just bail if we're short and
4774 * let the normal reservation dance happen higher up.
4776 if (should_throttle) {
4777 ret = btrfs_delayed_refs_rsv_refill(fs_info,
4778 BTRFS_RESERVE_NO_FLUSH);
4790 if (ret >= 0 && pending_del_nr) {
4793 err = btrfs_del_items(trans, root, path, pending_del_slot,
4796 btrfs_abort_transaction(trans, err);
4800 if (root->root_key.objectid != BTRFS_TREE_LOG_OBJECTID) {
4801 ASSERT(last_size >= new_size);
4802 if (!ret && last_size > new_size)
4803 last_size = new_size;
4804 btrfs_ordered_update_i_size(inode, last_size, NULL);
4807 btrfs_free_path(path);
4812 * btrfs_truncate_block - read, zero a chunk and write a block
4813 * @inode - inode that we're zeroing
4814 * @from - the offset to start zeroing
4815 * @len - the length to zero, 0 to zero the entire range respective to the
4817 * @front - zero up to the offset instead of from the offset on
4819 * This will find the block for the "from" offset and cow the block and zero the
4820 * part we want to zero. This is used with truncate and hole punching.
4822 int btrfs_truncate_block(struct inode *inode, loff_t from, loff_t len,
4825 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
4826 struct address_space *mapping = inode->i_mapping;
4827 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
4828 struct btrfs_ordered_extent *ordered;
4829 struct extent_state *cached_state = NULL;
4830 struct extent_changeset *data_reserved = NULL;
4832 u32 blocksize = fs_info->sectorsize;
4833 pgoff_t index = from >> PAGE_SHIFT;
4834 unsigned offset = from & (blocksize - 1);
4836 gfp_t mask = btrfs_alloc_write_mask(mapping);
4841 if (IS_ALIGNED(offset, blocksize) &&
4842 (!len || IS_ALIGNED(len, blocksize)))
4845 block_start = round_down(from, blocksize);
4846 block_end = block_start + blocksize - 1;
4848 ret = btrfs_delalloc_reserve_space(inode, &data_reserved,
4849 block_start, blocksize);
4854 page = find_or_create_page(mapping, index, mask);
4856 btrfs_delalloc_release_space(inode, data_reserved,
4857 block_start, blocksize, true);
4858 btrfs_delalloc_release_extents(BTRFS_I(inode), blocksize, true);
4863 if (!PageUptodate(page)) {
4864 ret = btrfs_readpage(NULL, page);
4866 if (page->mapping != mapping) {
4871 if (!PageUptodate(page)) {
4876 wait_on_page_writeback(page);
4878 lock_extent_bits(io_tree, block_start, block_end, &cached_state);
4879 set_page_extent_mapped(page);
4881 ordered = btrfs_lookup_ordered_extent(inode, block_start);
4883 unlock_extent_cached(io_tree, block_start, block_end,
4887 btrfs_start_ordered_extent(inode, ordered, 1);
4888 btrfs_put_ordered_extent(ordered);
4892 clear_extent_bit(&BTRFS_I(inode)->io_tree, block_start, block_end,
4893 EXTENT_DIRTY | EXTENT_DELALLOC |
4894 EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG,
4895 0, 0, &cached_state);
4897 ret = btrfs_set_extent_delalloc(inode, block_start, block_end, 0,
4900 unlock_extent_cached(io_tree, block_start, block_end,
4905 if (offset != blocksize) {
4907 len = blocksize - offset;
4910 memset(kaddr + (block_start - page_offset(page)),
4913 memset(kaddr + (block_start - page_offset(page)) + offset,
4915 flush_dcache_page(page);
4918 ClearPageChecked(page);
4919 set_page_dirty(page);
4920 unlock_extent_cached(io_tree, block_start, block_end, &cached_state);
4924 btrfs_delalloc_release_space(inode, data_reserved, block_start,
4926 btrfs_delalloc_release_extents(BTRFS_I(inode), blocksize, (ret != 0));
4930 extent_changeset_free(data_reserved);
4934 static int maybe_insert_hole(struct btrfs_root *root, struct inode *inode,
4935 u64 offset, u64 len)
4937 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
4938 struct btrfs_trans_handle *trans;
4942 * Still need to make sure the inode looks like it's been updated so
4943 * that any holes get logged if we fsync.
4945 if (btrfs_fs_incompat(fs_info, NO_HOLES)) {
4946 BTRFS_I(inode)->last_trans = fs_info->generation;
4947 BTRFS_I(inode)->last_sub_trans = root->log_transid;
4948 BTRFS_I(inode)->last_log_commit = root->last_log_commit;
4953 * 1 - for the one we're dropping
4954 * 1 - for the one we're adding
4955 * 1 - for updating the inode.
4957 trans = btrfs_start_transaction(root, 3);
4959 return PTR_ERR(trans);
4961 ret = btrfs_drop_extents(trans, root, inode, offset, offset + len, 1);
4963 btrfs_abort_transaction(trans, ret);
4964 btrfs_end_transaction(trans);
4968 ret = btrfs_insert_file_extent(trans, root, btrfs_ino(BTRFS_I(inode)),
4969 offset, 0, 0, len, 0, len, 0, 0, 0);
4971 btrfs_abort_transaction(trans, ret);
4973 btrfs_update_inode(trans, root, inode);
4974 btrfs_end_transaction(trans);
4979 * This function puts in dummy file extents for the area we're creating a hole
4980 * for. So if we are truncating this file to a larger size we need to insert
4981 * these file extents so that btrfs_get_extent will return a EXTENT_MAP_HOLE for
4982 * the range between oldsize and size
4984 int btrfs_cont_expand(struct inode *inode, loff_t oldsize, loff_t size)
4986 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
4987 struct btrfs_root *root = BTRFS_I(inode)->root;
4988 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
4989 struct extent_map *em = NULL;
4990 struct extent_state *cached_state = NULL;
4991 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
4992 u64 hole_start = ALIGN(oldsize, fs_info->sectorsize);
4993 u64 block_end = ALIGN(size, fs_info->sectorsize);
5000 * If our size started in the middle of a block we need to zero out the
5001 * rest of the block before we expand the i_size, otherwise we could
5002 * expose stale data.
5004 err = btrfs_truncate_block(inode, oldsize, 0, 0);
5008 if (size <= hole_start)
5012 struct btrfs_ordered_extent *ordered;
5014 lock_extent_bits(io_tree, hole_start, block_end - 1,
5016 ordered = btrfs_lookup_ordered_range(BTRFS_I(inode), hole_start,
5017 block_end - hole_start);
5020 unlock_extent_cached(io_tree, hole_start, block_end - 1,
5022 btrfs_start_ordered_extent(inode, ordered, 1);
5023 btrfs_put_ordered_extent(ordered);
5026 cur_offset = hole_start;
5028 em = btrfs_get_extent(BTRFS_I(inode), NULL, 0, cur_offset,
5029 block_end - cur_offset, 0);
5035 last_byte = min(extent_map_end(em), block_end);
5036 last_byte = ALIGN(last_byte, fs_info->sectorsize);
5037 if (!test_bit(EXTENT_FLAG_PREALLOC, &em->flags)) {
5038 struct extent_map *hole_em;
5039 hole_size = last_byte - cur_offset;
5041 err = maybe_insert_hole(root, inode, cur_offset,
5045 btrfs_drop_extent_cache(BTRFS_I(inode), cur_offset,
5046 cur_offset + hole_size - 1, 0);
5047 hole_em = alloc_extent_map();
5049 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
5050 &BTRFS_I(inode)->runtime_flags);
5053 hole_em->start = cur_offset;
5054 hole_em->len = hole_size;
5055 hole_em->orig_start = cur_offset;
5057 hole_em->block_start = EXTENT_MAP_HOLE;
5058 hole_em->block_len = 0;
5059 hole_em->orig_block_len = 0;
5060 hole_em->ram_bytes = hole_size;
5061 hole_em->bdev = fs_info->fs_devices->latest_bdev;
5062 hole_em->compress_type = BTRFS_COMPRESS_NONE;
5063 hole_em->generation = fs_info->generation;
5066 write_lock(&em_tree->lock);
5067 err = add_extent_mapping(em_tree, hole_em, 1);
5068 write_unlock(&em_tree->lock);
5071 btrfs_drop_extent_cache(BTRFS_I(inode),
5076 free_extent_map(hole_em);
5079 free_extent_map(em);
5081 cur_offset = last_byte;
5082 if (cur_offset >= block_end)
5085 free_extent_map(em);
5086 unlock_extent_cached(io_tree, hole_start, block_end - 1, &cached_state);
5090 static int btrfs_setsize(struct inode *inode, struct iattr *attr)
5092 struct btrfs_root *root = BTRFS_I(inode)->root;
5093 struct btrfs_trans_handle *trans;
5094 loff_t oldsize = i_size_read(inode);
5095 loff_t newsize = attr->ia_size;
5096 int mask = attr->ia_valid;
5100 * The regular truncate() case without ATTR_CTIME and ATTR_MTIME is a
5101 * special case where we need to update the times despite not having
5102 * these flags set. For all other operations the VFS set these flags
5103 * explicitly if it wants a timestamp update.
5105 if (newsize != oldsize) {
5106 inode_inc_iversion(inode);
5107 if (!(mask & (ATTR_CTIME | ATTR_MTIME)))
5108 inode->i_ctime = inode->i_mtime =
5109 current_time(inode);
5112 if (newsize > oldsize) {
5114 * Don't do an expanding truncate while snapshotting is ongoing.
5115 * This is to ensure the snapshot captures a fully consistent
5116 * state of this file - if the snapshot captures this expanding
5117 * truncation, it must capture all writes that happened before
5120 btrfs_wait_for_snapshot_creation(root);
5121 ret = btrfs_cont_expand(inode, oldsize, newsize);
5123 btrfs_end_write_no_snapshotting(root);
5127 trans = btrfs_start_transaction(root, 1);
5128 if (IS_ERR(trans)) {
5129 btrfs_end_write_no_snapshotting(root);
5130 return PTR_ERR(trans);
5133 i_size_write(inode, newsize);
5134 btrfs_ordered_update_i_size(inode, i_size_read(inode), NULL);
5135 pagecache_isize_extended(inode, oldsize, newsize);
5136 ret = btrfs_update_inode(trans, root, inode);
5137 btrfs_end_write_no_snapshotting(root);
5138 btrfs_end_transaction(trans);
5142 * We're truncating a file that used to have good data down to
5143 * zero. Make sure it gets into the ordered flush list so that
5144 * any new writes get down to disk quickly.
5147 set_bit(BTRFS_INODE_ORDERED_DATA_CLOSE,
5148 &BTRFS_I(inode)->runtime_flags);
5150 truncate_setsize(inode, newsize);
5152 /* Disable nonlocked read DIO to avoid the endless truncate */
5153 btrfs_inode_block_unlocked_dio(BTRFS_I(inode));
5154 inode_dio_wait(inode);
5155 btrfs_inode_resume_unlocked_dio(BTRFS_I(inode));
5157 ret = btrfs_truncate(inode, newsize == oldsize);
5158 if (ret && inode->i_nlink) {
5162 * Truncate failed, so fix up the in-memory size. We
5163 * adjusted disk_i_size down as we removed extents, so
5164 * wait for disk_i_size to be stable and then update the
5165 * in-memory size to match.
5167 err = btrfs_wait_ordered_range(inode, 0, (u64)-1);
5170 i_size_write(inode, BTRFS_I(inode)->disk_i_size);
5177 static int btrfs_setattr(struct dentry *dentry, struct iattr *attr)
5179 struct inode *inode = d_inode(dentry);
5180 struct btrfs_root *root = BTRFS_I(inode)->root;
5183 if (btrfs_root_readonly(root))
5186 err = setattr_prepare(dentry, attr);
5190 if (S_ISREG(inode->i_mode) && (attr->ia_valid & ATTR_SIZE)) {
5191 err = btrfs_setsize(inode, attr);
5196 if (attr->ia_valid) {
5197 setattr_copy(inode, attr);
5198 inode_inc_iversion(inode);
5199 err = btrfs_dirty_inode(inode);
5201 if (!err && attr->ia_valid & ATTR_MODE)
5202 err = posix_acl_chmod(inode, inode->i_mode);
5209 * While truncating the inode pages during eviction, we get the VFS calling
5210 * btrfs_invalidatepage() against each page of the inode. This is slow because
5211 * the calls to btrfs_invalidatepage() result in a huge amount of calls to
5212 * lock_extent_bits() and clear_extent_bit(), which keep merging and splitting
5213 * extent_state structures over and over, wasting lots of time.
5215 * Therefore if the inode is being evicted, let btrfs_invalidatepage() skip all
5216 * those expensive operations on a per page basis and do only the ordered io
5217 * finishing, while we release here the extent_map and extent_state structures,
5218 * without the excessive merging and splitting.
5220 static void evict_inode_truncate_pages(struct inode *inode)
5222 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
5223 struct extent_map_tree *map_tree = &BTRFS_I(inode)->extent_tree;
5224 struct rb_node *node;
5226 ASSERT(inode->i_state & I_FREEING);
5227 truncate_inode_pages_final(&inode->i_data);
5229 write_lock(&map_tree->lock);
5230 while (!RB_EMPTY_ROOT(&map_tree->map.rb_root)) {
5231 struct extent_map *em;
5233 node = rb_first_cached(&map_tree->map);
5234 em = rb_entry(node, struct extent_map, rb_node);
5235 clear_bit(EXTENT_FLAG_PINNED, &em->flags);
5236 clear_bit(EXTENT_FLAG_LOGGING, &em->flags);
5237 remove_extent_mapping(map_tree, em);
5238 free_extent_map(em);
5239 if (need_resched()) {
5240 write_unlock(&map_tree->lock);
5242 write_lock(&map_tree->lock);
5245 write_unlock(&map_tree->lock);
5248 * Keep looping until we have no more ranges in the io tree.
5249 * We can have ongoing bios started by readpages (called from readahead)
5250 * that have their endio callback (extent_io.c:end_bio_extent_readpage)
5251 * still in progress (unlocked the pages in the bio but did not yet
5252 * unlocked the ranges in the io tree). Therefore this means some
5253 * ranges can still be locked and eviction started because before
5254 * submitting those bios, which are executed by a separate task (work
5255 * queue kthread), inode references (inode->i_count) were not taken
5256 * (which would be dropped in the end io callback of each bio).
5257 * Therefore here we effectively end up waiting for those bios and
5258 * anyone else holding locked ranges without having bumped the inode's
5259 * reference count - if we don't do it, when they access the inode's
5260 * io_tree to unlock a range it may be too late, leading to an
5261 * use-after-free issue.
5263 spin_lock(&io_tree->lock);
5264 while (!RB_EMPTY_ROOT(&io_tree->state)) {
5265 struct extent_state *state;
5266 struct extent_state *cached_state = NULL;
5269 unsigned state_flags;
5271 node = rb_first(&io_tree->state);
5272 state = rb_entry(node, struct extent_state, rb_node);
5273 start = state->start;
5275 state_flags = state->state;
5276 spin_unlock(&io_tree->lock);
5278 lock_extent_bits(io_tree, start, end, &cached_state);
5281 * If still has DELALLOC flag, the extent didn't reach disk,
5282 * and its reserved space won't be freed by delayed_ref.
5283 * So we need to free its reserved space here.
5284 * (Refer to comment in btrfs_invalidatepage, case 2)
5286 * Note, end is the bytenr of last byte, so we need + 1 here.
5288 if (state_flags & EXTENT_DELALLOC)
5289 btrfs_qgroup_free_data(inode, NULL, start, end - start + 1);
5291 clear_extent_bit(io_tree, start, end,
5292 EXTENT_LOCKED | EXTENT_DIRTY |
5293 EXTENT_DELALLOC | EXTENT_DO_ACCOUNTING |
5294 EXTENT_DEFRAG, 1, 1, &cached_state);
5297 spin_lock(&io_tree->lock);
5299 spin_unlock(&io_tree->lock);
5302 static struct btrfs_trans_handle *evict_refill_and_join(struct btrfs_root *root,
5303 struct btrfs_block_rsv *rsv)
5305 struct btrfs_fs_info *fs_info = root->fs_info;
5306 struct btrfs_block_rsv *global_rsv = &fs_info->global_block_rsv;
5307 u64 delayed_refs_extra = btrfs_calc_trans_metadata_size(fs_info, 1);
5311 struct btrfs_trans_handle *trans;
5314 ret = btrfs_block_rsv_refill(root, rsv,
5315 rsv->size + delayed_refs_extra,
5316 BTRFS_RESERVE_FLUSH_LIMIT);
5318 if (ret && ++failures > 2) {
5320 "could not allocate space for a delete; will truncate on mount");
5321 return ERR_PTR(-ENOSPC);
5325 * Evict can generate a large amount of delayed refs without
5326 * having a way to add space back since we exhaust our temporary
5327 * block rsv. We aren't allowed to do FLUSH_ALL in this case
5328 * because we could deadlock with so many things in the flushing
5329 * code, so we have to try and hold some extra space to
5330 * compensate for our delayed ref generation. If we can't get
5331 * that space then we need see if we can steal our minimum from
5332 * the global reserve. We will be ratelimited by the amount of
5333 * space we have for the delayed refs rsv, so we'll end up
5334 * committing and trying again.
5336 trans = btrfs_join_transaction(root);
5337 if (IS_ERR(trans) || !ret) {
5338 if (!IS_ERR(trans)) {
5339 trans->block_rsv = &fs_info->trans_block_rsv;
5340 trans->bytes_reserved = delayed_refs_extra;
5341 btrfs_block_rsv_migrate(rsv, trans->block_rsv,
5342 delayed_refs_extra, 1);
5348 * Try to steal from the global reserve if there is space for
5351 if (!btrfs_check_space_for_delayed_refs(fs_info) &&
5352 !btrfs_block_rsv_migrate(global_rsv, rsv, rsv->size, 0))
5355 /* If not, commit and try again. */
5356 ret = btrfs_commit_transaction(trans);
5358 return ERR_PTR(ret);
5362 void btrfs_evict_inode(struct inode *inode)
5364 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
5365 struct btrfs_trans_handle *trans;
5366 struct btrfs_root *root = BTRFS_I(inode)->root;
5367 struct btrfs_block_rsv *rsv;
5370 trace_btrfs_inode_evict(inode);
5377 evict_inode_truncate_pages(inode);
5379 if (inode->i_nlink &&
5380 ((btrfs_root_refs(&root->root_item) != 0 &&
5381 root->root_key.objectid != BTRFS_ROOT_TREE_OBJECTID) ||
5382 btrfs_is_free_space_inode(BTRFS_I(inode))))
5385 if (is_bad_inode(inode))
5388 btrfs_free_io_failure_record(BTRFS_I(inode), 0, (u64)-1);
5390 if (test_bit(BTRFS_FS_LOG_RECOVERING, &fs_info->flags))
5393 if (inode->i_nlink > 0) {
5394 BUG_ON(btrfs_root_refs(&root->root_item) != 0 &&
5395 root->root_key.objectid != BTRFS_ROOT_TREE_OBJECTID);
5399 ret = btrfs_commit_inode_delayed_inode(BTRFS_I(inode));
5403 rsv = btrfs_alloc_block_rsv(fs_info, BTRFS_BLOCK_RSV_TEMP);
5406 rsv->size = btrfs_calc_trunc_metadata_size(fs_info, 1);
5409 btrfs_i_size_write(BTRFS_I(inode), 0);
5412 trans = evict_refill_and_join(root, rsv);
5416 trans->block_rsv = rsv;
5418 ret = btrfs_truncate_inode_items(trans, root, inode, 0, 0);
5419 trans->block_rsv = &fs_info->trans_block_rsv;
5420 btrfs_end_transaction(trans);
5421 btrfs_btree_balance_dirty(fs_info);
5422 if (ret && ret != -ENOSPC && ret != -EAGAIN)
5429 * Errors here aren't a big deal, it just means we leave orphan items in
5430 * the tree. They will be cleaned up on the next mount. If the inode
5431 * number gets reused, cleanup deletes the orphan item without doing
5432 * anything, and unlink reuses the existing orphan item.
5434 * If it turns out that we are dropping too many of these, we might want
5435 * to add a mechanism for retrying these after a commit.
5437 trans = evict_refill_and_join(root, rsv);
5438 if (!IS_ERR(trans)) {
5439 trans->block_rsv = rsv;
5440 btrfs_orphan_del(trans, BTRFS_I(inode));
5441 trans->block_rsv = &fs_info->trans_block_rsv;
5442 btrfs_end_transaction(trans);
5445 if (!(root == fs_info->tree_root ||
5446 root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID))
5447 btrfs_return_ino(root, btrfs_ino(BTRFS_I(inode)));
5450 btrfs_free_block_rsv(fs_info, rsv);
5453 * If we didn't successfully delete, the orphan item will still be in
5454 * the tree and we'll retry on the next mount. Again, we might also want
5455 * to retry these periodically in the future.
5457 btrfs_remove_delayed_node(BTRFS_I(inode));
5462 * Return the key found in the dir entry in the location pointer, fill @type
5463 * with BTRFS_FT_*, and return 0.
5465 * If no dir entries were found, returns -ENOENT.
5466 * If found a corrupted location in dir entry, returns -EUCLEAN.
5468 static int btrfs_inode_by_name(struct inode *dir, struct dentry *dentry,
5469 struct btrfs_key *location, u8 *type)
5471 const char *name = dentry->d_name.name;
5472 int namelen = dentry->d_name.len;
5473 struct btrfs_dir_item *di;
5474 struct btrfs_path *path;
5475 struct btrfs_root *root = BTRFS_I(dir)->root;
5478 path = btrfs_alloc_path();
5482 di = btrfs_lookup_dir_item(NULL, root, path, btrfs_ino(BTRFS_I(dir)),
5484 if (IS_ERR_OR_NULL(di)) {
5485 ret = di ? PTR_ERR(di) : -ENOENT;
5489 btrfs_dir_item_key_to_cpu(path->nodes[0], di, location);
5490 if (location->type != BTRFS_INODE_ITEM_KEY &&
5491 location->type != BTRFS_ROOT_ITEM_KEY) {
5493 btrfs_warn(root->fs_info,
5494 "%s gets something invalid in DIR_ITEM (name %s, directory ino %llu, location(%llu %u %llu))",
5495 __func__, name, btrfs_ino(BTRFS_I(dir)),
5496 location->objectid, location->type, location->offset);
5499 *type = btrfs_dir_type(path->nodes[0], di);
5501 btrfs_free_path(path);
5506 * when we hit a tree root in a directory, the btrfs part of the inode
5507 * needs to be changed to reflect the root directory of the tree root. This
5508 * is kind of like crossing a mount point.
5510 static int fixup_tree_root_location(struct btrfs_fs_info *fs_info,
5512 struct dentry *dentry,
5513 struct btrfs_key *location,
5514 struct btrfs_root **sub_root)
5516 struct btrfs_path *path;
5517 struct btrfs_root *new_root;
5518 struct btrfs_root_ref *ref;
5519 struct extent_buffer *leaf;
5520 struct btrfs_key key;
5524 path = btrfs_alloc_path();
5531 key.objectid = BTRFS_I(dir)->root->root_key.objectid;
5532 key.type = BTRFS_ROOT_REF_KEY;
5533 key.offset = location->objectid;
5535 ret = btrfs_search_slot(NULL, fs_info->tree_root, &key, path, 0, 0);
5542 leaf = path->nodes[0];
5543 ref = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_root_ref);
5544 if (btrfs_root_ref_dirid(leaf, ref) != btrfs_ino(BTRFS_I(dir)) ||
5545 btrfs_root_ref_name_len(leaf, ref) != dentry->d_name.len)
5548 ret = memcmp_extent_buffer(leaf, dentry->d_name.name,
5549 (unsigned long)(ref + 1),
5550 dentry->d_name.len);
5554 btrfs_release_path(path);
5556 new_root = btrfs_read_fs_root_no_name(fs_info, location);
5557 if (IS_ERR(new_root)) {
5558 err = PTR_ERR(new_root);
5562 *sub_root = new_root;
5563 location->objectid = btrfs_root_dirid(&new_root->root_item);
5564 location->type = BTRFS_INODE_ITEM_KEY;
5565 location->offset = 0;
5568 btrfs_free_path(path);
5572 static void inode_tree_add(struct inode *inode)
5574 struct btrfs_root *root = BTRFS_I(inode)->root;
5575 struct btrfs_inode *entry;
5577 struct rb_node *parent;
5578 struct rb_node *new = &BTRFS_I(inode)->rb_node;
5579 u64 ino = btrfs_ino(BTRFS_I(inode));
5581 if (inode_unhashed(inode))
5584 spin_lock(&root->inode_lock);
5585 p = &root->inode_tree.rb_node;
5588 entry = rb_entry(parent, struct btrfs_inode, rb_node);
5590 if (ino < btrfs_ino(entry))
5591 p = &parent->rb_left;
5592 else if (ino > btrfs_ino(entry))
5593 p = &parent->rb_right;
5595 WARN_ON(!(entry->vfs_inode.i_state &
5596 (I_WILL_FREE | I_FREEING)));
5597 rb_replace_node(parent, new, &root->inode_tree);
5598 RB_CLEAR_NODE(parent);
5599 spin_unlock(&root->inode_lock);
5603 rb_link_node(new, parent, p);
5604 rb_insert_color(new, &root->inode_tree);
5605 spin_unlock(&root->inode_lock);
5608 static void inode_tree_del(struct inode *inode)
5610 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
5611 struct btrfs_root *root = BTRFS_I(inode)->root;
5614 spin_lock(&root->inode_lock);
5615 if (!RB_EMPTY_NODE(&BTRFS_I(inode)->rb_node)) {
5616 rb_erase(&BTRFS_I(inode)->rb_node, &root->inode_tree);
5617 RB_CLEAR_NODE(&BTRFS_I(inode)->rb_node);
5618 empty = RB_EMPTY_ROOT(&root->inode_tree);
5620 spin_unlock(&root->inode_lock);
5622 if (empty && btrfs_root_refs(&root->root_item) == 0) {
5623 synchronize_srcu(&fs_info->subvol_srcu);
5624 spin_lock(&root->inode_lock);
5625 empty = RB_EMPTY_ROOT(&root->inode_tree);
5626 spin_unlock(&root->inode_lock);
5628 btrfs_add_dead_root(root);
5633 static int btrfs_init_locked_inode(struct inode *inode, void *p)
5635 struct btrfs_iget_args *args = p;
5636 inode->i_ino = args->location->objectid;
5637 memcpy(&BTRFS_I(inode)->location, args->location,
5638 sizeof(*args->location));
5639 BTRFS_I(inode)->root = args->root;
5643 static int btrfs_find_actor(struct inode *inode, void *opaque)
5645 struct btrfs_iget_args *args = opaque;
5646 return args->location->objectid == BTRFS_I(inode)->location.objectid &&
5647 args->root == BTRFS_I(inode)->root;
5650 static struct inode *btrfs_iget_locked(struct super_block *s,
5651 struct btrfs_key *location,
5652 struct btrfs_root *root)
5654 struct inode *inode;
5655 struct btrfs_iget_args args;
5656 unsigned long hashval = btrfs_inode_hash(location->objectid, root);
5658 args.location = location;
5661 inode = iget5_locked(s, hashval, btrfs_find_actor,
5662 btrfs_init_locked_inode,
5667 /* Get an inode object given its location and corresponding root.
5668 * Returns in *is_new if the inode was read from disk
5670 struct inode *btrfs_iget_path(struct super_block *s, struct btrfs_key *location,
5671 struct btrfs_root *root, int *new,
5672 struct btrfs_path *path)
5674 struct inode *inode;
5676 inode = btrfs_iget_locked(s, location, root);
5678 return ERR_PTR(-ENOMEM);
5680 if (inode->i_state & I_NEW) {
5683 ret = btrfs_read_locked_inode(inode, path);
5685 inode_tree_add(inode);
5686 unlock_new_inode(inode);
5692 * ret > 0 can come from btrfs_search_slot called by
5693 * btrfs_read_locked_inode, this means the inode item
5698 inode = ERR_PTR(ret);
5705 struct inode *btrfs_iget(struct super_block *s, struct btrfs_key *location,
5706 struct btrfs_root *root, int *new)
5708 return btrfs_iget_path(s, location, root, new, NULL);
5711 static struct inode *new_simple_dir(struct super_block *s,
5712 struct btrfs_key *key,
5713 struct btrfs_root *root)
5715 struct inode *inode = new_inode(s);
5718 return ERR_PTR(-ENOMEM);
5720 BTRFS_I(inode)->root = root;
5721 memcpy(&BTRFS_I(inode)->location, key, sizeof(*key));
5722 set_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags);
5724 inode->i_ino = BTRFS_EMPTY_SUBVOL_DIR_OBJECTID;
5725 inode->i_op = &btrfs_dir_ro_inode_operations;
5726 inode->i_opflags &= ~IOP_XATTR;
5727 inode->i_fop = &simple_dir_operations;
5728 inode->i_mode = S_IFDIR | S_IRUGO | S_IWUSR | S_IXUGO;
5729 inode->i_mtime = current_time(inode);
5730 inode->i_atime = inode->i_mtime;
5731 inode->i_ctime = inode->i_mtime;
5732 BTRFS_I(inode)->i_otime = inode->i_mtime;
5737 static inline u8 btrfs_inode_type(struct inode *inode)
5740 * Compile-time asserts that generic FT_* types still match
5743 BUILD_BUG_ON(BTRFS_FT_UNKNOWN != FT_UNKNOWN);
5744 BUILD_BUG_ON(BTRFS_FT_REG_FILE != FT_REG_FILE);
5745 BUILD_BUG_ON(BTRFS_FT_DIR != FT_DIR);
5746 BUILD_BUG_ON(BTRFS_FT_CHRDEV != FT_CHRDEV);
5747 BUILD_BUG_ON(BTRFS_FT_BLKDEV != FT_BLKDEV);
5748 BUILD_BUG_ON(BTRFS_FT_FIFO != FT_FIFO);
5749 BUILD_BUG_ON(BTRFS_FT_SOCK != FT_SOCK);
5750 BUILD_BUG_ON(BTRFS_FT_SYMLINK != FT_SYMLINK);
5752 return fs_umode_to_ftype(inode->i_mode);
5755 struct inode *btrfs_lookup_dentry(struct inode *dir, struct dentry *dentry)
5757 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
5758 struct inode *inode;
5759 struct btrfs_root *root = BTRFS_I(dir)->root;
5760 struct btrfs_root *sub_root = root;
5761 struct btrfs_key location;
5766 if (dentry->d_name.len > BTRFS_NAME_LEN)
5767 return ERR_PTR(-ENAMETOOLONG);
5769 ret = btrfs_inode_by_name(dir, dentry, &location, &di_type);
5771 return ERR_PTR(ret);
5773 if (location.type == BTRFS_INODE_ITEM_KEY) {
5774 inode = btrfs_iget(dir->i_sb, &location, root, NULL);
5778 /* Do extra check against inode mode with di_type */
5779 if (btrfs_inode_type(inode) != di_type) {
5781 "inode mode mismatch with dir: inode mode=0%o btrfs type=%u dir type=%u",
5782 inode->i_mode, btrfs_inode_type(inode),
5785 return ERR_PTR(-EUCLEAN);
5790 index = srcu_read_lock(&fs_info->subvol_srcu);
5791 ret = fixup_tree_root_location(fs_info, dir, dentry,
5792 &location, &sub_root);
5795 inode = ERR_PTR(ret);
5797 inode = new_simple_dir(dir->i_sb, &location, sub_root);
5799 inode = btrfs_iget(dir->i_sb, &location, sub_root, NULL);
5801 srcu_read_unlock(&fs_info->subvol_srcu, index);
5803 if (!IS_ERR(inode) && root != sub_root) {
5804 down_read(&fs_info->cleanup_work_sem);
5805 if (!sb_rdonly(inode->i_sb))
5806 ret = btrfs_orphan_cleanup(sub_root);
5807 up_read(&fs_info->cleanup_work_sem);
5810 inode = ERR_PTR(ret);
5817 static int btrfs_dentry_delete(const struct dentry *dentry)
5819 struct btrfs_root *root;
5820 struct inode *inode = d_inode(dentry);
5822 if (!inode && !IS_ROOT(dentry))
5823 inode = d_inode(dentry->d_parent);
5826 root = BTRFS_I(inode)->root;
5827 if (btrfs_root_refs(&root->root_item) == 0)
5830 if (btrfs_ino(BTRFS_I(inode)) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)
5836 static struct dentry *btrfs_lookup(struct inode *dir, struct dentry *dentry,
5839 struct inode *inode = btrfs_lookup_dentry(dir, dentry);
5841 if (inode == ERR_PTR(-ENOENT))
5843 return d_splice_alias(inode, dentry);
5847 * All this infrastructure exists because dir_emit can fault, and we are holding
5848 * the tree lock when doing readdir. For now just allocate a buffer and copy
5849 * our information into that, and then dir_emit from the buffer. This is
5850 * similar to what NFS does, only we don't keep the buffer around in pagecache
5851 * because I'm afraid I'll mess that up. Long term we need to make filldir do
5852 * copy_to_user_inatomic so we don't have to worry about page faulting under the
5855 static int btrfs_opendir(struct inode *inode, struct file *file)
5857 struct btrfs_file_private *private;
5859 private = kzalloc(sizeof(struct btrfs_file_private), GFP_KERNEL);
5862 private->filldir_buf = kzalloc(PAGE_SIZE, GFP_KERNEL);
5863 if (!private->filldir_buf) {
5867 file->private_data = private;
5878 static int btrfs_filldir(void *addr, int entries, struct dir_context *ctx)
5881 struct dir_entry *entry = addr;
5882 char *name = (char *)(entry + 1);
5884 ctx->pos = get_unaligned(&entry->offset);
5885 if (!dir_emit(ctx, name, get_unaligned(&entry->name_len),
5886 get_unaligned(&entry->ino),
5887 get_unaligned(&entry->type)))
5889 addr += sizeof(struct dir_entry) +
5890 get_unaligned(&entry->name_len);
5896 static int btrfs_real_readdir(struct file *file, struct dir_context *ctx)
5898 struct inode *inode = file_inode(file);
5899 struct btrfs_root *root = BTRFS_I(inode)->root;
5900 struct btrfs_file_private *private = file->private_data;
5901 struct btrfs_dir_item *di;
5902 struct btrfs_key key;
5903 struct btrfs_key found_key;
5904 struct btrfs_path *path;
5906 struct list_head ins_list;
5907 struct list_head del_list;
5909 struct extent_buffer *leaf;
5916 struct btrfs_key location;
5918 if (!dir_emit_dots(file, ctx))
5921 path = btrfs_alloc_path();
5925 addr = private->filldir_buf;
5926 path->reada = READA_FORWARD;
5928 INIT_LIST_HEAD(&ins_list);
5929 INIT_LIST_HEAD(&del_list);
5930 put = btrfs_readdir_get_delayed_items(inode, &ins_list, &del_list);
5933 key.type = BTRFS_DIR_INDEX_KEY;
5934 key.offset = ctx->pos;
5935 key.objectid = btrfs_ino(BTRFS_I(inode));
5937 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
5942 struct dir_entry *entry;
5944 leaf = path->nodes[0];
5945 slot = path->slots[0];
5946 if (slot >= btrfs_header_nritems(leaf)) {
5947 ret = btrfs_next_leaf(root, path);
5955 btrfs_item_key_to_cpu(leaf, &found_key, slot);
5957 if (found_key.objectid != key.objectid)
5959 if (found_key.type != BTRFS_DIR_INDEX_KEY)
5961 if (found_key.offset < ctx->pos)
5963 if (btrfs_should_delete_dir_index(&del_list, found_key.offset))
5965 di = btrfs_item_ptr(leaf, slot, struct btrfs_dir_item);
5966 name_len = btrfs_dir_name_len(leaf, di);
5967 if ((total_len + sizeof(struct dir_entry) + name_len) >=
5969 btrfs_release_path(path);
5970 ret = btrfs_filldir(private->filldir_buf, entries, ctx);
5973 addr = private->filldir_buf;
5980 put_unaligned(name_len, &entry->name_len);
5981 name_ptr = (char *)(entry + 1);
5982 read_extent_buffer(leaf, name_ptr, (unsigned long)(di + 1),
5984 put_unaligned(fs_ftype_to_dtype(btrfs_dir_type(leaf, di)),
5986 btrfs_dir_item_key_to_cpu(leaf, di, &location);
5987 put_unaligned(location.objectid, &entry->ino);
5988 put_unaligned(found_key.offset, &entry->offset);
5990 addr += sizeof(struct dir_entry) + name_len;
5991 total_len += sizeof(struct dir_entry) + name_len;
5995 btrfs_release_path(path);
5997 ret = btrfs_filldir(private->filldir_buf, entries, ctx);
6001 ret = btrfs_readdir_delayed_dir_index(ctx, &ins_list);
6006 * Stop new entries from being returned after we return the last
6009 * New directory entries are assigned a strictly increasing
6010 * offset. This means that new entries created during readdir
6011 * are *guaranteed* to be seen in the future by that readdir.
6012 * This has broken buggy programs which operate on names as
6013 * they're returned by readdir. Until we re-use freed offsets
6014 * we have this hack to stop new entries from being returned
6015 * under the assumption that they'll never reach this huge
6018 * This is being careful not to overflow 32bit loff_t unless the
6019 * last entry requires it because doing so has broken 32bit apps
6022 if (ctx->pos >= INT_MAX)
6023 ctx->pos = LLONG_MAX;
6030 btrfs_readdir_put_delayed_items(inode, &ins_list, &del_list);
6031 btrfs_free_path(path);
6036 * This is somewhat expensive, updating the tree every time the
6037 * inode changes. But, it is most likely to find the inode in cache.
6038 * FIXME, needs more benchmarking...there are no reasons other than performance
6039 * to keep or drop this code.
6041 static int btrfs_dirty_inode(struct inode *inode)
6043 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
6044 struct btrfs_root *root = BTRFS_I(inode)->root;
6045 struct btrfs_trans_handle *trans;
6048 if (test_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags))
6051 trans = btrfs_join_transaction(root);
6053 return PTR_ERR(trans);
6055 ret = btrfs_update_inode(trans, root, inode);
6056 if (ret && ret == -ENOSPC) {
6057 /* whoops, lets try again with the full transaction */
6058 btrfs_end_transaction(trans);
6059 trans = btrfs_start_transaction(root, 1);
6061 return PTR_ERR(trans);
6063 ret = btrfs_update_inode(trans, root, inode);
6065 btrfs_end_transaction(trans);
6066 if (BTRFS_I(inode)->delayed_node)
6067 btrfs_balance_delayed_items(fs_info);
6073 * This is a copy of file_update_time. We need this so we can return error on
6074 * ENOSPC for updating the inode in the case of file write and mmap writes.
6076 static int btrfs_update_time(struct inode *inode, struct timespec64 *now,
6079 struct btrfs_root *root = BTRFS_I(inode)->root;
6080 bool dirty = flags & ~S_VERSION;
6082 if (btrfs_root_readonly(root))
6085 if (flags & S_VERSION)
6086 dirty |= inode_maybe_inc_iversion(inode, dirty);
6087 if (flags & S_CTIME)
6088 inode->i_ctime = *now;
6089 if (flags & S_MTIME)
6090 inode->i_mtime = *now;
6091 if (flags & S_ATIME)
6092 inode->i_atime = *now;
6093 return dirty ? btrfs_dirty_inode(inode) : 0;
6097 * find the highest existing sequence number in a directory
6098 * and then set the in-memory index_cnt variable to reflect
6099 * free sequence numbers
6101 static int btrfs_set_inode_index_count(struct btrfs_inode *inode)
6103 struct btrfs_root *root = inode->root;
6104 struct btrfs_key key, found_key;
6105 struct btrfs_path *path;
6106 struct extent_buffer *leaf;
6109 key.objectid = btrfs_ino(inode);
6110 key.type = BTRFS_DIR_INDEX_KEY;
6111 key.offset = (u64)-1;
6113 path = btrfs_alloc_path();
6117 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
6120 /* FIXME: we should be able to handle this */
6126 * MAGIC NUMBER EXPLANATION:
6127 * since we search a directory based on f_pos we have to start at 2
6128 * since '.' and '..' have f_pos of 0 and 1 respectively, so everybody
6129 * else has to start at 2
6131 if (path->slots[0] == 0) {
6132 inode->index_cnt = 2;
6138 leaf = path->nodes[0];
6139 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
6141 if (found_key.objectid != btrfs_ino(inode) ||
6142 found_key.type != BTRFS_DIR_INDEX_KEY) {
6143 inode->index_cnt = 2;
6147 inode->index_cnt = found_key.offset + 1;
6149 btrfs_free_path(path);
6154 * helper to find a free sequence number in a given directory. This current
6155 * code is very simple, later versions will do smarter things in the btree
6157 int btrfs_set_inode_index(struct btrfs_inode *dir, u64 *index)
6161 if (dir->index_cnt == (u64)-1) {
6162 ret = btrfs_inode_delayed_dir_index_count(dir);
6164 ret = btrfs_set_inode_index_count(dir);
6170 *index = dir->index_cnt;
6176 static int btrfs_insert_inode_locked(struct inode *inode)
6178 struct btrfs_iget_args args;
6179 args.location = &BTRFS_I(inode)->location;
6180 args.root = BTRFS_I(inode)->root;
6182 return insert_inode_locked4(inode,
6183 btrfs_inode_hash(inode->i_ino, BTRFS_I(inode)->root),
6184 btrfs_find_actor, &args);
6188 * Inherit flags from the parent inode.
6190 * Currently only the compression flags and the cow flags are inherited.
6192 static void btrfs_inherit_iflags(struct inode *inode, struct inode *dir)
6199 flags = BTRFS_I(dir)->flags;
6201 if (flags & BTRFS_INODE_NOCOMPRESS) {
6202 BTRFS_I(inode)->flags &= ~BTRFS_INODE_COMPRESS;
6203 BTRFS_I(inode)->flags |= BTRFS_INODE_NOCOMPRESS;
6204 } else if (flags & BTRFS_INODE_COMPRESS) {
6205 BTRFS_I(inode)->flags &= ~BTRFS_INODE_NOCOMPRESS;
6206 BTRFS_I(inode)->flags |= BTRFS_INODE_COMPRESS;
6209 if (flags & BTRFS_INODE_NODATACOW) {
6210 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATACOW;
6211 if (S_ISREG(inode->i_mode))
6212 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATASUM;
6215 btrfs_sync_inode_flags_to_i_flags(inode);
6218 static struct inode *btrfs_new_inode(struct btrfs_trans_handle *trans,
6219 struct btrfs_root *root,
6221 const char *name, int name_len,
6222 u64 ref_objectid, u64 objectid,
6223 umode_t mode, u64 *index)
6225 struct btrfs_fs_info *fs_info = root->fs_info;
6226 struct inode *inode;
6227 struct btrfs_inode_item *inode_item;
6228 struct btrfs_key *location;
6229 struct btrfs_path *path;
6230 struct btrfs_inode_ref *ref;
6231 struct btrfs_key key[2];
6233 int nitems = name ? 2 : 1;
6237 path = btrfs_alloc_path();
6239 return ERR_PTR(-ENOMEM);
6241 inode = new_inode(fs_info->sb);
6243 btrfs_free_path(path);
6244 return ERR_PTR(-ENOMEM);
6248 * O_TMPFILE, set link count to 0, so that after this point,
6249 * we fill in an inode item with the correct link count.
6252 set_nlink(inode, 0);
6255 * we have to initialize this early, so we can reclaim the inode
6256 * number if we fail afterwards in this function.
6258 inode->i_ino = objectid;
6261 trace_btrfs_inode_request(dir);
6263 ret = btrfs_set_inode_index(BTRFS_I(dir), index);
6265 btrfs_free_path(path);
6267 return ERR_PTR(ret);
6273 * index_cnt is ignored for everything but a dir,
6274 * btrfs_set_inode_index_count has an explanation for the magic
6277 BTRFS_I(inode)->index_cnt = 2;
6278 BTRFS_I(inode)->dir_index = *index;
6279 BTRFS_I(inode)->root = root;
6280 BTRFS_I(inode)->generation = trans->transid;
6281 inode->i_generation = BTRFS_I(inode)->generation;
6284 * We could have gotten an inode number from somebody who was fsynced
6285 * and then removed in this same transaction, so let's just set full
6286 * sync since it will be a full sync anyway and this will blow away the
6287 * old info in the log.
6289 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &BTRFS_I(inode)->runtime_flags);
6291 key[0].objectid = objectid;
6292 key[0].type = BTRFS_INODE_ITEM_KEY;
6295 sizes[0] = sizeof(struct btrfs_inode_item);
6299 * Start new inodes with an inode_ref. This is slightly more
6300 * efficient for small numbers of hard links since they will
6301 * be packed into one item. Extended refs will kick in if we
6302 * add more hard links than can fit in the ref item.
6304 key[1].objectid = objectid;
6305 key[1].type = BTRFS_INODE_REF_KEY;
6306 key[1].offset = ref_objectid;
6308 sizes[1] = name_len + sizeof(*ref);
6311 location = &BTRFS_I(inode)->location;
6312 location->objectid = objectid;
6313 location->offset = 0;
6314 location->type = BTRFS_INODE_ITEM_KEY;
6316 ret = btrfs_insert_inode_locked(inode);
6322 path->leave_spinning = 1;
6323 ret = btrfs_insert_empty_items(trans, root, path, key, sizes, nitems);
6327 inode_init_owner(inode, dir, mode);
6328 inode_set_bytes(inode, 0);
6330 inode->i_mtime = current_time(inode);
6331 inode->i_atime = inode->i_mtime;
6332 inode->i_ctime = inode->i_mtime;
6333 BTRFS_I(inode)->i_otime = inode->i_mtime;
6335 inode_item = btrfs_item_ptr(path->nodes[0], path->slots[0],
6336 struct btrfs_inode_item);
6337 memzero_extent_buffer(path->nodes[0], (unsigned long)inode_item,
6338 sizeof(*inode_item));
6339 fill_inode_item(trans, path->nodes[0], inode_item, inode);
6342 ref = btrfs_item_ptr(path->nodes[0], path->slots[0] + 1,
6343 struct btrfs_inode_ref);
6344 btrfs_set_inode_ref_name_len(path->nodes[0], ref, name_len);
6345 btrfs_set_inode_ref_index(path->nodes[0], ref, *index);
6346 ptr = (unsigned long)(ref + 1);
6347 write_extent_buffer(path->nodes[0], name, ptr, name_len);
6350 btrfs_mark_buffer_dirty(path->nodes[0]);
6351 btrfs_free_path(path);
6353 btrfs_inherit_iflags(inode, dir);
6355 if (S_ISREG(mode)) {
6356 if (btrfs_test_opt(fs_info, NODATASUM))
6357 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATASUM;
6358 if (btrfs_test_opt(fs_info, NODATACOW))
6359 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATACOW |
6360 BTRFS_INODE_NODATASUM;
6363 inode_tree_add(inode);
6365 trace_btrfs_inode_new(inode);
6366 btrfs_set_inode_last_trans(trans, inode);
6368 btrfs_update_root_times(trans, root);
6370 ret = btrfs_inode_inherit_props(trans, inode, dir);
6373 "error inheriting props for ino %llu (root %llu): %d",
6374 btrfs_ino(BTRFS_I(inode)), root->root_key.objectid, ret);
6379 discard_new_inode(inode);
6382 BTRFS_I(dir)->index_cnt--;
6383 btrfs_free_path(path);
6384 return ERR_PTR(ret);
6388 * utility function to add 'inode' into 'parent_inode' with
6389 * a give name and a given sequence number.
6390 * if 'add_backref' is true, also insert a backref from the
6391 * inode to the parent directory.
6393 int btrfs_add_link(struct btrfs_trans_handle *trans,
6394 struct btrfs_inode *parent_inode, struct btrfs_inode *inode,
6395 const char *name, int name_len, int add_backref, u64 index)
6398 struct btrfs_key key;
6399 struct btrfs_root *root = parent_inode->root;
6400 u64 ino = btrfs_ino(inode);
6401 u64 parent_ino = btrfs_ino(parent_inode);
6403 if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
6404 memcpy(&key, &inode->root->root_key, sizeof(key));
6407 key.type = BTRFS_INODE_ITEM_KEY;
6411 if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
6412 ret = btrfs_add_root_ref(trans, key.objectid,
6413 root->root_key.objectid, parent_ino,
6414 index, name, name_len);
6415 } else if (add_backref) {
6416 ret = btrfs_insert_inode_ref(trans, root, name, name_len, ino,
6420 /* Nothing to clean up yet */
6424 ret = btrfs_insert_dir_item(trans, name, name_len, parent_inode, &key,
6425 btrfs_inode_type(&inode->vfs_inode), index);
6426 if (ret == -EEXIST || ret == -EOVERFLOW)
6429 btrfs_abort_transaction(trans, ret);
6433 btrfs_i_size_write(parent_inode, parent_inode->vfs_inode.i_size +
6435 inode_inc_iversion(&parent_inode->vfs_inode);
6436 parent_inode->vfs_inode.i_mtime = parent_inode->vfs_inode.i_ctime =
6437 current_time(&parent_inode->vfs_inode);
6438 ret = btrfs_update_inode(trans, root, &parent_inode->vfs_inode);
6440 btrfs_abort_transaction(trans, ret);
6444 if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
6447 err = btrfs_del_root_ref(trans, key.objectid,
6448 root->root_key.objectid, parent_ino,
6449 &local_index, name, name_len);
6451 btrfs_abort_transaction(trans, err);
6452 } else if (add_backref) {
6456 err = btrfs_del_inode_ref(trans, root, name, name_len,
6457 ino, parent_ino, &local_index);
6459 btrfs_abort_transaction(trans, err);
6462 /* Return the original error code */
6466 static int btrfs_add_nondir(struct btrfs_trans_handle *trans,
6467 struct btrfs_inode *dir, struct dentry *dentry,
6468 struct btrfs_inode *inode, int backref, u64 index)
6470 int err = btrfs_add_link(trans, dir, inode,
6471 dentry->d_name.name, dentry->d_name.len,
6478 static int btrfs_mknod(struct inode *dir, struct dentry *dentry,
6479 umode_t mode, dev_t rdev)
6481 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
6482 struct btrfs_trans_handle *trans;
6483 struct btrfs_root *root = BTRFS_I(dir)->root;
6484 struct inode *inode = NULL;
6490 * 2 for inode item and ref
6492 * 1 for xattr if selinux is on
6494 trans = btrfs_start_transaction(root, 5);
6496 return PTR_ERR(trans);
6498 err = btrfs_find_free_ino(root, &objectid);
6502 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
6503 dentry->d_name.len, btrfs_ino(BTRFS_I(dir)), objectid,
6505 if (IS_ERR(inode)) {
6506 err = PTR_ERR(inode);
6512 * If the active LSM wants to access the inode during
6513 * d_instantiate it needs these. Smack checks to see
6514 * if the filesystem supports xattrs by looking at the
6517 inode->i_op = &btrfs_special_inode_operations;
6518 init_special_inode(inode, inode->i_mode, rdev);
6520 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
6524 err = btrfs_add_nondir(trans, BTRFS_I(dir), dentry, BTRFS_I(inode),
6529 btrfs_update_inode(trans, root, inode);
6530 d_instantiate_new(dentry, inode);
6533 btrfs_end_transaction(trans);
6534 btrfs_btree_balance_dirty(fs_info);
6536 inode_dec_link_count(inode);
6537 discard_new_inode(inode);
6542 static int btrfs_create(struct inode *dir, struct dentry *dentry,
6543 umode_t mode, bool excl)
6545 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
6546 struct btrfs_trans_handle *trans;
6547 struct btrfs_root *root = BTRFS_I(dir)->root;
6548 struct inode *inode = NULL;
6554 * 2 for inode item and ref
6556 * 1 for xattr if selinux is on
6558 trans = btrfs_start_transaction(root, 5);
6560 return PTR_ERR(trans);
6562 err = btrfs_find_free_ino(root, &objectid);
6566 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
6567 dentry->d_name.len, btrfs_ino(BTRFS_I(dir)), objectid,
6569 if (IS_ERR(inode)) {
6570 err = PTR_ERR(inode);
6575 * If the active LSM wants to access the inode during
6576 * d_instantiate it needs these. Smack checks to see
6577 * if the filesystem supports xattrs by looking at the
6580 inode->i_fop = &btrfs_file_operations;
6581 inode->i_op = &btrfs_file_inode_operations;
6582 inode->i_mapping->a_ops = &btrfs_aops;
6584 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
6588 err = btrfs_update_inode(trans, root, inode);
6592 err = btrfs_add_nondir(trans, BTRFS_I(dir), dentry, BTRFS_I(inode),
6597 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
6598 d_instantiate_new(dentry, inode);
6601 btrfs_end_transaction(trans);
6603 inode_dec_link_count(inode);
6604 discard_new_inode(inode);
6606 btrfs_btree_balance_dirty(fs_info);
6610 static int btrfs_link(struct dentry *old_dentry, struct inode *dir,
6611 struct dentry *dentry)
6613 struct btrfs_trans_handle *trans = NULL;
6614 struct btrfs_root *root = BTRFS_I(dir)->root;
6615 struct inode *inode = d_inode(old_dentry);
6616 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
6621 /* do not allow sys_link's with other subvols of the same device */
6622 if (root->root_key.objectid != BTRFS_I(inode)->root->root_key.objectid)
6625 if (inode->i_nlink >= BTRFS_LINK_MAX)
6628 err = btrfs_set_inode_index(BTRFS_I(dir), &index);
6633 * 2 items for inode and inode ref
6634 * 2 items for dir items
6635 * 1 item for parent inode
6636 * 1 item for orphan item deletion if O_TMPFILE
6638 trans = btrfs_start_transaction(root, inode->i_nlink ? 5 : 6);
6639 if (IS_ERR(trans)) {
6640 err = PTR_ERR(trans);
6645 /* There are several dir indexes for this inode, clear the cache. */
6646 BTRFS_I(inode)->dir_index = 0ULL;
6648 inode_inc_iversion(inode);
6649 inode->i_ctime = current_time(inode);
6651 set_bit(BTRFS_INODE_COPY_EVERYTHING, &BTRFS_I(inode)->runtime_flags);
6653 err = btrfs_add_nondir(trans, BTRFS_I(dir), dentry, BTRFS_I(inode),
6659 struct dentry *parent = dentry->d_parent;
6662 err = btrfs_update_inode(trans, root, inode);
6665 if (inode->i_nlink == 1) {
6667 * If new hard link count is 1, it's a file created
6668 * with open(2) O_TMPFILE flag.
6670 err = btrfs_orphan_del(trans, BTRFS_I(inode));
6674 d_instantiate(dentry, inode);
6675 ret = btrfs_log_new_name(trans, BTRFS_I(inode), NULL, parent,
6677 if (ret == BTRFS_NEED_TRANS_COMMIT) {
6678 err = btrfs_commit_transaction(trans);
6685 btrfs_end_transaction(trans);
6687 inode_dec_link_count(inode);
6690 btrfs_btree_balance_dirty(fs_info);
6694 static int btrfs_mkdir(struct inode *dir, struct dentry *dentry, umode_t mode)
6696 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
6697 struct inode *inode = NULL;
6698 struct btrfs_trans_handle *trans;
6699 struct btrfs_root *root = BTRFS_I(dir)->root;
6705 * 2 items for inode and ref
6706 * 2 items for dir items
6707 * 1 for xattr if selinux is on
6709 trans = btrfs_start_transaction(root, 5);
6711 return PTR_ERR(trans);
6713 err = btrfs_find_free_ino(root, &objectid);
6717 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
6718 dentry->d_name.len, btrfs_ino(BTRFS_I(dir)), objectid,
6719 S_IFDIR | mode, &index);
6720 if (IS_ERR(inode)) {
6721 err = PTR_ERR(inode);
6726 /* these must be set before we unlock the inode */
6727 inode->i_op = &btrfs_dir_inode_operations;
6728 inode->i_fop = &btrfs_dir_file_operations;
6730 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
6734 btrfs_i_size_write(BTRFS_I(inode), 0);
6735 err = btrfs_update_inode(trans, root, inode);
6739 err = btrfs_add_link(trans, BTRFS_I(dir), BTRFS_I(inode),
6740 dentry->d_name.name,
6741 dentry->d_name.len, 0, index);
6745 d_instantiate_new(dentry, inode);
6748 btrfs_end_transaction(trans);
6750 inode_dec_link_count(inode);
6751 discard_new_inode(inode);
6753 btrfs_btree_balance_dirty(fs_info);
6757 static noinline int uncompress_inline(struct btrfs_path *path,
6759 size_t pg_offset, u64 extent_offset,
6760 struct btrfs_file_extent_item *item)
6763 struct extent_buffer *leaf = path->nodes[0];
6766 unsigned long inline_size;
6770 WARN_ON(pg_offset != 0);
6771 compress_type = btrfs_file_extent_compression(leaf, item);
6772 max_size = btrfs_file_extent_ram_bytes(leaf, item);
6773 inline_size = btrfs_file_extent_inline_item_len(leaf,
6774 btrfs_item_nr(path->slots[0]));
6775 tmp = kmalloc(inline_size, GFP_NOFS);
6778 ptr = btrfs_file_extent_inline_start(item);
6780 read_extent_buffer(leaf, tmp, ptr, inline_size);
6782 max_size = min_t(unsigned long, PAGE_SIZE, max_size);
6783 ret = btrfs_decompress(compress_type, tmp, page,
6784 extent_offset, inline_size, max_size);
6787 * decompression code contains a memset to fill in any space between the end
6788 * of the uncompressed data and the end of max_size in case the decompressed
6789 * data ends up shorter than ram_bytes. That doesn't cover the hole between
6790 * the end of an inline extent and the beginning of the next block, so we
6791 * cover that region here.
6794 if (max_size + pg_offset < PAGE_SIZE) {
6795 char *map = kmap(page);
6796 memset(map + pg_offset + max_size, 0, PAGE_SIZE - max_size - pg_offset);
6804 * a bit scary, this does extent mapping from logical file offset to the disk.
6805 * the ugly parts come from merging extents from the disk with the in-ram
6806 * representation. This gets more complex because of the data=ordered code,
6807 * where the in-ram extents might be locked pending data=ordered completion.
6809 * This also copies inline extents directly into the page.
6811 struct extent_map *btrfs_get_extent(struct btrfs_inode *inode,
6813 size_t pg_offset, u64 start, u64 len,
6816 struct btrfs_fs_info *fs_info = inode->root->fs_info;
6819 u64 extent_start = 0;
6821 u64 objectid = btrfs_ino(inode);
6822 int extent_type = -1;
6823 struct btrfs_path *path = NULL;
6824 struct btrfs_root *root = inode->root;
6825 struct btrfs_file_extent_item *item;
6826 struct extent_buffer *leaf;
6827 struct btrfs_key found_key;
6828 struct extent_map *em = NULL;
6829 struct extent_map_tree *em_tree = &inode->extent_tree;
6830 struct extent_io_tree *io_tree = &inode->io_tree;
6831 const bool new_inline = !page || create;
6833 read_lock(&em_tree->lock);
6834 em = lookup_extent_mapping(em_tree, start, len);
6836 em->bdev = fs_info->fs_devices->latest_bdev;
6837 read_unlock(&em_tree->lock);
6840 if (em->start > start || em->start + em->len <= start)
6841 free_extent_map(em);
6842 else if (em->block_start == EXTENT_MAP_INLINE && page)
6843 free_extent_map(em);
6847 em = alloc_extent_map();
6852 em->bdev = fs_info->fs_devices->latest_bdev;
6853 em->start = EXTENT_MAP_HOLE;
6854 em->orig_start = EXTENT_MAP_HOLE;
6856 em->block_len = (u64)-1;
6858 path = btrfs_alloc_path();
6864 /* Chances are we'll be called again, so go ahead and do readahead */
6865 path->reada = READA_FORWARD;
6868 * Unless we're going to uncompress the inline extent, no sleep would
6871 path->leave_spinning = 1;
6873 ret = btrfs_lookup_file_extent(NULL, root, path, objectid, start, 0);
6877 } else if (ret > 0) {
6878 if (path->slots[0] == 0)
6883 leaf = path->nodes[0];
6884 item = btrfs_item_ptr(leaf, path->slots[0],
6885 struct btrfs_file_extent_item);
6886 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
6887 if (found_key.objectid != objectid ||
6888 found_key.type != BTRFS_EXTENT_DATA_KEY) {
6890 * If we backup past the first extent we want to move forward
6891 * and see if there is an extent in front of us, otherwise we'll
6892 * say there is a hole for our whole search range which can
6899 extent_type = btrfs_file_extent_type(leaf, item);
6900 extent_start = found_key.offset;
6901 if (extent_type == BTRFS_FILE_EXTENT_REG ||
6902 extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
6903 /* Only regular file could have regular/prealloc extent */
6904 if (!S_ISREG(inode->vfs_inode.i_mode)) {
6907 "regular/prealloc extent found for non-regular inode %llu",
6911 extent_end = extent_start +
6912 btrfs_file_extent_num_bytes(leaf, item);
6914 trace_btrfs_get_extent_show_fi_regular(inode, leaf, item,
6916 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
6919 size = btrfs_file_extent_ram_bytes(leaf, item);
6920 extent_end = ALIGN(extent_start + size,
6921 fs_info->sectorsize);
6923 trace_btrfs_get_extent_show_fi_inline(inode, leaf, item,
6928 if (start >= extent_end) {
6930 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
6931 ret = btrfs_next_leaf(root, path);
6935 } else if (ret > 0) {
6938 leaf = path->nodes[0];
6940 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
6941 if (found_key.objectid != objectid ||
6942 found_key.type != BTRFS_EXTENT_DATA_KEY)
6944 if (start + len <= found_key.offset)
6946 if (start > found_key.offset)
6949 /* New extent overlaps with existing one */
6951 em->orig_start = start;
6952 em->len = found_key.offset - start;
6953 em->block_start = EXTENT_MAP_HOLE;
6957 btrfs_extent_item_to_extent_map(inode, path, item,
6960 if (extent_type == BTRFS_FILE_EXTENT_REG ||
6961 extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
6963 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
6967 size_t extent_offset;
6973 size = btrfs_file_extent_ram_bytes(leaf, item);
6974 extent_offset = page_offset(page) + pg_offset - extent_start;
6975 copy_size = min_t(u64, PAGE_SIZE - pg_offset,
6976 size - extent_offset);
6977 em->start = extent_start + extent_offset;
6978 em->len = ALIGN(copy_size, fs_info->sectorsize);
6979 em->orig_block_len = em->len;
6980 em->orig_start = em->start;
6981 ptr = btrfs_file_extent_inline_start(item) + extent_offset;
6983 btrfs_set_path_blocking(path);
6984 if (!PageUptodate(page)) {
6985 if (btrfs_file_extent_compression(leaf, item) !=
6986 BTRFS_COMPRESS_NONE) {
6987 ret = uncompress_inline(path, page, pg_offset,
6988 extent_offset, item);
6995 read_extent_buffer(leaf, map + pg_offset, ptr,
6997 if (pg_offset + copy_size < PAGE_SIZE) {
6998 memset(map + pg_offset + copy_size, 0,
6999 PAGE_SIZE - pg_offset -
7004 flush_dcache_page(page);
7006 set_extent_uptodate(io_tree, em->start,
7007 extent_map_end(em) - 1, NULL, GFP_NOFS);
7012 em->orig_start = start;
7014 em->block_start = EXTENT_MAP_HOLE;
7016 btrfs_release_path(path);
7017 if (em->start > start || extent_map_end(em) <= start) {
7019 "bad extent! em: [%llu %llu] passed [%llu %llu]",
7020 em->start, em->len, start, len);
7026 write_lock(&em_tree->lock);
7027 err = btrfs_add_extent_mapping(fs_info, em_tree, &em, start, len);
7028 write_unlock(&em_tree->lock);
7030 btrfs_free_path(path);
7032 trace_btrfs_get_extent(root, inode, em);
7035 free_extent_map(em);
7036 return ERR_PTR(err);
7038 BUG_ON(!em); /* Error is always set */
7042 struct extent_map *btrfs_get_extent_fiemap(struct btrfs_inode *inode,
7045 struct extent_map *em;
7046 struct extent_map *hole_em = NULL;
7047 u64 delalloc_start = start;
7053 em = btrfs_get_extent(inode, NULL, 0, start, len, 0);
7057 * If our em maps to:
7059 * - a pre-alloc extent,
7060 * there might actually be delalloc bytes behind it.
7062 if (em->block_start != EXTENT_MAP_HOLE &&
7063 !test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
7068 /* check to see if we've wrapped (len == -1 or similar) */
7077 /* ok, we didn't find anything, lets look for delalloc */
7078 delalloc_len = count_range_bits(&inode->io_tree, &delalloc_start,
7079 end, len, EXTENT_DELALLOC, 1);
7080 delalloc_end = delalloc_start + delalloc_len;
7081 if (delalloc_end < delalloc_start)
7082 delalloc_end = (u64)-1;
7085 * We didn't find anything useful, return the original results from
7088 if (delalloc_start > end || delalloc_end <= start) {
7095 * Adjust the delalloc_start to make sure it doesn't go backwards from
7096 * the start they passed in
7098 delalloc_start = max(start, delalloc_start);
7099 delalloc_len = delalloc_end - delalloc_start;
7101 if (delalloc_len > 0) {
7104 const u64 hole_end = extent_map_end(hole_em);
7106 em = alloc_extent_map();
7115 * When btrfs_get_extent can't find anything it returns one
7118 * Make sure what it found really fits our range, and adjust to
7119 * make sure it is based on the start from the caller
7121 if (hole_end <= start || hole_em->start > end) {
7122 free_extent_map(hole_em);
7125 hole_start = max(hole_em->start, start);
7126 hole_len = hole_end - hole_start;
7129 if (hole_em && delalloc_start > hole_start) {
7131 * Our hole starts before our delalloc, so we have to
7132 * return just the parts of the hole that go until the
7135 em->len = min(hole_len, delalloc_start - hole_start);
7136 em->start = hole_start;
7137 em->orig_start = hole_start;
7139 * Don't adjust block start at all, it is fixed at
7142 em->block_start = hole_em->block_start;
7143 em->block_len = hole_len;
7144 if (test_bit(EXTENT_FLAG_PREALLOC, &hole_em->flags))
7145 set_bit(EXTENT_FLAG_PREALLOC, &em->flags);
7148 * Hole is out of passed range or it starts after
7151 em->start = delalloc_start;
7152 em->len = delalloc_len;
7153 em->orig_start = delalloc_start;
7154 em->block_start = EXTENT_MAP_DELALLOC;
7155 em->block_len = delalloc_len;
7162 free_extent_map(hole_em);
7164 free_extent_map(em);
7165 return ERR_PTR(err);
7170 static struct extent_map *btrfs_create_dio_extent(struct inode *inode,
7173 const u64 orig_start,
7174 const u64 block_start,
7175 const u64 block_len,
7176 const u64 orig_block_len,
7177 const u64 ram_bytes,
7180 struct extent_map *em = NULL;
7183 if (type != BTRFS_ORDERED_NOCOW) {
7184 em = create_io_em(inode, start, len, orig_start,
7185 block_start, block_len, orig_block_len,
7187 BTRFS_COMPRESS_NONE, /* compress_type */
7192 ret = btrfs_add_ordered_extent_dio(inode, start, block_start,
7193 len, block_len, type);
7196 free_extent_map(em);
7197 btrfs_drop_extent_cache(BTRFS_I(inode), start,
7198 start + len - 1, 0);
7207 static struct extent_map *btrfs_new_extent_direct(struct inode *inode,
7210 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7211 struct btrfs_root *root = BTRFS_I(inode)->root;
7212 struct extent_map *em;
7213 struct btrfs_key ins;
7217 alloc_hint = get_extent_allocation_hint(inode, start, len);
7218 ret = btrfs_reserve_extent(root, len, len, fs_info->sectorsize,
7219 0, alloc_hint, &ins, 1, 1);
7221 return ERR_PTR(ret);
7223 em = btrfs_create_dio_extent(inode, start, ins.offset, start,
7224 ins.objectid, ins.offset, ins.offset,
7225 ins.offset, BTRFS_ORDERED_REGULAR);
7226 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
7228 btrfs_free_reserved_extent(fs_info, ins.objectid,
7235 * returns 1 when the nocow is safe, < 1 on error, 0 if the
7236 * block must be cow'd
7238 noinline int can_nocow_extent(struct inode *inode, u64 offset, u64 *len,
7239 u64 *orig_start, u64 *orig_block_len,
7242 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7243 struct btrfs_path *path;
7245 struct extent_buffer *leaf;
7246 struct btrfs_root *root = BTRFS_I(inode)->root;
7247 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
7248 struct btrfs_file_extent_item *fi;
7249 struct btrfs_key key;
7256 bool nocow = (BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW);
7258 path = btrfs_alloc_path();
7262 ret = btrfs_lookup_file_extent(NULL, root, path,
7263 btrfs_ino(BTRFS_I(inode)), offset, 0);
7267 slot = path->slots[0];
7270 /* can't find the item, must cow */
7277 leaf = path->nodes[0];
7278 btrfs_item_key_to_cpu(leaf, &key, slot);
7279 if (key.objectid != btrfs_ino(BTRFS_I(inode)) ||
7280 key.type != BTRFS_EXTENT_DATA_KEY) {
7281 /* not our file or wrong item type, must cow */
7285 if (key.offset > offset) {
7286 /* Wrong offset, must cow */
7290 fi = btrfs_item_ptr(leaf, slot, struct btrfs_file_extent_item);
7291 found_type = btrfs_file_extent_type(leaf, fi);
7292 if (found_type != BTRFS_FILE_EXTENT_REG &&
7293 found_type != BTRFS_FILE_EXTENT_PREALLOC) {
7294 /* not a regular extent, must cow */
7298 if (!nocow && found_type == BTRFS_FILE_EXTENT_REG)
7301 extent_end = key.offset + btrfs_file_extent_num_bytes(leaf, fi);
7302 if (extent_end <= offset)
7305 disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
7306 if (disk_bytenr == 0)
7309 if (btrfs_file_extent_compression(leaf, fi) ||
7310 btrfs_file_extent_encryption(leaf, fi) ||
7311 btrfs_file_extent_other_encoding(leaf, fi))
7315 * Do the same check as in btrfs_cross_ref_exist but without the
7316 * unnecessary search.
7318 if (btrfs_file_extent_generation(leaf, fi) <=
7319 btrfs_root_last_snapshot(&root->root_item))
7322 backref_offset = btrfs_file_extent_offset(leaf, fi);
7325 *orig_start = key.offset - backref_offset;
7326 *orig_block_len = btrfs_file_extent_disk_num_bytes(leaf, fi);
7327 *ram_bytes = btrfs_file_extent_ram_bytes(leaf, fi);
7330 if (btrfs_extent_readonly(fs_info, disk_bytenr))
7333 num_bytes = min(offset + *len, extent_end) - offset;
7334 if (!nocow && found_type == BTRFS_FILE_EXTENT_PREALLOC) {
7337 range_end = round_up(offset + num_bytes,
7338 root->fs_info->sectorsize) - 1;
7339 ret = test_range_bit(io_tree, offset, range_end,
7340 EXTENT_DELALLOC, 0, NULL);
7347 btrfs_release_path(path);
7350 * look for other files referencing this extent, if we
7351 * find any we must cow
7354 ret = btrfs_cross_ref_exist(root, btrfs_ino(BTRFS_I(inode)),
7355 key.offset - backref_offset, disk_bytenr);
7362 * adjust disk_bytenr and num_bytes to cover just the bytes
7363 * in this extent we are about to write. If there
7364 * are any csums in that range we have to cow in order
7365 * to keep the csums correct
7367 disk_bytenr += backref_offset;
7368 disk_bytenr += offset - key.offset;
7369 if (csum_exist_in_range(fs_info, disk_bytenr, num_bytes))
7372 * all of the above have passed, it is safe to overwrite this extent
7378 btrfs_free_path(path);
7382 static int lock_extent_direct(struct inode *inode, u64 lockstart, u64 lockend,
7383 struct extent_state **cached_state, int writing)
7385 struct btrfs_ordered_extent *ordered;
7389 lock_extent_bits(&BTRFS_I(inode)->io_tree, lockstart, lockend,
7392 * We're concerned with the entire range that we're going to be
7393 * doing DIO to, so we need to make sure there's no ordered
7394 * extents in this range.
7396 ordered = btrfs_lookup_ordered_range(BTRFS_I(inode), lockstart,
7397 lockend - lockstart + 1);
7400 * We need to make sure there are no buffered pages in this
7401 * range either, we could have raced between the invalidate in
7402 * generic_file_direct_write and locking the extent. The
7403 * invalidate needs to happen so that reads after a write do not
7407 (!writing || !filemap_range_has_page(inode->i_mapping,
7408 lockstart, lockend)))
7411 unlock_extent_cached(&BTRFS_I(inode)->io_tree, lockstart, lockend,
7416 * If we are doing a DIO read and the ordered extent we
7417 * found is for a buffered write, we can not wait for it
7418 * to complete and retry, because if we do so we can
7419 * deadlock with concurrent buffered writes on page
7420 * locks. This happens only if our DIO read covers more
7421 * than one extent map, if at this point has already
7422 * created an ordered extent for a previous extent map
7423 * and locked its range in the inode's io tree, and a
7424 * concurrent write against that previous extent map's
7425 * range and this range started (we unlock the ranges
7426 * in the io tree only when the bios complete and
7427 * buffered writes always lock pages before attempting
7428 * to lock range in the io tree).
7431 test_bit(BTRFS_ORDERED_DIRECT, &ordered->flags))
7432 btrfs_start_ordered_extent(inode, ordered, 1);
7435 btrfs_put_ordered_extent(ordered);
7438 * We could trigger writeback for this range (and wait
7439 * for it to complete) and then invalidate the pages for
7440 * this range (through invalidate_inode_pages2_range()),
7441 * but that can lead us to a deadlock with a concurrent
7442 * call to readpages() (a buffered read or a defrag call
7443 * triggered a readahead) on a page lock due to an
7444 * ordered dio extent we created before but did not have
7445 * yet a corresponding bio submitted (whence it can not
7446 * complete), which makes readpages() wait for that
7447 * ordered extent to complete while holding a lock on
7462 /* The callers of this must take lock_extent() */
7463 static struct extent_map *create_io_em(struct inode *inode, u64 start, u64 len,
7464 u64 orig_start, u64 block_start,
7465 u64 block_len, u64 orig_block_len,
7466 u64 ram_bytes, int compress_type,
7469 struct extent_map_tree *em_tree;
7470 struct extent_map *em;
7471 struct btrfs_root *root = BTRFS_I(inode)->root;
7474 ASSERT(type == BTRFS_ORDERED_PREALLOC ||
7475 type == BTRFS_ORDERED_COMPRESSED ||
7476 type == BTRFS_ORDERED_NOCOW ||
7477 type == BTRFS_ORDERED_REGULAR);
7479 em_tree = &BTRFS_I(inode)->extent_tree;
7480 em = alloc_extent_map();
7482 return ERR_PTR(-ENOMEM);
7485 em->orig_start = orig_start;
7487 em->block_len = block_len;
7488 em->block_start = block_start;
7489 em->bdev = root->fs_info->fs_devices->latest_bdev;
7490 em->orig_block_len = orig_block_len;
7491 em->ram_bytes = ram_bytes;
7492 em->generation = -1;
7493 set_bit(EXTENT_FLAG_PINNED, &em->flags);
7494 if (type == BTRFS_ORDERED_PREALLOC) {
7495 set_bit(EXTENT_FLAG_FILLING, &em->flags);
7496 } else if (type == BTRFS_ORDERED_COMPRESSED) {
7497 set_bit(EXTENT_FLAG_COMPRESSED, &em->flags);
7498 em->compress_type = compress_type;
7502 btrfs_drop_extent_cache(BTRFS_I(inode), em->start,
7503 em->start + em->len - 1, 0);
7504 write_lock(&em_tree->lock);
7505 ret = add_extent_mapping(em_tree, em, 1);
7506 write_unlock(&em_tree->lock);
7508 * The caller has taken lock_extent(), who could race with us
7511 } while (ret == -EEXIST);
7514 free_extent_map(em);
7515 return ERR_PTR(ret);
7518 /* em got 2 refs now, callers needs to do free_extent_map once. */
7523 static int btrfs_get_blocks_direct_read(struct extent_map *em,
7524 struct buffer_head *bh_result,
7525 struct inode *inode,
7528 if (em->block_start == EXTENT_MAP_HOLE ||
7529 test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
7532 len = min(len, em->len - (start - em->start));
7534 bh_result->b_blocknr = (em->block_start + (start - em->start)) >>
7536 bh_result->b_size = len;
7537 bh_result->b_bdev = em->bdev;
7538 set_buffer_mapped(bh_result);
7543 static int btrfs_get_blocks_direct_write(struct extent_map **map,
7544 struct buffer_head *bh_result,
7545 struct inode *inode,
7546 struct btrfs_dio_data *dio_data,
7549 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7550 struct extent_map *em = *map;
7554 * We don't allocate a new extent in the following cases
7556 * 1) The inode is marked as NODATACOW. In this case we'll just use the
7558 * 2) The extent is marked as PREALLOC. We're good to go here and can
7559 * just use the extent.
7562 if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags) ||
7563 ((BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW) &&
7564 em->block_start != EXTENT_MAP_HOLE)) {
7566 u64 block_start, orig_start, orig_block_len, ram_bytes;
7568 if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
7569 type = BTRFS_ORDERED_PREALLOC;
7571 type = BTRFS_ORDERED_NOCOW;
7572 len = min(len, em->len - (start - em->start));
7573 block_start = em->block_start + (start - em->start);
7575 if (can_nocow_extent(inode, start, &len, &orig_start,
7576 &orig_block_len, &ram_bytes) == 1 &&
7577 btrfs_inc_nocow_writers(fs_info, block_start)) {
7578 struct extent_map *em2;
7580 em2 = btrfs_create_dio_extent(inode, start, len,
7581 orig_start, block_start,
7582 len, orig_block_len,
7584 btrfs_dec_nocow_writers(fs_info, block_start);
7585 if (type == BTRFS_ORDERED_PREALLOC) {
7586 free_extent_map(em);
7590 if (em2 && IS_ERR(em2)) {
7595 * For inode marked NODATACOW or extent marked PREALLOC,
7596 * use the existing or preallocated extent, so does not
7597 * need to adjust btrfs_space_info's bytes_may_use.
7599 btrfs_free_reserved_data_space_noquota(inode, start,
7605 /* this will cow the extent */
7606 len = bh_result->b_size;
7607 free_extent_map(em);
7608 *map = em = btrfs_new_extent_direct(inode, start, len);
7614 len = min(len, em->len - (start - em->start));
7617 bh_result->b_blocknr = (em->block_start + (start - em->start)) >>
7619 bh_result->b_size = len;
7620 bh_result->b_bdev = em->bdev;
7621 set_buffer_mapped(bh_result);
7623 if (!test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
7624 set_buffer_new(bh_result);
7627 * Need to update the i_size under the extent lock so buffered
7628 * readers will get the updated i_size when we unlock.
7630 if (!dio_data->overwrite && start + len > i_size_read(inode))
7631 i_size_write(inode, start + len);
7633 WARN_ON(dio_data->reserve < len);
7634 dio_data->reserve -= len;
7635 dio_data->unsubmitted_oe_range_end = start + len;
7636 current->journal_info = dio_data;
7641 static int btrfs_get_blocks_direct(struct inode *inode, sector_t iblock,
7642 struct buffer_head *bh_result, int create)
7644 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7645 struct extent_map *em;
7646 struct extent_state *cached_state = NULL;
7647 struct btrfs_dio_data *dio_data = NULL;
7648 u64 start = iblock << inode->i_blkbits;
7649 u64 lockstart, lockend;
7650 u64 len = bh_result->b_size;
7651 int unlock_bits = EXTENT_LOCKED;
7655 unlock_bits |= EXTENT_DIRTY;
7657 len = min_t(u64, len, fs_info->sectorsize);
7660 lockend = start + len - 1;
7662 if (current->journal_info) {
7664 * Need to pull our outstanding extents and set journal_info to NULL so
7665 * that anything that needs to check if there's a transaction doesn't get
7668 dio_data = current->journal_info;
7669 current->journal_info = NULL;
7673 * If this errors out it's because we couldn't invalidate pagecache for
7674 * this range and we need to fallback to buffered.
7676 if (lock_extent_direct(inode, lockstart, lockend, &cached_state,
7682 em = btrfs_get_extent(BTRFS_I(inode), NULL, 0, start, len, 0);
7689 * Ok for INLINE and COMPRESSED extents we need to fallback on buffered
7690 * io. INLINE is special, and we could probably kludge it in here, but
7691 * it's still buffered so for safety lets just fall back to the generic
7694 * For COMPRESSED we _have_ to read the entire extent in so we can
7695 * decompress it, so there will be buffering required no matter what we
7696 * do, so go ahead and fallback to buffered.
7698 * We return -ENOTBLK because that's what makes DIO go ahead and go back
7699 * to buffered IO. Don't blame me, this is the price we pay for using
7702 if (test_bit(EXTENT_FLAG_COMPRESSED, &em->flags) ||
7703 em->block_start == EXTENT_MAP_INLINE) {
7704 free_extent_map(em);
7710 ret = btrfs_get_blocks_direct_write(&em, bh_result, inode,
7711 dio_data, start, len);
7715 /* clear and unlock the entire range */
7716 clear_extent_bit(&BTRFS_I(inode)->io_tree, lockstart, lockend,
7717 unlock_bits, 1, 0, &cached_state);
7719 ret = btrfs_get_blocks_direct_read(em, bh_result, inode,
7721 /* Can be negative only if we read from a hole */
7724 free_extent_map(em);
7728 * We need to unlock only the end area that we aren't using.
7729 * The rest is going to be unlocked by the endio routine.
7731 lockstart = start + bh_result->b_size;
7732 if (lockstart < lockend) {
7733 clear_extent_bit(&BTRFS_I(inode)->io_tree, lockstart,
7734 lockend, unlock_bits, 1, 0,
7737 free_extent_state(cached_state);
7741 free_extent_map(em);
7746 clear_extent_bit(&BTRFS_I(inode)->io_tree, lockstart, lockend,
7747 unlock_bits, 1, 0, &cached_state);
7750 current->journal_info = dio_data;
7754 static inline blk_status_t submit_dio_repair_bio(struct inode *inode,
7758 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7761 BUG_ON(bio_op(bio) == REQ_OP_WRITE);
7763 ret = btrfs_bio_wq_end_io(fs_info, bio, BTRFS_WQ_ENDIO_DIO_REPAIR);
7767 ret = btrfs_map_bio(fs_info, bio, mirror_num, 0);
7772 static int btrfs_check_dio_repairable(struct inode *inode,
7773 struct bio *failed_bio,
7774 struct io_failure_record *failrec,
7777 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7780 num_copies = btrfs_num_copies(fs_info, failrec->logical, failrec->len);
7781 if (num_copies == 1) {
7783 * we only have a single copy of the data, so don't bother with
7784 * all the retry and error correction code that follows. no
7785 * matter what the error is, it is very likely to persist.
7787 btrfs_debug(fs_info,
7788 "Check DIO Repairable: cannot repair, num_copies=%d, next_mirror %d, failed_mirror %d",
7789 num_copies, failrec->this_mirror, failed_mirror);
7793 failrec->failed_mirror = failed_mirror;
7794 failrec->this_mirror++;
7795 if (failrec->this_mirror == failed_mirror)
7796 failrec->this_mirror++;
7798 if (failrec->this_mirror > num_copies) {
7799 btrfs_debug(fs_info,
7800 "Check DIO Repairable: (fail) num_copies=%d, next_mirror %d, failed_mirror %d",
7801 num_copies, failrec->this_mirror, failed_mirror);
7808 static blk_status_t dio_read_error(struct inode *inode, struct bio *failed_bio,
7809 struct page *page, unsigned int pgoff,
7810 u64 start, u64 end, int failed_mirror,
7811 bio_end_io_t *repair_endio, void *repair_arg)
7813 struct io_failure_record *failrec;
7814 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
7815 struct extent_io_tree *failure_tree = &BTRFS_I(inode)->io_failure_tree;
7818 unsigned int read_mode = 0;
7821 blk_status_t status;
7822 struct bio_vec bvec;
7824 BUG_ON(bio_op(failed_bio) == REQ_OP_WRITE);
7826 ret = btrfs_get_io_failure_record(inode, start, end, &failrec);
7828 return errno_to_blk_status(ret);
7830 ret = btrfs_check_dio_repairable(inode, failed_bio, failrec,
7833 free_io_failure(failure_tree, io_tree, failrec);
7834 return BLK_STS_IOERR;
7837 segs = bio_segments(failed_bio);
7838 bio_get_first_bvec(failed_bio, &bvec);
7840 (bvec.bv_len > btrfs_inode_sectorsize(inode)))
7841 read_mode |= REQ_FAILFAST_DEV;
7843 isector = start - btrfs_io_bio(failed_bio)->logical;
7844 isector >>= inode->i_sb->s_blocksize_bits;
7845 bio = btrfs_create_repair_bio(inode, failed_bio, failrec, page,
7846 pgoff, isector, repair_endio, repair_arg);
7847 bio->bi_opf = REQ_OP_READ | read_mode;
7849 btrfs_debug(BTRFS_I(inode)->root->fs_info,
7850 "repair DIO read error: submitting new dio read[%#x] to this_mirror=%d, in_validation=%d",
7851 read_mode, failrec->this_mirror, failrec->in_validation);
7853 status = submit_dio_repair_bio(inode, bio, failrec->this_mirror);
7855 free_io_failure(failure_tree, io_tree, failrec);
7862 struct btrfs_retry_complete {
7863 struct completion done;
7864 struct inode *inode;
7869 static void btrfs_retry_endio_nocsum(struct bio *bio)
7871 struct btrfs_retry_complete *done = bio->bi_private;
7872 struct inode *inode = done->inode;
7873 struct bio_vec *bvec;
7874 struct extent_io_tree *io_tree, *failure_tree;
7875 struct bvec_iter_all iter_all;
7880 ASSERT(bio->bi_vcnt == 1);
7881 io_tree = &BTRFS_I(inode)->io_tree;
7882 failure_tree = &BTRFS_I(inode)->io_failure_tree;
7883 ASSERT(bio_first_bvec_all(bio)->bv_len == btrfs_inode_sectorsize(inode));
7886 ASSERT(!bio_flagged(bio, BIO_CLONED));
7887 bio_for_each_segment_all(bvec, bio, iter_all)
7888 clean_io_failure(BTRFS_I(inode)->root->fs_info, failure_tree,
7889 io_tree, done->start, bvec->bv_page,
7890 btrfs_ino(BTRFS_I(inode)), 0);
7892 complete(&done->done);
7896 static blk_status_t __btrfs_correct_data_nocsum(struct inode *inode,
7897 struct btrfs_io_bio *io_bio)
7899 struct btrfs_fs_info *fs_info;
7900 struct bio_vec bvec;
7901 struct bvec_iter iter;
7902 struct btrfs_retry_complete done;
7908 blk_status_t err = BLK_STS_OK;
7910 fs_info = BTRFS_I(inode)->root->fs_info;
7911 sectorsize = fs_info->sectorsize;
7913 start = io_bio->logical;
7915 io_bio->bio.bi_iter = io_bio->iter;
7917 bio_for_each_segment(bvec, &io_bio->bio, iter) {
7918 nr_sectors = BTRFS_BYTES_TO_BLKS(fs_info, bvec.bv_len);
7919 pgoff = bvec.bv_offset;
7921 next_block_or_try_again:
7924 init_completion(&done.done);
7926 ret = dio_read_error(inode, &io_bio->bio, bvec.bv_page,
7927 pgoff, start, start + sectorsize - 1,
7929 btrfs_retry_endio_nocsum, &done);
7935 wait_for_completion_io(&done.done);
7937 if (!done.uptodate) {
7938 /* We might have another mirror, so try again */
7939 goto next_block_or_try_again;
7943 start += sectorsize;
7947 pgoff += sectorsize;
7948 ASSERT(pgoff < PAGE_SIZE);
7949 goto next_block_or_try_again;
7956 static void btrfs_retry_endio(struct bio *bio)
7958 struct btrfs_retry_complete *done = bio->bi_private;
7959 struct btrfs_io_bio *io_bio = btrfs_io_bio(bio);
7960 struct extent_io_tree *io_tree, *failure_tree;
7961 struct inode *inode = done->inode;
7962 struct bio_vec *bvec;
7966 struct bvec_iter_all iter_all;
7973 ASSERT(bio->bi_vcnt == 1);
7974 ASSERT(bio_first_bvec_all(bio)->bv_len == btrfs_inode_sectorsize(done->inode));
7976 io_tree = &BTRFS_I(inode)->io_tree;
7977 failure_tree = &BTRFS_I(inode)->io_failure_tree;
7979 ASSERT(!bio_flagged(bio, BIO_CLONED));
7980 bio_for_each_segment_all(bvec, bio, iter_all) {
7981 ret = __readpage_endio_check(inode, io_bio, i, bvec->bv_page,
7982 bvec->bv_offset, done->start,
7985 clean_io_failure(BTRFS_I(inode)->root->fs_info,
7986 failure_tree, io_tree, done->start,
7988 btrfs_ino(BTRFS_I(inode)),
7995 done->uptodate = uptodate;
7997 complete(&done->done);
8001 static blk_status_t __btrfs_subio_endio_read(struct inode *inode,
8002 struct btrfs_io_bio *io_bio, blk_status_t err)
8004 struct btrfs_fs_info *fs_info;
8005 struct bio_vec bvec;
8006 struct bvec_iter iter;
8007 struct btrfs_retry_complete done;
8014 bool uptodate = (err == 0);
8016 blk_status_t status;
8018 fs_info = BTRFS_I(inode)->root->fs_info;
8019 sectorsize = fs_info->sectorsize;
8022 start = io_bio->logical;
8024 io_bio->bio.bi_iter = io_bio->iter;
8026 bio_for_each_segment(bvec, &io_bio->bio, iter) {
8027 nr_sectors = BTRFS_BYTES_TO_BLKS(fs_info, bvec.bv_len);
8029 pgoff = bvec.bv_offset;
8032 csum_pos = BTRFS_BYTES_TO_BLKS(fs_info, offset);
8033 ret = __readpage_endio_check(inode, io_bio, csum_pos,
8034 bvec.bv_page, pgoff, start, sectorsize);
8041 init_completion(&done.done);
8043 status = dio_read_error(inode, &io_bio->bio, bvec.bv_page,
8044 pgoff, start, start + sectorsize - 1,
8045 io_bio->mirror_num, btrfs_retry_endio,
8052 wait_for_completion_io(&done.done);
8054 if (!done.uptodate) {
8055 /* We might have another mirror, so try again */
8059 offset += sectorsize;
8060 start += sectorsize;
8066 pgoff += sectorsize;
8067 ASSERT(pgoff < PAGE_SIZE);
8075 static blk_status_t btrfs_subio_endio_read(struct inode *inode,
8076 struct btrfs_io_bio *io_bio, blk_status_t err)
8078 bool skip_csum = BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM;
8082 return __btrfs_correct_data_nocsum(inode, io_bio);
8086 return __btrfs_subio_endio_read(inode, io_bio, err);
8090 static void btrfs_endio_direct_read(struct bio *bio)
8092 struct btrfs_dio_private *dip = bio->bi_private;
8093 struct inode *inode = dip->inode;
8094 struct bio *dio_bio;
8095 struct btrfs_io_bio *io_bio = btrfs_io_bio(bio);
8096 blk_status_t err = bio->bi_status;
8098 if (dip->flags & BTRFS_DIO_ORIG_BIO_SUBMITTED)
8099 err = btrfs_subio_endio_read(inode, io_bio, err);
8101 unlock_extent(&BTRFS_I(inode)->io_tree, dip->logical_offset,
8102 dip->logical_offset + dip->bytes - 1);
8103 dio_bio = dip->dio_bio;
8107 dio_bio->bi_status = err;
8108 dio_end_io(dio_bio);
8109 btrfs_io_bio_free_csum(io_bio);
8113 static void __endio_write_update_ordered(struct inode *inode,
8114 const u64 offset, const u64 bytes,
8115 const bool uptodate)
8117 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
8118 struct btrfs_ordered_extent *ordered = NULL;
8119 struct btrfs_workqueue *wq;
8120 btrfs_work_func_t func;
8121 u64 ordered_offset = offset;
8122 u64 ordered_bytes = bytes;
8125 if (btrfs_is_free_space_inode(BTRFS_I(inode))) {
8126 wq = fs_info->endio_freespace_worker;
8127 func = btrfs_freespace_write_helper;
8129 wq = fs_info->endio_write_workers;
8130 func = btrfs_endio_write_helper;
8133 while (ordered_offset < offset + bytes) {
8134 last_offset = ordered_offset;
8135 if (btrfs_dec_test_first_ordered_pending(inode, &ordered,
8139 btrfs_init_work(&ordered->work, func,
8142 btrfs_queue_work(wq, &ordered->work);
8145 * If btrfs_dec_test_ordered_pending does not find any ordered
8146 * extent in the range, we can exit.
8148 if (ordered_offset == last_offset)
8151 * Our bio might span multiple ordered extents. In this case
8152 * we keep going until we have accounted the whole dio.
8154 if (ordered_offset < offset + bytes) {
8155 ordered_bytes = offset + bytes - ordered_offset;
8161 static void btrfs_endio_direct_write(struct bio *bio)
8163 struct btrfs_dio_private *dip = bio->bi_private;
8164 struct bio *dio_bio = dip->dio_bio;
8166 __endio_write_update_ordered(dip->inode, dip->logical_offset,
8167 dip->bytes, !bio->bi_status);
8171 dio_bio->bi_status = bio->bi_status;
8172 dio_end_io(dio_bio);
8176 static blk_status_t btrfs_submit_bio_start_direct_io(void *private_data,
8177 struct bio *bio, u64 offset)
8179 struct inode *inode = private_data;
8181 ret = btrfs_csum_one_bio(inode, bio, offset, 1);
8182 BUG_ON(ret); /* -ENOMEM */
8186 static void btrfs_end_dio_bio(struct bio *bio)
8188 struct btrfs_dio_private *dip = bio->bi_private;
8189 blk_status_t err = bio->bi_status;
8192 btrfs_warn(BTRFS_I(dip->inode)->root->fs_info,
8193 "direct IO failed ino %llu rw %d,%u sector %#Lx len %u err no %d",
8194 btrfs_ino(BTRFS_I(dip->inode)), bio_op(bio),
8196 (unsigned long long)bio->bi_iter.bi_sector,
8197 bio->bi_iter.bi_size, err);
8199 if (dip->subio_endio)
8200 err = dip->subio_endio(dip->inode, btrfs_io_bio(bio), err);
8204 * We want to perceive the errors flag being set before
8205 * decrementing the reference count. We don't need a barrier
8206 * since atomic operations with a return value are fully
8207 * ordered as per atomic_t.txt
8212 /* if there are more bios still pending for this dio, just exit */
8213 if (!atomic_dec_and_test(&dip->pending_bios))
8217 bio_io_error(dip->orig_bio);
8219 dip->dio_bio->bi_status = BLK_STS_OK;
8220 bio_endio(dip->orig_bio);
8226 static inline blk_status_t btrfs_lookup_and_bind_dio_csum(struct inode *inode,
8227 struct btrfs_dio_private *dip,
8231 struct btrfs_io_bio *io_bio = btrfs_io_bio(bio);
8232 struct btrfs_io_bio *orig_io_bio = btrfs_io_bio(dip->orig_bio);
8236 * We load all the csum data we need when we submit
8237 * the first bio to reduce the csum tree search and
8240 if (dip->logical_offset == file_offset) {
8241 ret = btrfs_lookup_bio_sums_dio(inode, dip->orig_bio,
8247 if (bio == dip->orig_bio)
8250 file_offset -= dip->logical_offset;
8251 file_offset >>= inode->i_sb->s_blocksize_bits;
8252 io_bio->csum = (u8 *)(((u32 *)orig_io_bio->csum) + file_offset);
8257 static inline blk_status_t btrfs_submit_dio_bio(struct bio *bio,
8258 struct inode *inode, u64 file_offset, int async_submit)
8260 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
8261 struct btrfs_dio_private *dip = bio->bi_private;
8262 bool write = bio_op(bio) == REQ_OP_WRITE;
8265 /* Check btrfs_submit_bio_hook() for rules about async submit. */
8267 async_submit = !atomic_read(&BTRFS_I(inode)->sync_writers);
8270 ret = btrfs_bio_wq_end_io(fs_info, bio, BTRFS_WQ_ENDIO_DATA);
8275 if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)
8278 if (write && async_submit) {
8279 ret = btrfs_wq_submit_bio(fs_info, bio, 0, 0,
8281 btrfs_submit_bio_start_direct_io);
8285 * If we aren't doing async submit, calculate the csum of the
8288 ret = btrfs_csum_one_bio(inode, bio, file_offset, 1);
8292 ret = btrfs_lookup_and_bind_dio_csum(inode, dip, bio,
8298 ret = btrfs_map_bio(fs_info, bio, 0, 0);
8303 static int btrfs_submit_direct_hook(struct btrfs_dio_private *dip)
8305 struct inode *inode = dip->inode;
8306 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
8308 struct bio *orig_bio = dip->orig_bio;
8309 u64 start_sector = orig_bio->bi_iter.bi_sector;
8310 u64 file_offset = dip->logical_offset;
8312 int async_submit = 0;
8314 int clone_offset = 0;
8317 blk_status_t status;
8319 map_length = orig_bio->bi_iter.bi_size;
8320 submit_len = map_length;
8321 ret = btrfs_map_block(fs_info, btrfs_op(orig_bio), start_sector << 9,
8322 &map_length, NULL, 0);
8326 if (map_length >= submit_len) {
8328 dip->flags |= BTRFS_DIO_ORIG_BIO_SUBMITTED;
8332 /* async crcs make it difficult to collect full stripe writes. */
8333 if (btrfs_data_alloc_profile(fs_info) & BTRFS_BLOCK_GROUP_RAID56_MASK)
8339 ASSERT(map_length <= INT_MAX);
8340 atomic_inc(&dip->pending_bios);
8342 clone_len = min_t(int, submit_len, map_length);
8345 * This will never fail as it's passing GPF_NOFS and
8346 * the allocation is backed by btrfs_bioset.
8348 bio = btrfs_bio_clone_partial(orig_bio, clone_offset,
8350 bio->bi_private = dip;
8351 bio->bi_end_io = btrfs_end_dio_bio;
8352 btrfs_io_bio(bio)->logical = file_offset;
8354 ASSERT(submit_len >= clone_len);
8355 submit_len -= clone_len;
8356 if (submit_len == 0)
8360 * Increase the count before we submit the bio so we know
8361 * the end IO handler won't happen before we increase the
8362 * count. Otherwise, the dip might get freed before we're
8363 * done setting it up.
8365 atomic_inc(&dip->pending_bios);
8367 status = btrfs_submit_dio_bio(bio, inode, file_offset,
8371 atomic_dec(&dip->pending_bios);
8375 clone_offset += clone_len;
8376 start_sector += clone_len >> 9;
8377 file_offset += clone_len;
8379 map_length = submit_len;
8380 ret = btrfs_map_block(fs_info, btrfs_op(orig_bio),
8381 start_sector << 9, &map_length, NULL, 0);
8384 } while (submit_len > 0);
8387 status = btrfs_submit_dio_bio(bio, inode, file_offset, async_submit);
8395 * Before atomic variable goto zero, we must make sure dip->errors is
8396 * perceived to be set. This ordering is ensured by the fact that an
8397 * atomic operations with a return value are fully ordered as per
8400 if (atomic_dec_and_test(&dip->pending_bios))
8401 bio_io_error(dip->orig_bio);
8403 /* bio_end_io() will handle error, so we needn't return it */
8407 static void btrfs_submit_direct(struct bio *dio_bio, struct inode *inode,
8410 struct btrfs_dio_private *dip = NULL;
8411 struct bio *bio = NULL;
8412 struct btrfs_io_bio *io_bio;
8413 bool write = (bio_op(dio_bio) == REQ_OP_WRITE);
8416 bio = btrfs_bio_clone(dio_bio);
8418 dip = kzalloc(sizeof(*dip), GFP_NOFS);
8424 dip->private = dio_bio->bi_private;
8426 dip->logical_offset = file_offset;
8427 dip->bytes = dio_bio->bi_iter.bi_size;
8428 dip->disk_bytenr = (u64)dio_bio->bi_iter.bi_sector << 9;
8429 bio->bi_private = dip;
8430 dip->orig_bio = bio;
8431 dip->dio_bio = dio_bio;
8432 atomic_set(&dip->pending_bios, 0);
8433 io_bio = btrfs_io_bio(bio);
8434 io_bio->logical = file_offset;
8437 bio->bi_end_io = btrfs_endio_direct_write;
8439 bio->bi_end_io = btrfs_endio_direct_read;
8440 dip->subio_endio = btrfs_subio_endio_read;
8444 * Reset the range for unsubmitted ordered extents (to a 0 length range)
8445 * even if we fail to submit a bio, because in such case we do the
8446 * corresponding error handling below and it must not be done a second
8447 * time by btrfs_direct_IO().
8450 struct btrfs_dio_data *dio_data = current->journal_info;
8452 dio_data->unsubmitted_oe_range_end = dip->logical_offset +
8454 dio_data->unsubmitted_oe_range_start =
8455 dio_data->unsubmitted_oe_range_end;
8458 ret = btrfs_submit_direct_hook(dip);
8462 btrfs_io_bio_free_csum(io_bio);
8466 * If we arrived here it means either we failed to submit the dip
8467 * or we either failed to clone the dio_bio or failed to allocate the
8468 * dip. If we cloned the dio_bio and allocated the dip, we can just
8469 * call bio_endio against our io_bio so that we get proper resource
8470 * cleanup if we fail to submit the dip, otherwise, we must do the
8471 * same as btrfs_endio_direct_[write|read] because we can't call these
8472 * callbacks - they require an allocated dip and a clone of dio_bio.
8477 * The end io callbacks free our dip, do the final put on bio
8478 * and all the cleanup and final put for dio_bio (through
8485 __endio_write_update_ordered(inode,
8487 dio_bio->bi_iter.bi_size,
8490 unlock_extent(&BTRFS_I(inode)->io_tree, file_offset,
8491 file_offset + dio_bio->bi_iter.bi_size - 1);
8493 dio_bio->bi_status = BLK_STS_IOERR;
8495 * Releases and cleans up our dio_bio, no need to bio_put()
8496 * nor bio_endio()/bio_io_error() against dio_bio.
8498 dio_end_io(dio_bio);
8505 static ssize_t check_direct_IO(struct btrfs_fs_info *fs_info,
8506 const struct iov_iter *iter, loff_t offset)
8510 unsigned int blocksize_mask = fs_info->sectorsize - 1;
8511 ssize_t retval = -EINVAL;
8513 if (offset & blocksize_mask)
8516 if (iov_iter_alignment(iter) & blocksize_mask)
8519 /* If this is a write we don't need to check anymore */
8520 if (iov_iter_rw(iter) != READ || !iter_is_iovec(iter))
8523 * Check to make sure we don't have duplicate iov_base's in this
8524 * iovec, if so return EINVAL, otherwise we'll get csum errors
8525 * when reading back.
8527 for (seg = 0; seg < iter->nr_segs; seg++) {
8528 for (i = seg + 1; i < iter->nr_segs; i++) {
8529 if (iter->iov[seg].iov_base == iter->iov[i].iov_base)
8538 static ssize_t btrfs_direct_IO(struct kiocb *iocb, struct iov_iter *iter)
8540 struct file *file = iocb->ki_filp;
8541 struct inode *inode = file->f_mapping->host;
8542 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
8543 struct btrfs_dio_data dio_data = { 0 };
8544 struct extent_changeset *data_reserved = NULL;
8545 loff_t offset = iocb->ki_pos;
8549 bool relock = false;
8552 if (check_direct_IO(fs_info, iter, offset))
8555 inode_dio_begin(inode);
8558 * The generic stuff only does filemap_write_and_wait_range, which
8559 * isn't enough if we've written compressed pages to this area, so
8560 * we need to flush the dirty pages again to make absolutely sure
8561 * that any outstanding dirty pages are on disk.
8563 count = iov_iter_count(iter);
8564 if (test_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
8565 &BTRFS_I(inode)->runtime_flags))
8566 filemap_fdatawrite_range(inode->i_mapping, offset,
8567 offset + count - 1);
8569 if (iov_iter_rw(iter) == WRITE) {
8571 * If the write DIO is beyond the EOF, we need update
8572 * the isize, but it is protected by i_mutex. So we can
8573 * not unlock the i_mutex at this case.
8575 if (offset + count <= inode->i_size) {
8576 dio_data.overwrite = 1;
8577 inode_unlock(inode);
8579 } else if (iocb->ki_flags & IOCB_NOWAIT) {
8583 ret = btrfs_delalloc_reserve_space(inode, &data_reserved,
8589 * We need to know how many extents we reserved so that we can
8590 * do the accounting properly if we go over the number we
8591 * originally calculated. Abuse current->journal_info for this.
8593 dio_data.reserve = round_up(count,
8594 fs_info->sectorsize);
8595 dio_data.unsubmitted_oe_range_start = (u64)offset;
8596 dio_data.unsubmitted_oe_range_end = (u64)offset;
8597 current->journal_info = &dio_data;
8598 down_read(&BTRFS_I(inode)->dio_sem);
8599 } else if (test_bit(BTRFS_INODE_READDIO_NEED_LOCK,
8600 &BTRFS_I(inode)->runtime_flags)) {
8601 inode_dio_end(inode);
8602 flags = DIO_LOCKING | DIO_SKIP_HOLES;
8606 ret = __blockdev_direct_IO(iocb, inode,
8607 fs_info->fs_devices->latest_bdev,
8608 iter, btrfs_get_blocks_direct, NULL,
8609 btrfs_submit_direct, flags);
8610 if (iov_iter_rw(iter) == WRITE) {
8611 up_read(&BTRFS_I(inode)->dio_sem);
8612 current->journal_info = NULL;
8613 if (ret < 0 && ret != -EIOCBQUEUED) {
8614 if (dio_data.reserve)
8615 btrfs_delalloc_release_space(inode, data_reserved,
8616 offset, dio_data.reserve, true);
8618 * On error we might have left some ordered extents
8619 * without submitting corresponding bios for them, so
8620 * cleanup them up to avoid other tasks getting them
8621 * and waiting for them to complete forever.
8623 if (dio_data.unsubmitted_oe_range_start <
8624 dio_data.unsubmitted_oe_range_end)
8625 __endio_write_update_ordered(inode,
8626 dio_data.unsubmitted_oe_range_start,
8627 dio_data.unsubmitted_oe_range_end -
8628 dio_data.unsubmitted_oe_range_start,
8630 } else if (ret >= 0 && (size_t)ret < count)
8631 btrfs_delalloc_release_space(inode, data_reserved,
8632 offset, count - (size_t)ret, true);
8633 btrfs_delalloc_release_extents(BTRFS_I(inode), count, false);
8637 inode_dio_end(inode);
8641 extent_changeset_free(data_reserved);
8645 #define BTRFS_FIEMAP_FLAGS (FIEMAP_FLAG_SYNC)
8647 static int btrfs_fiemap(struct inode *inode, struct fiemap_extent_info *fieinfo,
8648 __u64 start, __u64 len)
8652 ret = fiemap_check_flags(fieinfo, BTRFS_FIEMAP_FLAGS);
8656 return extent_fiemap(inode, fieinfo, start, len);
8659 int btrfs_readpage(struct file *file, struct page *page)
8661 struct extent_io_tree *tree;
8662 tree = &BTRFS_I(page->mapping->host)->io_tree;
8663 return extent_read_full_page(tree, page, btrfs_get_extent, 0);
8666 static int btrfs_writepage(struct page *page, struct writeback_control *wbc)
8668 struct inode *inode = page->mapping->host;
8671 if (current->flags & PF_MEMALLOC) {
8672 redirty_page_for_writepage(wbc, page);
8678 * If we are under memory pressure we will call this directly from the
8679 * VM, we need to make sure we have the inode referenced for the ordered
8680 * extent. If not just return like we didn't do anything.
8682 if (!igrab(inode)) {
8683 redirty_page_for_writepage(wbc, page);
8684 return AOP_WRITEPAGE_ACTIVATE;
8686 ret = extent_write_full_page(page, wbc);
8687 btrfs_add_delayed_iput(inode);
8691 static int btrfs_writepages(struct address_space *mapping,
8692 struct writeback_control *wbc)
8694 return extent_writepages(mapping, wbc);
8698 btrfs_readpages(struct file *file, struct address_space *mapping,
8699 struct list_head *pages, unsigned nr_pages)
8701 return extent_readpages(mapping, pages, nr_pages);
8704 static int __btrfs_releasepage(struct page *page, gfp_t gfp_flags)
8706 int ret = try_release_extent_mapping(page, gfp_flags);
8708 ClearPagePrivate(page);
8709 set_page_private(page, 0);
8715 static int btrfs_releasepage(struct page *page, gfp_t gfp_flags)
8717 if (PageWriteback(page) || PageDirty(page))
8719 return __btrfs_releasepage(page, gfp_flags);
8722 static void btrfs_invalidatepage(struct page *page, unsigned int offset,
8723 unsigned int length)
8725 struct inode *inode = page->mapping->host;
8726 struct extent_io_tree *tree;
8727 struct btrfs_ordered_extent *ordered;
8728 struct extent_state *cached_state = NULL;
8729 u64 page_start = page_offset(page);
8730 u64 page_end = page_start + PAGE_SIZE - 1;
8733 int inode_evicting = inode->i_state & I_FREEING;
8736 * we have the page locked, so new writeback can't start,
8737 * and the dirty bit won't be cleared while we are here.
8739 * Wait for IO on this page so that we can safely clear
8740 * the PagePrivate2 bit and do ordered accounting
8742 wait_on_page_writeback(page);
8744 tree = &BTRFS_I(inode)->io_tree;
8746 btrfs_releasepage(page, GFP_NOFS);
8750 if (!inode_evicting)
8751 lock_extent_bits(tree, page_start, page_end, &cached_state);
8754 ordered = btrfs_lookup_ordered_range(BTRFS_I(inode), start,
8755 page_end - start + 1);
8757 end = min(page_end, ordered->file_offset + ordered->len - 1);
8759 * IO on this page will never be started, so we need
8760 * to account for any ordered extents now
8762 if (!inode_evicting)
8763 clear_extent_bit(tree, start, end,
8764 EXTENT_DIRTY | EXTENT_DELALLOC |
8765 EXTENT_DELALLOC_NEW |
8766 EXTENT_LOCKED | EXTENT_DO_ACCOUNTING |
8767 EXTENT_DEFRAG, 1, 0, &cached_state);
8769 * whoever cleared the private bit is responsible
8770 * for the finish_ordered_io
8772 if (TestClearPagePrivate2(page)) {
8773 struct btrfs_ordered_inode_tree *tree;
8776 tree = &BTRFS_I(inode)->ordered_tree;
8778 spin_lock_irq(&tree->lock);
8779 set_bit(BTRFS_ORDERED_TRUNCATED, &ordered->flags);
8780 new_len = start - ordered->file_offset;
8781 if (new_len < ordered->truncated_len)
8782 ordered->truncated_len = new_len;
8783 spin_unlock_irq(&tree->lock);
8785 if (btrfs_dec_test_ordered_pending(inode, &ordered,
8787 end - start + 1, 1))
8788 btrfs_finish_ordered_io(ordered);
8790 btrfs_put_ordered_extent(ordered);
8791 if (!inode_evicting) {
8792 cached_state = NULL;
8793 lock_extent_bits(tree, start, end,
8798 if (start < page_end)
8803 * Qgroup reserved space handler
8804 * Page here will be either
8805 * 1) Already written to disk
8806 * In this case, its reserved space is released from data rsv map
8807 * and will be freed by delayed_ref handler finally.
8808 * So even we call qgroup_free_data(), it won't decrease reserved
8810 * 2) Not written to disk
8811 * This means the reserved space should be freed here. However,
8812 * if a truncate invalidates the page (by clearing PageDirty)
8813 * and the page is accounted for while allocating extent
8814 * in btrfs_check_data_free_space() we let delayed_ref to
8815 * free the entire extent.
8817 if (PageDirty(page))
8818 btrfs_qgroup_free_data(inode, NULL, page_start, PAGE_SIZE);
8819 if (!inode_evicting) {
8820 clear_extent_bit(tree, page_start, page_end,
8821 EXTENT_LOCKED | EXTENT_DIRTY |
8822 EXTENT_DELALLOC | EXTENT_DELALLOC_NEW |
8823 EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG, 1, 1,
8826 __btrfs_releasepage(page, GFP_NOFS);
8829 ClearPageChecked(page);
8830 if (PagePrivate(page)) {
8831 ClearPagePrivate(page);
8832 set_page_private(page, 0);
8838 * btrfs_page_mkwrite() is not allowed to change the file size as it gets
8839 * called from a page fault handler when a page is first dirtied. Hence we must
8840 * be careful to check for EOF conditions here. We set the page up correctly
8841 * for a written page which means we get ENOSPC checking when writing into
8842 * holes and correct delalloc and unwritten extent mapping on filesystems that
8843 * support these features.
8845 * We are not allowed to take the i_mutex here so we have to play games to
8846 * protect against truncate races as the page could now be beyond EOF. Because
8847 * truncate_setsize() writes the inode size before removing pages, once we have
8848 * the page lock we can determine safely if the page is beyond EOF. If it is not
8849 * beyond EOF, then the page is guaranteed safe against truncation until we
8852 vm_fault_t btrfs_page_mkwrite(struct vm_fault *vmf)
8854 struct page *page = vmf->page;
8855 struct inode *inode = file_inode(vmf->vma->vm_file);
8856 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
8857 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
8858 struct btrfs_ordered_extent *ordered;
8859 struct extent_state *cached_state = NULL;
8860 struct extent_changeset *data_reserved = NULL;
8862 unsigned long zero_start;
8872 reserved_space = PAGE_SIZE;
8874 sb_start_pagefault(inode->i_sb);
8875 page_start = page_offset(page);
8876 page_end = page_start + PAGE_SIZE - 1;
8880 * Reserving delalloc space after obtaining the page lock can lead to
8881 * deadlock. For example, if a dirty page is locked by this function
8882 * and the call to btrfs_delalloc_reserve_space() ends up triggering
8883 * dirty page write out, then the btrfs_writepage() function could
8884 * end up waiting indefinitely to get a lock on the page currently
8885 * being processed by btrfs_page_mkwrite() function.
8887 ret2 = btrfs_delalloc_reserve_space(inode, &data_reserved, page_start,
8890 ret2 = file_update_time(vmf->vma->vm_file);
8894 ret = vmf_error(ret2);
8900 ret = VM_FAULT_NOPAGE; /* make the VM retry the fault */
8903 size = i_size_read(inode);
8905 if ((page->mapping != inode->i_mapping) ||
8906 (page_start >= size)) {
8907 /* page got truncated out from underneath us */
8910 wait_on_page_writeback(page);
8912 lock_extent_bits(io_tree, page_start, page_end, &cached_state);
8913 set_page_extent_mapped(page);
8916 * we can't set the delalloc bits if there are pending ordered
8917 * extents. Drop our locks and wait for them to finish
8919 ordered = btrfs_lookup_ordered_range(BTRFS_I(inode), page_start,
8922 unlock_extent_cached(io_tree, page_start, page_end,
8925 btrfs_start_ordered_extent(inode, ordered, 1);
8926 btrfs_put_ordered_extent(ordered);
8930 if (page->index == ((size - 1) >> PAGE_SHIFT)) {
8931 reserved_space = round_up(size - page_start,
8932 fs_info->sectorsize);
8933 if (reserved_space < PAGE_SIZE) {
8934 end = page_start + reserved_space - 1;
8935 btrfs_delalloc_release_space(inode, data_reserved,
8936 page_start, PAGE_SIZE - reserved_space,
8942 * page_mkwrite gets called when the page is firstly dirtied after it's
8943 * faulted in, but write(2) could also dirty a page and set delalloc
8944 * bits, thus in this case for space account reason, we still need to
8945 * clear any delalloc bits within this page range since we have to
8946 * reserve data&meta space before lock_page() (see above comments).
8948 clear_extent_bit(&BTRFS_I(inode)->io_tree, page_start, end,
8949 EXTENT_DIRTY | EXTENT_DELALLOC |
8950 EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG,
8951 0, 0, &cached_state);
8953 ret2 = btrfs_set_extent_delalloc(inode, page_start, end, 0,
8956 unlock_extent_cached(io_tree, page_start, page_end,
8958 ret = VM_FAULT_SIGBUS;
8963 /* page is wholly or partially inside EOF */
8964 if (page_start + PAGE_SIZE > size)
8965 zero_start = offset_in_page(size);
8967 zero_start = PAGE_SIZE;
8969 if (zero_start != PAGE_SIZE) {
8971 memset(kaddr + zero_start, 0, PAGE_SIZE - zero_start);
8972 flush_dcache_page(page);
8975 ClearPageChecked(page);
8976 set_page_dirty(page);
8977 SetPageUptodate(page);
8979 BTRFS_I(inode)->last_trans = fs_info->generation;
8980 BTRFS_I(inode)->last_sub_trans = BTRFS_I(inode)->root->log_transid;
8981 BTRFS_I(inode)->last_log_commit = BTRFS_I(inode)->root->last_log_commit;
8983 unlock_extent_cached(io_tree, page_start, page_end, &cached_state);
8986 btrfs_delalloc_release_extents(BTRFS_I(inode), PAGE_SIZE, true);
8987 sb_end_pagefault(inode->i_sb);
8988 extent_changeset_free(data_reserved);
8989 return VM_FAULT_LOCKED;
8995 btrfs_delalloc_release_extents(BTRFS_I(inode), PAGE_SIZE, (ret != 0));
8996 btrfs_delalloc_release_space(inode, data_reserved, page_start,
8997 reserved_space, (ret != 0));
8999 sb_end_pagefault(inode->i_sb);
9000 extent_changeset_free(data_reserved);
9004 static int btrfs_truncate(struct inode *inode, bool skip_writeback)
9006 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
9007 struct btrfs_root *root = BTRFS_I(inode)->root;
9008 struct btrfs_block_rsv *rsv;
9010 struct btrfs_trans_handle *trans;
9011 u64 mask = fs_info->sectorsize - 1;
9012 u64 min_size = btrfs_calc_trunc_metadata_size(fs_info, 1);
9014 if (!skip_writeback) {
9015 ret = btrfs_wait_ordered_range(inode, inode->i_size & (~mask),
9022 * Yes ladies and gentlemen, this is indeed ugly. We have a couple of
9023 * things going on here:
9025 * 1) We need to reserve space to update our inode.
9027 * 2) We need to have something to cache all the space that is going to
9028 * be free'd up by the truncate operation, but also have some slack
9029 * space reserved in case it uses space during the truncate (thank you
9030 * very much snapshotting).
9032 * And we need these to be separate. The fact is we can use a lot of
9033 * space doing the truncate, and we have no earthly idea how much space
9034 * we will use, so we need the truncate reservation to be separate so it
9035 * doesn't end up using space reserved for updating the inode. We also
9036 * need to be able to stop the transaction and start a new one, which
9037 * means we need to be able to update the inode several times, and we
9038 * have no idea of knowing how many times that will be, so we can't just
9039 * reserve 1 item for the entirety of the operation, so that has to be
9040 * done separately as well.
9042 * So that leaves us with
9044 * 1) rsv - for the truncate reservation, which we will steal from the
9045 * transaction reservation.
9046 * 2) fs_info->trans_block_rsv - this will have 1 items worth left for
9047 * updating the inode.
9049 rsv = btrfs_alloc_block_rsv(fs_info, BTRFS_BLOCK_RSV_TEMP);
9052 rsv->size = min_size;
9056 * 1 for the truncate slack space
9057 * 1 for updating the inode.
9059 trans = btrfs_start_transaction(root, 2);
9060 if (IS_ERR(trans)) {
9061 ret = PTR_ERR(trans);
9065 /* Migrate the slack space for the truncate to our reserve */
9066 ret = btrfs_block_rsv_migrate(&fs_info->trans_block_rsv, rsv,
9071 * So if we truncate and then write and fsync we normally would just
9072 * write the extents that changed, which is a problem if we need to
9073 * first truncate that entire inode. So set this flag so we write out
9074 * all of the extents in the inode to the sync log so we're completely
9077 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &BTRFS_I(inode)->runtime_flags);
9078 trans->block_rsv = rsv;
9081 ret = btrfs_truncate_inode_items(trans, root, inode,
9083 BTRFS_EXTENT_DATA_KEY);
9084 trans->block_rsv = &fs_info->trans_block_rsv;
9085 if (ret != -ENOSPC && ret != -EAGAIN)
9088 ret = btrfs_update_inode(trans, root, inode);
9092 btrfs_end_transaction(trans);
9093 btrfs_btree_balance_dirty(fs_info);
9095 trans = btrfs_start_transaction(root, 2);
9096 if (IS_ERR(trans)) {
9097 ret = PTR_ERR(trans);
9102 btrfs_block_rsv_release(fs_info, rsv, -1);
9103 ret = btrfs_block_rsv_migrate(&fs_info->trans_block_rsv,
9104 rsv, min_size, false);
9105 BUG_ON(ret); /* shouldn't happen */
9106 trans->block_rsv = rsv;
9110 * We can't call btrfs_truncate_block inside a trans handle as we could
9111 * deadlock with freeze, if we got NEED_TRUNCATE_BLOCK then we know
9112 * we've truncated everything except the last little bit, and can do
9113 * btrfs_truncate_block and then update the disk_i_size.
9115 if (ret == NEED_TRUNCATE_BLOCK) {
9116 btrfs_end_transaction(trans);
9117 btrfs_btree_balance_dirty(fs_info);
9119 ret = btrfs_truncate_block(inode, inode->i_size, 0, 0);
9122 trans = btrfs_start_transaction(root, 1);
9123 if (IS_ERR(trans)) {
9124 ret = PTR_ERR(trans);
9127 btrfs_ordered_update_i_size(inode, inode->i_size, NULL);
9133 trans->block_rsv = &fs_info->trans_block_rsv;
9134 ret2 = btrfs_update_inode(trans, root, inode);
9138 ret2 = btrfs_end_transaction(trans);
9141 btrfs_btree_balance_dirty(fs_info);
9144 btrfs_free_block_rsv(fs_info, rsv);
9150 * create a new subvolume directory/inode (helper for the ioctl).
9152 int btrfs_create_subvol_root(struct btrfs_trans_handle *trans,
9153 struct btrfs_root *new_root,
9154 struct btrfs_root *parent_root,
9157 struct inode *inode;
9161 inode = btrfs_new_inode(trans, new_root, NULL, "..", 2,
9162 new_dirid, new_dirid,
9163 S_IFDIR | (~current_umask() & S_IRWXUGO),
9166 return PTR_ERR(inode);
9167 inode->i_op = &btrfs_dir_inode_operations;
9168 inode->i_fop = &btrfs_dir_file_operations;
9170 set_nlink(inode, 1);
9171 btrfs_i_size_write(BTRFS_I(inode), 0);
9172 unlock_new_inode(inode);
9174 err = btrfs_subvol_inherit_props(trans, new_root, parent_root);
9176 btrfs_err(new_root->fs_info,
9177 "error inheriting subvolume %llu properties: %d",
9178 new_root->root_key.objectid, err);
9180 err = btrfs_update_inode(trans, new_root, inode);
9186 struct inode *btrfs_alloc_inode(struct super_block *sb)
9188 struct btrfs_fs_info *fs_info = btrfs_sb(sb);
9189 struct btrfs_inode *ei;
9190 struct inode *inode;
9192 ei = kmem_cache_alloc(btrfs_inode_cachep, GFP_KERNEL);
9199 ei->last_sub_trans = 0;
9200 ei->logged_trans = 0;
9201 ei->delalloc_bytes = 0;
9202 ei->new_delalloc_bytes = 0;
9203 ei->defrag_bytes = 0;
9204 ei->disk_i_size = 0;
9207 ei->index_cnt = (u64)-1;
9209 ei->last_unlink_trans = 0;
9210 ei->last_log_commit = 0;
9212 spin_lock_init(&ei->lock);
9213 ei->outstanding_extents = 0;
9214 if (sb->s_magic != BTRFS_TEST_MAGIC)
9215 btrfs_init_metadata_block_rsv(fs_info, &ei->block_rsv,
9216 BTRFS_BLOCK_RSV_DELALLOC);
9217 ei->runtime_flags = 0;
9218 ei->prop_compress = BTRFS_COMPRESS_NONE;
9219 ei->defrag_compress = BTRFS_COMPRESS_NONE;
9221 ei->delayed_node = NULL;
9223 ei->i_otime.tv_sec = 0;
9224 ei->i_otime.tv_nsec = 0;
9226 inode = &ei->vfs_inode;
9227 extent_map_tree_init(&ei->extent_tree);
9228 extent_io_tree_init(fs_info, &ei->io_tree, IO_TREE_INODE_IO, inode);
9229 extent_io_tree_init(fs_info, &ei->io_failure_tree,
9230 IO_TREE_INODE_IO_FAILURE, inode);
9231 ei->io_tree.track_uptodate = true;
9232 ei->io_failure_tree.track_uptodate = true;
9233 atomic_set(&ei->sync_writers, 0);
9234 mutex_init(&ei->log_mutex);
9235 mutex_init(&ei->delalloc_mutex);
9236 btrfs_ordered_inode_tree_init(&ei->ordered_tree);
9237 INIT_LIST_HEAD(&ei->delalloc_inodes);
9238 INIT_LIST_HEAD(&ei->delayed_iput);
9239 RB_CLEAR_NODE(&ei->rb_node);
9240 init_rwsem(&ei->dio_sem);
9245 #ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
9246 void btrfs_test_destroy_inode(struct inode *inode)
9248 btrfs_drop_extent_cache(BTRFS_I(inode), 0, (u64)-1, 0);
9249 kmem_cache_free(btrfs_inode_cachep, BTRFS_I(inode));
9253 void btrfs_free_inode(struct inode *inode)
9255 kmem_cache_free(btrfs_inode_cachep, BTRFS_I(inode));
9258 void btrfs_destroy_inode(struct inode *inode)
9260 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
9261 struct btrfs_ordered_extent *ordered;
9262 struct btrfs_root *root = BTRFS_I(inode)->root;
9264 WARN_ON(!hlist_empty(&inode->i_dentry));
9265 WARN_ON(inode->i_data.nrpages);
9266 WARN_ON(BTRFS_I(inode)->block_rsv.reserved);
9267 WARN_ON(BTRFS_I(inode)->block_rsv.size);
9268 WARN_ON(BTRFS_I(inode)->outstanding_extents);
9269 WARN_ON(BTRFS_I(inode)->delalloc_bytes);
9270 WARN_ON(BTRFS_I(inode)->new_delalloc_bytes);
9271 WARN_ON(BTRFS_I(inode)->csum_bytes);
9272 WARN_ON(BTRFS_I(inode)->defrag_bytes);
9275 * This can happen where we create an inode, but somebody else also
9276 * created the same inode and we need to destroy the one we already
9283 ordered = btrfs_lookup_first_ordered_extent(inode, (u64)-1);
9288 "found ordered extent %llu %llu on inode cleanup",
9289 ordered->file_offset, ordered->len);
9290 btrfs_remove_ordered_extent(inode, ordered);
9291 btrfs_put_ordered_extent(ordered);
9292 btrfs_put_ordered_extent(ordered);
9295 btrfs_qgroup_check_reserved_leak(inode);
9296 inode_tree_del(inode);
9297 btrfs_drop_extent_cache(BTRFS_I(inode), 0, (u64)-1, 0);
9300 int btrfs_drop_inode(struct inode *inode)
9302 struct btrfs_root *root = BTRFS_I(inode)->root;
9307 /* the snap/subvol tree is on deleting */
9308 if (btrfs_root_refs(&root->root_item) == 0)
9311 return generic_drop_inode(inode);
9314 static void init_once(void *foo)
9316 struct btrfs_inode *ei = (struct btrfs_inode *) foo;
9318 inode_init_once(&ei->vfs_inode);
9321 void __cold btrfs_destroy_cachep(void)
9324 * Make sure all delayed rcu free inodes are flushed before we
9328 kmem_cache_destroy(btrfs_inode_cachep);
9329 kmem_cache_destroy(btrfs_trans_handle_cachep);
9330 kmem_cache_destroy(btrfs_path_cachep);
9331 kmem_cache_destroy(btrfs_free_space_cachep);
9334 int __init btrfs_init_cachep(void)
9336 btrfs_inode_cachep = kmem_cache_create("btrfs_inode",
9337 sizeof(struct btrfs_inode), 0,
9338 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD | SLAB_ACCOUNT,
9340 if (!btrfs_inode_cachep)
9343 btrfs_trans_handle_cachep = kmem_cache_create("btrfs_trans_handle",
9344 sizeof(struct btrfs_trans_handle), 0,
9345 SLAB_TEMPORARY | SLAB_MEM_SPREAD, NULL);
9346 if (!btrfs_trans_handle_cachep)
9349 btrfs_path_cachep = kmem_cache_create("btrfs_path",
9350 sizeof(struct btrfs_path), 0,
9351 SLAB_MEM_SPREAD, NULL);
9352 if (!btrfs_path_cachep)
9355 btrfs_free_space_cachep = kmem_cache_create("btrfs_free_space",
9356 sizeof(struct btrfs_free_space), 0,
9357 SLAB_MEM_SPREAD, NULL);
9358 if (!btrfs_free_space_cachep)
9363 btrfs_destroy_cachep();
9367 static int btrfs_getattr(const struct path *path, struct kstat *stat,
9368 u32 request_mask, unsigned int flags)
9371 struct inode *inode = d_inode(path->dentry);
9372 u32 blocksize = inode->i_sb->s_blocksize;
9373 u32 bi_flags = BTRFS_I(inode)->flags;
9375 stat->result_mask |= STATX_BTIME;
9376 stat->btime.tv_sec = BTRFS_I(inode)->i_otime.tv_sec;
9377 stat->btime.tv_nsec = BTRFS_I(inode)->i_otime.tv_nsec;
9378 if (bi_flags & BTRFS_INODE_APPEND)
9379 stat->attributes |= STATX_ATTR_APPEND;
9380 if (bi_flags & BTRFS_INODE_COMPRESS)
9381 stat->attributes |= STATX_ATTR_COMPRESSED;
9382 if (bi_flags & BTRFS_INODE_IMMUTABLE)
9383 stat->attributes |= STATX_ATTR_IMMUTABLE;
9384 if (bi_flags & BTRFS_INODE_NODUMP)
9385 stat->attributes |= STATX_ATTR_NODUMP;
9387 stat->attributes_mask |= (STATX_ATTR_APPEND |
9388 STATX_ATTR_COMPRESSED |
9389 STATX_ATTR_IMMUTABLE |
9392 generic_fillattr(inode, stat);
9393 stat->dev = BTRFS_I(inode)->root->anon_dev;
9395 spin_lock(&BTRFS_I(inode)->lock);
9396 delalloc_bytes = BTRFS_I(inode)->new_delalloc_bytes;
9397 spin_unlock(&BTRFS_I(inode)->lock);
9398 stat->blocks = (ALIGN(inode_get_bytes(inode), blocksize) +
9399 ALIGN(delalloc_bytes, blocksize)) >> 9;
9403 static int btrfs_rename_exchange(struct inode *old_dir,
9404 struct dentry *old_dentry,
9405 struct inode *new_dir,
9406 struct dentry *new_dentry)
9408 struct btrfs_fs_info *fs_info = btrfs_sb(old_dir->i_sb);
9409 struct btrfs_trans_handle *trans;
9410 struct btrfs_root *root = BTRFS_I(old_dir)->root;
9411 struct btrfs_root *dest = BTRFS_I(new_dir)->root;
9412 struct inode *new_inode = new_dentry->d_inode;
9413 struct inode *old_inode = old_dentry->d_inode;
9414 struct timespec64 ctime = current_time(old_inode);
9415 struct dentry *parent;
9416 u64 old_ino = btrfs_ino(BTRFS_I(old_inode));
9417 u64 new_ino = btrfs_ino(BTRFS_I(new_inode));
9422 bool root_log_pinned = false;
9423 bool dest_log_pinned = false;
9424 struct btrfs_log_ctx ctx_root;
9425 struct btrfs_log_ctx ctx_dest;
9426 bool sync_log_root = false;
9427 bool sync_log_dest = false;
9428 bool commit_transaction = false;
9430 /* we only allow rename subvolume link between subvolumes */
9431 if (old_ino != BTRFS_FIRST_FREE_OBJECTID && root != dest)
9434 btrfs_init_log_ctx(&ctx_root, old_inode);
9435 btrfs_init_log_ctx(&ctx_dest, new_inode);
9437 /* close the race window with snapshot create/destroy ioctl */
9438 if (old_ino == BTRFS_FIRST_FREE_OBJECTID)
9439 down_read(&fs_info->subvol_sem);
9440 if (new_ino == BTRFS_FIRST_FREE_OBJECTID)
9441 down_read(&fs_info->subvol_sem);
9444 * We want to reserve the absolute worst case amount of items. So if
9445 * both inodes are subvols and we need to unlink them then that would
9446 * require 4 item modifications, but if they are both normal inodes it
9447 * would require 5 item modifications, so we'll assume their normal
9448 * inodes. So 5 * 2 is 10, plus 2 for the new links, so 12 total items
9449 * should cover the worst case number of items we'll modify.
9451 trans = btrfs_start_transaction(root, 12);
9452 if (IS_ERR(trans)) {
9453 ret = PTR_ERR(trans);
9458 * We need to find a free sequence number both in the source and
9459 * in the destination directory for the exchange.
9461 ret = btrfs_set_inode_index(BTRFS_I(new_dir), &old_idx);
9464 ret = btrfs_set_inode_index(BTRFS_I(old_dir), &new_idx);
9468 BTRFS_I(old_inode)->dir_index = 0ULL;
9469 BTRFS_I(new_inode)->dir_index = 0ULL;
9471 /* Reference for the source. */
9472 if (old_ino == BTRFS_FIRST_FREE_OBJECTID) {
9473 /* force full log commit if subvolume involved. */
9474 btrfs_set_log_full_commit(trans);
9476 btrfs_pin_log_trans(root);
9477 root_log_pinned = true;
9478 ret = btrfs_insert_inode_ref(trans, dest,
9479 new_dentry->d_name.name,
9480 new_dentry->d_name.len,
9482 btrfs_ino(BTRFS_I(new_dir)),
9488 /* And now for the dest. */
9489 if (new_ino == BTRFS_FIRST_FREE_OBJECTID) {
9490 /* force full log commit if subvolume involved. */
9491 btrfs_set_log_full_commit(trans);
9493 btrfs_pin_log_trans(dest);
9494 dest_log_pinned = true;
9495 ret = btrfs_insert_inode_ref(trans, root,
9496 old_dentry->d_name.name,
9497 old_dentry->d_name.len,
9499 btrfs_ino(BTRFS_I(old_dir)),
9505 /* Update inode version and ctime/mtime. */
9506 inode_inc_iversion(old_dir);
9507 inode_inc_iversion(new_dir);
9508 inode_inc_iversion(old_inode);
9509 inode_inc_iversion(new_inode);
9510 old_dir->i_ctime = old_dir->i_mtime = ctime;
9511 new_dir->i_ctime = new_dir->i_mtime = ctime;
9512 old_inode->i_ctime = ctime;
9513 new_inode->i_ctime = ctime;
9515 if (old_dentry->d_parent != new_dentry->d_parent) {
9516 btrfs_record_unlink_dir(trans, BTRFS_I(old_dir),
9517 BTRFS_I(old_inode), 1);
9518 btrfs_record_unlink_dir(trans, BTRFS_I(new_dir),
9519 BTRFS_I(new_inode), 1);
9522 /* src is a subvolume */
9523 if (old_ino == BTRFS_FIRST_FREE_OBJECTID) {
9524 root_objectid = BTRFS_I(old_inode)->root->root_key.objectid;
9525 ret = btrfs_unlink_subvol(trans, old_dir, root_objectid,
9526 old_dentry->d_name.name,
9527 old_dentry->d_name.len);
9528 } else { /* src is an inode */
9529 ret = __btrfs_unlink_inode(trans, root, BTRFS_I(old_dir),
9530 BTRFS_I(old_dentry->d_inode),
9531 old_dentry->d_name.name,
9532 old_dentry->d_name.len);
9534 ret = btrfs_update_inode(trans, root, old_inode);
9537 btrfs_abort_transaction(trans, ret);
9541 /* dest is a subvolume */
9542 if (new_ino == BTRFS_FIRST_FREE_OBJECTID) {
9543 root_objectid = BTRFS_I(new_inode)->root->root_key.objectid;
9544 ret = btrfs_unlink_subvol(trans, new_dir, root_objectid,
9545 new_dentry->d_name.name,
9546 new_dentry->d_name.len);
9547 } else { /* dest is an inode */
9548 ret = __btrfs_unlink_inode(trans, dest, BTRFS_I(new_dir),
9549 BTRFS_I(new_dentry->d_inode),
9550 new_dentry->d_name.name,
9551 new_dentry->d_name.len);
9553 ret = btrfs_update_inode(trans, dest, new_inode);
9556 btrfs_abort_transaction(trans, ret);
9560 ret = btrfs_add_link(trans, BTRFS_I(new_dir), BTRFS_I(old_inode),
9561 new_dentry->d_name.name,
9562 new_dentry->d_name.len, 0, old_idx);
9564 btrfs_abort_transaction(trans, ret);
9568 ret = btrfs_add_link(trans, BTRFS_I(old_dir), BTRFS_I(new_inode),
9569 old_dentry->d_name.name,
9570 old_dentry->d_name.len, 0, new_idx);
9572 btrfs_abort_transaction(trans, ret);
9576 if (old_inode->i_nlink == 1)
9577 BTRFS_I(old_inode)->dir_index = old_idx;
9578 if (new_inode->i_nlink == 1)
9579 BTRFS_I(new_inode)->dir_index = new_idx;
9581 if (root_log_pinned) {
9582 parent = new_dentry->d_parent;
9583 ret = btrfs_log_new_name(trans, BTRFS_I(old_inode),
9584 BTRFS_I(old_dir), parent,
9586 if (ret == BTRFS_NEED_LOG_SYNC)
9587 sync_log_root = true;
9588 else if (ret == BTRFS_NEED_TRANS_COMMIT)
9589 commit_transaction = true;
9591 btrfs_end_log_trans(root);
9592 root_log_pinned = false;
9594 if (dest_log_pinned) {
9595 if (!commit_transaction) {
9596 parent = old_dentry->d_parent;
9597 ret = btrfs_log_new_name(trans, BTRFS_I(new_inode),
9598 BTRFS_I(new_dir), parent,
9600 if (ret == BTRFS_NEED_LOG_SYNC)
9601 sync_log_dest = true;
9602 else if (ret == BTRFS_NEED_TRANS_COMMIT)
9603 commit_transaction = true;
9606 btrfs_end_log_trans(dest);
9607 dest_log_pinned = false;
9611 * If we have pinned a log and an error happened, we unpin tasks
9612 * trying to sync the log and force them to fallback to a transaction
9613 * commit if the log currently contains any of the inodes involved in
9614 * this rename operation (to ensure we do not persist a log with an
9615 * inconsistent state for any of these inodes or leading to any
9616 * inconsistencies when replayed). If the transaction was aborted, the
9617 * abortion reason is propagated to userspace when attempting to commit
9618 * the transaction. If the log does not contain any of these inodes, we
9619 * allow the tasks to sync it.
9621 if (ret && (root_log_pinned || dest_log_pinned)) {
9622 if (btrfs_inode_in_log(BTRFS_I(old_dir), fs_info->generation) ||
9623 btrfs_inode_in_log(BTRFS_I(new_dir), fs_info->generation) ||
9624 btrfs_inode_in_log(BTRFS_I(old_inode), fs_info->generation) ||
9626 btrfs_inode_in_log(BTRFS_I(new_inode), fs_info->generation)))
9627 btrfs_set_log_full_commit(trans);
9629 if (root_log_pinned) {
9630 btrfs_end_log_trans(root);
9631 root_log_pinned = false;
9633 if (dest_log_pinned) {
9634 btrfs_end_log_trans(dest);
9635 dest_log_pinned = false;
9638 if (!ret && sync_log_root && !commit_transaction) {
9639 ret = btrfs_sync_log(trans, BTRFS_I(old_inode)->root,
9642 commit_transaction = true;
9644 if (!ret && sync_log_dest && !commit_transaction) {
9645 ret = btrfs_sync_log(trans, BTRFS_I(new_inode)->root,
9648 commit_transaction = true;
9650 if (commit_transaction) {
9651 ret = btrfs_commit_transaction(trans);
9655 ret2 = btrfs_end_transaction(trans);
9656 ret = ret ? ret : ret2;
9659 if (new_ino == BTRFS_FIRST_FREE_OBJECTID)
9660 up_read(&fs_info->subvol_sem);
9661 if (old_ino == BTRFS_FIRST_FREE_OBJECTID)
9662 up_read(&fs_info->subvol_sem);
9667 static int btrfs_whiteout_for_rename(struct btrfs_trans_handle *trans,
9668 struct btrfs_root *root,
9670 struct dentry *dentry)
9673 struct inode *inode;
9677 ret = btrfs_find_free_ino(root, &objectid);
9681 inode = btrfs_new_inode(trans, root, dir,
9682 dentry->d_name.name,
9684 btrfs_ino(BTRFS_I(dir)),
9686 S_IFCHR | WHITEOUT_MODE,
9689 if (IS_ERR(inode)) {
9690 ret = PTR_ERR(inode);
9694 inode->i_op = &btrfs_special_inode_operations;
9695 init_special_inode(inode, inode->i_mode,
9698 ret = btrfs_init_inode_security(trans, inode, dir,
9703 ret = btrfs_add_nondir(trans, BTRFS_I(dir), dentry,
9704 BTRFS_I(inode), 0, index);
9708 ret = btrfs_update_inode(trans, root, inode);
9710 unlock_new_inode(inode);
9712 inode_dec_link_count(inode);
9718 static int btrfs_rename(struct inode *old_dir, struct dentry *old_dentry,
9719 struct inode *new_dir, struct dentry *new_dentry,
9722 struct btrfs_fs_info *fs_info = btrfs_sb(old_dir->i_sb);
9723 struct btrfs_trans_handle *trans;
9724 unsigned int trans_num_items;
9725 struct btrfs_root *root = BTRFS_I(old_dir)->root;
9726 struct btrfs_root *dest = BTRFS_I(new_dir)->root;
9727 struct inode *new_inode = d_inode(new_dentry);
9728 struct inode *old_inode = d_inode(old_dentry);
9732 u64 old_ino = btrfs_ino(BTRFS_I(old_inode));
9733 bool log_pinned = false;
9734 struct btrfs_log_ctx ctx;
9735 bool sync_log = false;
9736 bool commit_transaction = false;
9738 if (btrfs_ino(BTRFS_I(new_dir)) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)
9741 /* we only allow rename subvolume link between subvolumes */
9742 if (old_ino != BTRFS_FIRST_FREE_OBJECTID && root != dest)
9745 if (old_ino == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID ||
9746 (new_inode && btrfs_ino(BTRFS_I(new_inode)) == BTRFS_FIRST_FREE_OBJECTID))
9749 if (S_ISDIR(old_inode->i_mode) && new_inode &&
9750 new_inode->i_size > BTRFS_EMPTY_DIR_SIZE)
9754 /* check for collisions, even if the name isn't there */
9755 ret = btrfs_check_dir_item_collision(dest, new_dir->i_ino,
9756 new_dentry->d_name.name,
9757 new_dentry->d_name.len);
9760 if (ret == -EEXIST) {
9762 * eexist without a new_inode */
9763 if (WARN_ON(!new_inode)) {
9767 /* maybe -EOVERFLOW */
9774 * we're using rename to replace one file with another. Start IO on it
9775 * now so we don't add too much work to the end of the transaction
9777 if (new_inode && S_ISREG(old_inode->i_mode) && new_inode->i_size)
9778 filemap_flush(old_inode->i_mapping);
9780 /* close the racy window with snapshot create/destroy ioctl */
9781 if (old_ino == BTRFS_FIRST_FREE_OBJECTID)
9782 down_read(&fs_info->subvol_sem);
9784 * We want to reserve the absolute worst case amount of items. So if
9785 * both inodes are subvols and we need to unlink them then that would
9786 * require 4 item modifications, but if they are both normal inodes it
9787 * would require 5 item modifications, so we'll assume they are normal
9788 * inodes. So 5 * 2 is 10, plus 1 for the new link, so 11 total items
9789 * should cover the worst case number of items we'll modify.
9790 * If our rename has the whiteout flag, we need more 5 units for the
9791 * new inode (1 inode item, 1 inode ref, 2 dir items and 1 xattr item
9792 * when selinux is enabled).
9794 trans_num_items = 11;
9795 if (flags & RENAME_WHITEOUT)
9796 trans_num_items += 5;
9797 trans = btrfs_start_transaction(root, trans_num_items);
9798 if (IS_ERR(trans)) {
9799 ret = PTR_ERR(trans);
9804 btrfs_record_root_in_trans(trans, dest);
9806 ret = btrfs_set_inode_index(BTRFS_I(new_dir), &index);
9810 BTRFS_I(old_inode)->dir_index = 0ULL;
9811 if (unlikely(old_ino == BTRFS_FIRST_FREE_OBJECTID)) {
9812 /* force full log commit if subvolume involved. */
9813 btrfs_set_log_full_commit(trans);
9815 btrfs_pin_log_trans(root);
9817 ret = btrfs_insert_inode_ref(trans, dest,
9818 new_dentry->d_name.name,
9819 new_dentry->d_name.len,
9821 btrfs_ino(BTRFS_I(new_dir)), index);
9826 inode_inc_iversion(old_dir);
9827 inode_inc_iversion(new_dir);
9828 inode_inc_iversion(old_inode);
9829 old_dir->i_ctime = old_dir->i_mtime =
9830 new_dir->i_ctime = new_dir->i_mtime =
9831 old_inode->i_ctime = current_time(old_dir);
9833 if (old_dentry->d_parent != new_dentry->d_parent)
9834 btrfs_record_unlink_dir(trans, BTRFS_I(old_dir),
9835 BTRFS_I(old_inode), 1);
9837 if (unlikely(old_ino == BTRFS_FIRST_FREE_OBJECTID)) {
9838 root_objectid = BTRFS_I(old_inode)->root->root_key.objectid;
9839 ret = btrfs_unlink_subvol(trans, old_dir, root_objectid,
9840 old_dentry->d_name.name,
9841 old_dentry->d_name.len);
9843 ret = __btrfs_unlink_inode(trans, root, BTRFS_I(old_dir),
9844 BTRFS_I(d_inode(old_dentry)),
9845 old_dentry->d_name.name,
9846 old_dentry->d_name.len);
9848 ret = btrfs_update_inode(trans, root, old_inode);
9851 btrfs_abort_transaction(trans, ret);
9856 inode_inc_iversion(new_inode);
9857 new_inode->i_ctime = current_time(new_inode);
9858 if (unlikely(btrfs_ino(BTRFS_I(new_inode)) ==
9859 BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)) {
9860 root_objectid = BTRFS_I(new_inode)->location.objectid;
9861 ret = btrfs_unlink_subvol(trans, new_dir, root_objectid,
9862 new_dentry->d_name.name,
9863 new_dentry->d_name.len);
9864 BUG_ON(new_inode->i_nlink == 0);
9866 ret = btrfs_unlink_inode(trans, dest, BTRFS_I(new_dir),
9867 BTRFS_I(d_inode(new_dentry)),
9868 new_dentry->d_name.name,
9869 new_dentry->d_name.len);
9871 if (!ret && new_inode->i_nlink == 0)
9872 ret = btrfs_orphan_add(trans,
9873 BTRFS_I(d_inode(new_dentry)));
9875 btrfs_abort_transaction(trans, ret);
9880 ret = btrfs_add_link(trans, BTRFS_I(new_dir), BTRFS_I(old_inode),
9881 new_dentry->d_name.name,
9882 new_dentry->d_name.len, 0, index);
9884 btrfs_abort_transaction(trans, ret);
9888 if (old_inode->i_nlink == 1)
9889 BTRFS_I(old_inode)->dir_index = index;
9892 struct dentry *parent = new_dentry->d_parent;
9894 btrfs_init_log_ctx(&ctx, old_inode);
9895 ret = btrfs_log_new_name(trans, BTRFS_I(old_inode),
9896 BTRFS_I(old_dir), parent,
9898 if (ret == BTRFS_NEED_LOG_SYNC)
9900 else if (ret == BTRFS_NEED_TRANS_COMMIT)
9901 commit_transaction = true;
9903 btrfs_end_log_trans(root);
9907 if (flags & RENAME_WHITEOUT) {
9908 ret = btrfs_whiteout_for_rename(trans, root, old_dir,
9912 btrfs_abort_transaction(trans, ret);
9918 * If we have pinned the log and an error happened, we unpin tasks
9919 * trying to sync the log and force them to fallback to a transaction
9920 * commit if the log currently contains any of the inodes involved in
9921 * this rename operation (to ensure we do not persist a log with an
9922 * inconsistent state for any of these inodes or leading to any
9923 * inconsistencies when replayed). If the transaction was aborted, the
9924 * abortion reason is propagated to userspace when attempting to commit
9925 * the transaction. If the log does not contain any of these inodes, we
9926 * allow the tasks to sync it.
9928 if (ret && log_pinned) {
9929 if (btrfs_inode_in_log(BTRFS_I(old_dir), fs_info->generation) ||
9930 btrfs_inode_in_log(BTRFS_I(new_dir), fs_info->generation) ||
9931 btrfs_inode_in_log(BTRFS_I(old_inode), fs_info->generation) ||
9933 btrfs_inode_in_log(BTRFS_I(new_inode), fs_info->generation)))
9934 btrfs_set_log_full_commit(trans);
9936 btrfs_end_log_trans(root);
9939 if (!ret && sync_log) {
9940 ret = btrfs_sync_log(trans, BTRFS_I(old_inode)->root, &ctx);
9942 commit_transaction = true;
9944 if (commit_transaction) {
9945 ret = btrfs_commit_transaction(trans);
9949 ret2 = btrfs_end_transaction(trans);
9950 ret = ret ? ret : ret2;
9953 if (old_ino == BTRFS_FIRST_FREE_OBJECTID)
9954 up_read(&fs_info->subvol_sem);
9959 static int btrfs_rename2(struct inode *old_dir, struct dentry *old_dentry,
9960 struct inode *new_dir, struct dentry *new_dentry,
9963 if (flags & ~(RENAME_NOREPLACE | RENAME_EXCHANGE | RENAME_WHITEOUT))
9966 if (flags & RENAME_EXCHANGE)
9967 return btrfs_rename_exchange(old_dir, old_dentry, new_dir,
9970 return btrfs_rename(old_dir, old_dentry, new_dir, new_dentry, flags);
9973 struct btrfs_delalloc_work {
9974 struct inode *inode;
9975 struct completion completion;
9976 struct list_head list;
9977 struct btrfs_work work;
9980 static void btrfs_run_delalloc_work(struct btrfs_work *work)
9982 struct btrfs_delalloc_work *delalloc_work;
9983 struct inode *inode;
9985 delalloc_work = container_of(work, struct btrfs_delalloc_work,
9987 inode = delalloc_work->inode;
9988 filemap_flush(inode->i_mapping);
9989 if (test_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
9990 &BTRFS_I(inode)->runtime_flags))
9991 filemap_flush(inode->i_mapping);
9994 complete(&delalloc_work->completion);
9997 static struct btrfs_delalloc_work *btrfs_alloc_delalloc_work(struct inode *inode)
9999 struct btrfs_delalloc_work *work;
10001 work = kmalloc(sizeof(*work), GFP_NOFS);
10005 init_completion(&work->completion);
10006 INIT_LIST_HEAD(&work->list);
10007 work->inode = inode;
10008 btrfs_init_work(&work->work, btrfs_flush_delalloc_helper,
10009 btrfs_run_delalloc_work, NULL, NULL);
10015 * some fairly slow code that needs optimization. This walks the list
10016 * of all the inodes with pending delalloc and forces them to disk.
10018 static int start_delalloc_inodes(struct btrfs_root *root, int nr, bool snapshot)
10020 struct btrfs_inode *binode;
10021 struct inode *inode;
10022 struct btrfs_delalloc_work *work, *next;
10023 struct list_head works;
10024 struct list_head splice;
10027 INIT_LIST_HEAD(&works);
10028 INIT_LIST_HEAD(&splice);
10030 mutex_lock(&root->delalloc_mutex);
10031 spin_lock(&root->delalloc_lock);
10032 list_splice_init(&root->delalloc_inodes, &splice);
10033 while (!list_empty(&splice)) {
10034 binode = list_entry(splice.next, struct btrfs_inode,
10037 list_move_tail(&binode->delalloc_inodes,
10038 &root->delalloc_inodes);
10039 inode = igrab(&binode->vfs_inode);
10041 cond_resched_lock(&root->delalloc_lock);
10044 spin_unlock(&root->delalloc_lock);
10047 set_bit(BTRFS_INODE_SNAPSHOT_FLUSH,
10048 &binode->runtime_flags);
10049 work = btrfs_alloc_delalloc_work(inode);
10055 list_add_tail(&work->list, &works);
10056 btrfs_queue_work(root->fs_info->flush_workers,
10059 if (nr != -1 && ret >= nr)
10062 spin_lock(&root->delalloc_lock);
10064 spin_unlock(&root->delalloc_lock);
10067 list_for_each_entry_safe(work, next, &works, list) {
10068 list_del_init(&work->list);
10069 wait_for_completion(&work->completion);
10073 if (!list_empty(&splice)) {
10074 spin_lock(&root->delalloc_lock);
10075 list_splice_tail(&splice, &root->delalloc_inodes);
10076 spin_unlock(&root->delalloc_lock);
10078 mutex_unlock(&root->delalloc_mutex);
10082 int btrfs_start_delalloc_snapshot(struct btrfs_root *root)
10084 struct btrfs_fs_info *fs_info = root->fs_info;
10087 if (test_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state))
10090 ret = start_delalloc_inodes(root, -1, true);
10096 int btrfs_start_delalloc_roots(struct btrfs_fs_info *fs_info, int nr)
10098 struct btrfs_root *root;
10099 struct list_head splice;
10102 if (test_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state))
10105 INIT_LIST_HEAD(&splice);
10107 mutex_lock(&fs_info->delalloc_root_mutex);
10108 spin_lock(&fs_info->delalloc_root_lock);
10109 list_splice_init(&fs_info->delalloc_roots, &splice);
10110 while (!list_empty(&splice) && nr) {
10111 root = list_first_entry(&splice, struct btrfs_root,
10113 root = btrfs_grab_fs_root(root);
10115 list_move_tail(&root->delalloc_root,
10116 &fs_info->delalloc_roots);
10117 spin_unlock(&fs_info->delalloc_root_lock);
10119 ret = start_delalloc_inodes(root, nr, false);
10120 btrfs_put_fs_root(root);
10128 spin_lock(&fs_info->delalloc_root_lock);
10130 spin_unlock(&fs_info->delalloc_root_lock);
10134 if (!list_empty(&splice)) {
10135 spin_lock(&fs_info->delalloc_root_lock);
10136 list_splice_tail(&splice, &fs_info->delalloc_roots);
10137 spin_unlock(&fs_info->delalloc_root_lock);
10139 mutex_unlock(&fs_info->delalloc_root_mutex);
10143 static int btrfs_symlink(struct inode *dir, struct dentry *dentry,
10144 const char *symname)
10146 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
10147 struct btrfs_trans_handle *trans;
10148 struct btrfs_root *root = BTRFS_I(dir)->root;
10149 struct btrfs_path *path;
10150 struct btrfs_key key;
10151 struct inode *inode = NULL;
10158 struct btrfs_file_extent_item *ei;
10159 struct extent_buffer *leaf;
10161 name_len = strlen(symname);
10162 if (name_len > BTRFS_MAX_INLINE_DATA_SIZE(fs_info))
10163 return -ENAMETOOLONG;
10166 * 2 items for inode item and ref
10167 * 2 items for dir items
10168 * 1 item for updating parent inode item
10169 * 1 item for the inline extent item
10170 * 1 item for xattr if selinux is on
10172 trans = btrfs_start_transaction(root, 7);
10174 return PTR_ERR(trans);
10176 err = btrfs_find_free_ino(root, &objectid);
10180 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
10181 dentry->d_name.len, btrfs_ino(BTRFS_I(dir)),
10182 objectid, S_IFLNK|S_IRWXUGO, &index);
10183 if (IS_ERR(inode)) {
10184 err = PTR_ERR(inode);
10190 * If the active LSM wants to access the inode during
10191 * d_instantiate it needs these. Smack checks to see
10192 * if the filesystem supports xattrs by looking at the
10195 inode->i_fop = &btrfs_file_operations;
10196 inode->i_op = &btrfs_file_inode_operations;
10197 inode->i_mapping->a_ops = &btrfs_aops;
10198 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
10200 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
10204 path = btrfs_alloc_path();
10209 key.objectid = btrfs_ino(BTRFS_I(inode));
10211 key.type = BTRFS_EXTENT_DATA_KEY;
10212 datasize = btrfs_file_extent_calc_inline_size(name_len);
10213 err = btrfs_insert_empty_item(trans, root, path, &key,
10216 btrfs_free_path(path);
10219 leaf = path->nodes[0];
10220 ei = btrfs_item_ptr(leaf, path->slots[0],
10221 struct btrfs_file_extent_item);
10222 btrfs_set_file_extent_generation(leaf, ei, trans->transid);
10223 btrfs_set_file_extent_type(leaf, ei,
10224 BTRFS_FILE_EXTENT_INLINE);
10225 btrfs_set_file_extent_encryption(leaf, ei, 0);
10226 btrfs_set_file_extent_compression(leaf, ei, 0);
10227 btrfs_set_file_extent_other_encoding(leaf, ei, 0);
10228 btrfs_set_file_extent_ram_bytes(leaf, ei, name_len);
10230 ptr = btrfs_file_extent_inline_start(ei);
10231 write_extent_buffer(leaf, symname, ptr, name_len);
10232 btrfs_mark_buffer_dirty(leaf);
10233 btrfs_free_path(path);
10235 inode->i_op = &btrfs_symlink_inode_operations;
10236 inode_nohighmem(inode);
10237 inode_set_bytes(inode, name_len);
10238 btrfs_i_size_write(BTRFS_I(inode), name_len);
10239 err = btrfs_update_inode(trans, root, inode);
10241 * Last step, add directory indexes for our symlink inode. This is the
10242 * last step to avoid extra cleanup of these indexes if an error happens
10246 err = btrfs_add_nondir(trans, BTRFS_I(dir), dentry,
10247 BTRFS_I(inode), 0, index);
10251 d_instantiate_new(dentry, inode);
10254 btrfs_end_transaction(trans);
10255 if (err && inode) {
10256 inode_dec_link_count(inode);
10257 discard_new_inode(inode);
10259 btrfs_btree_balance_dirty(fs_info);
10263 static int __btrfs_prealloc_file_range(struct inode *inode, int mode,
10264 u64 start, u64 num_bytes, u64 min_size,
10265 loff_t actual_len, u64 *alloc_hint,
10266 struct btrfs_trans_handle *trans)
10268 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
10269 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
10270 struct extent_map *em;
10271 struct btrfs_root *root = BTRFS_I(inode)->root;
10272 struct btrfs_key ins;
10273 u64 cur_offset = start;
10276 u64 last_alloc = (u64)-1;
10278 bool own_trans = true;
10279 u64 end = start + num_bytes - 1;
10283 while (num_bytes > 0) {
10285 trans = btrfs_start_transaction(root, 3);
10286 if (IS_ERR(trans)) {
10287 ret = PTR_ERR(trans);
10292 cur_bytes = min_t(u64, num_bytes, SZ_256M);
10293 cur_bytes = max(cur_bytes, min_size);
10295 * If we are severely fragmented we could end up with really
10296 * small allocations, so if the allocator is returning small
10297 * chunks lets make its job easier by only searching for those
10300 cur_bytes = min(cur_bytes, last_alloc);
10301 ret = btrfs_reserve_extent(root, cur_bytes, cur_bytes,
10302 min_size, 0, *alloc_hint, &ins, 1, 0);
10305 btrfs_end_transaction(trans);
10308 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
10310 last_alloc = ins.offset;
10311 ret = insert_reserved_file_extent(trans, inode,
10312 cur_offset, ins.objectid,
10313 ins.offset, ins.offset,
10314 ins.offset, 0, 0, 0,
10315 BTRFS_FILE_EXTENT_PREALLOC);
10317 btrfs_free_reserved_extent(fs_info, ins.objectid,
10319 btrfs_abort_transaction(trans, ret);
10321 btrfs_end_transaction(trans);
10325 btrfs_drop_extent_cache(BTRFS_I(inode), cur_offset,
10326 cur_offset + ins.offset -1, 0);
10328 em = alloc_extent_map();
10330 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
10331 &BTRFS_I(inode)->runtime_flags);
10335 em->start = cur_offset;
10336 em->orig_start = cur_offset;
10337 em->len = ins.offset;
10338 em->block_start = ins.objectid;
10339 em->block_len = ins.offset;
10340 em->orig_block_len = ins.offset;
10341 em->ram_bytes = ins.offset;
10342 em->bdev = fs_info->fs_devices->latest_bdev;
10343 set_bit(EXTENT_FLAG_PREALLOC, &em->flags);
10344 em->generation = trans->transid;
10347 write_lock(&em_tree->lock);
10348 ret = add_extent_mapping(em_tree, em, 1);
10349 write_unlock(&em_tree->lock);
10350 if (ret != -EEXIST)
10352 btrfs_drop_extent_cache(BTRFS_I(inode), cur_offset,
10353 cur_offset + ins.offset - 1,
10356 free_extent_map(em);
10358 num_bytes -= ins.offset;
10359 cur_offset += ins.offset;
10360 *alloc_hint = ins.objectid + ins.offset;
10362 inode_inc_iversion(inode);
10363 inode->i_ctime = current_time(inode);
10364 BTRFS_I(inode)->flags |= BTRFS_INODE_PREALLOC;
10365 if (!(mode & FALLOC_FL_KEEP_SIZE) &&
10366 (actual_len > inode->i_size) &&
10367 (cur_offset > inode->i_size)) {
10368 if (cur_offset > actual_len)
10369 i_size = actual_len;
10371 i_size = cur_offset;
10372 i_size_write(inode, i_size);
10373 btrfs_ordered_update_i_size(inode, i_size, NULL);
10376 ret = btrfs_update_inode(trans, root, inode);
10379 btrfs_abort_transaction(trans, ret);
10381 btrfs_end_transaction(trans);
10386 btrfs_end_transaction(trans);
10388 if (cur_offset < end)
10389 btrfs_free_reserved_data_space(inode, NULL, cur_offset,
10390 end - cur_offset + 1);
10394 int btrfs_prealloc_file_range(struct inode *inode, int mode,
10395 u64 start, u64 num_bytes, u64 min_size,
10396 loff_t actual_len, u64 *alloc_hint)
10398 return __btrfs_prealloc_file_range(inode, mode, start, num_bytes,
10399 min_size, actual_len, alloc_hint,
10403 int btrfs_prealloc_file_range_trans(struct inode *inode,
10404 struct btrfs_trans_handle *trans, int mode,
10405 u64 start, u64 num_bytes, u64 min_size,
10406 loff_t actual_len, u64 *alloc_hint)
10408 return __btrfs_prealloc_file_range(inode, mode, start, num_bytes,
10409 min_size, actual_len, alloc_hint, trans);
10412 static int btrfs_set_page_dirty(struct page *page)
10414 return __set_page_dirty_nobuffers(page);
10417 static int btrfs_permission(struct inode *inode, int mask)
10419 struct btrfs_root *root = BTRFS_I(inode)->root;
10420 umode_t mode = inode->i_mode;
10422 if (mask & MAY_WRITE &&
10423 (S_ISREG(mode) || S_ISDIR(mode) || S_ISLNK(mode))) {
10424 if (btrfs_root_readonly(root))
10426 if (BTRFS_I(inode)->flags & BTRFS_INODE_READONLY)
10429 return generic_permission(inode, mask);
10432 static int btrfs_tmpfile(struct inode *dir, struct dentry *dentry, umode_t mode)
10434 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
10435 struct btrfs_trans_handle *trans;
10436 struct btrfs_root *root = BTRFS_I(dir)->root;
10437 struct inode *inode = NULL;
10443 * 5 units required for adding orphan entry
10445 trans = btrfs_start_transaction(root, 5);
10447 return PTR_ERR(trans);
10449 ret = btrfs_find_free_ino(root, &objectid);
10453 inode = btrfs_new_inode(trans, root, dir, NULL, 0,
10454 btrfs_ino(BTRFS_I(dir)), objectid, mode, &index);
10455 if (IS_ERR(inode)) {
10456 ret = PTR_ERR(inode);
10461 inode->i_fop = &btrfs_file_operations;
10462 inode->i_op = &btrfs_file_inode_operations;
10464 inode->i_mapping->a_ops = &btrfs_aops;
10465 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
10467 ret = btrfs_init_inode_security(trans, inode, dir, NULL);
10471 ret = btrfs_update_inode(trans, root, inode);
10474 ret = btrfs_orphan_add(trans, BTRFS_I(inode));
10479 * We set number of links to 0 in btrfs_new_inode(), and here we set
10480 * it to 1 because d_tmpfile() will issue a warning if the count is 0,
10483 * d_tmpfile() -> inode_dec_link_count() -> drop_nlink()
10485 set_nlink(inode, 1);
10486 d_tmpfile(dentry, inode);
10487 unlock_new_inode(inode);
10488 mark_inode_dirty(inode);
10490 btrfs_end_transaction(trans);
10492 discard_new_inode(inode);
10493 btrfs_btree_balance_dirty(fs_info);
10497 void btrfs_set_range_writeback(struct extent_io_tree *tree, u64 start, u64 end)
10499 struct inode *inode = tree->private_data;
10500 unsigned long index = start >> PAGE_SHIFT;
10501 unsigned long end_index = end >> PAGE_SHIFT;
10504 while (index <= end_index) {
10505 page = find_get_page(inode->i_mapping, index);
10506 ASSERT(page); /* Pages should be in the extent_io_tree */
10507 set_page_writeback(page);
10515 * Add an entry indicating a block group or device which is pinned by a
10516 * swapfile. Returns 0 on success, 1 if there is already an entry for it, or a
10517 * negative errno on failure.
10519 static int btrfs_add_swapfile_pin(struct inode *inode, void *ptr,
10520 bool is_block_group)
10522 struct btrfs_fs_info *fs_info = BTRFS_I(inode)->root->fs_info;
10523 struct btrfs_swapfile_pin *sp, *entry;
10524 struct rb_node **p;
10525 struct rb_node *parent = NULL;
10527 sp = kmalloc(sizeof(*sp), GFP_NOFS);
10532 sp->is_block_group = is_block_group;
10534 spin_lock(&fs_info->swapfile_pins_lock);
10535 p = &fs_info->swapfile_pins.rb_node;
10538 entry = rb_entry(parent, struct btrfs_swapfile_pin, node);
10539 if (sp->ptr < entry->ptr ||
10540 (sp->ptr == entry->ptr && sp->inode < entry->inode)) {
10541 p = &(*p)->rb_left;
10542 } else if (sp->ptr > entry->ptr ||
10543 (sp->ptr == entry->ptr && sp->inode > entry->inode)) {
10544 p = &(*p)->rb_right;
10546 spin_unlock(&fs_info->swapfile_pins_lock);
10551 rb_link_node(&sp->node, parent, p);
10552 rb_insert_color(&sp->node, &fs_info->swapfile_pins);
10553 spin_unlock(&fs_info->swapfile_pins_lock);
10557 /* Free all of the entries pinned by this swapfile. */
10558 static void btrfs_free_swapfile_pins(struct inode *inode)
10560 struct btrfs_fs_info *fs_info = BTRFS_I(inode)->root->fs_info;
10561 struct btrfs_swapfile_pin *sp;
10562 struct rb_node *node, *next;
10564 spin_lock(&fs_info->swapfile_pins_lock);
10565 node = rb_first(&fs_info->swapfile_pins);
10567 next = rb_next(node);
10568 sp = rb_entry(node, struct btrfs_swapfile_pin, node);
10569 if (sp->inode == inode) {
10570 rb_erase(&sp->node, &fs_info->swapfile_pins);
10571 if (sp->is_block_group)
10572 btrfs_put_block_group(sp->ptr);
10577 spin_unlock(&fs_info->swapfile_pins_lock);
10580 struct btrfs_swap_info {
10586 unsigned long nr_pages;
10590 static int btrfs_add_swap_extent(struct swap_info_struct *sis,
10591 struct btrfs_swap_info *bsi)
10593 unsigned long nr_pages;
10594 u64 first_ppage, first_ppage_reported, next_ppage;
10597 first_ppage = ALIGN(bsi->block_start, PAGE_SIZE) >> PAGE_SHIFT;
10598 next_ppage = ALIGN_DOWN(bsi->block_start + bsi->block_len,
10599 PAGE_SIZE) >> PAGE_SHIFT;
10601 if (first_ppage >= next_ppage)
10603 nr_pages = next_ppage - first_ppage;
10605 first_ppage_reported = first_ppage;
10606 if (bsi->start == 0)
10607 first_ppage_reported++;
10608 if (bsi->lowest_ppage > first_ppage_reported)
10609 bsi->lowest_ppage = first_ppage_reported;
10610 if (bsi->highest_ppage < (next_ppage - 1))
10611 bsi->highest_ppage = next_ppage - 1;
10613 ret = add_swap_extent(sis, bsi->nr_pages, nr_pages, first_ppage);
10616 bsi->nr_extents += ret;
10617 bsi->nr_pages += nr_pages;
10621 static void btrfs_swap_deactivate(struct file *file)
10623 struct inode *inode = file_inode(file);
10625 btrfs_free_swapfile_pins(inode);
10626 atomic_dec(&BTRFS_I(inode)->root->nr_swapfiles);
10629 static int btrfs_swap_activate(struct swap_info_struct *sis, struct file *file,
10632 struct inode *inode = file_inode(file);
10633 struct btrfs_fs_info *fs_info = BTRFS_I(inode)->root->fs_info;
10634 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
10635 struct extent_state *cached_state = NULL;
10636 struct extent_map *em = NULL;
10637 struct btrfs_device *device = NULL;
10638 struct btrfs_swap_info bsi = {
10639 .lowest_ppage = (sector_t)-1ULL,
10646 * If the swap file was just created, make sure delalloc is done. If the
10647 * file changes again after this, the user is doing something stupid and
10648 * we don't really care.
10650 ret = btrfs_wait_ordered_range(inode, 0, (u64)-1);
10655 * The inode is locked, so these flags won't change after we check them.
10657 if (BTRFS_I(inode)->flags & BTRFS_INODE_COMPRESS) {
10658 btrfs_warn(fs_info, "swapfile must not be compressed");
10661 if (!(BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW)) {
10662 btrfs_warn(fs_info, "swapfile must not be copy-on-write");
10665 if (!(BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)) {
10666 btrfs_warn(fs_info, "swapfile must not be checksummed");
10671 * Balance or device remove/replace/resize can move stuff around from
10672 * under us. The EXCL_OP flag makes sure they aren't running/won't run
10673 * concurrently while we are mapping the swap extents, and
10674 * fs_info->swapfile_pins prevents them from running while the swap file
10675 * is active and moving the extents. Note that this also prevents a
10676 * concurrent device add which isn't actually necessary, but it's not
10677 * really worth the trouble to allow it.
10679 if (test_and_set_bit(BTRFS_FS_EXCL_OP, &fs_info->flags)) {
10680 btrfs_warn(fs_info,
10681 "cannot activate swapfile while exclusive operation is running");
10685 * Snapshots can create extents which require COW even if NODATACOW is
10686 * set. We use this counter to prevent snapshots. We must increment it
10687 * before walking the extents because we don't want a concurrent
10688 * snapshot to run after we've already checked the extents.
10690 atomic_inc(&BTRFS_I(inode)->root->nr_swapfiles);
10692 isize = ALIGN_DOWN(inode->i_size, fs_info->sectorsize);
10694 lock_extent_bits(io_tree, 0, isize - 1, &cached_state);
10696 while (start < isize) {
10697 u64 logical_block_start, physical_block_start;
10698 struct btrfs_block_group_cache *bg;
10699 u64 len = isize - start;
10701 em = btrfs_get_extent(BTRFS_I(inode), NULL, 0, start, len, 0);
10707 if (em->block_start == EXTENT_MAP_HOLE) {
10708 btrfs_warn(fs_info, "swapfile must not have holes");
10712 if (em->block_start == EXTENT_MAP_INLINE) {
10714 * It's unlikely we'll ever actually find ourselves
10715 * here, as a file small enough to fit inline won't be
10716 * big enough to store more than the swap header, but in
10717 * case something changes in the future, let's catch it
10718 * here rather than later.
10720 btrfs_warn(fs_info, "swapfile must not be inline");
10724 if (test_bit(EXTENT_FLAG_COMPRESSED, &em->flags)) {
10725 btrfs_warn(fs_info, "swapfile must not be compressed");
10730 logical_block_start = em->block_start + (start - em->start);
10731 len = min(len, em->len - (start - em->start));
10732 free_extent_map(em);
10735 ret = can_nocow_extent(inode, start, &len, NULL, NULL, NULL);
10741 btrfs_warn(fs_info,
10742 "swapfile must not be copy-on-write");
10747 em = btrfs_get_chunk_map(fs_info, logical_block_start, len);
10753 if (em->map_lookup->type & BTRFS_BLOCK_GROUP_PROFILE_MASK) {
10754 btrfs_warn(fs_info,
10755 "swapfile must have single data profile");
10760 if (device == NULL) {
10761 device = em->map_lookup->stripes[0].dev;
10762 ret = btrfs_add_swapfile_pin(inode, device, false);
10767 } else if (device != em->map_lookup->stripes[0].dev) {
10768 btrfs_warn(fs_info, "swapfile must be on one device");
10773 physical_block_start = (em->map_lookup->stripes[0].physical +
10774 (logical_block_start - em->start));
10775 len = min(len, em->len - (logical_block_start - em->start));
10776 free_extent_map(em);
10779 bg = btrfs_lookup_block_group(fs_info, logical_block_start);
10781 btrfs_warn(fs_info,
10782 "could not find block group containing swapfile");
10787 ret = btrfs_add_swapfile_pin(inode, bg, true);
10789 btrfs_put_block_group(bg);
10796 if (bsi.block_len &&
10797 bsi.block_start + bsi.block_len == physical_block_start) {
10798 bsi.block_len += len;
10800 if (bsi.block_len) {
10801 ret = btrfs_add_swap_extent(sis, &bsi);
10806 bsi.block_start = physical_block_start;
10807 bsi.block_len = len;
10814 ret = btrfs_add_swap_extent(sis, &bsi);
10817 if (!IS_ERR_OR_NULL(em))
10818 free_extent_map(em);
10820 unlock_extent_cached(io_tree, 0, isize - 1, &cached_state);
10823 btrfs_swap_deactivate(file);
10825 clear_bit(BTRFS_FS_EXCL_OP, &fs_info->flags);
10831 sis->bdev = device->bdev;
10832 *span = bsi.highest_ppage - bsi.lowest_ppage + 1;
10833 sis->max = bsi.nr_pages;
10834 sis->pages = bsi.nr_pages - 1;
10835 sis->highest_bit = bsi.nr_pages - 1;
10836 return bsi.nr_extents;
10839 static void btrfs_swap_deactivate(struct file *file)
10843 static int btrfs_swap_activate(struct swap_info_struct *sis, struct file *file,
10846 return -EOPNOTSUPP;
10850 static const struct inode_operations btrfs_dir_inode_operations = {
10851 .getattr = btrfs_getattr,
10852 .lookup = btrfs_lookup,
10853 .create = btrfs_create,
10854 .unlink = btrfs_unlink,
10855 .link = btrfs_link,
10856 .mkdir = btrfs_mkdir,
10857 .rmdir = btrfs_rmdir,
10858 .rename = btrfs_rename2,
10859 .symlink = btrfs_symlink,
10860 .setattr = btrfs_setattr,
10861 .mknod = btrfs_mknod,
10862 .listxattr = btrfs_listxattr,
10863 .permission = btrfs_permission,
10864 .get_acl = btrfs_get_acl,
10865 .set_acl = btrfs_set_acl,
10866 .update_time = btrfs_update_time,
10867 .tmpfile = btrfs_tmpfile,
10869 static const struct inode_operations btrfs_dir_ro_inode_operations = {
10870 .lookup = btrfs_lookup,
10871 .permission = btrfs_permission,
10872 .update_time = btrfs_update_time,
10875 static const struct file_operations btrfs_dir_file_operations = {
10876 .llseek = generic_file_llseek,
10877 .read = generic_read_dir,
10878 .iterate_shared = btrfs_real_readdir,
10879 .open = btrfs_opendir,
10880 .unlocked_ioctl = btrfs_ioctl,
10881 #ifdef CONFIG_COMPAT
10882 .compat_ioctl = btrfs_compat_ioctl,
10884 .release = btrfs_release_file,
10885 .fsync = btrfs_sync_file,
10888 static const struct extent_io_ops btrfs_extent_io_ops = {
10889 /* mandatory callbacks */
10890 .submit_bio_hook = btrfs_submit_bio_hook,
10891 .readpage_end_io_hook = btrfs_readpage_end_io_hook,
10895 * btrfs doesn't support the bmap operation because swapfiles
10896 * use bmap to make a mapping of extents in the file. They assume
10897 * these extents won't change over the life of the file and they
10898 * use the bmap result to do IO directly to the drive.
10900 * the btrfs bmap call would return logical addresses that aren't
10901 * suitable for IO and they also will change frequently as COW
10902 * operations happen. So, swapfile + btrfs == corruption.
10904 * For now we're avoiding this by dropping bmap.
10906 static const struct address_space_operations btrfs_aops = {
10907 .readpage = btrfs_readpage,
10908 .writepage = btrfs_writepage,
10909 .writepages = btrfs_writepages,
10910 .readpages = btrfs_readpages,
10911 .direct_IO = btrfs_direct_IO,
10912 .invalidatepage = btrfs_invalidatepage,
10913 .releasepage = btrfs_releasepage,
10914 .set_page_dirty = btrfs_set_page_dirty,
10915 .error_remove_page = generic_error_remove_page,
10916 .swap_activate = btrfs_swap_activate,
10917 .swap_deactivate = btrfs_swap_deactivate,
10920 static const struct inode_operations btrfs_file_inode_operations = {
10921 .getattr = btrfs_getattr,
10922 .setattr = btrfs_setattr,
10923 .listxattr = btrfs_listxattr,
10924 .permission = btrfs_permission,
10925 .fiemap = btrfs_fiemap,
10926 .get_acl = btrfs_get_acl,
10927 .set_acl = btrfs_set_acl,
10928 .update_time = btrfs_update_time,
10930 static const struct inode_operations btrfs_special_inode_operations = {
10931 .getattr = btrfs_getattr,
10932 .setattr = btrfs_setattr,
10933 .permission = btrfs_permission,
10934 .listxattr = btrfs_listxattr,
10935 .get_acl = btrfs_get_acl,
10936 .set_acl = btrfs_set_acl,
10937 .update_time = btrfs_update_time,
10939 static const struct inode_operations btrfs_symlink_inode_operations = {
10940 .get_link = page_get_link,
10941 .getattr = btrfs_getattr,
10942 .setattr = btrfs_setattr,
10943 .permission = btrfs_permission,
10944 .listxattr = btrfs_listxattr,
10945 .update_time = btrfs_update_time,
10948 const struct dentry_operations btrfs_dentry_operations = {
10949 .d_delete = btrfs_dentry_delete,