1 // SPDX-License-Identifier: GPL-2.0
3 * Copyright (C) 2007 Oracle. All rights reserved.
6 #include <linux/kernel.h>
8 #include <linux/buffer_head.h>
9 #include <linux/file.h>
11 #include <linux/pagemap.h>
12 #include <linux/highmem.h>
13 #include <linux/time.h>
14 #include <linux/init.h>
15 #include <linux/string.h>
16 #include <linux/backing-dev.h>
17 #include <linux/writeback.h>
18 #include <linux/compat.h>
19 #include <linux/xattr.h>
20 #include <linux/posix_acl.h>
21 #include <linux/falloc.h>
22 #include <linux/slab.h>
23 #include <linux/ratelimit.h>
24 #include <linux/btrfs.h>
25 #include <linux/blkdev.h>
26 #include <linux/posix_acl_xattr.h>
27 #include <linux/uio.h>
28 #include <linux/magic.h>
29 #include <linux/iversion.h>
30 #include <linux/swap.h>
31 #include <linux/sched/mm.h>
32 #include <asm/unaligned.h>
35 #include "transaction.h"
36 #include "btrfs_inode.h"
37 #include "print-tree.h"
38 #include "ordered-data.h"
42 #include "compression.h"
44 #include "free-space-cache.h"
45 #include "inode-map.h"
50 #include "delalloc-space.h"
52 struct btrfs_iget_args {
53 struct btrfs_key *location;
54 struct btrfs_root *root;
57 struct btrfs_dio_data {
59 u64 unsubmitted_oe_range_start;
60 u64 unsubmitted_oe_range_end;
64 static const struct inode_operations btrfs_dir_inode_operations;
65 static const struct inode_operations btrfs_symlink_inode_operations;
66 static const struct inode_operations btrfs_dir_ro_inode_operations;
67 static const struct inode_operations btrfs_special_inode_operations;
68 static const struct inode_operations btrfs_file_inode_operations;
69 static const struct address_space_operations btrfs_aops;
70 static const struct file_operations btrfs_dir_file_operations;
71 static const struct extent_io_ops btrfs_extent_io_ops;
73 static struct kmem_cache *btrfs_inode_cachep;
74 struct kmem_cache *btrfs_trans_handle_cachep;
75 struct kmem_cache *btrfs_path_cachep;
76 struct kmem_cache *btrfs_free_space_cachep;
78 static int btrfs_setsize(struct inode *inode, struct iattr *attr);
79 static int btrfs_truncate(struct inode *inode, bool skip_writeback);
80 static int btrfs_finish_ordered_io(struct btrfs_ordered_extent *ordered_extent);
81 static noinline int cow_file_range(struct inode *inode,
82 struct page *locked_page,
83 u64 start, u64 end, u64 delalloc_end,
84 int *page_started, unsigned long *nr_written,
85 int unlock, struct btrfs_dedupe_hash *hash);
86 static struct extent_map *create_io_em(struct inode *inode, u64 start, u64 len,
87 u64 orig_start, u64 block_start,
88 u64 block_len, u64 orig_block_len,
89 u64 ram_bytes, int compress_type,
92 static void __endio_write_update_ordered(struct inode *inode,
93 const u64 offset, const u64 bytes,
97 * Cleanup all submitted ordered extents in specified range to handle errors
98 * from the btrfs_run_delalloc_range() callback.
100 * NOTE: caller must ensure that when an error happens, it can not call
101 * extent_clear_unlock_delalloc() to clear both the bits EXTENT_DO_ACCOUNTING
102 * and EXTENT_DELALLOC simultaneously, because that causes the reserved metadata
103 * to be released, which we want to happen only when finishing the ordered
104 * extent (btrfs_finish_ordered_io()).
106 static inline void btrfs_cleanup_ordered_extents(struct inode *inode,
107 struct page *locked_page,
108 u64 offset, u64 bytes)
110 unsigned long index = offset >> PAGE_SHIFT;
111 unsigned long end_index = (offset + bytes - 1) >> PAGE_SHIFT;
112 u64 page_start = page_offset(locked_page);
113 u64 page_end = page_start + PAGE_SIZE - 1;
117 while (index <= end_index) {
118 page = find_get_page(inode->i_mapping, index);
122 ClearPagePrivate2(page);
127 * In case this page belongs to the delalloc range being instantiated
128 * then skip it, since the first page of a range is going to be
129 * properly cleaned up by the caller of run_delalloc_range
131 if (page_start >= offset && page_end <= (offset + bytes - 1)) {
136 return __endio_write_update_ordered(inode, offset, bytes, false);
139 static int btrfs_dirty_inode(struct inode *inode);
141 #ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
142 void btrfs_test_inode_set_ops(struct inode *inode)
144 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
148 static int btrfs_init_inode_security(struct btrfs_trans_handle *trans,
149 struct inode *inode, struct inode *dir,
150 const struct qstr *qstr)
154 err = btrfs_init_acl(trans, inode, dir);
156 err = btrfs_xattr_security_init(trans, inode, dir, qstr);
161 * this does all the hard work for inserting an inline extent into
162 * the btree. The caller should have done a btrfs_drop_extents so that
163 * no overlapping inline items exist in the btree
165 static int insert_inline_extent(struct btrfs_trans_handle *trans,
166 struct btrfs_path *path, int extent_inserted,
167 struct btrfs_root *root, struct inode *inode,
168 u64 start, size_t size, size_t compressed_size,
170 struct page **compressed_pages)
172 struct extent_buffer *leaf;
173 struct page *page = NULL;
176 struct btrfs_file_extent_item *ei;
178 size_t cur_size = size;
179 unsigned long offset;
181 if (compressed_size && compressed_pages)
182 cur_size = compressed_size;
184 inode_add_bytes(inode, size);
186 if (!extent_inserted) {
187 struct btrfs_key key;
190 key.objectid = btrfs_ino(BTRFS_I(inode));
192 key.type = BTRFS_EXTENT_DATA_KEY;
194 datasize = btrfs_file_extent_calc_inline_size(cur_size);
195 path->leave_spinning = 1;
196 ret = btrfs_insert_empty_item(trans, root, path, &key,
201 leaf = path->nodes[0];
202 ei = btrfs_item_ptr(leaf, path->slots[0],
203 struct btrfs_file_extent_item);
204 btrfs_set_file_extent_generation(leaf, ei, trans->transid);
205 btrfs_set_file_extent_type(leaf, ei, BTRFS_FILE_EXTENT_INLINE);
206 btrfs_set_file_extent_encryption(leaf, ei, 0);
207 btrfs_set_file_extent_other_encoding(leaf, ei, 0);
208 btrfs_set_file_extent_ram_bytes(leaf, ei, size);
209 ptr = btrfs_file_extent_inline_start(ei);
211 if (compress_type != BTRFS_COMPRESS_NONE) {
214 while (compressed_size > 0) {
215 cpage = compressed_pages[i];
216 cur_size = min_t(unsigned long, compressed_size,
219 kaddr = kmap_atomic(cpage);
220 write_extent_buffer(leaf, kaddr, ptr, cur_size);
221 kunmap_atomic(kaddr);
225 compressed_size -= cur_size;
227 btrfs_set_file_extent_compression(leaf, ei,
230 page = find_get_page(inode->i_mapping,
231 start >> PAGE_SHIFT);
232 btrfs_set_file_extent_compression(leaf, ei, 0);
233 kaddr = kmap_atomic(page);
234 offset = offset_in_page(start);
235 write_extent_buffer(leaf, kaddr + offset, ptr, size);
236 kunmap_atomic(kaddr);
239 btrfs_mark_buffer_dirty(leaf);
240 btrfs_release_path(path);
243 * we're an inline extent, so nobody can
244 * extend the file past i_size without locking
245 * a page we already have locked.
247 * We must do any isize and inode updates
248 * before we unlock the pages. Otherwise we
249 * could end up racing with unlink.
251 BTRFS_I(inode)->disk_i_size = inode->i_size;
252 ret = btrfs_update_inode(trans, root, inode);
260 * conditionally insert an inline extent into the file. This
261 * does the checks required to make sure the data is small enough
262 * to fit as an inline extent.
264 static noinline int cow_file_range_inline(struct inode *inode, u64 start,
265 u64 end, size_t compressed_size,
267 struct page **compressed_pages)
269 struct btrfs_root *root = BTRFS_I(inode)->root;
270 struct btrfs_fs_info *fs_info = root->fs_info;
271 struct btrfs_trans_handle *trans;
272 u64 isize = i_size_read(inode);
273 u64 actual_end = min(end + 1, isize);
274 u64 inline_len = actual_end - start;
275 u64 aligned_end = ALIGN(end, fs_info->sectorsize);
276 u64 data_len = inline_len;
278 struct btrfs_path *path;
279 int extent_inserted = 0;
280 u32 extent_item_size;
283 data_len = compressed_size;
286 actual_end > fs_info->sectorsize ||
287 data_len > BTRFS_MAX_INLINE_DATA_SIZE(fs_info) ||
289 (actual_end & (fs_info->sectorsize - 1)) == 0) ||
291 data_len > fs_info->max_inline) {
295 path = btrfs_alloc_path();
299 trans = btrfs_join_transaction(root);
301 btrfs_free_path(path);
302 return PTR_ERR(trans);
304 trans->block_rsv = &BTRFS_I(inode)->block_rsv;
306 if (compressed_size && compressed_pages)
307 extent_item_size = btrfs_file_extent_calc_inline_size(
310 extent_item_size = btrfs_file_extent_calc_inline_size(
313 ret = __btrfs_drop_extents(trans, root, inode, path,
314 start, aligned_end, NULL,
315 1, 1, extent_item_size, &extent_inserted);
317 btrfs_abort_transaction(trans, ret);
321 if (isize > actual_end)
322 inline_len = min_t(u64, isize, actual_end);
323 ret = insert_inline_extent(trans, path, extent_inserted,
325 inline_len, compressed_size,
326 compress_type, compressed_pages);
327 if (ret && ret != -ENOSPC) {
328 btrfs_abort_transaction(trans, ret);
330 } else if (ret == -ENOSPC) {
335 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &BTRFS_I(inode)->runtime_flags);
336 btrfs_drop_extent_cache(BTRFS_I(inode), start, aligned_end - 1, 0);
339 * Don't forget to free the reserved space, as for inlined extent
340 * it won't count as data extent, free them directly here.
341 * And at reserve time, it's always aligned to page size, so
342 * just free one page here.
344 btrfs_qgroup_free_data(inode, NULL, 0, PAGE_SIZE);
345 btrfs_free_path(path);
346 btrfs_end_transaction(trans);
350 struct async_extent {
355 unsigned long nr_pages;
357 struct list_head list;
362 struct page *locked_page;
365 unsigned int write_flags;
366 struct list_head extents;
367 struct btrfs_work work;
372 /* Number of chunks in flight; must be first in the structure */
374 struct async_chunk chunks[];
377 static noinline int add_async_extent(struct async_chunk *cow,
378 u64 start, u64 ram_size,
381 unsigned long nr_pages,
384 struct async_extent *async_extent;
386 async_extent = kmalloc(sizeof(*async_extent), GFP_NOFS);
387 BUG_ON(!async_extent); /* -ENOMEM */
388 async_extent->start = start;
389 async_extent->ram_size = ram_size;
390 async_extent->compressed_size = compressed_size;
391 async_extent->pages = pages;
392 async_extent->nr_pages = nr_pages;
393 async_extent->compress_type = compress_type;
394 list_add_tail(&async_extent->list, &cow->extents);
399 * Check if the inode has flags compatible with compression
401 static inline bool inode_can_compress(struct inode *inode)
403 if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW ||
404 BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)
410 * Check if the inode needs to be submitted to compression, based on mount
411 * options, defragmentation, properties or heuristics.
413 static inline int inode_need_compress(struct inode *inode, u64 start, u64 end)
415 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
417 if (!inode_can_compress(inode)) {
418 WARN(IS_ENABLED(CONFIG_BTRFS_DEBUG),
419 KERN_ERR "BTRFS: unexpected compression for ino %llu\n",
420 btrfs_ino(BTRFS_I(inode)));
424 if (btrfs_test_opt(fs_info, FORCE_COMPRESS))
427 if (BTRFS_I(inode)->defrag_compress)
429 /* bad compression ratios */
430 if (BTRFS_I(inode)->flags & BTRFS_INODE_NOCOMPRESS)
432 if (btrfs_test_opt(fs_info, COMPRESS) ||
433 BTRFS_I(inode)->flags & BTRFS_INODE_COMPRESS ||
434 BTRFS_I(inode)->prop_compress)
435 return btrfs_compress_heuristic(inode, start, end);
439 static inline void inode_should_defrag(struct btrfs_inode *inode,
440 u64 start, u64 end, u64 num_bytes, u64 small_write)
442 /* If this is a small write inside eof, kick off a defrag */
443 if (num_bytes < small_write &&
444 (start > 0 || end + 1 < inode->disk_i_size))
445 btrfs_add_inode_defrag(NULL, inode);
449 * we create compressed extents in two phases. The first
450 * phase compresses a range of pages that have already been
451 * locked (both pages and state bits are locked).
453 * This is done inside an ordered work queue, and the compression
454 * is spread across many cpus. The actual IO submission is step
455 * two, and the ordered work queue takes care of making sure that
456 * happens in the same order things were put onto the queue by
457 * writepages and friends.
459 * If this code finds it can't get good compression, it puts an
460 * entry onto the work queue to write the uncompressed bytes. This
461 * makes sure that both compressed inodes and uncompressed inodes
462 * are written in the same order that the flusher thread sent them
465 static noinline void compress_file_range(struct async_chunk *async_chunk,
468 struct inode *inode = async_chunk->inode;
469 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
470 u64 blocksize = fs_info->sectorsize;
471 u64 start = async_chunk->start;
472 u64 end = async_chunk->end;
475 struct page **pages = NULL;
476 unsigned long nr_pages;
477 unsigned long total_compressed = 0;
478 unsigned long total_in = 0;
481 int compress_type = fs_info->compress_type;
484 inode_should_defrag(BTRFS_I(inode), start, end, end - start + 1,
487 actual_end = min_t(u64, i_size_read(inode), end + 1);
490 nr_pages = (end >> PAGE_SHIFT) - (start >> PAGE_SHIFT) + 1;
491 BUILD_BUG_ON((BTRFS_MAX_COMPRESSED % PAGE_SIZE) != 0);
492 nr_pages = min_t(unsigned long, nr_pages,
493 BTRFS_MAX_COMPRESSED / PAGE_SIZE);
496 * we don't want to send crud past the end of i_size through
497 * compression, that's just a waste of CPU time. So, if the
498 * end of the file is before the start of our current
499 * requested range of bytes, we bail out to the uncompressed
500 * cleanup code that can deal with all of this.
502 * It isn't really the fastest way to fix things, but this is a
503 * very uncommon corner.
505 if (actual_end <= start)
506 goto cleanup_and_bail_uncompressed;
508 total_compressed = actual_end - start;
511 * skip compression for a small file range(<=blocksize) that
512 * isn't an inline extent, since it doesn't save disk space at all.
514 if (total_compressed <= blocksize &&
515 (start > 0 || end + 1 < BTRFS_I(inode)->disk_i_size))
516 goto cleanup_and_bail_uncompressed;
518 total_compressed = min_t(unsigned long, total_compressed,
519 BTRFS_MAX_UNCOMPRESSED);
524 * we do compression for mount -o compress and when the
525 * inode has not been flagged as nocompress. This flag can
526 * change at any time if we discover bad compression ratios.
528 if (inode_need_compress(inode, start, end)) {
530 pages = kcalloc(nr_pages, sizeof(struct page *), GFP_NOFS);
532 /* just bail out to the uncompressed code */
537 if (BTRFS_I(inode)->defrag_compress)
538 compress_type = BTRFS_I(inode)->defrag_compress;
539 else if (BTRFS_I(inode)->prop_compress)
540 compress_type = BTRFS_I(inode)->prop_compress;
543 * we need to call clear_page_dirty_for_io on each
544 * page in the range. Otherwise applications with the file
545 * mmap'd can wander in and change the page contents while
546 * we are compressing them.
548 * If the compression fails for any reason, we set the pages
549 * dirty again later on.
551 * Note that the remaining part is redirtied, the start pointer
552 * has moved, the end is the original one.
555 extent_range_clear_dirty_for_io(inode, start, end);
559 /* Compression level is applied here and only here */
560 ret = btrfs_compress_pages(
561 compress_type | (fs_info->compress_level << 4),
562 inode->i_mapping, start,
569 unsigned long offset = offset_in_page(total_compressed);
570 struct page *page = pages[nr_pages - 1];
573 /* zero the tail end of the last page, we might be
574 * sending it down to disk
577 kaddr = kmap_atomic(page);
578 memset(kaddr + offset, 0,
580 kunmap_atomic(kaddr);
587 /* lets try to make an inline extent */
588 if (ret || total_in < actual_end) {
589 /* we didn't compress the entire range, try
590 * to make an uncompressed inline extent.
592 ret = cow_file_range_inline(inode, start, end, 0,
593 BTRFS_COMPRESS_NONE, NULL);
595 /* try making a compressed inline extent */
596 ret = cow_file_range_inline(inode, start, end,
598 compress_type, pages);
601 unsigned long clear_flags = EXTENT_DELALLOC |
602 EXTENT_DELALLOC_NEW | EXTENT_DEFRAG |
603 EXTENT_DO_ACCOUNTING;
604 unsigned long page_error_op;
606 page_error_op = ret < 0 ? PAGE_SET_ERROR : 0;
609 * inline extent creation worked or returned error,
610 * we don't need to create any more async work items.
611 * Unlock and free up our temp pages.
613 * We use DO_ACCOUNTING here because we need the
614 * delalloc_release_metadata to be done _after_ we drop
615 * our outstanding extent for clearing delalloc for this
618 extent_clear_unlock_delalloc(inode, start, end, end,
631 * we aren't doing an inline extent round the compressed size
632 * up to a block size boundary so the allocator does sane
635 total_compressed = ALIGN(total_compressed, blocksize);
638 * one last check to make sure the compression is really a
639 * win, compare the page count read with the blocks on disk,
640 * compression must free at least one sector size
642 total_in = ALIGN(total_in, PAGE_SIZE);
643 if (total_compressed + blocksize <= total_in) {
647 * The async work queues will take care of doing actual
648 * allocation on disk for these compressed pages, and
649 * will submit them to the elevator.
651 add_async_extent(async_chunk, start, total_in,
652 total_compressed, pages, nr_pages,
655 if (start + total_in < end) {
666 * the compression code ran but failed to make things smaller,
667 * free any pages it allocated and our page pointer array
669 for (i = 0; i < nr_pages; i++) {
670 WARN_ON(pages[i]->mapping);
675 total_compressed = 0;
678 /* flag the file so we don't compress in the future */
679 if (!btrfs_test_opt(fs_info, FORCE_COMPRESS) &&
680 !(BTRFS_I(inode)->prop_compress)) {
681 BTRFS_I(inode)->flags |= BTRFS_INODE_NOCOMPRESS;
684 cleanup_and_bail_uncompressed:
686 * No compression, but we still need to write the pages in the file
687 * we've been given so far. redirty the locked page if it corresponds
688 * to our extent and set things up for the async work queue to run
689 * cow_file_range to do the normal delalloc dance.
691 if (page_offset(async_chunk->locked_page) >= start &&
692 page_offset(async_chunk->locked_page) <= end)
693 __set_page_dirty_nobuffers(async_chunk->locked_page);
694 /* unlocked later on in the async handlers */
697 extent_range_redirty_for_io(inode, start, end);
698 add_async_extent(async_chunk, start, end - start + 1, 0, NULL, 0,
699 BTRFS_COMPRESS_NONE);
705 for (i = 0; i < nr_pages; i++) {
706 WARN_ON(pages[i]->mapping);
712 static void free_async_extent_pages(struct async_extent *async_extent)
716 if (!async_extent->pages)
719 for (i = 0; i < async_extent->nr_pages; i++) {
720 WARN_ON(async_extent->pages[i]->mapping);
721 put_page(async_extent->pages[i]);
723 kfree(async_extent->pages);
724 async_extent->nr_pages = 0;
725 async_extent->pages = NULL;
729 * phase two of compressed writeback. This is the ordered portion
730 * of the code, which only gets called in the order the work was
731 * queued. We walk all the async extents created by compress_file_range
732 * and send them down to the disk.
734 static noinline void submit_compressed_extents(struct async_chunk *async_chunk)
736 struct inode *inode = async_chunk->inode;
737 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
738 struct async_extent *async_extent;
740 struct btrfs_key ins;
741 struct extent_map *em;
742 struct btrfs_root *root = BTRFS_I(inode)->root;
743 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
747 while (!list_empty(&async_chunk->extents)) {
748 async_extent = list_entry(async_chunk->extents.next,
749 struct async_extent, list);
750 list_del(&async_extent->list);
753 lock_extent(io_tree, async_extent->start,
754 async_extent->start + async_extent->ram_size - 1);
755 /* did the compression code fall back to uncompressed IO? */
756 if (!async_extent->pages) {
757 int page_started = 0;
758 unsigned long nr_written = 0;
760 /* allocate blocks */
761 ret = cow_file_range(inode, async_chunk->locked_page,
763 async_extent->start +
764 async_extent->ram_size - 1,
765 async_extent->start +
766 async_extent->ram_size - 1,
767 &page_started, &nr_written, 0,
773 * if page_started, cow_file_range inserted an
774 * inline extent and took care of all the unlocking
775 * and IO for us. Otherwise, we need to submit
776 * all those pages down to the drive.
778 if (!page_started && !ret)
779 extent_write_locked_range(inode,
781 async_extent->start +
782 async_extent->ram_size - 1,
785 unlock_page(async_chunk->locked_page);
791 ret = btrfs_reserve_extent(root, async_extent->ram_size,
792 async_extent->compressed_size,
793 async_extent->compressed_size,
794 0, alloc_hint, &ins, 1, 1);
796 free_async_extent_pages(async_extent);
798 if (ret == -ENOSPC) {
799 unlock_extent(io_tree, async_extent->start,
800 async_extent->start +
801 async_extent->ram_size - 1);
804 * we need to redirty the pages if we decide to
805 * fallback to uncompressed IO, otherwise we
806 * will not submit these pages down to lower
809 extent_range_redirty_for_io(inode,
811 async_extent->start +
812 async_extent->ram_size - 1);
819 * here we're doing allocation and writeback of the
822 em = create_io_em(inode, async_extent->start,
823 async_extent->ram_size, /* len */
824 async_extent->start, /* orig_start */
825 ins.objectid, /* block_start */
826 ins.offset, /* block_len */
827 ins.offset, /* orig_block_len */
828 async_extent->ram_size, /* ram_bytes */
829 async_extent->compress_type,
830 BTRFS_ORDERED_COMPRESSED);
832 /* ret value is not necessary due to void function */
833 goto out_free_reserve;
836 ret = btrfs_add_ordered_extent_compress(inode,
839 async_extent->ram_size,
841 BTRFS_ORDERED_COMPRESSED,
842 async_extent->compress_type);
844 btrfs_drop_extent_cache(BTRFS_I(inode),
846 async_extent->start +
847 async_extent->ram_size - 1, 0);
848 goto out_free_reserve;
850 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
853 * clear dirty, set writeback and unlock the pages.
855 extent_clear_unlock_delalloc(inode, async_extent->start,
856 async_extent->start +
857 async_extent->ram_size - 1,
858 async_extent->start +
859 async_extent->ram_size - 1,
860 NULL, EXTENT_LOCKED | EXTENT_DELALLOC,
861 PAGE_UNLOCK | PAGE_CLEAR_DIRTY |
863 if (btrfs_submit_compressed_write(inode,
865 async_extent->ram_size,
867 ins.offset, async_extent->pages,
868 async_extent->nr_pages,
869 async_chunk->write_flags)) {
870 struct page *p = async_extent->pages[0];
871 const u64 start = async_extent->start;
872 const u64 end = start + async_extent->ram_size - 1;
874 p->mapping = inode->i_mapping;
875 btrfs_writepage_endio_finish_ordered(p, start, end, 0);
878 extent_clear_unlock_delalloc(inode, start, end, end,
882 free_async_extent_pages(async_extent);
884 alloc_hint = ins.objectid + ins.offset;
890 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
891 btrfs_free_reserved_extent(fs_info, ins.objectid, ins.offset, 1);
893 extent_clear_unlock_delalloc(inode, async_extent->start,
894 async_extent->start +
895 async_extent->ram_size - 1,
896 async_extent->start +
897 async_extent->ram_size - 1,
898 NULL, EXTENT_LOCKED | EXTENT_DELALLOC |
899 EXTENT_DELALLOC_NEW |
900 EXTENT_DEFRAG | EXTENT_DO_ACCOUNTING,
901 PAGE_UNLOCK | PAGE_CLEAR_DIRTY |
902 PAGE_SET_WRITEBACK | PAGE_END_WRITEBACK |
904 free_async_extent_pages(async_extent);
909 static u64 get_extent_allocation_hint(struct inode *inode, u64 start,
912 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
913 struct extent_map *em;
916 read_lock(&em_tree->lock);
917 em = search_extent_mapping(em_tree, start, num_bytes);
920 * if block start isn't an actual block number then find the
921 * first block in this inode and use that as a hint. If that
922 * block is also bogus then just don't worry about it.
924 if (em->block_start >= EXTENT_MAP_LAST_BYTE) {
926 em = search_extent_mapping(em_tree, 0, 0);
927 if (em && em->block_start < EXTENT_MAP_LAST_BYTE)
928 alloc_hint = em->block_start;
932 alloc_hint = em->block_start;
936 read_unlock(&em_tree->lock);
942 * when extent_io.c finds a delayed allocation range in the file,
943 * the call backs end up in this code. The basic idea is to
944 * allocate extents on disk for the range, and create ordered data structs
945 * in ram to track those extents.
947 * locked_page is the page that writepage had locked already. We use
948 * it to make sure we don't do extra locks or unlocks.
950 * *page_started is set to one if we unlock locked_page and do everything
951 * required to start IO on it. It may be clean and already done with
954 static noinline int cow_file_range(struct inode *inode,
955 struct page *locked_page,
956 u64 start, u64 end, u64 delalloc_end,
957 int *page_started, unsigned long *nr_written,
958 int unlock, struct btrfs_dedupe_hash *hash)
960 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
961 struct btrfs_root *root = BTRFS_I(inode)->root;
964 unsigned long ram_size;
965 u64 cur_alloc_size = 0;
966 u64 blocksize = fs_info->sectorsize;
967 struct btrfs_key ins;
968 struct extent_map *em;
970 unsigned long page_ops;
971 bool extent_reserved = false;
974 if (btrfs_is_free_space_inode(BTRFS_I(inode))) {
980 num_bytes = ALIGN(end - start + 1, blocksize);
981 num_bytes = max(blocksize, num_bytes);
982 ASSERT(num_bytes <= btrfs_super_total_bytes(fs_info->super_copy));
984 inode_should_defrag(BTRFS_I(inode), start, end, num_bytes, SZ_64K);
987 /* lets try to make an inline extent */
988 ret = cow_file_range_inline(inode, start, end, 0,
989 BTRFS_COMPRESS_NONE, NULL);
992 * We use DO_ACCOUNTING here because we need the
993 * delalloc_release_metadata to be run _after_ we drop
994 * our outstanding extent for clearing delalloc for this
997 extent_clear_unlock_delalloc(inode, start, end,
999 EXTENT_LOCKED | EXTENT_DELALLOC |
1000 EXTENT_DELALLOC_NEW | EXTENT_DEFRAG |
1001 EXTENT_DO_ACCOUNTING, PAGE_UNLOCK |
1002 PAGE_CLEAR_DIRTY | PAGE_SET_WRITEBACK |
1003 PAGE_END_WRITEBACK);
1004 *nr_written = *nr_written +
1005 (end - start + PAGE_SIZE) / PAGE_SIZE;
1008 } else if (ret < 0) {
1013 alloc_hint = get_extent_allocation_hint(inode, start, num_bytes);
1014 btrfs_drop_extent_cache(BTRFS_I(inode), start,
1015 start + num_bytes - 1, 0);
1017 while (num_bytes > 0) {
1018 cur_alloc_size = num_bytes;
1019 ret = btrfs_reserve_extent(root, cur_alloc_size, cur_alloc_size,
1020 fs_info->sectorsize, 0, alloc_hint,
1024 cur_alloc_size = ins.offset;
1025 extent_reserved = true;
1027 ram_size = ins.offset;
1028 em = create_io_em(inode, start, ins.offset, /* len */
1029 start, /* orig_start */
1030 ins.objectid, /* block_start */
1031 ins.offset, /* block_len */
1032 ins.offset, /* orig_block_len */
1033 ram_size, /* ram_bytes */
1034 BTRFS_COMPRESS_NONE, /* compress_type */
1035 BTRFS_ORDERED_REGULAR /* type */);
1040 free_extent_map(em);
1042 ret = btrfs_add_ordered_extent(inode, start, ins.objectid,
1043 ram_size, cur_alloc_size, 0);
1045 goto out_drop_extent_cache;
1047 if (root->root_key.objectid ==
1048 BTRFS_DATA_RELOC_TREE_OBJECTID) {
1049 ret = btrfs_reloc_clone_csums(inode, start,
1052 * Only drop cache here, and process as normal.
1054 * We must not allow extent_clear_unlock_delalloc()
1055 * at out_unlock label to free meta of this ordered
1056 * extent, as its meta should be freed by
1057 * btrfs_finish_ordered_io().
1059 * So we must continue until @start is increased to
1060 * skip current ordered extent.
1063 btrfs_drop_extent_cache(BTRFS_I(inode), start,
1064 start + ram_size - 1, 0);
1067 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
1069 /* we're not doing compressed IO, don't unlock the first
1070 * page (which the caller expects to stay locked), don't
1071 * clear any dirty bits and don't set any writeback bits
1073 * Do set the Private2 bit so we know this page was properly
1074 * setup for writepage
1076 page_ops = unlock ? PAGE_UNLOCK : 0;
1077 page_ops |= PAGE_SET_PRIVATE2;
1079 extent_clear_unlock_delalloc(inode, start,
1080 start + ram_size - 1,
1081 delalloc_end, locked_page,
1082 EXTENT_LOCKED | EXTENT_DELALLOC,
1084 if (num_bytes < cur_alloc_size)
1087 num_bytes -= cur_alloc_size;
1088 alloc_hint = ins.objectid + ins.offset;
1089 start += cur_alloc_size;
1090 extent_reserved = false;
1093 * btrfs_reloc_clone_csums() error, since start is increased
1094 * extent_clear_unlock_delalloc() at out_unlock label won't
1095 * free metadata of current ordered extent, we're OK to exit.
1103 out_drop_extent_cache:
1104 btrfs_drop_extent_cache(BTRFS_I(inode), start, start + ram_size - 1, 0);
1106 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
1107 btrfs_free_reserved_extent(fs_info, ins.objectid, ins.offset, 1);
1109 clear_bits = EXTENT_LOCKED | EXTENT_DELALLOC | EXTENT_DELALLOC_NEW |
1110 EXTENT_DEFRAG | EXTENT_CLEAR_META_RESV;
1111 page_ops = PAGE_UNLOCK | PAGE_CLEAR_DIRTY | PAGE_SET_WRITEBACK |
1114 * If we reserved an extent for our delalloc range (or a subrange) and
1115 * failed to create the respective ordered extent, then it means that
1116 * when we reserved the extent we decremented the extent's size from
1117 * the data space_info's bytes_may_use counter and incremented the
1118 * space_info's bytes_reserved counter by the same amount. We must make
1119 * sure extent_clear_unlock_delalloc() does not try to decrement again
1120 * the data space_info's bytes_may_use counter, therefore we do not pass
1121 * it the flag EXTENT_CLEAR_DATA_RESV.
1123 if (extent_reserved) {
1124 extent_clear_unlock_delalloc(inode, start,
1125 start + cur_alloc_size,
1126 start + cur_alloc_size,
1130 start += cur_alloc_size;
1134 extent_clear_unlock_delalloc(inode, start, end, delalloc_end,
1136 clear_bits | EXTENT_CLEAR_DATA_RESV,
1142 * work queue call back to started compression on a file and pages
1144 static noinline void async_cow_start(struct btrfs_work *work)
1146 struct async_chunk *async_chunk;
1149 async_chunk = container_of(work, struct async_chunk, work);
1151 compress_file_range(async_chunk, &num_added);
1152 if (num_added == 0) {
1153 btrfs_add_delayed_iput(async_chunk->inode);
1154 async_chunk->inode = NULL;
1159 * work queue call back to submit previously compressed pages
1161 static noinline void async_cow_submit(struct btrfs_work *work)
1163 struct async_chunk *async_chunk = container_of(work, struct async_chunk,
1165 struct btrfs_fs_info *fs_info = btrfs_work_owner(work);
1166 unsigned long nr_pages;
1168 nr_pages = (async_chunk->end - async_chunk->start + PAGE_SIZE) >>
1171 /* atomic_sub_return implies a barrier */
1172 if (atomic_sub_return(nr_pages, &fs_info->async_delalloc_pages) <
1174 cond_wake_up_nomb(&fs_info->async_submit_wait);
1177 * ->inode could be NULL if async_chunk_start has failed to compress,
1178 * in which case we don't have anything to submit, yet we need to
1179 * always adjust ->async_delalloc_pages as its paired with the init
1180 * happening in cow_file_range_async
1182 if (async_chunk->inode)
1183 submit_compressed_extents(async_chunk);
1186 static noinline void async_cow_free(struct btrfs_work *work)
1188 struct async_chunk *async_chunk;
1190 async_chunk = container_of(work, struct async_chunk, work);
1191 if (async_chunk->inode)
1192 btrfs_add_delayed_iput(async_chunk->inode);
1194 * Since the pointer to 'pending' is at the beginning of the array of
1195 * async_chunk's, freeing it ensures the whole array has been freed.
1197 if (atomic_dec_and_test(async_chunk->pending))
1198 kvfree(async_chunk->pending);
1201 static int cow_file_range_async(struct inode *inode, struct page *locked_page,
1202 u64 start, u64 end, int *page_started,
1203 unsigned long *nr_written,
1204 unsigned int write_flags)
1206 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1207 struct async_cow *ctx;
1208 struct async_chunk *async_chunk;
1209 unsigned long nr_pages;
1211 u64 num_chunks = DIV_ROUND_UP(end - start, SZ_512K);
1213 bool should_compress;
1216 unlock_extent(&BTRFS_I(inode)->io_tree, start, end);
1218 if (BTRFS_I(inode)->flags & BTRFS_INODE_NOCOMPRESS &&
1219 !btrfs_test_opt(fs_info, FORCE_COMPRESS)) {
1221 should_compress = false;
1223 should_compress = true;
1226 nofs_flag = memalloc_nofs_save();
1227 ctx = kvmalloc(struct_size(ctx, chunks, num_chunks), GFP_KERNEL);
1228 memalloc_nofs_restore(nofs_flag);
1231 unsigned clear_bits = EXTENT_LOCKED | EXTENT_DELALLOC |
1232 EXTENT_DELALLOC_NEW | EXTENT_DEFRAG |
1233 EXTENT_DO_ACCOUNTING;
1234 unsigned long page_ops = PAGE_UNLOCK | PAGE_CLEAR_DIRTY |
1235 PAGE_SET_WRITEBACK | PAGE_END_WRITEBACK |
1238 extent_clear_unlock_delalloc(inode, start, end, 0, locked_page,
1239 clear_bits, page_ops);
1243 async_chunk = ctx->chunks;
1244 atomic_set(&ctx->num_chunks, num_chunks);
1246 for (i = 0; i < num_chunks; i++) {
1247 if (should_compress)
1248 cur_end = min(end, start + SZ_512K - 1);
1253 * igrab is called higher up in the call chain, take only the
1254 * lightweight reference for the callback lifetime
1257 async_chunk[i].pending = &ctx->num_chunks;
1258 async_chunk[i].inode = inode;
1259 async_chunk[i].start = start;
1260 async_chunk[i].end = cur_end;
1261 async_chunk[i].locked_page = locked_page;
1262 async_chunk[i].write_flags = write_flags;
1263 INIT_LIST_HEAD(&async_chunk[i].extents);
1265 btrfs_init_work(&async_chunk[i].work,
1266 btrfs_delalloc_helper,
1267 async_cow_start, async_cow_submit,
1270 nr_pages = DIV_ROUND_UP(cur_end - start, PAGE_SIZE);
1271 atomic_add(nr_pages, &fs_info->async_delalloc_pages);
1273 btrfs_queue_work(fs_info->delalloc_workers, &async_chunk[i].work);
1275 *nr_written += nr_pages;
1276 start = cur_end + 1;
1282 static noinline int csum_exist_in_range(struct btrfs_fs_info *fs_info,
1283 u64 bytenr, u64 num_bytes)
1286 struct btrfs_ordered_sum *sums;
1289 ret = btrfs_lookup_csums_range(fs_info->csum_root, bytenr,
1290 bytenr + num_bytes - 1, &list, 0);
1291 if (ret == 0 && list_empty(&list))
1294 while (!list_empty(&list)) {
1295 sums = list_entry(list.next, struct btrfs_ordered_sum, list);
1296 list_del(&sums->list);
1305 * when nowcow writeback call back. This checks for snapshots or COW copies
1306 * of the extents that exist in the file, and COWs the file as required.
1308 * If no cow copies or snapshots exist, we write directly to the existing
1311 static noinline int run_delalloc_nocow(struct inode *inode,
1312 struct page *locked_page,
1313 u64 start, u64 end, int *page_started, int force,
1314 unsigned long *nr_written)
1316 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1317 struct btrfs_root *root = BTRFS_I(inode)->root;
1318 struct extent_buffer *leaf;
1319 struct btrfs_path *path;
1320 struct btrfs_file_extent_item *fi;
1321 struct btrfs_key found_key;
1322 struct extent_map *em;
1337 u64 ino = btrfs_ino(BTRFS_I(inode));
1339 path = btrfs_alloc_path();
1341 extent_clear_unlock_delalloc(inode, start, end, end,
1343 EXTENT_LOCKED | EXTENT_DELALLOC |
1344 EXTENT_DO_ACCOUNTING |
1345 EXTENT_DEFRAG, PAGE_UNLOCK |
1347 PAGE_SET_WRITEBACK |
1348 PAGE_END_WRITEBACK);
1352 nolock = btrfs_is_free_space_inode(BTRFS_I(inode));
1354 cow_start = (u64)-1;
1357 ret = btrfs_lookup_file_extent(NULL, root, path, ino,
1361 if (ret > 0 && path->slots[0] > 0 && check_prev) {
1362 leaf = path->nodes[0];
1363 btrfs_item_key_to_cpu(leaf, &found_key,
1364 path->slots[0] - 1);
1365 if (found_key.objectid == ino &&
1366 found_key.type == BTRFS_EXTENT_DATA_KEY)
1371 leaf = path->nodes[0];
1372 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
1373 ret = btrfs_next_leaf(root, path);
1375 if (cow_start != (u64)-1)
1376 cur_offset = cow_start;
1381 leaf = path->nodes[0];
1387 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
1389 if (found_key.objectid > ino)
1391 if (WARN_ON_ONCE(found_key.objectid < ino) ||
1392 found_key.type < BTRFS_EXTENT_DATA_KEY) {
1396 if (found_key.type > BTRFS_EXTENT_DATA_KEY ||
1397 found_key.offset > end)
1400 if (found_key.offset > cur_offset) {
1401 extent_end = found_key.offset;
1406 fi = btrfs_item_ptr(leaf, path->slots[0],
1407 struct btrfs_file_extent_item);
1408 extent_type = btrfs_file_extent_type(leaf, fi);
1410 ram_bytes = btrfs_file_extent_ram_bytes(leaf, fi);
1411 if (extent_type == BTRFS_FILE_EXTENT_REG ||
1412 extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
1413 disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
1414 extent_offset = btrfs_file_extent_offset(leaf, fi);
1415 extent_end = found_key.offset +
1416 btrfs_file_extent_num_bytes(leaf, fi);
1418 btrfs_file_extent_disk_num_bytes(leaf, fi);
1419 if (extent_end <= start) {
1423 if (disk_bytenr == 0)
1425 if (btrfs_file_extent_compression(leaf, fi) ||
1426 btrfs_file_extent_encryption(leaf, fi) ||
1427 btrfs_file_extent_other_encoding(leaf, fi))
1430 * Do the same check as in btrfs_cross_ref_exist but
1431 * without the unnecessary search.
1434 btrfs_file_extent_generation(leaf, fi) <=
1435 btrfs_root_last_snapshot(&root->root_item))
1437 if (extent_type == BTRFS_FILE_EXTENT_REG && !force)
1439 if (btrfs_extent_readonly(fs_info, disk_bytenr))
1441 ret = btrfs_cross_ref_exist(root, ino,
1443 extent_offset, disk_bytenr);
1446 * ret could be -EIO if the above fails to read
1450 if (cow_start != (u64)-1)
1451 cur_offset = cow_start;
1455 WARN_ON_ONCE(nolock);
1458 disk_bytenr += extent_offset;
1459 disk_bytenr += cur_offset - found_key.offset;
1460 num_bytes = min(end + 1, extent_end) - cur_offset;
1462 * if there are pending snapshots for this root,
1463 * we fall into common COW way.
1465 if (!nolock && atomic_read(&root->snapshot_force_cow))
1468 * force cow if csum exists in the range.
1469 * this ensure that csum for a given extent are
1470 * either valid or do not exist.
1472 ret = csum_exist_in_range(fs_info, disk_bytenr,
1476 * ret could be -EIO if the above fails to read
1480 if (cow_start != (u64)-1)
1481 cur_offset = cow_start;
1484 WARN_ON_ONCE(nolock);
1487 if (!btrfs_inc_nocow_writers(fs_info, disk_bytenr))
1490 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
1491 extent_end = found_key.offset +
1492 btrfs_file_extent_ram_bytes(leaf, fi);
1493 extent_end = ALIGN(extent_end,
1494 fs_info->sectorsize);
1499 if (extent_end <= start) {
1502 btrfs_dec_nocow_writers(fs_info, disk_bytenr);
1506 if (cow_start == (u64)-1)
1507 cow_start = cur_offset;
1508 cur_offset = extent_end;
1509 if (cur_offset > end)
1515 btrfs_release_path(path);
1516 if (cow_start != (u64)-1) {
1517 ret = cow_file_range(inode, locked_page,
1518 cow_start, found_key.offset - 1,
1519 end, page_started, nr_written, 1,
1523 btrfs_dec_nocow_writers(fs_info,
1527 cow_start = (u64)-1;
1530 if (extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
1531 u64 orig_start = found_key.offset - extent_offset;
1533 em = create_io_em(inode, cur_offset, num_bytes,
1535 disk_bytenr, /* block_start */
1536 num_bytes, /* block_len */
1537 disk_num_bytes, /* orig_block_len */
1538 ram_bytes, BTRFS_COMPRESS_NONE,
1539 BTRFS_ORDERED_PREALLOC);
1542 btrfs_dec_nocow_writers(fs_info,
1547 free_extent_map(em);
1550 if (extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
1551 type = BTRFS_ORDERED_PREALLOC;
1553 type = BTRFS_ORDERED_NOCOW;
1556 ret = btrfs_add_ordered_extent(inode, cur_offset, disk_bytenr,
1557 num_bytes, num_bytes, type);
1559 btrfs_dec_nocow_writers(fs_info, disk_bytenr);
1560 BUG_ON(ret); /* -ENOMEM */
1562 if (root->root_key.objectid ==
1563 BTRFS_DATA_RELOC_TREE_OBJECTID)
1565 * Error handled later, as we must prevent
1566 * extent_clear_unlock_delalloc() in error handler
1567 * from freeing metadata of created ordered extent.
1569 ret = btrfs_reloc_clone_csums(inode, cur_offset,
1572 extent_clear_unlock_delalloc(inode, cur_offset,
1573 cur_offset + num_bytes - 1, end,
1574 locked_page, EXTENT_LOCKED |
1576 EXTENT_CLEAR_DATA_RESV,
1577 PAGE_UNLOCK | PAGE_SET_PRIVATE2);
1579 cur_offset = extent_end;
1582 * btrfs_reloc_clone_csums() error, now we're OK to call error
1583 * handler, as metadata for created ordered extent will only
1584 * be freed by btrfs_finish_ordered_io().
1588 if (cur_offset > end)
1591 btrfs_release_path(path);
1593 if (cur_offset <= end && cow_start == (u64)-1)
1594 cow_start = cur_offset;
1596 if (cow_start != (u64)-1) {
1598 ret = cow_file_range(inode, locked_page, cow_start, end, end,
1599 page_started, nr_written, 1, NULL);
1605 if (ret && cur_offset < end)
1606 extent_clear_unlock_delalloc(inode, cur_offset, end, end,
1607 locked_page, EXTENT_LOCKED |
1608 EXTENT_DELALLOC | EXTENT_DEFRAG |
1609 EXTENT_DO_ACCOUNTING, PAGE_UNLOCK |
1611 PAGE_SET_WRITEBACK |
1612 PAGE_END_WRITEBACK);
1613 btrfs_free_path(path);
1617 static inline int need_force_cow(struct inode *inode, u64 start, u64 end)
1620 if (!(BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW) &&
1621 !(BTRFS_I(inode)->flags & BTRFS_INODE_PREALLOC))
1625 * @defrag_bytes is a hint value, no spinlock held here,
1626 * if is not zero, it means the file is defragging.
1627 * Force cow if given extent needs to be defragged.
1629 if (BTRFS_I(inode)->defrag_bytes &&
1630 test_range_bit(&BTRFS_I(inode)->io_tree, start, end,
1631 EXTENT_DEFRAG, 0, NULL))
1638 * Function to process delayed allocation (create CoW) for ranges which are
1639 * being touched for the first time.
1641 int btrfs_run_delalloc_range(struct inode *inode, struct page *locked_page,
1642 u64 start, u64 end, int *page_started, unsigned long *nr_written,
1643 struct writeback_control *wbc)
1646 int force_cow = need_force_cow(inode, start, end);
1647 unsigned int write_flags = wbc_to_write_flags(wbc);
1649 if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW && !force_cow) {
1650 ret = run_delalloc_nocow(inode, locked_page, start, end,
1651 page_started, 1, nr_written);
1652 } else if (BTRFS_I(inode)->flags & BTRFS_INODE_PREALLOC && !force_cow) {
1653 ret = run_delalloc_nocow(inode, locked_page, start, end,
1654 page_started, 0, nr_written);
1655 } else if (!inode_can_compress(inode) ||
1656 !inode_need_compress(inode, start, end)) {
1657 ret = cow_file_range(inode, locked_page, start, end, end,
1658 page_started, nr_written, 1, NULL);
1660 set_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
1661 &BTRFS_I(inode)->runtime_flags);
1662 ret = cow_file_range_async(inode, locked_page, start, end,
1663 page_started, nr_written,
1667 btrfs_cleanup_ordered_extents(inode, locked_page, start,
1672 void btrfs_split_delalloc_extent(struct inode *inode,
1673 struct extent_state *orig, u64 split)
1677 /* not delalloc, ignore it */
1678 if (!(orig->state & EXTENT_DELALLOC))
1681 size = orig->end - orig->start + 1;
1682 if (size > BTRFS_MAX_EXTENT_SIZE) {
1687 * See the explanation in btrfs_merge_delalloc_extent, the same
1688 * applies here, just in reverse.
1690 new_size = orig->end - split + 1;
1691 num_extents = count_max_extents(new_size);
1692 new_size = split - orig->start;
1693 num_extents += count_max_extents(new_size);
1694 if (count_max_extents(size) >= num_extents)
1698 spin_lock(&BTRFS_I(inode)->lock);
1699 btrfs_mod_outstanding_extents(BTRFS_I(inode), 1);
1700 spin_unlock(&BTRFS_I(inode)->lock);
1704 * Handle merged delayed allocation extents so we can keep track of new extents
1705 * that are just merged onto old extents, such as when we are doing sequential
1706 * writes, so we can properly account for the metadata space we'll need.
1708 void btrfs_merge_delalloc_extent(struct inode *inode, struct extent_state *new,
1709 struct extent_state *other)
1711 u64 new_size, old_size;
1714 /* not delalloc, ignore it */
1715 if (!(other->state & EXTENT_DELALLOC))
1718 if (new->start > other->start)
1719 new_size = new->end - other->start + 1;
1721 new_size = other->end - new->start + 1;
1723 /* we're not bigger than the max, unreserve the space and go */
1724 if (new_size <= BTRFS_MAX_EXTENT_SIZE) {
1725 spin_lock(&BTRFS_I(inode)->lock);
1726 btrfs_mod_outstanding_extents(BTRFS_I(inode), -1);
1727 spin_unlock(&BTRFS_I(inode)->lock);
1732 * We have to add up either side to figure out how many extents were
1733 * accounted for before we merged into one big extent. If the number of
1734 * extents we accounted for is <= the amount we need for the new range
1735 * then we can return, otherwise drop. Think of it like this
1739 * So we've grown the extent by a MAX_SIZE extent, this would mean we
1740 * need 2 outstanding extents, on one side we have 1 and the other side
1741 * we have 1 so they are == and we can return. But in this case
1743 * [MAX_SIZE+4k][MAX_SIZE+4k]
1745 * Each range on their own accounts for 2 extents, but merged together
1746 * they are only 3 extents worth of accounting, so we need to drop in
1749 old_size = other->end - other->start + 1;
1750 num_extents = count_max_extents(old_size);
1751 old_size = new->end - new->start + 1;
1752 num_extents += count_max_extents(old_size);
1753 if (count_max_extents(new_size) >= num_extents)
1756 spin_lock(&BTRFS_I(inode)->lock);
1757 btrfs_mod_outstanding_extents(BTRFS_I(inode), -1);
1758 spin_unlock(&BTRFS_I(inode)->lock);
1761 static void btrfs_add_delalloc_inodes(struct btrfs_root *root,
1762 struct inode *inode)
1764 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1766 spin_lock(&root->delalloc_lock);
1767 if (list_empty(&BTRFS_I(inode)->delalloc_inodes)) {
1768 list_add_tail(&BTRFS_I(inode)->delalloc_inodes,
1769 &root->delalloc_inodes);
1770 set_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1771 &BTRFS_I(inode)->runtime_flags);
1772 root->nr_delalloc_inodes++;
1773 if (root->nr_delalloc_inodes == 1) {
1774 spin_lock(&fs_info->delalloc_root_lock);
1775 BUG_ON(!list_empty(&root->delalloc_root));
1776 list_add_tail(&root->delalloc_root,
1777 &fs_info->delalloc_roots);
1778 spin_unlock(&fs_info->delalloc_root_lock);
1781 spin_unlock(&root->delalloc_lock);
1785 void __btrfs_del_delalloc_inode(struct btrfs_root *root,
1786 struct btrfs_inode *inode)
1788 struct btrfs_fs_info *fs_info = root->fs_info;
1790 if (!list_empty(&inode->delalloc_inodes)) {
1791 list_del_init(&inode->delalloc_inodes);
1792 clear_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1793 &inode->runtime_flags);
1794 root->nr_delalloc_inodes--;
1795 if (!root->nr_delalloc_inodes) {
1796 ASSERT(list_empty(&root->delalloc_inodes));
1797 spin_lock(&fs_info->delalloc_root_lock);
1798 BUG_ON(list_empty(&root->delalloc_root));
1799 list_del_init(&root->delalloc_root);
1800 spin_unlock(&fs_info->delalloc_root_lock);
1805 static void btrfs_del_delalloc_inode(struct btrfs_root *root,
1806 struct btrfs_inode *inode)
1808 spin_lock(&root->delalloc_lock);
1809 __btrfs_del_delalloc_inode(root, inode);
1810 spin_unlock(&root->delalloc_lock);
1814 * Properly track delayed allocation bytes in the inode and to maintain the
1815 * list of inodes that have pending delalloc work to be done.
1817 void btrfs_set_delalloc_extent(struct inode *inode, struct extent_state *state,
1820 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1822 if ((*bits & EXTENT_DEFRAG) && !(*bits & EXTENT_DELALLOC))
1825 * set_bit and clear bit hooks normally require _irqsave/restore
1826 * but in this case, we are only testing for the DELALLOC
1827 * bit, which is only set or cleared with irqs on
1829 if (!(state->state & EXTENT_DELALLOC) && (*bits & EXTENT_DELALLOC)) {
1830 struct btrfs_root *root = BTRFS_I(inode)->root;
1831 u64 len = state->end + 1 - state->start;
1832 u32 num_extents = count_max_extents(len);
1833 bool do_list = !btrfs_is_free_space_inode(BTRFS_I(inode));
1835 spin_lock(&BTRFS_I(inode)->lock);
1836 btrfs_mod_outstanding_extents(BTRFS_I(inode), num_extents);
1837 spin_unlock(&BTRFS_I(inode)->lock);
1839 /* For sanity tests */
1840 if (btrfs_is_testing(fs_info))
1843 percpu_counter_add_batch(&fs_info->delalloc_bytes, len,
1844 fs_info->delalloc_batch);
1845 spin_lock(&BTRFS_I(inode)->lock);
1846 BTRFS_I(inode)->delalloc_bytes += len;
1847 if (*bits & EXTENT_DEFRAG)
1848 BTRFS_I(inode)->defrag_bytes += len;
1849 if (do_list && !test_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1850 &BTRFS_I(inode)->runtime_flags))
1851 btrfs_add_delalloc_inodes(root, inode);
1852 spin_unlock(&BTRFS_I(inode)->lock);
1855 if (!(state->state & EXTENT_DELALLOC_NEW) &&
1856 (*bits & EXTENT_DELALLOC_NEW)) {
1857 spin_lock(&BTRFS_I(inode)->lock);
1858 BTRFS_I(inode)->new_delalloc_bytes += state->end + 1 -
1860 spin_unlock(&BTRFS_I(inode)->lock);
1865 * Once a range is no longer delalloc this function ensures that proper
1866 * accounting happens.
1868 void btrfs_clear_delalloc_extent(struct inode *vfs_inode,
1869 struct extent_state *state, unsigned *bits)
1871 struct btrfs_inode *inode = BTRFS_I(vfs_inode);
1872 struct btrfs_fs_info *fs_info = btrfs_sb(vfs_inode->i_sb);
1873 u64 len = state->end + 1 - state->start;
1874 u32 num_extents = count_max_extents(len);
1876 if ((state->state & EXTENT_DEFRAG) && (*bits & EXTENT_DEFRAG)) {
1877 spin_lock(&inode->lock);
1878 inode->defrag_bytes -= len;
1879 spin_unlock(&inode->lock);
1883 * set_bit and clear bit hooks normally require _irqsave/restore
1884 * but in this case, we are only testing for the DELALLOC
1885 * bit, which is only set or cleared with irqs on
1887 if ((state->state & EXTENT_DELALLOC) && (*bits & EXTENT_DELALLOC)) {
1888 struct btrfs_root *root = inode->root;
1889 bool do_list = !btrfs_is_free_space_inode(inode);
1891 spin_lock(&inode->lock);
1892 btrfs_mod_outstanding_extents(inode, -num_extents);
1893 spin_unlock(&inode->lock);
1896 * We don't reserve metadata space for space cache inodes so we
1897 * don't need to call delalloc_release_metadata if there is an
1900 if (*bits & EXTENT_CLEAR_META_RESV &&
1901 root != fs_info->tree_root)
1902 btrfs_delalloc_release_metadata(inode, len, false);
1904 /* For sanity tests. */
1905 if (btrfs_is_testing(fs_info))
1908 if (root->root_key.objectid != BTRFS_DATA_RELOC_TREE_OBJECTID &&
1909 do_list && !(state->state & EXTENT_NORESERVE) &&
1910 (*bits & EXTENT_CLEAR_DATA_RESV))
1911 btrfs_free_reserved_data_space_noquota(
1915 percpu_counter_add_batch(&fs_info->delalloc_bytes, -len,
1916 fs_info->delalloc_batch);
1917 spin_lock(&inode->lock);
1918 inode->delalloc_bytes -= len;
1919 if (do_list && inode->delalloc_bytes == 0 &&
1920 test_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1921 &inode->runtime_flags))
1922 btrfs_del_delalloc_inode(root, inode);
1923 spin_unlock(&inode->lock);
1926 if ((state->state & EXTENT_DELALLOC_NEW) &&
1927 (*bits & EXTENT_DELALLOC_NEW)) {
1928 spin_lock(&inode->lock);
1929 ASSERT(inode->new_delalloc_bytes >= len);
1930 inode->new_delalloc_bytes -= len;
1931 spin_unlock(&inode->lock);
1936 * btrfs_bio_fits_in_stripe - Checks whether the size of the given bio will fit
1937 * in a chunk's stripe. This function ensures that bios do not span a
1940 * @page - The page we are about to add to the bio
1941 * @size - size we want to add to the bio
1942 * @bio - bio we want to ensure is smaller than a stripe
1943 * @bio_flags - flags of the bio
1945 * return 1 if page cannot be added to the bio
1946 * return 0 if page can be added to the bio
1947 * return error otherwise
1949 int btrfs_bio_fits_in_stripe(struct page *page, size_t size, struct bio *bio,
1950 unsigned long bio_flags)
1952 struct inode *inode = page->mapping->host;
1953 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1954 u64 logical = (u64)bio->bi_iter.bi_sector << 9;
1958 struct btrfs_io_geometry geom;
1960 if (bio_flags & EXTENT_BIO_COMPRESSED)
1963 length = bio->bi_iter.bi_size;
1964 map_length = length;
1965 ret = btrfs_get_io_geometry(fs_info, btrfs_op(bio), logical, map_length,
1970 if (geom.len < length + size)
1976 * in order to insert checksums into the metadata in large chunks,
1977 * we wait until bio submission time. All the pages in the bio are
1978 * checksummed and sums are attached onto the ordered extent record.
1980 * At IO completion time the cums attached on the ordered extent record
1981 * are inserted into the btree
1983 static blk_status_t btrfs_submit_bio_start(void *private_data, struct bio *bio,
1986 struct inode *inode = private_data;
1987 blk_status_t ret = 0;
1989 ret = btrfs_csum_one_bio(inode, bio, 0, 0);
1990 BUG_ON(ret); /* -ENOMEM */
1995 * extent_io.c submission hook. This does the right thing for csum calculation
1996 * on write, or reading the csums from the tree before a read.
1998 * Rules about async/sync submit,
1999 * a) read: sync submit
2001 * b) write without checksum: sync submit
2003 * c) write with checksum:
2004 * c-1) if bio is issued by fsync: sync submit
2005 * (sync_writers != 0)
2007 * c-2) if root is reloc root: sync submit
2008 * (only in case of buffered IO)
2010 * c-3) otherwise: async submit
2012 static blk_status_t btrfs_submit_bio_hook(struct inode *inode, struct bio *bio,
2014 unsigned long bio_flags)
2017 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2018 struct btrfs_root *root = BTRFS_I(inode)->root;
2019 enum btrfs_wq_endio_type metadata = BTRFS_WQ_ENDIO_DATA;
2020 blk_status_t ret = 0;
2022 int async = !atomic_read(&BTRFS_I(inode)->sync_writers);
2024 skip_sum = BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM;
2026 if (btrfs_is_free_space_inode(BTRFS_I(inode)))
2027 metadata = BTRFS_WQ_ENDIO_FREE_SPACE;
2029 if (bio_op(bio) != REQ_OP_WRITE) {
2030 ret = btrfs_bio_wq_end_io(fs_info, bio, metadata);
2034 if (bio_flags & EXTENT_BIO_COMPRESSED) {
2035 ret = btrfs_submit_compressed_read(inode, bio,
2039 } else if (!skip_sum) {
2040 ret = btrfs_lookup_bio_sums(inode, bio, NULL);
2045 } else if (async && !skip_sum) {
2046 /* csum items have already been cloned */
2047 if (root->root_key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID)
2049 /* we're doing a write, do the async checksumming */
2050 ret = btrfs_wq_submit_bio(fs_info, bio, mirror_num, bio_flags,
2051 0, inode, btrfs_submit_bio_start);
2053 } else if (!skip_sum) {
2054 ret = btrfs_csum_one_bio(inode, bio, 0, 0);
2060 ret = btrfs_map_bio(fs_info, bio, mirror_num, 0);
2064 bio->bi_status = ret;
2071 * given a list of ordered sums record them in the inode. This happens
2072 * at IO completion time based on sums calculated at bio submission time.
2074 static noinline int add_pending_csums(struct btrfs_trans_handle *trans,
2075 struct inode *inode, struct list_head *list)
2077 struct btrfs_ordered_sum *sum;
2080 list_for_each_entry(sum, list, list) {
2081 trans->adding_csums = true;
2082 ret = btrfs_csum_file_blocks(trans,
2083 BTRFS_I(inode)->root->fs_info->csum_root, sum);
2084 trans->adding_csums = false;
2091 int btrfs_set_extent_delalloc(struct inode *inode, u64 start, u64 end,
2092 unsigned int extra_bits,
2093 struct extent_state **cached_state, int dedupe)
2095 WARN_ON(PAGE_ALIGNED(end));
2096 return set_extent_delalloc(&BTRFS_I(inode)->io_tree, start, end,
2097 extra_bits, cached_state);
2100 /* see btrfs_writepage_start_hook for details on why this is required */
2101 struct btrfs_writepage_fixup {
2103 struct btrfs_work work;
2106 static void btrfs_writepage_fixup_worker(struct btrfs_work *work)
2108 struct btrfs_writepage_fixup *fixup;
2109 struct btrfs_ordered_extent *ordered;
2110 struct extent_state *cached_state = NULL;
2111 struct extent_changeset *data_reserved = NULL;
2113 struct inode *inode;
2118 fixup = container_of(work, struct btrfs_writepage_fixup, work);
2122 if (!page->mapping || !PageDirty(page) || !PageChecked(page)) {
2123 ClearPageChecked(page);
2127 inode = page->mapping->host;
2128 page_start = page_offset(page);
2129 page_end = page_offset(page) + PAGE_SIZE - 1;
2131 lock_extent_bits(&BTRFS_I(inode)->io_tree, page_start, page_end,
2134 /* already ordered? We're done */
2135 if (PagePrivate2(page))
2138 ordered = btrfs_lookup_ordered_range(BTRFS_I(inode), page_start,
2141 unlock_extent_cached(&BTRFS_I(inode)->io_tree, page_start,
2142 page_end, &cached_state);
2144 btrfs_start_ordered_extent(inode, ordered, 1);
2145 btrfs_put_ordered_extent(ordered);
2149 ret = btrfs_delalloc_reserve_space(inode, &data_reserved, page_start,
2152 mapping_set_error(page->mapping, ret);
2153 end_extent_writepage(page, ret, page_start, page_end);
2154 ClearPageChecked(page);
2158 ret = btrfs_set_extent_delalloc(inode, page_start, page_end, 0,
2161 mapping_set_error(page->mapping, ret);
2162 end_extent_writepage(page, ret, page_start, page_end);
2163 ClearPageChecked(page);
2167 ClearPageChecked(page);
2168 set_page_dirty(page);
2169 btrfs_delalloc_release_extents(BTRFS_I(inode), PAGE_SIZE, false);
2171 unlock_extent_cached(&BTRFS_I(inode)->io_tree, page_start, page_end,
2177 extent_changeset_free(data_reserved);
2181 * There are a few paths in the higher layers of the kernel that directly
2182 * set the page dirty bit without asking the filesystem if it is a
2183 * good idea. This causes problems because we want to make sure COW
2184 * properly happens and the data=ordered rules are followed.
2186 * In our case any range that doesn't have the ORDERED bit set
2187 * hasn't been properly setup for IO. We kick off an async process
2188 * to fix it up. The async helper will wait for ordered extents, set
2189 * the delalloc bit and make it safe to write the page.
2191 int btrfs_writepage_cow_fixup(struct page *page, u64 start, u64 end)
2193 struct inode *inode = page->mapping->host;
2194 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2195 struct btrfs_writepage_fixup *fixup;
2197 /* this page is properly in the ordered list */
2198 if (TestClearPagePrivate2(page))
2201 if (PageChecked(page))
2204 fixup = kzalloc(sizeof(*fixup), GFP_NOFS);
2208 SetPageChecked(page);
2210 btrfs_init_work(&fixup->work, btrfs_fixup_helper,
2211 btrfs_writepage_fixup_worker, NULL, NULL);
2213 btrfs_queue_work(fs_info->fixup_workers, &fixup->work);
2217 static int insert_reserved_file_extent(struct btrfs_trans_handle *trans,
2218 struct inode *inode, u64 file_pos,
2219 u64 disk_bytenr, u64 disk_num_bytes,
2220 u64 num_bytes, u64 ram_bytes,
2221 u8 compression, u8 encryption,
2222 u16 other_encoding, int extent_type)
2224 struct btrfs_root *root = BTRFS_I(inode)->root;
2225 struct btrfs_file_extent_item *fi;
2226 struct btrfs_path *path;
2227 struct extent_buffer *leaf;
2228 struct btrfs_key ins;
2230 int extent_inserted = 0;
2233 path = btrfs_alloc_path();
2238 * we may be replacing one extent in the tree with another.
2239 * The new extent is pinned in the extent map, and we don't want
2240 * to drop it from the cache until it is completely in the btree.
2242 * So, tell btrfs_drop_extents to leave this extent in the cache.
2243 * the caller is expected to unpin it and allow it to be merged
2246 ret = __btrfs_drop_extents(trans, root, inode, path, file_pos,
2247 file_pos + num_bytes, NULL, 0,
2248 1, sizeof(*fi), &extent_inserted);
2252 if (!extent_inserted) {
2253 ins.objectid = btrfs_ino(BTRFS_I(inode));
2254 ins.offset = file_pos;
2255 ins.type = BTRFS_EXTENT_DATA_KEY;
2257 path->leave_spinning = 1;
2258 ret = btrfs_insert_empty_item(trans, root, path, &ins,
2263 leaf = path->nodes[0];
2264 fi = btrfs_item_ptr(leaf, path->slots[0],
2265 struct btrfs_file_extent_item);
2266 btrfs_set_file_extent_generation(leaf, fi, trans->transid);
2267 btrfs_set_file_extent_type(leaf, fi, extent_type);
2268 btrfs_set_file_extent_disk_bytenr(leaf, fi, disk_bytenr);
2269 btrfs_set_file_extent_disk_num_bytes(leaf, fi, disk_num_bytes);
2270 btrfs_set_file_extent_offset(leaf, fi, 0);
2271 btrfs_set_file_extent_num_bytes(leaf, fi, num_bytes);
2272 btrfs_set_file_extent_ram_bytes(leaf, fi, ram_bytes);
2273 btrfs_set_file_extent_compression(leaf, fi, compression);
2274 btrfs_set_file_extent_encryption(leaf, fi, encryption);
2275 btrfs_set_file_extent_other_encoding(leaf, fi, other_encoding);
2277 btrfs_mark_buffer_dirty(leaf);
2278 btrfs_release_path(path);
2280 inode_add_bytes(inode, num_bytes);
2282 ins.objectid = disk_bytenr;
2283 ins.offset = disk_num_bytes;
2284 ins.type = BTRFS_EXTENT_ITEM_KEY;
2287 * Release the reserved range from inode dirty range map, as it is
2288 * already moved into delayed_ref_head
2290 ret = btrfs_qgroup_release_data(inode, file_pos, ram_bytes);
2294 ret = btrfs_alloc_reserved_file_extent(trans, root,
2295 btrfs_ino(BTRFS_I(inode)),
2296 file_pos, qg_released, &ins);
2298 btrfs_free_path(path);
2303 /* snapshot-aware defrag */
2304 struct sa_defrag_extent_backref {
2305 struct rb_node node;
2306 struct old_sa_defrag_extent *old;
2315 struct old_sa_defrag_extent {
2316 struct list_head list;
2317 struct new_sa_defrag_extent *new;
2326 struct new_sa_defrag_extent {
2327 struct rb_root root;
2328 struct list_head head;
2329 struct btrfs_path *path;
2330 struct inode *inode;
2338 static int backref_comp(struct sa_defrag_extent_backref *b1,
2339 struct sa_defrag_extent_backref *b2)
2341 if (b1->root_id < b2->root_id)
2343 else if (b1->root_id > b2->root_id)
2346 if (b1->inum < b2->inum)
2348 else if (b1->inum > b2->inum)
2351 if (b1->file_pos < b2->file_pos)
2353 else if (b1->file_pos > b2->file_pos)
2357 * [------------------------------] ===> (a range of space)
2358 * |<--->| |<---->| =============> (fs/file tree A)
2359 * |<---------------------------->| ===> (fs/file tree B)
2361 * A range of space can refer to two file extents in one tree while
2362 * refer to only one file extent in another tree.
2364 * So we may process a disk offset more than one time(two extents in A)
2365 * and locate at the same extent(one extent in B), then insert two same
2366 * backrefs(both refer to the extent in B).
2371 static void backref_insert(struct rb_root *root,
2372 struct sa_defrag_extent_backref *backref)
2374 struct rb_node **p = &root->rb_node;
2375 struct rb_node *parent = NULL;
2376 struct sa_defrag_extent_backref *entry;
2381 entry = rb_entry(parent, struct sa_defrag_extent_backref, node);
2383 ret = backref_comp(backref, entry);
2387 p = &(*p)->rb_right;
2390 rb_link_node(&backref->node, parent, p);
2391 rb_insert_color(&backref->node, root);
2395 * Note the backref might has changed, and in this case we just return 0.
2397 static noinline int record_one_backref(u64 inum, u64 offset, u64 root_id,
2400 struct btrfs_file_extent_item *extent;
2401 struct old_sa_defrag_extent *old = ctx;
2402 struct new_sa_defrag_extent *new = old->new;
2403 struct btrfs_path *path = new->path;
2404 struct btrfs_key key;
2405 struct btrfs_root *root;
2406 struct sa_defrag_extent_backref *backref;
2407 struct extent_buffer *leaf;
2408 struct inode *inode = new->inode;
2409 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2415 if (BTRFS_I(inode)->root->root_key.objectid == root_id &&
2416 inum == btrfs_ino(BTRFS_I(inode)))
2419 key.objectid = root_id;
2420 key.type = BTRFS_ROOT_ITEM_KEY;
2421 key.offset = (u64)-1;
2423 root = btrfs_read_fs_root_no_name(fs_info, &key);
2425 if (PTR_ERR(root) == -ENOENT)
2428 btrfs_debug(fs_info, "inum=%llu, offset=%llu, root_id=%llu",
2429 inum, offset, root_id);
2430 return PTR_ERR(root);
2433 key.objectid = inum;
2434 key.type = BTRFS_EXTENT_DATA_KEY;
2435 if (offset > (u64)-1 << 32)
2438 key.offset = offset;
2440 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2441 if (WARN_ON(ret < 0))
2448 leaf = path->nodes[0];
2449 slot = path->slots[0];
2451 if (slot >= btrfs_header_nritems(leaf)) {
2452 ret = btrfs_next_leaf(root, path);
2455 } else if (ret > 0) {
2464 btrfs_item_key_to_cpu(leaf, &key, slot);
2466 if (key.objectid > inum)
2469 if (key.objectid < inum || key.type != BTRFS_EXTENT_DATA_KEY)
2472 extent = btrfs_item_ptr(leaf, slot,
2473 struct btrfs_file_extent_item);
2475 if (btrfs_file_extent_disk_bytenr(leaf, extent) != old->bytenr)
2479 * 'offset' refers to the exact key.offset,
2480 * NOT the 'offset' field in btrfs_extent_data_ref, ie.
2481 * (key.offset - extent_offset).
2483 if (key.offset != offset)
2486 extent_offset = btrfs_file_extent_offset(leaf, extent);
2487 num_bytes = btrfs_file_extent_num_bytes(leaf, extent);
2489 if (extent_offset >= old->extent_offset + old->offset +
2490 old->len || extent_offset + num_bytes <=
2491 old->extent_offset + old->offset)
2496 backref = kmalloc(sizeof(*backref), GFP_NOFS);
2502 backref->root_id = root_id;
2503 backref->inum = inum;
2504 backref->file_pos = offset;
2505 backref->num_bytes = num_bytes;
2506 backref->extent_offset = extent_offset;
2507 backref->generation = btrfs_file_extent_generation(leaf, extent);
2509 backref_insert(&new->root, backref);
2512 btrfs_release_path(path);
2517 static noinline bool record_extent_backrefs(struct btrfs_path *path,
2518 struct new_sa_defrag_extent *new)
2520 struct btrfs_fs_info *fs_info = btrfs_sb(new->inode->i_sb);
2521 struct old_sa_defrag_extent *old, *tmp;
2526 list_for_each_entry_safe(old, tmp, &new->head, list) {
2527 ret = iterate_inodes_from_logical(old->bytenr +
2528 old->extent_offset, fs_info,
2529 path, record_one_backref,
2531 if (ret < 0 && ret != -ENOENT)
2534 /* no backref to be processed for this extent */
2536 list_del(&old->list);
2541 if (list_empty(&new->head))
2547 static int relink_is_mergable(struct extent_buffer *leaf,
2548 struct btrfs_file_extent_item *fi,
2549 struct new_sa_defrag_extent *new)
2551 if (btrfs_file_extent_disk_bytenr(leaf, fi) != new->bytenr)
2554 if (btrfs_file_extent_type(leaf, fi) != BTRFS_FILE_EXTENT_REG)
2557 if (btrfs_file_extent_compression(leaf, fi) != new->compress_type)
2560 if (btrfs_file_extent_encryption(leaf, fi) ||
2561 btrfs_file_extent_other_encoding(leaf, fi))
2568 * Note the backref might has changed, and in this case we just return 0.
2570 static noinline int relink_extent_backref(struct btrfs_path *path,
2571 struct sa_defrag_extent_backref *prev,
2572 struct sa_defrag_extent_backref *backref)
2574 struct btrfs_file_extent_item *extent;
2575 struct btrfs_file_extent_item *item;
2576 struct btrfs_ordered_extent *ordered;
2577 struct btrfs_trans_handle *trans;
2578 struct btrfs_ref ref = { 0 };
2579 struct btrfs_root *root;
2580 struct btrfs_key key;
2581 struct extent_buffer *leaf;
2582 struct old_sa_defrag_extent *old = backref->old;
2583 struct new_sa_defrag_extent *new = old->new;
2584 struct btrfs_fs_info *fs_info = btrfs_sb(new->inode->i_sb);
2585 struct inode *inode;
2586 struct extent_state *cached = NULL;
2595 if (prev && prev->root_id == backref->root_id &&
2596 prev->inum == backref->inum &&
2597 prev->file_pos + prev->num_bytes == backref->file_pos)
2600 /* step 1: get root */
2601 key.objectid = backref->root_id;
2602 key.type = BTRFS_ROOT_ITEM_KEY;
2603 key.offset = (u64)-1;
2605 index = srcu_read_lock(&fs_info->subvol_srcu);
2607 root = btrfs_read_fs_root_no_name(fs_info, &key);
2609 srcu_read_unlock(&fs_info->subvol_srcu, index);
2610 if (PTR_ERR(root) == -ENOENT)
2612 return PTR_ERR(root);
2615 if (btrfs_root_readonly(root)) {
2616 srcu_read_unlock(&fs_info->subvol_srcu, index);
2620 /* step 2: get inode */
2621 key.objectid = backref->inum;
2622 key.type = BTRFS_INODE_ITEM_KEY;
2625 inode = btrfs_iget(fs_info->sb, &key, root, NULL);
2626 if (IS_ERR(inode)) {
2627 srcu_read_unlock(&fs_info->subvol_srcu, index);
2631 srcu_read_unlock(&fs_info->subvol_srcu, index);
2633 /* step 3: relink backref */
2634 lock_start = backref->file_pos;
2635 lock_end = backref->file_pos + backref->num_bytes - 1;
2636 lock_extent_bits(&BTRFS_I(inode)->io_tree, lock_start, lock_end,
2639 ordered = btrfs_lookup_first_ordered_extent(inode, lock_end);
2641 btrfs_put_ordered_extent(ordered);
2645 trans = btrfs_join_transaction(root);
2646 if (IS_ERR(trans)) {
2647 ret = PTR_ERR(trans);
2651 key.objectid = backref->inum;
2652 key.type = BTRFS_EXTENT_DATA_KEY;
2653 key.offset = backref->file_pos;
2655 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2658 } else if (ret > 0) {
2663 extent = btrfs_item_ptr(path->nodes[0], path->slots[0],
2664 struct btrfs_file_extent_item);
2666 if (btrfs_file_extent_generation(path->nodes[0], extent) !=
2667 backref->generation)
2670 btrfs_release_path(path);
2672 start = backref->file_pos;
2673 if (backref->extent_offset < old->extent_offset + old->offset)
2674 start += old->extent_offset + old->offset -
2675 backref->extent_offset;
2677 len = min(backref->extent_offset + backref->num_bytes,
2678 old->extent_offset + old->offset + old->len);
2679 len -= max(backref->extent_offset, old->extent_offset + old->offset);
2681 ret = btrfs_drop_extents(trans, root, inode, start,
2686 key.objectid = btrfs_ino(BTRFS_I(inode));
2687 key.type = BTRFS_EXTENT_DATA_KEY;
2690 path->leave_spinning = 1;
2692 struct btrfs_file_extent_item *fi;
2694 struct btrfs_key found_key;
2696 ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
2701 leaf = path->nodes[0];
2702 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
2704 fi = btrfs_item_ptr(leaf, path->slots[0],
2705 struct btrfs_file_extent_item);
2706 extent_len = btrfs_file_extent_num_bytes(leaf, fi);
2708 if (extent_len + found_key.offset == start &&
2709 relink_is_mergable(leaf, fi, new)) {
2710 btrfs_set_file_extent_num_bytes(leaf, fi,
2712 btrfs_mark_buffer_dirty(leaf);
2713 inode_add_bytes(inode, len);
2719 btrfs_release_path(path);
2724 ret = btrfs_insert_empty_item(trans, root, path, &key,
2727 btrfs_abort_transaction(trans, ret);
2731 leaf = path->nodes[0];
2732 item = btrfs_item_ptr(leaf, path->slots[0],
2733 struct btrfs_file_extent_item);
2734 btrfs_set_file_extent_disk_bytenr(leaf, item, new->bytenr);
2735 btrfs_set_file_extent_disk_num_bytes(leaf, item, new->disk_len);
2736 btrfs_set_file_extent_offset(leaf, item, start - new->file_pos);
2737 btrfs_set_file_extent_num_bytes(leaf, item, len);
2738 btrfs_set_file_extent_ram_bytes(leaf, item, new->len);
2739 btrfs_set_file_extent_generation(leaf, item, trans->transid);
2740 btrfs_set_file_extent_type(leaf, item, BTRFS_FILE_EXTENT_REG);
2741 btrfs_set_file_extent_compression(leaf, item, new->compress_type);
2742 btrfs_set_file_extent_encryption(leaf, item, 0);
2743 btrfs_set_file_extent_other_encoding(leaf, item, 0);
2745 btrfs_mark_buffer_dirty(leaf);
2746 inode_add_bytes(inode, len);
2747 btrfs_release_path(path);
2749 btrfs_init_generic_ref(&ref, BTRFS_ADD_DELAYED_REF, new->bytenr,
2751 btrfs_init_data_ref(&ref, backref->root_id, backref->inum,
2752 new->file_pos); /* start - extent_offset */
2753 ret = btrfs_inc_extent_ref(trans, &ref);
2755 btrfs_abort_transaction(trans, ret);
2761 btrfs_release_path(path);
2762 path->leave_spinning = 0;
2763 btrfs_end_transaction(trans);
2765 unlock_extent_cached(&BTRFS_I(inode)->io_tree, lock_start, lock_end,
2771 static void free_sa_defrag_extent(struct new_sa_defrag_extent *new)
2773 struct old_sa_defrag_extent *old, *tmp;
2778 list_for_each_entry_safe(old, tmp, &new->head, list) {
2784 static void relink_file_extents(struct new_sa_defrag_extent *new)
2786 struct btrfs_fs_info *fs_info = btrfs_sb(new->inode->i_sb);
2787 struct btrfs_path *path;
2788 struct sa_defrag_extent_backref *backref;
2789 struct sa_defrag_extent_backref *prev = NULL;
2790 struct rb_node *node;
2793 path = btrfs_alloc_path();
2797 if (!record_extent_backrefs(path, new)) {
2798 btrfs_free_path(path);
2801 btrfs_release_path(path);
2804 node = rb_first(&new->root);
2807 rb_erase(node, &new->root);
2809 backref = rb_entry(node, struct sa_defrag_extent_backref, node);
2811 ret = relink_extent_backref(path, prev, backref);
2824 btrfs_free_path(path);
2826 free_sa_defrag_extent(new);
2828 atomic_dec(&fs_info->defrag_running);
2829 wake_up(&fs_info->transaction_wait);
2832 static struct new_sa_defrag_extent *
2833 record_old_file_extents(struct inode *inode,
2834 struct btrfs_ordered_extent *ordered)
2836 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2837 struct btrfs_root *root = BTRFS_I(inode)->root;
2838 struct btrfs_path *path;
2839 struct btrfs_key key;
2840 struct old_sa_defrag_extent *old;
2841 struct new_sa_defrag_extent *new;
2844 new = kmalloc(sizeof(*new), GFP_NOFS);
2849 new->file_pos = ordered->file_offset;
2850 new->len = ordered->len;
2851 new->bytenr = ordered->start;
2852 new->disk_len = ordered->disk_len;
2853 new->compress_type = ordered->compress_type;
2854 new->root = RB_ROOT;
2855 INIT_LIST_HEAD(&new->head);
2857 path = btrfs_alloc_path();
2861 key.objectid = btrfs_ino(BTRFS_I(inode));
2862 key.type = BTRFS_EXTENT_DATA_KEY;
2863 key.offset = new->file_pos;
2865 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2868 if (ret > 0 && path->slots[0] > 0)
2871 /* find out all the old extents for the file range */
2873 struct btrfs_file_extent_item *extent;
2874 struct extent_buffer *l;
2883 slot = path->slots[0];
2885 if (slot >= btrfs_header_nritems(l)) {
2886 ret = btrfs_next_leaf(root, path);
2894 btrfs_item_key_to_cpu(l, &key, slot);
2896 if (key.objectid != btrfs_ino(BTRFS_I(inode)))
2898 if (key.type != BTRFS_EXTENT_DATA_KEY)
2900 if (key.offset >= new->file_pos + new->len)
2903 extent = btrfs_item_ptr(l, slot, struct btrfs_file_extent_item);
2905 num_bytes = btrfs_file_extent_num_bytes(l, extent);
2906 if (key.offset + num_bytes < new->file_pos)
2909 disk_bytenr = btrfs_file_extent_disk_bytenr(l, extent);
2913 extent_offset = btrfs_file_extent_offset(l, extent);
2915 old = kmalloc(sizeof(*old), GFP_NOFS);
2919 offset = max(new->file_pos, key.offset);
2920 end = min(new->file_pos + new->len, key.offset + num_bytes);
2922 old->bytenr = disk_bytenr;
2923 old->extent_offset = extent_offset;
2924 old->offset = offset - key.offset;
2925 old->len = end - offset;
2928 list_add_tail(&old->list, &new->head);
2934 btrfs_free_path(path);
2935 atomic_inc(&fs_info->defrag_running);
2940 btrfs_free_path(path);
2942 free_sa_defrag_extent(new);
2946 static void btrfs_release_delalloc_bytes(struct btrfs_fs_info *fs_info,
2949 struct btrfs_block_group_cache *cache;
2951 cache = btrfs_lookup_block_group(fs_info, start);
2954 spin_lock(&cache->lock);
2955 cache->delalloc_bytes -= len;
2956 spin_unlock(&cache->lock);
2958 btrfs_put_block_group(cache);
2961 /* as ordered data IO finishes, this gets called so we can finish
2962 * an ordered extent if the range of bytes in the file it covers are
2965 static int btrfs_finish_ordered_io(struct btrfs_ordered_extent *ordered_extent)
2967 struct inode *inode = ordered_extent->inode;
2968 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2969 struct btrfs_root *root = BTRFS_I(inode)->root;
2970 struct btrfs_trans_handle *trans = NULL;
2971 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
2972 struct extent_state *cached_state = NULL;
2973 struct new_sa_defrag_extent *new = NULL;
2974 int compress_type = 0;
2976 u64 logical_len = ordered_extent->len;
2978 bool truncated = false;
2979 bool range_locked = false;
2980 bool clear_new_delalloc_bytes = false;
2981 bool clear_reserved_extent = true;
2983 if (!test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags) &&
2984 !test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags) &&
2985 !test_bit(BTRFS_ORDERED_DIRECT, &ordered_extent->flags))
2986 clear_new_delalloc_bytes = true;
2988 nolock = btrfs_is_free_space_inode(BTRFS_I(inode));
2990 if (test_bit(BTRFS_ORDERED_IOERR, &ordered_extent->flags)) {
2995 btrfs_free_io_failure_record(BTRFS_I(inode),
2996 ordered_extent->file_offset,
2997 ordered_extent->file_offset +
2998 ordered_extent->len - 1);
3000 if (test_bit(BTRFS_ORDERED_TRUNCATED, &ordered_extent->flags)) {
3002 logical_len = ordered_extent->truncated_len;
3003 /* Truncated the entire extent, don't bother adding */
3008 if (test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags)) {
3009 BUG_ON(!list_empty(&ordered_extent->list)); /* Logic error */
3012 * For mwrite(mmap + memset to write) case, we still reserve
3013 * space for NOCOW range.
3014 * As NOCOW won't cause a new delayed ref, just free the space
3016 btrfs_qgroup_free_data(inode, NULL, ordered_extent->file_offset,
3017 ordered_extent->len);
3018 btrfs_ordered_update_i_size(inode, 0, ordered_extent);
3020 trans = btrfs_join_transaction_nolock(root);
3022 trans = btrfs_join_transaction(root);
3023 if (IS_ERR(trans)) {
3024 ret = PTR_ERR(trans);
3028 trans->block_rsv = &BTRFS_I(inode)->block_rsv;
3029 ret = btrfs_update_inode_fallback(trans, root, inode);
3030 if (ret) /* -ENOMEM or corruption */
3031 btrfs_abort_transaction(trans, ret);
3035 range_locked = true;
3036 lock_extent_bits(io_tree, ordered_extent->file_offset,
3037 ordered_extent->file_offset + ordered_extent->len - 1,
3040 ret = test_range_bit(io_tree, ordered_extent->file_offset,
3041 ordered_extent->file_offset + ordered_extent->len - 1,
3042 EXTENT_DEFRAG, 0, cached_state);
3044 u64 last_snapshot = btrfs_root_last_snapshot(&root->root_item);
3045 if (0 && last_snapshot >= BTRFS_I(inode)->generation)
3046 /* the inode is shared */
3047 new = record_old_file_extents(inode, ordered_extent);
3049 clear_extent_bit(io_tree, ordered_extent->file_offset,
3050 ordered_extent->file_offset + ordered_extent->len - 1,
3051 EXTENT_DEFRAG, 0, 0, &cached_state);
3055 trans = btrfs_join_transaction_nolock(root);
3057 trans = btrfs_join_transaction(root);
3058 if (IS_ERR(trans)) {
3059 ret = PTR_ERR(trans);
3064 trans->block_rsv = &BTRFS_I(inode)->block_rsv;
3066 if (test_bit(BTRFS_ORDERED_COMPRESSED, &ordered_extent->flags))
3067 compress_type = ordered_extent->compress_type;
3068 if (test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags)) {
3069 BUG_ON(compress_type);
3070 btrfs_qgroup_free_data(inode, NULL, ordered_extent->file_offset,
3071 ordered_extent->len);
3072 ret = btrfs_mark_extent_written(trans, BTRFS_I(inode),
3073 ordered_extent->file_offset,
3074 ordered_extent->file_offset +
3077 BUG_ON(root == fs_info->tree_root);
3078 ret = insert_reserved_file_extent(trans, inode,
3079 ordered_extent->file_offset,
3080 ordered_extent->start,
3081 ordered_extent->disk_len,
3082 logical_len, logical_len,
3083 compress_type, 0, 0,
3084 BTRFS_FILE_EXTENT_REG);
3086 clear_reserved_extent = false;
3087 btrfs_release_delalloc_bytes(fs_info,
3088 ordered_extent->start,
3089 ordered_extent->disk_len);
3092 unpin_extent_cache(&BTRFS_I(inode)->extent_tree,
3093 ordered_extent->file_offset, ordered_extent->len,
3096 btrfs_abort_transaction(trans, ret);
3100 ret = add_pending_csums(trans, inode, &ordered_extent->list);
3102 btrfs_abort_transaction(trans, ret);
3106 btrfs_ordered_update_i_size(inode, 0, ordered_extent);
3107 ret = btrfs_update_inode_fallback(trans, root, inode);
3108 if (ret) { /* -ENOMEM or corruption */
3109 btrfs_abort_transaction(trans, ret);
3114 if (range_locked || clear_new_delalloc_bytes) {
3115 unsigned int clear_bits = 0;
3118 clear_bits |= EXTENT_LOCKED;
3119 if (clear_new_delalloc_bytes)
3120 clear_bits |= EXTENT_DELALLOC_NEW;
3121 clear_extent_bit(&BTRFS_I(inode)->io_tree,
3122 ordered_extent->file_offset,
3123 ordered_extent->file_offset +
3124 ordered_extent->len - 1,
3126 (clear_bits & EXTENT_LOCKED) ? 1 : 0,
3131 btrfs_end_transaction(trans);
3133 if (ret || truncated) {
3137 start = ordered_extent->file_offset + logical_len;
3139 start = ordered_extent->file_offset;
3140 end = ordered_extent->file_offset + ordered_extent->len - 1;
3141 clear_extent_uptodate(io_tree, start, end, NULL);
3143 /* Drop the cache for the part of the extent we didn't write. */
3144 btrfs_drop_extent_cache(BTRFS_I(inode), start, end, 0);
3147 * If the ordered extent had an IOERR or something else went
3148 * wrong we need to return the space for this ordered extent
3149 * back to the allocator. We only free the extent in the
3150 * truncated case if we didn't write out the extent at all.
3152 * If we made it past insert_reserved_file_extent before we
3153 * errored out then we don't need to do this as the accounting
3154 * has already been done.
3156 if ((ret || !logical_len) &&
3157 clear_reserved_extent &&
3158 !test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags) &&
3159 !test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags))
3160 btrfs_free_reserved_extent(fs_info,
3161 ordered_extent->start,
3162 ordered_extent->disk_len, 1);
3167 * This needs to be done to make sure anybody waiting knows we are done
3168 * updating everything for this ordered extent.
3170 btrfs_remove_ordered_extent(inode, ordered_extent);
3172 /* for snapshot-aware defrag */
3175 free_sa_defrag_extent(new);
3176 atomic_dec(&fs_info->defrag_running);
3178 relink_file_extents(new);
3183 btrfs_put_ordered_extent(ordered_extent);
3184 /* once for the tree */
3185 btrfs_put_ordered_extent(ordered_extent);
3190 static void finish_ordered_fn(struct btrfs_work *work)
3192 struct btrfs_ordered_extent *ordered_extent;
3193 ordered_extent = container_of(work, struct btrfs_ordered_extent, work);
3194 btrfs_finish_ordered_io(ordered_extent);
3197 void btrfs_writepage_endio_finish_ordered(struct page *page, u64 start,
3198 u64 end, int uptodate)
3200 struct inode *inode = page->mapping->host;
3201 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
3202 struct btrfs_ordered_extent *ordered_extent = NULL;
3203 struct btrfs_workqueue *wq;
3204 btrfs_work_func_t func;
3206 trace_btrfs_writepage_end_io_hook(page, start, end, uptodate);
3208 ClearPagePrivate2(page);
3209 if (!btrfs_dec_test_ordered_pending(inode, &ordered_extent, start,
3210 end - start + 1, uptodate))
3213 if (btrfs_is_free_space_inode(BTRFS_I(inode))) {
3214 wq = fs_info->endio_freespace_worker;
3215 func = btrfs_freespace_write_helper;
3217 wq = fs_info->endio_write_workers;
3218 func = btrfs_endio_write_helper;
3221 btrfs_init_work(&ordered_extent->work, func, finish_ordered_fn, NULL,
3223 btrfs_queue_work(wq, &ordered_extent->work);
3226 static int __readpage_endio_check(struct inode *inode,
3227 struct btrfs_io_bio *io_bio,
3228 int icsum, struct page *page,
3229 int pgoff, u64 start, size_t len)
3231 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
3232 SHASH_DESC_ON_STACK(shash, fs_info->csum_shash);
3234 u16 csum_size = btrfs_super_csum_size(fs_info->super_copy);
3236 u8 csum[BTRFS_CSUM_SIZE];
3238 csum_expected = ((u8 *)io_bio->csum) + icsum * csum_size;
3240 kaddr = kmap_atomic(page);
3241 shash->tfm = fs_info->csum_shash;
3243 crypto_shash_init(shash);
3244 crypto_shash_update(shash, kaddr + pgoff, len);
3245 crypto_shash_final(shash, csum);
3247 if (memcmp(csum, csum_expected, csum_size))
3250 kunmap_atomic(kaddr);
3253 btrfs_print_data_csum_error(BTRFS_I(inode), start, csum, csum_expected,
3254 io_bio->mirror_num);
3255 memset(kaddr + pgoff, 1, len);
3256 flush_dcache_page(page);
3257 kunmap_atomic(kaddr);
3262 * when reads are done, we need to check csums to verify the data is correct
3263 * if there's a match, we allow the bio to finish. If not, the code in
3264 * extent_io.c will try to find good copies for us.
3266 static int btrfs_readpage_end_io_hook(struct btrfs_io_bio *io_bio,
3267 u64 phy_offset, struct page *page,
3268 u64 start, u64 end, int mirror)
3270 size_t offset = start - page_offset(page);
3271 struct inode *inode = page->mapping->host;
3272 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
3273 struct btrfs_root *root = BTRFS_I(inode)->root;
3275 if (PageChecked(page)) {
3276 ClearPageChecked(page);
3280 if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)
3283 if (root->root_key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID &&
3284 test_range_bit(io_tree, start, end, EXTENT_NODATASUM, 1, NULL)) {
3285 clear_extent_bits(io_tree, start, end, EXTENT_NODATASUM);
3289 phy_offset >>= inode->i_sb->s_blocksize_bits;
3290 return __readpage_endio_check(inode, io_bio, phy_offset, page, offset,
3291 start, (size_t)(end - start + 1));
3295 * btrfs_add_delayed_iput - perform a delayed iput on @inode
3297 * @inode: The inode we want to perform iput on
3299 * This function uses the generic vfs_inode::i_count to track whether we should
3300 * just decrement it (in case it's > 1) or if this is the last iput then link
3301 * the inode to the delayed iput machinery. Delayed iputs are processed at
3302 * transaction commit time/superblock commit/cleaner kthread.
3304 void btrfs_add_delayed_iput(struct inode *inode)
3306 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
3307 struct btrfs_inode *binode = BTRFS_I(inode);
3309 if (atomic_add_unless(&inode->i_count, -1, 1))
3312 atomic_inc(&fs_info->nr_delayed_iputs);
3313 spin_lock(&fs_info->delayed_iput_lock);
3314 ASSERT(list_empty(&binode->delayed_iput));
3315 list_add_tail(&binode->delayed_iput, &fs_info->delayed_iputs);
3316 spin_unlock(&fs_info->delayed_iput_lock);
3317 if (!test_bit(BTRFS_FS_CLEANER_RUNNING, &fs_info->flags))
3318 wake_up_process(fs_info->cleaner_kthread);
3321 static void run_delayed_iput_locked(struct btrfs_fs_info *fs_info,
3322 struct btrfs_inode *inode)
3324 list_del_init(&inode->delayed_iput);
3325 spin_unlock(&fs_info->delayed_iput_lock);
3326 iput(&inode->vfs_inode);
3327 if (atomic_dec_and_test(&fs_info->nr_delayed_iputs))
3328 wake_up(&fs_info->delayed_iputs_wait);
3329 spin_lock(&fs_info->delayed_iput_lock);
3332 static void btrfs_run_delayed_iput(struct btrfs_fs_info *fs_info,
3333 struct btrfs_inode *inode)
3335 if (!list_empty(&inode->delayed_iput)) {
3336 spin_lock(&fs_info->delayed_iput_lock);
3337 if (!list_empty(&inode->delayed_iput))
3338 run_delayed_iput_locked(fs_info, inode);
3339 spin_unlock(&fs_info->delayed_iput_lock);
3343 void btrfs_run_delayed_iputs(struct btrfs_fs_info *fs_info)
3346 spin_lock(&fs_info->delayed_iput_lock);
3347 while (!list_empty(&fs_info->delayed_iputs)) {
3348 struct btrfs_inode *inode;
3350 inode = list_first_entry(&fs_info->delayed_iputs,
3351 struct btrfs_inode, delayed_iput);
3352 run_delayed_iput_locked(fs_info, inode);
3354 spin_unlock(&fs_info->delayed_iput_lock);
3358 * btrfs_wait_on_delayed_iputs - wait on the delayed iputs to be done running
3359 * @fs_info - the fs_info for this fs
3360 * @return - EINTR if we were killed, 0 if nothing's pending
3362 * This will wait on any delayed iputs that are currently running with KILLABLE
3363 * set. Once they are all done running we will return, unless we are killed in
3364 * which case we return EINTR. This helps in user operations like fallocate etc
3365 * that might get blocked on the iputs.
3367 int btrfs_wait_on_delayed_iputs(struct btrfs_fs_info *fs_info)
3369 int ret = wait_event_killable(fs_info->delayed_iputs_wait,
3370 atomic_read(&fs_info->nr_delayed_iputs) == 0);
3377 * This creates an orphan entry for the given inode in case something goes wrong
3378 * in the middle of an unlink.
3380 int btrfs_orphan_add(struct btrfs_trans_handle *trans,
3381 struct btrfs_inode *inode)
3385 ret = btrfs_insert_orphan_item(trans, inode->root, btrfs_ino(inode));
3386 if (ret && ret != -EEXIST) {
3387 btrfs_abort_transaction(trans, ret);
3395 * We have done the delete so we can go ahead and remove the orphan item for
3396 * this particular inode.
3398 static int btrfs_orphan_del(struct btrfs_trans_handle *trans,
3399 struct btrfs_inode *inode)
3401 return btrfs_del_orphan_item(trans, inode->root, btrfs_ino(inode));
3405 * this cleans up any orphans that may be left on the list from the last use
3408 int btrfs_orphan_cleanup(struct btrfs_root *root)
3410 struct btrfs_fs_info *fs_info = root->fs_info;
3411 struct btrfs_path *path;
3412 struct extent_buffer *leaf;
3413 struct btrfs_key key, found_key;
3414 struct btrfs_trans_handle *trans;
3415 struct inode *inode;
3416 u64 last_objectid = 0;
3417 int ret = 0, nr_unlink = 0;
3419 if (cmpxchg(&root->orphan_cleanup_state, 0, ORPHAN_CLEANUP_STARTED))
3422 path = btrfs_alloc_path();
3427 path->reada = READA_BACK;
3429 key.objectid = BTRFS_ORPHAN_OBJECTID;
3430 key.type = BTRFS_ORPHAN_ITEM_KEY;
3431 key.offset = (u64)-1;
3434 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
3439 * if ret == 0 means we found what we were searching for, which
3440 * is weird, but possible, so only screw with path if we didn't
3441 * find the key and see if we have stuff that matches
3445 if (path->slots[0] == 0)
3450 /* pull out the item */
3451 leaf = path->nodes[0];
3452 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
3454 /* make sure the item matches what we want */
3455 if (found_key.objectid != BTRFS_ORPHAN_OBJECTID)
3457 if (found_key.type != BTRFS_ORPHAN_ITEM_KEY)
3460 /* release the path since we're done with it */
3461 btrfs_release_path(path);
3464 * this is where we are basically btrfs_lookup, without the
3465 * crossing root thing. we store the inode number in the
3466 * offset of the orphan item.
3469 if (found_key.offset == last_objectid) {
3471 "Error removing orphan entry, stopping orphan cleanup");
3476 last_objectid = found_key.offset;
3478 found_key.objectid = found_key.offset;
3479 found_key.type = BTRFS_INODE_ITEM_KEY;
3480 found_key.offset = 0;
3481 inode = btrfs_iget(fs_info->sb, &found_key, root, NULL);
3482 ret = PTR_ERR_OR_ZERO(inode);
3483 if (ret && ret != -ENOENT)
3486 if (ret == -ENOENT && root == fs_info->tree_root) {
3487 struct btrfs_root *dead_root;
3488 struct btrfs_fs_info *fs_info = root->fs_info;
3489 int is_dead_root = 0;
3492 * this is an orphan in the tree root. Currently these
3493 * could come from 2 sources:
3494 * a) a snapshot deletion in progress
3495 * b) a free space cache inode
3496 * We need to distinguish those two, as the snapshot
3497 * orphan must not get deleted.
3498 * find_dead_roots already ran before us, so if this
3499 * is a snapshot deletion, we should find the root
3500 * in the dead_roots list
3502 spin_lock(&fs_info->trans_lock);
3503 list_for_each_entry(dead_root, &fs_info->dead_roots,
3505 if (dead_root->root_key.objectid ==
3506 found_key.objectid) {
3511 spin_unlock(&fs_info->trans_lock);
3513 /* prevent this orphan from being found again */
3514 key.offset = found_key.objectid - 1;
3521 * If we have an inode with links, there are a couple of
3522 * possibilities. Old kernels (before v3.12) used to create an
3523 * orphan item for truncate indicating that there were possibly
3524 * extent items past i_size that needed to be deleted. In v3.12,
3525 * truncate was changed to update i_size in sync with the extent
3526 * items, but the (useless) orphan item was still created. Since
3527 * v4.18, we don't create the orphan item for truncate at all.
3529 * So, this item could mean that we need to do a truncate, but
3530 * only if this filesystem was last used on a pre-v3.12 kernel
3531 * and was not cleanly unmounted. The odds of that are quite
3532 * slim, and it's a pain to do the truncate now, so just delete
3535 * It's also possible that this orphan item was supposed to be
3536 * deleted but wasn't. The inode number may have been reused,
3537 * but either way, we can delete the orphan item.
3539 if (ret == -ENOENT || inode->i_nlink) {
3542 trans = btrfs_start_transaction(root, 1);
3543 if (IS_ERR(trans)) {
3544 ret = PTR_ERR(trans);
3547 btrfs_debug(fs_info, "auto deleting %Lu",
3548 found_key.objectid);
3549 ret = btrfs_del_orphan_item(trans, root,
3550 found_key.objectid);
3551 btrfs_end_transaction(trans);
3559 /* this will do delete_inode and everything for us */
3562 /* release the path since we're done with it */
3563 btrfs_release_path(path);
3565 root->orphan_cleanup_state = ORPHAN_CLEANUP_DONE;
3567 if (test_bit(BTRFS_ROOT_ORPHAN_ITEM_INSERTED, &root->state)) {
3568 trans = btrfs_join_transaction(root);
3570 btrfs_end_transaction(trans);
3574 btrfs_debug(fs_info, "unlinked %d orphans", nr_unlink);
3578 btrfs_err(fs_info, "could not do orphan cleanup %d", ret);
3579 btrfs_free_path(path);
3584 * very simple check to peek ahead in the leaf looking for xattrs. If we
3585 * don't find any xattrs, we know there can't be any acls.
3587 * slot is the slot the inode is in, objectid is the objectid of the inode
3589 static noinline int acls_after_inode_item(struct extent_buffer *leaf,
3590 int slot, u64 objectid,
3591 int *first_xattr_slot)
3593 u32 nritems = btrfs_header_nritems(leaf);
3594 struct btrfs_key found_key;
3595 static u64 xattr_access = 0;
3596 static u64 xattr_default = 0;
3599 if (!xattr_access) {
3600 xattr_access = btrfs_name_hash(XATTR_NAME_POSIX_ACL_ACCESS,
3601 strlen(XATTR_NAME_POSIX_ACL_ACCESS));
3602 xattr_default = btrfs_name_hash(XATTR_NAME_POSIX_ACL_DEFAULT,
3603 strlen(XATTR_NAME_POSIX_ACL_DEFAULT));
3607 *first_xattr_slot = -1;
3608 while (slot < nritems) {
3609 btrfs_item_key_to_cpu(leaf, &found_key, slot);
3611 /* we found a different objectid, there must not be acls */
3612 if (found_key.objectid != objectid)
3615 /* we found an xattr, assume we've got an acl */
3616 if (found_key.type == BTRFS_XATTR_ITEM_KEY) {
3617 if (*first_xattr_slot == -1)
3618 *first_xattr_slot = slot;
3619 if (found_key.offset == xattr_access ||
3620 found_key.offset == xattr_default)
3625 * we found a key greater than an xattr key, there can't
3626 * be any acls later on
3628 if (found_key.type > BTRFS_XATTR_ITEM_KEY)
3635 * it goes inode, inode backrefs, xattrs, extents,
3636 * so if there are a ton of hard links to an inode there can
3637 * be a lot of backrefs. Don't waste time searching too hard,
3638 * this is just an optimization
3643 /* we hit the end of the leaf before we found an xattr or
3644 * something larger than an xattr. We have to assume the inode
3647 if (*first_xattr_slot == -1)
3648 *first_xattr_slot = slot;
3653 * read an inode from the btree into the in-memory inode
3655 static int btrfs_read_locked_inode(struct inode *inode,
3656 struct btrfs_path *in_path)
3658 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
3659 struct btrfs_path *path = in_path;
3660 struct extent_buffer *leaf;
3661 struct btrfs_inode_item *inode_item;
3662 struct btrfs_root *root = BTRFS_I(inode)->root;
3663 struct btrfs_key location;
3668 bool filled = false;
3669 int first_xattr_slot;
3671 ret = btrfs_fill_inode(inode, &rdev);
3676 path = btrfs_alloc_path();
3681 memcpy(&location, &BTRFS_I(inode)->location, sizeof(location));
3683 ret = btrfs_lookup_inode(NULL, root, path, &location, 0);
3685 if (path != in_path)
3686 btrfs_free_path(path);
3690 leaf = path->nodes[0];
3695 inode_item = btrfs_item_ptr(leaf, path->slots[0],
3696 struct btrfs_inode_item);
3697 inode->i_mode = btrfs_inode_mode(leaf, inode_item);
3698 set_nlink(inode, btrfs_inode_nlink(leaf, inode_item));
3699 i_uid_write(inode, btrfs_inode_uid(leaf, inode_item));
3700 i_gid_write(inode, btrfs_inode_gid(leaf, inode_item));
3701 btrfs_i_size_write(BTRFS_I(inode), btrfs_inode_size(leaf, inode_item));
3703 inode->i_atime.tv_sec = btrfs_timespec_sec(leaf, &inode_item->atime);
3704 inode->i_atime.tv_nsec = btrfs_timespec_nsec(leaf, &inode_item->atime);
3706 inode->i_mtime.tv_sec = btrfs_timespec_sec(leaf, &inode_item->mtime);
3707 inode->i_mtime.tv_nsec = btrfs_timespec_nsec(leaf, &inode_item->mtime);
3709 inode->i_ctime.tv_sec = btrfs_timespec_sec(leaf, &inode_item->ctime);
3710 inode->i_ctime.tv_nsec = btrfs_timespec_nsec(leaf, &inode_item->ctime);
3712 BTRFS_I(inode)->i_otime.tv_sec =
3713 btrfs_timespec_sec(leaf, &inode_item->otime);
3714 BTRFS_I(inode)->i_otime.tv_nsec =
3715 btrfs_timespec_nsec(leaf, &inode_item->otime);
3717 inode_set_bytes(inode, btrfs_inode_nbytes(leaf, inode_item));
3718 BTRFS_I(inode)->generation = btrfs_inode_generation(leaf, inode_item);
3719 BTRFS_I(inode)->last_trans = btrfs_inode_transid(leaf, inode_item);
3721 inode_set_iversion_queried(inode,
3722 btrfs_inode_sequence(leaf, inode_item));
3723 inode->i_generation = BTRFS_I(inode)->generation;
3725 rdev = btrfs_inode_rdev(leaf, inode_item);
3727 BTRFS_I(inode)->index_cnt = (u64)-1;
3728 BTRFS_I(inode)->flags = btrfs_inode_flags(leaf, inode_item);
3732 * If we were modified in the current generation and evicted from memory
3733 * and then re-read we need to do a full sync since we don't have any
3734 * idea about which extents were modified before we were evicted from
3737 * This is required for both inode re-read from disk and delayed inode
3738 * in delayed_nodes_tree.
3740 if (BTRFS_I(inode)->last_trans == fs_info->generation)
3741 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
3742 &BTRFS_I(inode)->runtime_flags);
3745 * We don't persist the id of the transaction where an unlink operation
3746 * against the inode was last made. So here we assume the inode might
3747 * have been evicted, and therefore the exact value of last_unlink_trans
3748 * lost, and set it to last_trans to avoid metadata inconsistencies
3749 * between the inode and its parent if the inode is fsync'ed and the log
3750 * replayed. For example, in the scenario:
3753 * ln mydir/foo mydir/bar
3756 * echo 2 > /proc/sys/vm/drop_caches # evicts inode
3757 * xfs_io -c fsync mydir/foo
3759 * mount fs, triggers fsync log replay
3761 * We must make sure that when we fsync our inode foo we also log its
3762 * parent inode, otherwise after log replay the parent still has the
3763 * dentry with the "bar" name but our inode foo has a link count of 1
3764 * and doesn't have an inode ref with the name "bar" anymore.
3766 * Setting last_unlink_trans to last_trans is a pessimistic approach,
3767 * but it guarantees correctness at the expense of occasional full
3768 * transaction commits on fsync if our inode is a directory, or if our
3769 * inode is not a directory, logging its parent unnecessarily.
3771 BTRFS_I(inode)->last_unlink_trans = BTRFS_I(inode)->last_trans;
3774 if (inode->i_nlink != 1 ||
3775 path->slots[0] >= btrfs_header_nritems(leaf))
3778 btrfs_item_key_to_cpu(leaf, &location, path->slots[0]);
3779 if (location.objectid != btrfs_ino(BTRFS_I(inode)))
3782 ptr = btrfs_item_ptr_offset(leaf, path->slots[0]);
3783 if (location.type == BTRFS_INODE_REF_KEY) {
3784 struct btrfs_inode_ref *ref;
3786 ref = (struct btrfs_inode_ref *)ptr;
3787 BTRFS_I(inode)->dir_index = btrfs_inode_ref_index(leaf, ref);
3788 } else if (location.type == BTRFS_INODE_EXTREF_KEY) {
3789 struct btrfs_inode_extref *extref;
3791 extref = (struct btrfs_inode_extref *)ptr;
3792 BTRFS_I(inode)->dir_index = btrfs_inode_extref_index(leaf,
3797 * try to precache a NULL acl entry for files that don't have
3798 * any xattrs or acls
3800 maybe_acls = acls_after_inode_item(leaf, path->slots[0],
3801 btrfs_ino(BTRFS_I(inode)), &first_xattr_slot);
3802 if (first_xattr_slot != -1) {
3803 path->slots[0] = first_xattr_slot;
3804 ret = btrfs_load_inode_props(inode, path);
3807 "error loading props for ino %llu (root %llu): %d",
3808 btrfs_ino(BTRFS_I(inode)),
3809 root->root_key.objectid, ret);
3811 if (path != in_path)
3812 btrfs_free_path(path);
3815 cache_no_acl(inode);
3817 switch (inode->i_mode & S_IFMT) {
3819 inode->i_mapping->a_ops = &btrfs_aops;
3820 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
3821 inode->i_fop = &btrfs_file_operations;
3822 inode->i_op = &btrfs_file_inode_operations;
3825 inode->i_fop = &btrfs_dir_file_operations;
3826 inode->i_op = &btrfs_dir_inode_operations;
3829 inode->i_op = &btrfs_symlink_inode_operations;
3830 inode_nohighmem(inode);
3831 inode->i_mapping->a_ops = &btrfs_aops;
3834 inode->i_op = &btrfs_special_inode_operations;
3835 init_special_inode(inode, inode->i_mode, rdev);
3839 btrfs_sync_inode_flags_to_i_flags(inode);
3844 * given a leaf and an inode, copy the inode fields into the leaf
3846 static void fill_inode_item(struct btrfs_trans_handle *trans,
3847 struct extent_buffer *leaf,
3848 struct btrfs_inode_item *item,
3849 struct inode *inode)
3851 struct btrfs_map_token token;
3853 btrfs_init_map_token(&token);
3855 btrfs_set_token_inode_uid(leaf, item, i_uid_read(inode), &token);
3856 btrfs_set_token_inode_gid(leaf, item, i_gid_read(inode), &token);
3857 btrfs_set_token_inode_size(leaf, item, BTRFS_I(inode)->disk_i_size,
3859 btrfs_set_token_inode_mode(leaf, item, inode->i_mode, &token);
3860 btrfs_set_token_inode_nlink(leaf, item, inode->i_nlink, &token);
3862 btrfs_set_token_timespec_sec(leaf, &item->atime,
3863 inode->i_atime.tv_sec, &token);
3864 btrfs_set_token_timespec_nsec(leaf, &item->atime,
3865 inode->i_atime.tv_nsec, &token);
3867 btrfs_set_token_timespec_sec(leaf, &item->mtime,
3868 inode->i_mtime.tv_sec, &token);
3869 btrfs_set_token_timespec_nsec(leaf, &item->mtime,
3870 inode->i_mtime.tv_nsec, &token);
3872 btrfs_set_token_timespec_sec(leaf, &item->ctime,
3873 inode->i_ctime.tv_sec, &token);
3874 btrfs_set_token_timespec_nsec(leaf, &item->ctime,
3875 inode->i_ctime.tv_nsec, &token);
3877 btrfs_set_token_timespec_sec(leaf, &item->otime,
3878 BTRFS_I(inode)->i_otime.tv_sec, &token);
3879 btrfs_set_token_timespec_nsec(leaf, &item->otime,
3880 BTRFS_I(inode)->i_otime.tv_nsec, &token);
3882 btrfs_set_token_inode_nbytes(leaf, item, inode_get_bytes(inode),
3884 btrfs_set_token_inode_generation(leaf, item, BTRFS_I(inode)->generation,
3886 btrfs_set_token_inode_sequence(leaf, item, inode_peek_iversion(inode),
3888 btrfs_set_token_inode_transid(leaf, item, trans->transid, &token);
3889 btrfs_set_token_inode_rdev(leaf, item, inode->i_rdev, &token);
3890 btrfs_set_token_inode_flags(leaf, item, BTRFS_I(inode)->flags, &token);
3891 btrfs_set_token_inode_block_group(leaf, item, 0, &token);
3895 * copy everything in the in-memory inode into the btree.
3897 static noinline int btrfs_update_inode_item(struct btrfs_trans_handle *trans,
3898 struct btrfs_root *root, struct inode *inode)
3900 struct btrfs_inode_item *inode_item;
3901 struct btrfs_path *path;
3902 struct extent_buffer *leaf;
3905 path = btrfs_alloc_path();
3909 path->leave_spinning = 1;
3910 ret = btrfs_lookup_inode(trans, root, path, &BTRFS_I(inode)->location,
3918 leaf = path->nodes[0];
3919 inode_item = btrfs_item_ptr(leaf, path->slots[0],
3920 struct btrfs_inode_item);
3922 fill_inode_item(trans, leaf, inode_item, inode);
3923 btrfs_mark_buffer_dirty(leaf);
3924 btrfs_set_inode_last_trans(trans, inode);
3927 btrfs_free_path(path);
3932 * copy everything in the in-memory inode into the btree.
3934 noinline int btrfs_update_inode(struct btrfs_trans_handle *trans,
3935 struct btrfs_root *root, struct inode *inode)
3937 struct btrfs_fs_info *fs_info = root->fs_info;
3941 * If the inode is a free space inode, we can deadlock during commit
3942 * if we put it into the delayed code.
3944 * The data relocation inode should also be directly updated
3947 if (!btrfs_is_free_space_inode(BTRFS_I(inode))
3948 && root->root_key.objectid != BTRFS_DATA_RELOC_TREE_OBJECTID
3949 && !test_bit(BTRFS_FS_LOG_RECOVERING, &fs_info->flags)) {
3950 btrfs_update_root_times(trans, root);
3952 ret = btrfs_delayed_update_inode(trans, root, inode);
3954 btrfs_set_inode_last_trans(trans, inode);
3958 return btrfs_update_inode_item(trans, root, inode);
3961 noinline int btrfs_update_inode_fallback(struct btrfs_trans_handle *trans,
3962 struct btrfs_root *root,
3963 struct inode *inode)
3967 ret = btrfs_update_inode(trans, root, inode);
3969 return btrfs_update_inode_item(trans, root, inode);
3974 * unlink helper that gets used here in inode.c and in the tree logging
3975 * recovery code. It remove a link in a directory with a given name, and
3976 * also drops the back refs in the inode to the directory
3978 static int __btrfs_unlink_inode(struct btrfs_trans_handle *trans,
3979 struct btrfs_root *root,
3980 struct btrfs_inode *dir,
3981 struct btrfs_inode *inode,
3982 const char *name, int name_len)
3984 struct btrfs_fs_info *fs_info = root->fs_info;
3985 struct btrfs_path *path;
3987 struct btrfs_dir_item *di;
3989 u64 ino = btrfs_ino(inode);
3990 u64 dir_ino = btrfs_ino(dir);
3992 path = btrfs_alloc_path();
3998 path->leave_spinning = 1;
3999 di = btrfs_lookup_dir_item(trans, root, path, dir_ino,
4000 name, name_len, -1);
4001 if (IS_ERR_OR_NULL(di)) {
4002 ret = di ? PTR_ERR(di) : -ENOENT;
4005 ret = btrfs_delete_one_dir_name(trans, root, path, di);
4008 btrfs_release_path(path);
4011 * If we don't have dir index, we have to get it by looking up
4012 * the inode ref, since we get the inode ref, remove it directly,
4013 * it is unnecessary to do delayed deletion.
4015 * But if we have dir index, needn't search inode ref to get it.
4016 * Since the inode ref is close to the inode item, it is better
4017 * that we delay to delete it, and just do this deletion when
4018 * we update the inode item.
4020 if (inode->dir_index) {
4021 ret = btrfs_delayed_delete_inode_ref(inode);
4023 index = inode->dir_index;
4028 ret = btrfs_del_inode_ref(trans, root, name, name_len, ino,
4032 "failed to delete reference to %.*s, inode %llu parent %llu",
4033 name_len, name, ino, dir_ino);
4034 btrfs_abort_transaction(trans, ret);
4038 ret = btrfs_delete_delayed_dir_index(trans, dir, index);
4040 btrfs_abort_transaction(trans, ret);
4044 ret = btrfs_del_inode_ref_in_log(trans, root, name, name_len, inode,
4046 if (ret != 0 && ret != -ENOENT) {
4047 btrfs_abort_transaction(trans, ret);
4051 ret = btrfs_del_dir_entries_in_log(trans, root, name, name_len, dir,
4056 btrfs_abort_transaction(trans, ret);
4059 * If we have a pending delayed iput we could end up with the final iput
4060 * being run in btrfs-cleaner context. If we have enough of these built
4061 * up we can end up burning a lot of time in btrfs-cleaner without any
4062 * way to throttle the unlinks. Since we're currently holding a ref on
4063 * the inode we can run the delayed iput here without any issues as the
4064 * final iput won't be done until after we drop the ref we're currently
4067 btrfs_run_delayed_iput(fs_info, inode);
4069 btrfs_free_path(path);
4073 btrfs_i_size_write(dir, dir->vfs_inode.i_size - name_len * 2);
4074 inode_inc_iversion(&inode->vfs_inode);
4075 inode_inc_iversion(&dir->vfs_inode);
4076 inode->vfs_inode.i_ctime = dir->vfs_inode.i_mtime =
4077 dir->vfs_inode.i_ctime = current_time(&inode->vfs_inode);
4078 ret = btrfs_update_inode(trans, root, &dir->vfs_inode);
4083 int btrfs_unlink_inode(struct btrfs_trans_handle *trans,
4084 struct btrfs_root *root,
4085 struct btrfs_inode *dir, struct btrfs_inode *inode,
4086 const char *name, int name_len)
4089 ret = __btrfs_unlink_inode(trans, root, dir, inode, name, name_len);
4091 drop_nlink(&inode->vfs_inode);
4092 ret = btrfs_update_inode(trans, root, &inode->vfs_inode);
4098 * helper to start transaction for unlink and rmdir.
4100 * unlink and rmdir are special in btrfs, they do not always free space, so
4101 * if we cannot make our reservations the normal way try and see if there is
4102 * plenty of slack room in the global reserve to migrate, otherwise we cannot
4103 * allow the unlink to occur.
4105 static struct btrfs_trans_handle *__unlink_start_trans(struct inode *dir)
4107 struct btrfs_root *root = BTRFS_I(dir)->root;
4110 * 1 for the possible orphan item
4111 * 1 for the dir item
4112 * 1 for the dir index
4113 * 1 for the inode ref
4116 return btrfs_start_transaction_fallback_global_rsv(root, 5, 5);
4119 static int btrfs_unlink(struct inode *dir, struct dentry *dentry)
4121 struct btrfs_root *root = BTRFS_I(dir)->root;
4122 struct btrfs_trans_handle *trans;
4123 struct inode *inode = d_inode(dentry);
4126 trans = __unlink_start_trans(dir);
4128 return PTR_ERR(trans);
4130 btrfs_record_unlink_dir(trans, BTRFS_I(dir), BTRFS_I(d_inode(dentry)),
4133 ret = btrfs_unlink_inode(trans, root, BTRFS_I(dir),
4134 BTRFS_I(d_inode(dentry)), dentry->d_name.name,
4135 dentry->d_name.len);
4139 if (inode->i_nlink == 0) {
4140 ret = btrfs_orphan_add(trans, BTRFS_I(inode));
4146 btrfs_end_transaction(trans);
4147 btrfs_btree_balance_dirty(root->fs_info);
4151 static int btrfs_unlink_subvol(struct btrfs_trans_handle *trans,
4152 struct inode *dir, u64 objectid,
4153 const char *name, int name_len)
4155 struct btrfs_root *root = BTRFS_I(dir)->root;
4156 struct btrfs_path *path;
4157 struct extent_buffer *leaf;
4158 struct btrfs_dir_item *di;
4159 struct btrfs_key key;
4162 u64 dir_ino = btrfs_ino(BTRFS_I(dir));
4164 path = btrfs_alloc_path();
4168 di = btrfs_lookup_dir_item(trans, root, path, dir_ino,
4169 name, name_len, -1);
4170 if (IS_ERR_OR_NULL(di)) {
4171 ret = di ? PTR_ERR(di) : -ENOENT;
4175 leaf = path->nodes[0];
4176 btrfs_dir_item_key_to_cpu(leaf, di, &key);
4177 WARN_ON(key.type != BTRFS_ROOT_ITEM_KEY || key.objectid != objectid);
4178 ret = btrfs_delete_one_dir_name(trans, root, path, di);
4180 btrfs_abort_transaction(trans, ret);
4183 btrfs_release_path(path);
4185 ret = btrfs_del_root_ref(trans, objectid, root->root_key.objectid,
4186 dir_ino, &index, name, name_len);
4188 if (ret != -ENOENT) {
4189 btrfs_abort_transaction(trans, ret);
4192 di = btrfs_search_dir_index_item(root, path, dir_ino,
4194 if (IS_ERR_OR_NULL(di)) {
4199 btrfs_abort_transaction(trans, ret);
4203 leaf = path->nodes[0];
4204 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
4207 btrfs_release_path(path);
4209 ret = btrfs_delete_delayed_dir_index(trans, BTRFS_I(dir), index);
4211 btrfs_abort_transaction(trans, ret);
4215 btrfs_i_size_write(BTRFS_I(dir), dir->i_size - name_len * 2);
4216 inode_inc_iversion(dir);
4217 dir->i_mtime = dir->i_ctime = current_time(dir);
4218 ret = btrfs_update_inode_fallback(trans, root, dir);
4220 btrfs_abort_transaction(trans, ret);
4222 btrfs_free_path(path);
4227 * Helper to check if the subvolume references other subvolumes or if it's
4230 static noinline int may_destroy_subvol(struct btrfs_root *root)
4232 struct btrfs_fs_info *fs_info = root->fs_info;
4233 struct btrfs_path *path;
4234 struct btrfs_dir_item *di;
4235 struct btrfs_key key;
4239 path = btrfs_alloc_path();
4243 /* Make sure this root isn't set as the default subvol */
4244 dir_id = btrfs_super_root_dir(fs_info->super_copy);
4245 di = btrfs_lookup_dir_item(NULL, fs_info->tree_root, path,
4246 dir_id, "default", 7, 0);
4247 if (di && !IS_ERR(di)) {
4248 btrfs_dir_item_key_to_cpu(path->nodes[0], di, &key);
4249 if (key.objectid == root->root_key.objectid) {
4252 "deleting default subvolume %llu is not allowed",
4256 btrfs_release_path(path);
4259 key.objectid = root->root_key.objectid;
4260 key.type = BTRFS_ROOT_REF_KEY;
4261 key.offset = (u64)-1;
4263 ret = btrfs_search_slot(NULL, fs_info->tree_root, &key, path, 0, 0);
4269 if (path->slots[0] > 0) {
4271 btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
4272 if (key.objectid == root->root_key.objectid &&
4273 key.type == BTRFS_ROOT_REF_KEY)
4277 btrfs_free_path(path);
4281 /* Delete all dentries for inodes belonging to the root */
4282 static void btrfs_prune_dentries(struct btrfs_root *root)
4284 struct btrfs_fs_info *fs_info = root->fs_info;
4285 struct rb_node *node;
4286 struct rb_node *prev;
4287 struct btrfs_inode *entry;
4288 struct inode *inode;
4291 if (!test_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state))
4292 WARN_ON(btrfs_root_refs(&root->root_item) != 0);
4294 spin_lock(&root->inode_lock);
4296 node = root->inode_tree.rb_node;
4300 entry = rb_entry(node, struct btrfs_inode, rb_node);
4302 if (objectid < btrfs_ino(entry))
4303 node = node->rb_left;
4304 else if (objectid > btrfs_ino(entry))
4305 node = node->rb_right;
4311 entry = rb_entry(prev, struct btrfs_inode, rb_node);
4312 if (objectid <= btrfs_ino(entry)) {
4316 prev = rb_next(prev);
4320 entry = rb_entry(node, struct btrfs_inode, rb_node);
4321 objectid = btrfs_ino(entry) + 1;
4322 inode = igrab(&entry->vfs_inode);
4324 spin_unlock(&root->inode_lock);
4325 if (atomic_read(&inode->i_count) > 1)
4326 d_prune_aliases(inode);
4328 * btrfs_drop_inode will have it removed from the inode
4329 * cache when its usage count hits zero.
4333 spin_lock(&root->inode_lock);
4337 if (cond_resched_lock(&root->inode_lock))
4340 node = rb_next(node);
4342 spin_unlock(&root->inode_lock);
4345 int btrfs_delete_subvolume(struct inode *dir, struct dentry *dentry)
4347 struct btrfs_fs_info *fs_info = btrfs_sb(dentry->d_sb);
4348 struct btrfs_root *root = BTRFS_I(dir)->root;
4349 struct inode *inode = d_inode(dentry);
4350 struct btrfs_root *dest = BTRFS_I(inode)->root;
4351 struct btrfs_trans_handle *trans;
4352 struct btrfs_block_rsv block_rsv;
4358 * Don't allow to delete a subvolume with send in progress. This is
4359 * inside the inode lock so the error handling that has to drop the bit
4360 * again is not run concurrently.
4362 spin_lock(&dest->root_item_lock);
4363 if (dest->send_in_progress) {
4364 spin_unlock(&dest->root_item_lock);
4366 "attempt to delete subvolume %llu during send",
4367 dest->root_key.objectid);
4370 root_flags = btrfs_root_flags(&dest->root_item);
4371 btrfs_set_root_flags(&dest->root_item,
4372 root_flags | BTRFS_ROOT_SUBVOL_DEAD);
4373 spin_unlock(&dest->root_item_lock);
4375 down_write(&fs_info->subvol_sem);
4377 err = may_destroy_subvol(dest);
4381 btrfs_init_block_rsv(&block_rsv, BTRFS_BLOCK_RSV_TEMP);
4383 * One for dir inode,
4384 * two for dir entries,
4385 * two for root ref/backref.
4387 err = btrfs_subvolume_reserve_metadata(root, &block_rsv, 5, true);
4391 trans = btrfs_start_transaction(root, 0);
4392 if (IS_ERR(trans)) {
4393 err = PTR_ERR(trans);
4396 trans->block_rsv = &block_rsv;
4397 trans->bytes_reserved = block_rsv.size;
4399 btrfs_record_snapshot_destroy(trans, BTRFS_I(dir));
4401 ret = btrfs_unlink_subvol(trans, dir, dest->root_key.objectid,
4402 dentry->d_name.name, dentry->d_name.len);
4405 btrfs_abort_transaction(trans, ret);
4409 btrfs_record_root_in_trans(trans, dest);
4411 memset(&dest->root_item.drop_progress, 0,
4412 sizeof(dest->root_item.drop_progress));
4413 dest->root_item.drop_level = 0;
4414 btrfs_set_root_refs(&dest->root_item, 0);
4416 if (!test_and_set_bit(BTRFS_ROOT_ORPHAN_ITEM_INSERTED, &dest->state)) {
4417 ret = btrfs_insert_orphan_item(trans,
4419 dest->root_key.objectid);
4421 btrfs_abort_transaction(trans, ret);
4427 ret = btrfs_uuid_tree_remove(trans, dest->root_item.uuid,
4428 BTRFS_UUID_KEY_SUBVOL,
4429 dest->root_key.objectid);
4430 if (ret && ret != -ENOENT) {
4431 btrfs_abort_transaction(trans, ret);
4435 if (!btrfs_is_empty_uuid(dest->root_item.received_uuid)) {
4436 ret = btrfs_uuid_tree_remove(trans,
4437 dest->root_item.received_uuid,
4438 BTRFS_UUID_KEY_RECEIVED_SUBVOL,
4439 dest->root_key.objectid);
4440 if (ret && ret != -ENOENT) {
4441 btrfs_abort_transaction(trans, ret);
4448 trans->block_rsv = NULL;
4449 trans->bytes_reserved = 0;
4450 ret = btrfs_end_transaction(trans);
4453 inode->i_flags |= S_DEAD;
4455 btrfs_subvolume_release_metadata(fs_info, &block_rsv);
4457 up_write(&fs_info->subvol_sem);
4459 spin_lock(&dest->root_item_lock);
4460 root_flags = btrfs_root_flags(&dest->root_item);
4461 btrfs_set_root_flags(&dest->root_item,
4462 root_flags & ~BTRFS_ROOT_SUBVOL_DEAD);
4463 spin_unlock(&dest->root_item_lock);
4465 d_invalidate(dentry);
4466 btrfs_prune_dentries(dest);
4467 ASSERT(dest->send_in_progress == 0);
4470 if (dest->ino_cache_inode) {
4471 iput(dest->ino_cache_inode);
4472 dest->ino_cache_inode = NULL;
4479 static int btrfs_rmdir(struct inode *dir, struct dentry *dentry)
4481 struct inode *inode = d_inode(dentry);
4483 struct btrfs_root *root = BTRFS_I(dir)->root;
4484 struct btrfs_trans_handle *trans;
4485 u64 last_unlink_trans;
4487 if (inode->i_size > BTRFS_EMPTY_DIR_SIZE)
4489 if (btrfs_ino(BTRFS_I(inode)) == BTRFS_FIRST_FREE_OBJECTID)
4490 return btrfs_delete_subvolume(dir, dentry);
4492 trans = __unlink_start_trans(dir);
4494 return PTR_ERR(trans);
4496 if (unlikely(btrfs_ino(BTRFS_I(inode)) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)) {
4497 err = btrfs_unlink_subvol(trans, dir,
4498 BTRFS_I(inode)->location.objectid,
4499 dentry->d_name.name,
4500 dentry->d_name.len);
4504 err = btrfs_orphan_add(trans, BTRFS_I(inode));
4508 last_unlink_trans = BTRFS_I(inode)->last_unlink_trans;
4510 /* now the directory is empty */
4511 err = btrfs_unlink_inode(trans, root, BTRFS_I(dir),
4512 BTRFS_I(d_inode(dentry)), dentry->d_name.name,
4513 dentry->d_name.len);
4515 btrfs_i_size_write(BTRFS_I(inode), 0);
4517 * Propagate the last_unlink_trans value of the deleted dir to
4518 * its parent directory. This is to prevent an unrecoverable
4519 * log tree in the case we do something like this:
4521 * 2) create snapshot under dir foo
4522 * 3) delete the snapshot
4525 * 6) fsync foo or some file inside foo
4527 if (last_unlink_trans >= trans->transid)
4528 BTRFS_I(dir)->last_unlink_trans = last_unlink_trans;
4531 btrfs_end_transaction(trans);
4532 btrfs_btree_balance_dirty(root->fs_info);
4538 * Return this if we need to call truncate_block for the last bit of the
4541 #define NEED_TRUNCATE_BLOCK 1
4544 * this can truncate away extent items, csum items and directory items.
4545 * It starts at a high offset and removes keys until it can't find
4546 * any higher than new_size
4548 * csum items that cross the new i_size are truncated to the new size
4551 * min_type is the minimum key type to truncate down to. If set to 0, this
4552 * will kill all the items on this inode, including the INODE_ITEM_KEY.
4554 int btrfs_truncate_inode_items(struct btrfs_trans_handle *trans,
4555 struct btrfs_root *root,
4556 struct inode *inode,
4557 u64 new_size, u32 min_type)
4559 struct btrfs_fs_info *fs_info = root->fs_info;
4560 struct btrfs_path *path;
4561 struct extent_buffer *leaf;
4562 struct btrfs_file_extent_item *fi;
4563 struct btrfs_key key;
4564 struct btrfs_key found_key;
4565 u64 extent_start = 0;
4566 u64 extent_num_bytes = 0;
4567 u64 extent_offset = 0;
4569 u64 last_size = new_size;
4570 u32 found_type = (u8)-1;
4573 int pending_del_nr = 0;
4574 int pending_del_slot = 0;
4575 int extent_type = -1;
4577 u64 ino = btrfs_ino(BTRFS_I(inode));
4578 u64 bytes_deleted = 0;
4579 bool be_nice = false;
4580 bool should_throttle = false;
4582 BUG_ON(new_size > 0 && min_type != BTRFS_EXTENT_DATA_KEY);
4585 * for non-free space inodes and ref cows, we want to back off from
4588 if (!btrfs_is_free_space_inode(BTRFS_I(inode)) &&
4589 test_bit(BTRFS_ROOT_REF_COWS, &root->state))
4592 path = btrfs_alloc_path();
4595 path->reada = READA_BACK;
4598 * We want to drop from the next block forward in case this new size is
4599 * not block aligned since we will be keeping the last block of the
4600 * extent just the way it is.
4602 if (test_bit(BTRFS_ROOT_REF_COWS, &root->state) ||
4603 root == fs_info->tree_root)
4604 btrfs_drop_extent_cache(BTRFS_I(inode), ALIGN(new_size,
4605 fs_info->sectorsize),
4609 * This function is also used to drop the items in the log tree before
4610 * we relog the inode, so if root != BTRFS_I(inode)->root, it means
4611 * it is used to drop the logged items. So we shouldn't kill the delayed
4614 if (min_type == 0 && root == BTRFS_I(inode)->root)
4615 btrfs_kill_delayed_inode_items(BTRFS_I(inode));
4618 key.offset = (u64)-1;
4623 * with a 16K leaf size and 128MB extents, you can actually queue
4624 * up a huge file in a single leaf. Most of the time that
4625 * bytes_deleted is > 0, it will be huge by the time we get here
4627 if (be_nice && bytes_deleted > SZ_32M &&
4628 btrfs_should_end_transaction(trans)) {
4633 path->leave_spinning = 1;
4634 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
4640 /* there are no items in the tree for us to truncate, we're
4643 if (path->slots[0] == 0)
4650 leaf = path->nodes[0];
4651 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
4652 found_type = found_key.type;
4654 if (found_key.objectid != ino)
4657 if (found_type < min_type)
4660 item_end = found_key.offset;
4661 if (found_type == BTRFS_EXTENT_DATA_KEY) {
4662 fi = btrfs_item_ptr(leaf, path->slots[0],
4663 struct btrfs_file_extent_item);
4664 extent_type = btrfs_file_extent_type(leaf, fi);
4665 if (extent_type != BTRFS_FILE_EXTENT_INLINE) {
4667 btrfs_file_extent_num_bytes(leaf, fi);
4669 trace_btrfs_truncate_show_fi_regular(
4670 BTRFS_I(inode), leaf, fi,
4672 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
4673 item_end += btrfs_file_extent_ram_bytes(leaf,
4676 trace_btrfs_truncate_show_fi_inline(
4677 BTRFS_I(inode), leaf, fi, path->slots[0],
4682 if (found_type > min_type) {
4685 if (item_end < new_size)
4687 if (found_key.offset >= new_size)
4693 /* FIXME, shrink the extent if the ref count is only 1 */
4694 if (found_type != BTRFS_EXTENT_DATA_KEY)
4697 if (extent_type != BTRFS_FILE_EXTENT_INLINE) {
4699 extent_start = btrfs_file_extent_disk_bytenr(leaf, fi);
4701 u64 orig_num_bytes =
4702 btrfs_file_extent_num_bytes(leaf, fi);
4703 extent_num_bytes = ALIGN(new_size -
4705 fs_info->sectorsize);
4706 btrfs_set_file_extent_num_bytes(leaf, fi,
4708 num_dec = (orig_num_bytes -
4710 if (test_bit(BTRFS_ROOT_REF_COWS,
4713 inode_sub_bytes(inode, num_dec);
4714 btrfs_mark_buffer_dirty(leaf);
4717 btrfs_file_extent_disk_num_bytes(leaf,
4719 extent_offset = found_key.offset -
4720 btrfs_file_extent_offset(leaf, fi);
4722 /* FIXME blocksize != 4096 */
4723 num_dec = btrfs_file_extent_num_bytes(leaf, fi);
4724 if (extent_start != 0) {
4726 if (test_bit(BTRFS_ROOT_REF_COWS,
4728 inode_sub_bytes(inode, num_dec);
4731 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
4733 * we can't truncate inline items that have had
4737 btrfs_file_extent_encryption(leaf, fi) == 0 &&
4738 btrfs_file_extent_other_encoding(leaf, fi) == 0 &&
4739 btrfs_file_extent_compression(leaf, fi) == 0) {
4740 u32 size = (u32)(new_size - found_key.offset);
4742 btrfs_set_file_extent_ram_bytes(leaf, fi, size);
4743 size = btrfs_file_extent_calc_inline_size(size);
4744 btrfs_truncate_item(path, size, 1);
4745 } else if (!del_item) {
4747 * We have to bail so the last_size is set to
4748 * just before this extent.
4750 ret = NEED_TRUNCATE_BLOCK;
4754 if (test_bit(BTRFS_ROOT_REF_COWS, &root->state))
4755 inode_sub_bytes(inode, item_end + 1 - new_size);
4759 last_size = found_key.offset;
4761 last_size = new_size;
4763 if (!pending_del_nr) {
4764 /* no pending yet, add ourselves */
4765 pending_del_slot = path->slots[0];
4767 } else if (pending_del_nr &&
4768 path->slots[0] + 1 == pending_del_slot) {
4769 /* hop on the pending chunk */
4771 pending_del_slot = path->slots[0];
4778 should_throttle = false;
4781 (test_bit(BTRFS_ROOT_REF_COWS, &root->state) ||
4782 root == fs_info->tree_root)) {
4783 struct btrfs_ref ref = { 0 };
4785 btrfs_set_path_blocking(path);
4786 bytes_deleted += extent_num_bytes;
4788 btrfs_init_generic_ref(&ref, BTRFS_DROP_DELAYED_REF,
4789 extent_start, extent_num_bytes, 0);
4790 ref.real_root = root->root_key.objectid;
4791 btrfs_init_data_ref(&ref, btrfs_header_owner(leaf),
4792 ino, extent_offset);
4793 ret = btrfs_free_extent(trans, &ref);
4795 btrfs_abort_transaction(trans, ret);
4799 if (btrfs_should_throttle_delayed_refs(trans))
4800 should_throttle = true;
4804 if (found_type == BTRFS_INODE_ITEM_KEY)
4807 if (path->slots[0] == 0 ||
4808 path->slots[0] != pending_del_slot ||
4810 if (pending_del_nr) {
4811 ret = btrfs_del_items(trans, root, path,
4815 btrfs_abort_transaction(trans, ret);
4820 btrfs_release_path(path);
4823 * We can generate a lot of delayed refs, so we need to
4824 * throttle every once and a while and make sure we're
4825 * adding enough space to keep up with the work we are
4826 * generating. Since we hold a transaction here we
4827 * can't flush, and we don't want to FLUSH_LIMIT because
4828 * we could have generated too many delayed refs to
4829 * actually allocate, so just bail if we're short and
4830 * let the normal reservation dance happen higher up.
4832 if (should_throttle) {
4833 ret = btrfs_delayed_refs_rsv_refill(fs_info,
4834 BTRFS_RESERVE_NO_FLUSH);
4846 if (ret >= 0 && pending_del_nr) {
4849 err = btrfs_del_items(trans, root, path, pending_del_slot,
4852 btrfs_abort_transaction(trans, err);
4856 if (root->root_key.objectid != BTRFS_TREE_LOG_OBJECTID) {
4857 ASSERT(last_size >= new_size);
4858 if (!ret && last_size > new_size)
4859 last_size = new_size;
4860 btrfs_ordered_update_i_size(inode, last_size, NULL);
4863 btrfs_free_path(path);
4868 * btrfs_truncate_block - read, zero a chunk and write a block
4869 * @inode - inode that we're zeroing
4870 * @from - the offset to start zeroing
4871 * @len - the length to zero, 0 to zero the entire range respective to the
4873 * @front - zero up to the offset instead of from the offset on
4875 * This will find the block for the "from" offset and cow the block and zero the
4876 * part we want to zero. This is used with truncate and hole punching.
4878 int btrfs_truncate_block(struct inode *inode, loff_t from, loff_t len,
4881 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
4882 struct address_space *mapping = inode->i_mapping;
4883 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
4884 struct btrfs_ordered_extent *ordered;
4885 struct extent_state *cached_state = NULL;
4886 struct extent_changeset *data_reserved = NULL;
4888 u32 blocksize = fs_info->sectorsize;
4889 pgoff_t index = from >> PAGE_SHIFT;
4890 unsigned offset = from & (blocksize - 1);
4892 gfp_t mask = btrfs_alloc_write_mask(mapping);
4897 if (IS_ALIGNED(offset, blocksize) &&
4898 (!len || IS_ALIGNED(len, blocksize)))
4901 block_start = round_down(from, blocksize);
4902 block_end = block_start + blocksize - 1;
4904 ret = btrfs_delalloc_reserve_space(inode, &data_reserved,
4905 block_start, blocksize);
4910 page = find_or_create_page(mapping, index, mask);
4912 btrfs_delalloc_release_space(inode, data_reserved,
4913 block_start, blocksize, true);
4914 btrfs_delalloc_release_extents(BTRFS_I(inode), blocksize, true);
4919 if (!PageUptodate(page)) {
4920 ret = btrfs_readpage(NULL, page);
4922 if (page->mapping != mapping) {
4927 if (!PageUptodate(page)) {
4932 wait_on_page_writeback(page);
4934 lock_extent_bits(io_tree, block_start, block_end, &cached_state);
4935 set_page_extent_mapped(page);
4937 ordered = btrfs_lookup_ordered_extent(inode, block_start);
4939 unlock_extent_cached(io_tree, block_start, block_end,
4943 btrfs_start_ordered_extent(inode, ordered, 1);
4944 btrfs_put_ordered_extent(ordered);
4948 clear_extent_bit(&BTRFS_I(inode)->io_tree, block_start, block_end,
4949 EXTENT_DIRTY | EXTENT_DELALLOC |
4950 EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG,
4951 0, 0, &cached_state);
4953 ret = btrfs_set_extent_delalloc(inode, block_start, block_end, 0,
4956 unlock_extent_cached(io_tree, block_start, block_end,
4961 if (offset != blocksize) {
4963 len = blocksize - offset;
4966 memset(kaddr + (block_start - page_offset(page)),
4969 memset(kaddr + (block_start - page_offset(page)) + offset,
4971 flush_dcache_page(page);
4974 ClearPageChecked(page);
4975 set_page_dirty(page);
4976 unlock_extent_cached(io_tree, block_start, block_end, &cached_state);
4980 btrfs_delalloc_release_space(inode, data_reserved, block_start,
4982 btrfs_delalloc_release_extents(BTRFS_I(inode), blocksize, (ret != 0));
4986 extent_changeset_free(data_reserved);
4990 static int maybe_insert_hole(struct btrfs_root *root, struct inode *inode,
4991 u64 offset, u64 len)
4993 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
4994 struct btrfs_trans_handle *trans;
4998 * Still need to make sure the inode looks like it's been updated so
4999 * that any holes get logged if we fsync.
5001 if (btrfs_fs_incompat(fs_info, NO_HOLES)) {
5002 BTRFS_I(inode)->last_trans = fs_info->generation;
5003 BTRFS_I(inode)->last_sub_trans = root->log_transid;
5004 BTRFS_I(inode)->last_log_commit = root->last_log_commit;
5009 * 1 - for the one we're dropping
5010 * 1 - for the one we're adding
5011 * 1 - for updating the inode.
5013 trans = btrfs_start_transaction(root, 3);
5015 return PTR_ERR(trans);
5017 ret = btrfs_drop_extents(trans, root, inode, offset, offset + len, 1);
5019 btrfs_abort_transaction(trans, ret);
5020 btrfs_end_transaction(trans);
5024 ret = btrfs_insert_file_extent(trans, root, btrfs_ino(BTRFS_I(inode)),
5025 offset, 0, 0, len, 0, len, 0, 0, 0);
5027 btrfs_abort_transaction(trans, ret);
5029 btrfs_update_inode(trans, root, inode);
5030 btrfs_end_transaction(trans);
5035 * This function puts in dummy file extents for the area we're creating a hole
5036 * for. So if we are truncating this file to a larger size we need to insert
5037 * these file extents so that btrfs_get_extent will return a EXTENT_MAP_HOLE for
5038 * the range between oldsize and size
5040 int btrfs_cont_expand(struct inode *inode, loff_t oldsize, loff_t size)
5042 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
5043 struct btrfs_root *root = BTRFS_I(inode)->root;
5044 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
5045 struct extent_map *em = NULL;
5046 struct extent_state *cached_state = NULL;
5047 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
5048 u64 hole_start = ALIGN(oldsize, fs_info->sectorsize);
5049 u64 block_end = ALIGN(size, fs_info->sectorsize);
5056 * If our size started in the middle of a block we need to zero out the
5057 * rest of the block before we expand the i_size, otherwise we could
5058 * expose stale data.
5060 err = btrfs_truncate_block(inode, oldsize, 0, 0);
5064 if (size <= hole_start)
5067 btrfs_lock_and_flush_ordered_range(io_tree, BTRFS_I(inode), hole_start,
5068 block_end - 1, &cached_state);
5069 cur_offset = hole_start;
5071 em = btrfs_get_extent(BTRFS_I(inode), NULL, 0, cur_offset,
5072 block_end - cur_offset, 0);
5078 last_byte = min(extent_map_end(em), block_end);
5079 last_byte = ALIGN(last_byte, fs_info->sectorsize);
5080 if (!test_bit(EXTENT_FLAG_PREALLOC, &em->flags)) {
5081 struct extent_map *hole_em;
5082 hole_size = last_byte - cur_offset;
5084 err = maybe_insert_hole(root, inode, cur_offset,
5088 btrfs_drop_extent_cache(BTRFS_I(inode), cur_offset,
5089 cur_offset + hole_size - 1, 0);
5090 hole_em = alloc_extent_map();
5092 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
5093 &BTRFS_I(inode)->runtime_flags);
5096 hole_em->start = cur_offset;
5097 hole_em->len = hole_size;
5098 hole_em->orig_start = cur_offset;
5100 hole_em->block_start = EXTENT_MAP_HOLE;
5101 hole_em->block_len = 0;
5102 hole_em->orig_block_len = 0;
5103 hole_em->ram_bytes = hole_size;
5104 hole_em->bdev = fs_info->fs_devices->latest_bdev;
5105 hole_em->compress_type = BTRFS_COMPRESS_NONE;
5106 hole_em->generation = fs_info->generation;
5109 write_lock(&em_tree->lock);
5110 err = add_extent_mapping(em_tree, hole_em, 1);
5111 write_unlock(&em_tree->lock);
5114 btrfs_drop_extent_cache(BTRFS_I(inode),
5119 free_extent_map(hole_em);
5122 free_extent_map(em);
5124 cur_offset = last_byte;
5125 if (cur_offset >= block_end)
5128 free_extent_map(em);
5129 unlock_extent_cached(io_tree, hole_start, block_end - 1, &cached_state);
5133 static int btrfs_setsize(struct inode *inode, struct iattr *attr)
5135 struct btrfs_root *root = BTRFS_I(inode)->root;
5136 struct btrfs_trans_handle *trans;
5137 loff_t oldsize = i_size_read(inode);
5138 loff_t newsize = attr->ia_size;
5139 int mask = attr->ia_valid;
5143 * The regular truncate() case without ATTR_CTIME and ATTR_MTIME is a
5144 * special case where we need to update the times despite not having
5145 * these flags set. For all other operations the VFS set these flags
5146 * explicitly if it wants a timestamp update.
5148 if (newsize != oldsize) {
5149 inode_inc_iversion(inode);
5150 if (!(mask & (ATTR_CTIME | ATTR_MTIME)))
5151 inode->i_ctime = inode->i_mtime =
5152 current_time(inode);
5155 if (newsize > oldsize) {
5157 * Don't do an expanding truncate while snapshotting is ongoing.
5158 * This is to ensure the snapshot captures a fully consistent
5159 * state of this file - if the snapshot captures this expanding
5160 * truncation, it must capture all writes that happened before
5163 btrfs_wait_for_snapshot_creation(root);
5164 ret = btrfs_cont_expand(inode, oldsize, newsize);
5166 btrfs_end_write_no_snapshotting(root);
5170 trans = btrfs_start_transaction(root, 1);
5171 if (IS_ERR(trans)) {
5172 btrfs_end_write_no_snapshotting(root);
5173 return PTR_ERR(trans);
5176 i_size_write(inode, newsize);
5177 btrfs_ordered_update_i_size(inode, i_size_read(inode), NULL);
5178 pagecache_isize_extended(inode, oldsize, newsize);
5179 ret = btrfs_update_inode(trans, root, inode);
5180 btrfs_end_write_no_snapshotting(root);
5181 btrfs_end_transaction(trans);
5185 * We're truncating a file that used to have good data down to
5186 * zero. Make sure it gets into the ordered flush list so that
5187 * any new writes get down to disk quickly.
5190 set_bit(BTRFS_INODE_ORDERED_DATA_CLOSE,
5191 &BTRFS_I(inode)->runtime_flags);
5193 truncate_setsize(inode, newsize);
5195 /* Disable nonlocked read DIO to avoid the endless truncate */
5196 btrfs_inode_block_unlocked_dio(BTRFS_I(inode));
5197 inode_dio_wait(inode);
5198 btrfs_inode_resume_unlocked_dio(BTRFS_I(inode));
5200 ret = btrfs_truncate(inode, newsize == oldsize);
5201 if (ret && inode->i_nlink) {
5205 * Truncate failed, so fix up the in-memory size. We
5206 * adjusted disk_i_size down as we removed extents, so
5207 * wait for disk_i_size to be stable and then update the
5208 * in-memory size to match.
5210 err = btrfs_wait_ordered_range(inode, 0, (u64)-1);
5213 i_size_write(inode, BTRFS_I(inode)->disk_i_size);
5220 static int btrfs_setattr(struct dentry *dentry, struct iattr *attr)
5222 struct inode *inode = d_inode(dentry);
5223 struct btrfs_root *root = BTRFS_I(inode)->root;
5226 if (btrfs_root_readonly(root))
5229 err = setattr_prepare(dentry, attr);
5233 if (S_ISREG(inode->i_mode) && (attr->ia_valid & ATTR_SIZE)) {
5234 err = btrfs_setsize(inode, attr);
5239 if (attr->ia_valid) {
5240 setattr_copy(inode, attr);
5241 inode_inc_iversion(inode);
5242 err = btrfs_dirty_inode(inode);
5244 if (!err && attr->ia_valid & ATTR_MODE)
5245 err = posix_acl_chmod(inode, inode->i_mode);
5252 * While truncating the inode pages during eviction, we get the VFS calling
5253 * btrfs_invalidatepage() against each page of the inode. This is slow because
5254 * the calls to btrfs_invalidatepage() result in a huge amount of calls to
5255 * lock_extent_bits() and clear_extent_bit(), which keep merging and splitting
5256 * extent_state structures over and over, wasting lots of time.
5258 * Therefore if the inode is being evicted, let btrfs_invalidatepage() skip all
5259 * those expensive operations on a per page basis and do only the ordered io
5260 * finishing, while we release here the extent_map and extent_state structures,
5261 * without the excessive merging and splitting.
5263 static void evict_inode_truncate_pages(struct inode *inode)
5265 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
5266 struct extent_map_tree *map_tree = &BTRFS_I(inode)->extent_tree;
5267 struct rb_node *node;
5269 ASSERT(inode->i_state & I_FREEING);
5270 truncate_inode_pages_final(&inode->i_data);
5272 write_lock(&map_tree->lock);
5273 while (!RB_EMPTY_ROOT(&map_tree->map.rb_root)) {
5274 struct extent_map *em;
5276 node = rb_first_cached(&map_tree->map);
5277 em = rb_entry(node, struct extent_map, rb_node);
5278 clear_bit(EXTENT_FLAG_PINNED, &em->flags);
5279 clear_bit(EXTENT_FLAG_LOGGING, &em->flags);
5280 remove_extent_mapping(map_tree, em);
5281 free_extent_map(em);
5282 if (need_resched()) {
5283 write_unlock(&map_tree->lock);
5285 write_lock(&map_tree->lock);
5288 write_unlock(&map_tree->lock);
5291 * Keep looping until we have no more ranges in the io tree.
5292 * We can have ongoing bios started by readpages (called from readahead)
5293 * that have their endio callback (extent_io.c:end_bio_extent_readpage)
5294 * still in progress (unlocked the pages in the bio but did not yet
5295 * unlocked the ranges in the io tree). Therefore this means some
5296 * ranges can still be locked and eviction started because before
5297 * submitting those bios, which are executed by a separate task (work
5298 * queue kthread), inode references (inode->i_count) were not taken
5299 * (which would be dropped in the end io callback of each bio).
5300 * Therefore here we effectively end up waiting for those bios and
5301 * anyone else holding locked ranges without having bumped the inode's
5302 * reference count - if we don't do it, when they access the inode's
5303 * io_tree to unlock a range it may be too late, leading to an
5304 * use-after-free issue.
5306 spin_lock(&io_tree->lock);
5307 while (!RB_EMPTY_ROOT(&io_tree->state)) {
5308 struct extent_state *state;
5309 struct extent_state *cached_state = NULL;
5312 unsigned state_flags;
5314 node = rb_first(&io_tree->state);
5315 state = rb_entry(node, struct extent_state, rb_node);
5316 start = state->start;
5318 state_flags = state->state;
5319 spin_unlock(&io_tree->lock);
5321 lock_extent_bits(io_tree, start, end, &cached_state);
5324 * If still has DELALLOC flag, the extent didn't reach disk,
5325 * and its reserved space won't be freed by delayed_ref.
5326 * So we need to free its reserved space here.
5327 * (Refer to comment in btrfs_invalidatepage, case 2)
5329 * Note, end is the bytenr of last byte, so we need + 1 here.
5331 if (state_flags & EXTENT_DELALLOC)
5332 btrfs_qgroup_free_data(inode, NULL, start, end - start + 1);
5334 clear_extent_bit(io_tree, start, end,
5335 EXTENT_LOCKED | EXTENT_DIRTY |
5336 EXTENT_DELALLOC | EXTENT_DO_ACCOUNTING |
5337 EXTENT_DEFRAG, 1, 1, &cached_state);
5340 spin_lock(&io_tree->lock);
5342 spin_unlock(&io_tree->lock);
5345 static struct btrfs_trans_handle *evict_refill_and_join(struct btrfs_root *root,
5346 struct btrfs_block_rsv *rsv)
5348 struct btrfs_fs_info *fs_info = root->fs_info;
5349 struct btrfs_block_rsv *global_rsv = &fs_info->global_block_rsv;
5350 u64 delayed_refs_extra = btrfs_calc_trans_metadata_size(fs_info, 1);
5354 struct btrfs_trans_handle *trans;
5357 ret = btrfs_block_rsv_refill(root, rsv,
5358 rsv->size + delayed_refs_extra,
5359 BTRFS_RESERVE_FLUSH_LIMIT);
5361 if (ret && ++failures > 2) {
5363 "could not allocate space for a delete; will truncate on mount");
5364 return ERR_PTR(-ENOSPC);
5368 * Evict can generate a large amount of delayed refs without
5369 * having a way to add space back since we exhaust our temporary
5370 * block rsv. We aren't allowed to do FLUSH_ALL in this case
5371 * because we could deadlock with so many things in the flushing
5372 * code, so we have to try and hold some extra space to
5373 * compensate for our delayed ref generation. If we can't get
5374 * that space then we need see if we can steal our minimum from
5375 * the global reserve. We will be ratelimited by the amount of
5376 * space we have for the delayed refs rsv, so we'll end up
5377 * committing and trying again.
5379 trans = btrfs_join_transaction(root);
5380 if (IS_ERR(trans) || !ret) {
5381 if (!IS_ERR(trans)) {
5382 trans->block_rsv = &fs_info->trans_block_rsv;
5383 trans->bytes_reserved = delayed_refs_extra;
5384 btrfs_block_rsv_migrate(rsv, trans->block_rsv,
5385 delayed_refs_extra, 1);
5391 * Try to steal from the global reserve if there is space for
5394 if (!btrfs_check_space_for_delayed_refs(fs_info) &&
5395 !btrfs_block_rsv_migrate(global_rsv, rsv, rsv->size, 0))
5398 /* If not, commit and try again. */
5399 ret = btrfs_commit_transaction(trans);
5401 return ERR_PTR(ret);
5405 void btrfs_evict_inode(struct inode *inode)
5407 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
5408 struct btrfs_trans_handle *trans;
5409 struct btrfs_root *root = BTRFS_I(inode)->root;
5410 struct btrfs_block_rsv *rsv;
5413 trace_btrfs_inode_evict(inode);
5420 evict_inode_truncate_pages(inode);
5422 if (inode->i_nlink &&
5423 ((btrfs_root_refs(&root->root_item) != 0 &&
5424 root->root_key.objectid != BTRFS_ROOT_TREE_OBJECTID) ||
5425 btrfs_is_free_space_inode(BTRFS_I(inode))))
5428 if (is_bad_inode(inode))
5431 btrfs_free_io_failure_record(BTRFS_I(inode), 0, (u64)-1);
5433 if (test_bit(BTRFS_FS_LOG_RECOVERING, &fs_info->flags))
5436 if (inode->i_nlink > 0) {
5437 BUG_ON(btrfs_root_refs(&root->root_item) != 0 &&
5438 root->root_key.objectid != BTRFS_ROOT_TREE_OBJECTID);
5442 ret = btrfs_commit_inode_delayed_inode(BTRFS_I(inode));
5446 rsv = btrfs_alloc_block_rsv(fs_info, BTRFS_BLOCK_RSV_TEMP);
5449 rsv->size = btrfs_calc_trunc_metadata_size(fs_info, 1);
5452 btrfs_i_size_write(BTRFS_I(inode), 0);
5455 trans = evict_refill_and_join(root, rsv);
5459 trans->block_rsv = rsv;
5461 ret = btrfs_truncate_inode_items(trans, root, inode, 0, 0);
5462 trans->block_rsv = &fs_info->trans_block_rsv;
5463 btrfs_end_transaction(trans);
5464 btrfs_btree_balance_dirty(fs_info);
5465 if (ret && ret != -ENOSPC && ret != -EAGAIN)
5472 * Errors here aren't a big deal, it just means we leave orphan items in
5473 * the tree. They will be cleaned up on the next mount. If the inode
5474 * number gets reused, cleanup deletes the orphan item without doing
5475 * anything, and unlink reuses the existing orphan item.
5477 * If it turns out that we are dropping too many of these, we might want
5478 * to add a mechanism for retrying these after a commit.
5480 trans = evict_refill_and_join(root, rsv);
5481 if (!IS_ERR(trans)) {
5482 trans->block_rsv = rsv;
5483 btrfs_orphan_del(trans, BTRFS_I(inode));
5484 trans->block_rsv = &fs_info->trans_block_rsv;
5485 btrfs_end_transaction(trans);
5488 if (!(root == fs_info->tree_root ||
5489 root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID))
5490 btrfs_return_ino(root, btrfs_ino(BTRFS_I(inode)));
5493 btrfs_free_block_rsv(fs_info, rsv);
5496 * If we didn't successfully delete, the orphan item will still be in
5497 * the tree and we'll retry on the next mount. Again, we might also want
5498 * to retry these periodically in the future.
5500 btrfs_remove_delayed_node(BTRFS_I(inode));
5505 * Return the key found in the dir entry in the location pointer, fill @type
5506 * with BTRFS_FT_*, and return 0.
5508 * If no dir entries were found, returns -ENOENT.
5509 * If found a corrupted location in dir entry, returns -EUCLEAN.
5511 static int btrfs_inode_by_name(struct inode *dir, struct dentry *dentry,
5512 struct btrfs_key *location, u8 *type)
5514 const char *name = dentry->d_name.name;
5515 int namelen = dentry->d_name.len;
5516 struct btrfs_dir_item *di;
5517 struct btrfs_path *path;
5518 struct btrfs_root *root = BTRFS_I(dir)->root;
5521 path = btrfs_alloc_path();
5525 di = btrfs_lookup_dir_item(NULL, root, path, btrfs_ino(BTRFS_I(dir)),
5527 if (IS_ERR_OR_NULL(di)) {
5528 ret = di ? PTR_ERR(di) : -ENOENT;
5532 btrfs_dir_item_key_to_cpu(path->nodes[0], di, location);
5533 if (location->type != BTRFS_INODE_ITEM_KEY &&
5534 location->type != BTRFS_ROOT_ITEM_KEY) {
5536 btrfs_warn(root->fs_info,
5537 "%s gets something invalid in DIR_ITEM (name %s, directory ino %llu, location(%llu %u %llu))",
5538 __func__, name, btrfs_ino(BTRFS_I(dir)),
5539 location->objectid, location->type, location->offset);
5542 *type = btrfs_dir_type(path->nodes[0], di);
5544 btrfs_free_path(path);
5549 * when we hit a tree root in a directory, the btrfs part of the inode
5550 * needs to be changed to reflect the root directory of the tree root. This
5551 * is kind of like crossing a mount point.
5553 static int fixup_tree_root_location(struct btrfs_fs_info *fs_info,
5555 struct dentry *dentry,
5556 struct btrfs_key *location,
5557 struct btrfs_root **sub_root)
5559 struct btrfs_path *path;
5560 struct btrfs_root *new_root;
5561 struct btrfs_root_ref *ref;
5562 struct extent_buffer *leaf;
5563 struct btrfs_key key;
5567 path = btrfs_alloc_path();
5574 key.objectid = BTRFS_I(dir)->root->root_key.objectid;
5575 key.type = BTRFS_ROOT_REF_KEY;
5576 key.offset = location->objectid;
5578 ret = btrfs_search_slot(NULL, fs_info->tree_root, &key, path, 0, 0);
5585 leaf = path->nodes[0];
5586 ref = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_root_ref);
5587 if (btrfs_root_ref_dirid(leaf, ref) != btrfs_ino(BTRFS_I(dir)) ||
5588 btrfs_root_ref_name_len(leaf, ref) != dentry->d_name.len)
5591 ret = memcmp_extent_buffer(leaf, dentry->d_name.name,
5592 (unsigned long)(ref + 1),
5593 dentry->d_name.len);
5597 btrfs_release_path(path);
5599 new_root = btrfs_read_fs_root_no_name(fs_info, location);
5600 if (IS_ERR(new_root)) {
5601 err = PTR_ERR(new_root);
5605 *sub_root = new_root;
5606 location->objectid = btrfs_root_dirid(&new_root->root_item);
5607 location->type = BTRFS_INODE_ITEM_KEY;
5608 location->offset = 0;
5611 btrfs_free_path(path);
5615 static void inode_tree_add(struct inode *inode)
5617 struct btrfs_root *root = BTRFS_I(inode)->root;
5618 struct btrfs_inode *entry;
5620 struct rb_node *parent;
5621 struct rb_node *new = &BTRFS_I(inode)->rb_node;
5622 u64 ino = btrfs_ino(BTRFS_I(inode));
5624 if (inode_unhashed(inode))
5627 spin_lock(&root->inode_lock);
5628 p = &root->inode_tree.rb_node;
5631 entry = rb_entry(parent, struct btrfs_inode, rb_node);
5633 if (ino < btrfs_ino(entry))
5634 p = &parent->rb_left;
5635 else if (ino > btrfs_ino(entry))
5636 p = &parent->rb_right;
5638 WARN_ON(!(entry->vfs_inode.i_state &
5639 (I_WILL_FREE | I_FREEING)));
5640 rb_replace_node(parent, new, &root->inode_tree);
5641 RB_CLEAR_NODE(parent);
5642 spin_unlock(&root->inode_lock);
5646 rb_link_node(new, parent, p);
5647 rb_insert_color(new, &root->inode_tree);
5648 spin_unlock(&root->inode_lock);
5651 static void inode_tree_del(struct inode *inode)
5653 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
5654 struct btrfs_root *root = BTRFS_I(inode)->root;
5657 spin_lock(&root->inode_lock);
5658 if (!RB_EMPTY_NODE(&BTRFS_I(inode)->rb_node)) {
5659 rb_erase(&BTRFS_I(inode)->rb_node, &root->inode_tree);
5660 RB_CLEAR_NODE(&BTRFS_I(inode)->rb_node);
5661 empty = RB_EMPTY_ROOT(&root->inode_tree);
5663 spin_unlock(&root->inode_lock);
5665 if (empty && btrfs_root_refs(&root->root_item) == 0) {
5666 synchronize_srcu(&fs_info->subvol_srcu);
5667 spin_lock(&root->inode_lock);
5668 empty = RB_EMPTY_ROOT(&root->inode_tree);
5669 spin_unlock(&root->inode_lock);
5671 btrfs_add_dead_root(root);
5676 static int btrfs_init_locked_inode(struct inode *inode, void *p)
5678 struct btrfs_iget_args *args = p;
5679 inode->i_ino = args->location->objectid;
5680 memcpy(&BTRFS_I(inode)->location, args->location,
5681 sizeof(*args->location));
5682 BTRFS_I(inode)->root = args->root;
5686 static int btrfs_find_actor(struct inode *inode, void *opaque)
5688 struct btrfs_iget_args *args = opaque;
5689 return args->location->objectid == BTRFS_I(inode)->location.objectid &&
5690 args->root == BTRFS_I(inode)->root;
5693 static struct inode *btrfs_iget_locked(struct super_block *s,
5694 struct btrfs_key *location,
5695 struct btrfs_root *root)
5697 struct inode *inode;
5698 struct btrfs_iget_args args;
5699 unsigned long hashval = btrfs_inode_hash(location->objectid, root);
5701 args.location = location;
5704 inode = iget5_locked(s, hashval, btrfs_find_actor,
5705 btrfs_init_locked_inode,
5710 /* Get an inode object given its location and corresponding root.
5711 * Returns in *is_new if the inode was read from disk
5713 struct inode *btrfs_iget_path(struct super_block *s, struct btrfs_key *location,
5714 struct btrfs_root *root, int *new,
5715 struct btrfs_path *path)
5717 struct inode *inode;
5719 inode = btrfs_iget_locked(s, location, root);
5721 return ERR_PTR(-ENOMEM);
5723 if (inode->i_state & I_NEW) {
5726 ret = btrfs_read_locked_inode(inode, path);
5728 inode_tree_add(inode);
5729 unlock_new_inode(inode);
5735 * ret > 0 can come from btrfs_search_slot called by
5736 * btrfs_read_locked_inode, this means the inode item
5741 inode = ERR_PTR(ret);
5748 struct inode *btrfs_iget(struct super_block *s, struct btrfs_key *location,
5749 struct btrfs_root *root, int *new)
5751 return btrfs_iget_path(s, location, root, new, NULL);
5754 static struct inode *new_simple_dir(struct super_block *s,
5755 struct btrfs_key *key,
5756 struct btrfs_root *root)
5758 struct inode *inode = new_inode(s);
5761 return ERR_PTR(-ENOMEM);
5763 BTRFS_I(inode)->root = root;
5764 memcpy(&BTRFS_I(inode)->location, key, sizeof(*key));
5765 set_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags);
5767 inode->i_ino = BTRFS_EMPTY_SUBVOL_DIR_OBJECTID;
5768 inode->i_op = &btrfs_dir_ro_inode_operations;
5769 inode->i_opflags &= ~IOP_XATTR;
5770 inode->i_fop = &simple_dir_operations;
5771 inode->i_mode = S_IFDIR | S_IRUGO | S_IWUSR | S_IXUGO;
5772 inode->i_mtime = current_time(inode);
5773 inode->i_atime = inode->i_mtime;
5774 inode->i_ctime = inode->i_mtime;
5775 BTRFS_I(inode)->i_otime = inode->i_mtime;
5780 static inline u8 btrfs_inode_type(struct inode *inode)
5783 * Compile-time asserts that generic FT_* types still match
5786 BUILD_BUG_ON(BTRFS_FT_UNKNOWN != FT_UNKNOWN);
5787 BUILD_BUG_ON(BTRFS_FT_REG_FILE != FT_REG_FILE);
5788 BUILD_BUG_ON(BTRFS_FT_DIR != FT_DIR);
5789 BUILD_BUG_ON(BTRFS_FT_CHRDEV != FT_CHRDEV);
5790 BUILD_BUG_ON(BTRFS_FT_BLKDEV != FT_BLKDEV);
5791 BUILD_BUG_ON(BTRFS_FT_FIFO != FT_FIFO);
5792 BUILD_BUG_ON(BTRFS_FT_SOCK != FT_SOCK);
5793 BUILD_BUG_ON(BTRFS_FT_SYMLINK != FT_SYMLINK);
5795 return fs_umode_to_ftype(inode->i_mode);
5798 struct inode *btrfs_lookup_dentry(struct inode *dir, struct dentry *dentry)
5800 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
5801 struct inode *inode;
5802 struct btrfs_root *root = BTRFS_I(dir)->root;
5803 struct btrfs_root *sub_root = root;
5804 struct btrfs_key location;
5809 if (dentry->d_name.len > BTRFS_NAME_LEN)
5810 return ERR_PTR(-ENAMETOOLONG);
5812 ret = btrfs_inode_by_name(dir, dentry, &location, &di_type);
5814 return ERR_PTR(ret);
5816 if (location.type == BTRFS_INODE_ITEM_KEY) {
5817 inode = btrfs_iget(dir->i_sb, &location, root, NULL);
5821 /* Do extra check against inode mode with di_type */
5822 if (btrfs_inode_type(inode) != di_type) {
5824 "inode mode mismatch with dir: inode mode=0%o btrfs type=%u dir type=%u",
5825 inode->i_mode, btrfs_inode_type(inode),
5828 return ERR_PTR(-EUCLEAN);
5833 index = srcu_read_lock(&fs_info->subvol_srcu);
5834 ret = fixup_tree_root_location(fs_info, dir, dentry,
5835 &location, &sub_root);
5838 inode = ERR_PTR(ret);
5840 inode = new_simple_dir(dir->i_sb, &location, sub_root);
5842 inode = btrfs_iget(dir->i_sb, &location, sub_root, NULL);
5844 srcu_read_unlock(&fs_info->subvol_srcu, index);
5846 if (!IS_ERR(inode) && root != sub_root) {
5847 down_read(&fs_info->cleanup_work_sem);
5848 if (!sb_rdonly(inode->i_sb))
5849 ret = btrfs_orphan_cleanup(sub_root);
5850 up_read(&fs_info->cleanup_work_sem);
5853 inode = ERR_PTR(ret);
5860 static int btrfs_dentry_delete(const struct dentry *dentry)
5862 struct btrfs_root *root;
5863 struct inode *inode = d_inode(dentry);
5865 if (!inode && !IS_ROOT(dentry))
5866 inode = d_inode(dentry->d_parent);
5869 root = BTRFS_I(inode)->root;
5870 if (btrfs_root_refs(&root->root_item) == 0)
5873 if (btrfs_ino(BTRFS_I(inode)) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)
5879 static struct dentry *btrfs_lookup(struct inode *dir, struct dentry *dentry,
5882 struct inode *inode = btrfs_lookup_dentry(dir, dentry);
5884 if (inode == ERR_PTR(-ENOENT))
5886 return d_splice_alias(inode, dentry);
5890 * All this infrastructure exists because dir_emit can fault, and we are holding
5891 * the tree lock when doing readdir. For now just allocate a buffer and copy
5892 * our information into that, and then dir_emit from the buffer. This is
5893 * similar to what NFS does, only we don't keep the buffer around in pagecache
5894 * because I'm afraid I'll mess that up. Long term we need to make filldir do
5895 * copy_to_user_inatomic so we don't have to worry about page faulting under the
5898 static int btrfs_opendir(struct inode *inode, struct file *file)
5900 struct btrfs_file_private *private;
5902 private = kzalloc(sizeof(struct btrfs_file_private), GFP_KERNEL);
5905 private->filldir_buf = kzalloc(PAGE_SIZE, GFP_KERNEL);
5906 if (!private->filldir_buf) {
5910 file->private_data = private;
5921 static int btrfs_filldir(void *addr, int entries, struct dir_context *ctx)
5924 struct dir_entry *entry = addr;
5925 char *name = (char *)(entry + 1);
5927 ctx->pos = get_unaligned(&entry->offset);
5928 if (!dir_emit(ctx, name, get_unaligned(&entry->name_len),
5929 get_unaligned(&entry->ino),
5930 get_unaligned(&entry->type)))
5932 addr += sizeof(struct dir_entry) +
5933 get_unaligned(&entry->name_len);
5939 static int btrfs_real_readdir(struct file *file, struct dir_context *ctx)
5941 struct inode *inode = file_inode(file);
5942 struct btrfs_root *root = BTRFS_I(inode)->root;
5943 struct btrfs_file_private *private = file->private_data;
5944 struct btrfs_dir_item *di;
5945 struct btrfs_key key;
5946 struct btrfs_key found_key;
5947 struct btrfs_path *path;
5949 struct list_head ins_list;
5950 struct list_head del_list;
5952 struct extent_buffer *leaf;
5959 struct btrfs_key location;
5961 if (!dir_emit_dots(file, ctx))
5964 path = btrfs_alloc_path();
5968 addr = private->filldir_buf;
5969 path->reada = READA_FORWARD;
5971 INIT_LIST_HEAD(&ins_list);
5972 INIT_LIST_HEAD(&del_list);
5973 put = btrfs_readdir_get_delayed_items(inode, &ins_list, &del_list);
5976 key.type = BTRFS_DIR_INDEX_KEY;
5977 key.offset = ctx->pos;
5978 key.objectid = btrfs_ino(BTRFS_I(inode));
5980 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
5985 struct dir_entry *entry;
5987 leaf = path->nodes[0];
5988 slot = path->slots[0];
5989 if (slot >= btrfs_header_nritems(leaf)) {
5990 ret = btrfs_next_leaf(root, path);
5998 btrfs_item_key_to_cpu(leaf, &found_key, slot);
6000 if (found_key.objectid != key.objectid)
6002 if (found_key.type != BTRFS_DIR_INDEX_KEY)
6004 if (found_key.offset < ctx->pos)
6006 if (btrfs_should_delete_dir_index(&del_list, found_key.offset))
6008 di = btrfs_item_ptr(leaf, slot, struct btrfs_dir_item);
6009 name_len = btrfs_dir_name_len(leaf, di);
6010 if ((total_len + sizeof(struct dir_entry) + name_len) >=
6012 btrfs_release_path(path);
6013 ret = btrfs_filldir(private->filldir_buf, entries, ctx);
6016 addr = private->filldir_buf;
6023 put_unaligned(name_len, &entry->name_len);
6024 name_ptr = (char *)(entry + 1);
6025 read_extent_buffer(leaf, name_ptr, (unsigned long)(di + 1),
6027 put_unaligned(fs_ftype_to_dtype(btrfs_dir_type(leaf, di)),
6029 btrfs_dir_item_key_to_cpu(leaf, di, &location);
6030 put_unaligned(location.objectid, &entry->ino);
6031 put_unaligned(found_key.offset, &entry->offset);
6033 addr += sizeof(struct dir_entry) + name_len;
6034 total_len += sizeof(struct dir_entry) + name_len;
6038 btrfs_release_path(path);
6040 ret = btrfs_filldir(private->filldir_buf, entries, ctx);
6044 ret = btrfs_readdir_delayed_dir_index(ctx, &ins_list);
6049 * Stop new entries from being returned after we return the last
6052 * New directory entries are assigned a strictly increasing
6053 * offset. This means that new entries created during readdir
6054 * are *guaranteed* to be seen in the future by that readdir.
6055 * This has broken buggy programs which operate on names as
6056 * they're returned by readdir. Until we re-use freed offsets
6057 * we have this hack to stop new entries from being returned
6058 * under the assumption that they'll never reach this huge
6061 * This is being careful not to overflow 32bit loff_t unless the
6062 * last entry requires it because doing so has broken 32bit apps
6065 if (ctx->pos >= INT_MAX)
6066 ctx->pos = LLONG_MAX;
6073 btrfs_readdir_put_delayed_items(inode, &ins_list, &del_list);
6074 btrfs_free_path(path);
6079 * This is somewhat expensive, updating the tree every time the
6080 * inode changes. But, it is most likely to find the inode in cache.
6081 * FIXME, needs more benchmarking...there are no reasons other than performance
6082 * to keep or drop this code.
6084 static int btrfs_dirty_inode(struct inode *inode)
6086 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
6087 struct btrfs_root *root = BTRFS_I(inode)->root;
6088 struct btrfs_trans_handle *trans;
6091 if (test_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags))
6094 trans = btrfs_join_transaction(root);
6096 return PTR_ERR(trans);
6098 ret = btrfs_update_inode(trans, root, inode);
6099 if (ret && ret == -ENOSPC) {
6100 /* whoops, lets try again with the full transaction */
6101 btrfs_end_transaction(trans);
6102 trans = btrfs_start_transaction(root, 1);
6104 return PTR_ERR(trans);
6106 ret = btrfs_update_inode(trans, root, inode);
6108 btrfs_end_transaction(trans);
6109 if (BTRFS_I(inode)->delayed_node)
6110 btrfs_balance_delayed_items(fs_info);
6116 * This is a copy of file_update_time. We need this so we can return error on
6117 * ENOSPC for updating the inode in the case of file write and mmap writes.
6119 static int btrfs_update_time(struct inode *inode, struct timespec64 *now,
6122 struct btrfs_root *root = BTRFS_I(inode)->root;
6123 bool dirty = flags & ~S_VERSION;
6125 if (btrfs_root_readonly(root))
6128 if (flags & S_VERSION)
6129 dirty |= inode_maybe_inc_iversion(inode, dirty);
6130 if (flags & S_CTIME)
6131 inode->i_ctime = *now;
6132 if (flags & S_MTIME)
6133 inode->i_mtime = *now;
6134 if (flags & S_ATIME)
6135 inode->i_atime = *now;
6136 return dirty ? btrfs_dirty_inode(inode) : 0;
6140 * find the highest existing sequence number in a directory
6141 * and then set the in-memory index_cnt variable to reflect
6142 * free sequence numbers
6144 static int btrfs_set_inode_index_count(struct btrfs_inode *inode)
6146 struct btrfs_root *root = inode->root;
6147 struct btrfs_key key, found_key;
6148 struct btrfs_path *path;
6149 struct extent_buffer *leaf;
6152 key.objectid = btrfs_ino(inode);
6153 key.type = BTRFS_DIR_INDEX_KEY;
6154 key.offset = (u64)-1;
6156 path = btrfs_alloc_path();
6160 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
6163 /* FIXME: we should be able to handle this */
6169 * MAGIC NUMBER EXPLANATION:
6170 * since we search a directory based on f_pos we have to start at 2
6171 * since '.' and '..' have f_pos of 0 and 1 respectively, so everybody
6172 * else has to start at 2
6174 if (path->slots[0] == 0) {
6175 inode->index_cnt = 2;
6181 leaf = path->nodes[0];
6182 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
6184 if (found_key.objectid != btrfs_ino(inode) ||
6185 found_key.type != BTRFS_DIR_INDEX_KEY) {
6186 inode->index_cnt = 2;
6190 inode->index_cnt = found_key.offset + 1;
6192 btrfs_free_path(path);
6197 * helper to find a free sequence number in a given directory. This current
6198 * code is very simple, later versions will do smarter things in the btree
6200 int btrfs_set_inode_index(struct btrfs_inode *dir, u64 *index)
6204 if (dir->index_cnt == (u64)-1) {
6205 ret = btrfs_inode_delayed_dir_index_count(dir);
6207 ret = btrfs_set_inode_index_count(dir);
6213 *index = dir->index_cnt;
6219 static int btrfs_insert_inode_locked(struct inode *inode)
6221 struct btrfs_iget_args args;
6222 args.location = &BTRFS_I(inode)->location;
6223 args.root = BTRFS_I(inode)->root;
6225 return insert_inode_locked4(inode,
6226 btrfs_inode_hash(inode->i_ino, BTRFS_I(inode)->root),
6227 btrfs_find_actor, &args);
6231 * Inherit flags from the parent inode.
6233 * Currently only the compression flags and the cow flags are inherited.
6235 static void btrfs_inherit_iflags(struct inode *inode, struct inode *dir)
6242 flags = BTRFS_I(dir)->flags;
6244 if (flags & BTRFS_INODE_NOCOMPRESS) {
6245 BTRFS_I(inode)->flags &= ~BTRFS_INODE_COMPRESS;
6246 BTRFS_I(inode)->flags |= BTRFS_INODE_NOCOMPRESS;
6247 } else if (flags & BTRFS_INODE_COMPRESS) {
6248 BTRFS_I(inode)->flags &= ~BTRFS_INODE_NOCOMPRESS;
6249 BTRFS_I(inode)->flags |= BTRFS_INODE_COMPRESS;
6252 if (flags & BTRFS_INODE_NODATACOW) {
6253 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATACOW;
6254 if (S_ISREG(inode->i_mode))
6255 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATASUM;
6258 btrfs_sync_inode_flags_to_i_flags(inode);
6261 static struct inode *btrfs_new_inode(struct btrfs_trans_handle *trans,
6262 struct btrfs_root *root,
6264 const char *name, int name_len,
6265 u64 ref_objectid, u64 objectid,
6266 umode_t mode, u64 *index)
6268 struct btrfs_fs_info *fs_info = root->fs_info;
6269 struct inode *inode;
6270 struct btrfs_inode_item *inode_item;
6271 struct btrfs_key *location;
6272 struct btrfs_path *path;
6273 struct btrfs_inode_ref *ref;
6274 struct btrfs_key key[2];
6276 int nitems = name ? 2 : 1;
6280 path = btrfs_alloc_path();
6282 return ERR_PTR(-ENOMEM);
6284 inode = new_inode(fs_info->sb);
6286 btrfs_free_path(path);
6287 return ERR_PTR(-ENOMEM);
6291 * O_TMPFILE, set link count to 0, so that after this point,
6292 * we fill in an inode item with the correct link count.
6295 set_nlink(inode, 0);
6298 * we have to initialize this early, so we can reclaim the inode
6299 * number if we fail afterwards in this function.
6301 inode->i_ino = objectid;
6304 trace_btrfs_inode_request(dir);
6306 ret = btrfs_set_inode_index(BTRFS_I(dir), index);
6308 btrfs_free_path(path);
6310 return ERR_PTR(ret);
6316 * index_cnt is ignored for everything but a dir,
6317 * btrfs_set_inode_index_count has an explanation for the magic
6320 BTRFS_I(inode)->index_cnt = 2;
6321 BTRFS_I(inode)->dir_index = *index;
6322 BTRFS_I(inode)->root = root;
6323 BTRFS_I(inode)->generation = trans->transid;
6324 inode->i_generation = BTRFS_I(inode)->generation;
6327 * We could have gotten an inode number from somebody who was fsynced
6328 * and then removed in this same transaction, so let's just set full
6329 * sync since it will be a full sync anyway and this will blow away the
6330 * old info in the log.
6332 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &BTRFS_I(inode)->runtime_flags);
6334 key[0].objectid = objectid;
6335 key[0].type = BTRFS_INODE_ITEM_KEY;
6338 sizes[0] = sizeof(struct btrfs_inode_item);
6342 * Start new inodes with an inode_ref. This is slightly more
6343 * efficient for small numbers of hard links since they will
6344 * be packed into one item. Extended refs will kick in if we
6345 * add more hard links than can fit in the ref item.
6347 key[1].objectid = objectid;
6348 key[1].type = BTRFS_INODE_REF_KEY;
6349 key[1].offset = ref_objectid;
6351 sizes[1] = name_len + sizeof(*ref);
6354 location = &BTRFS_I(inode)->location;
6355 location->objectid = objectid;
6356 location->offset = 0;
6357 location->type = BTRFS_INODE_ITEM_KEY;
6359 ret = btrfs_insert_inode_locked(inode);
6365 path->leave_spinning = 1;
6366 ret = btrfs_insert_empty_items(trans, root, path, key, sizes, nitems);
6370 inode_init_owner(inode, dir, mode);
6371 inode_set_bytes(inode, 0);
6373 inode->i_mtime = current_time(inode);
6374 inode->i_atime = inode->i_mtime;
6375 inode->i_ctime = inode->i_mtime;
6376 BTRFS_I(inode)->i_otime = inode->i_mtime;
6378 inode_item = btrfs_item_ptr(path->nodes[0], path->slots[0],
6379 struct btrfs_inode_item);
6380 memzero_extent_buffer(path->nodes[0], (unsigned long)inode_item,
6381 sizeof(*inode_item));
6382 fill_inode_item(trans, path->nodes[0], inode_item, inode);
6385 ref = btrfs_item_ptr(path->nodes[0], path->slots[0] + 1,
6386 struct btrfs_inode_ref);
6387 btrfs_set_inode_ref_name_len(path->nodes[0], ref, name_len);
6388 btrfs_set_inode_ref_index(path->nodes[0], ref, *index);
6389 ptr = (unsigned long)(ref + 1);
6390 write_extent_buffer(path->nodes[0], name, ptr, name_len);
6393 btrfs_mark_buffer_dirty(path->nodes[0]);
6394 btrfs_free_path(path);
6396 btrfs_inherit_iflags(inode, dir);
6398 if (S_ISREG(mode)) {
6399 if (btrfs_test_opt(fs_info, NODATASUM))
6400 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATASUM;
6401 if (btrfs_test_opt(fs_info, NODATACOW))
6402 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATACOW |
6403 BTRFS_INODE_NODATASUM;
6406 inode_tree_add(inode);
6408 trace_btrfs_inode_new(inode);
6409 btrfs_set_inode_last_trans(trans, inode);
6411 btrfs_update_root_times(trans, root);
6413 ret = btrfs_inode_inherit_props(trans, inode, dir);
6416 "error inheriting props for ino %llu (root %llu): %d",
6417 btrfs_ino(BTRFS_I(inode)), root->root_key.objectid, ret);
6422 discard_new_inode(inode);
6425 BTRFS_I(dir)->index_cnt--;
6426 btrfs_free_path(path);
6427 return ERR_PTR(ret);
6431 * utility function to add 'inode' into 'parent_inode' with
6432 * a give name and a given sequence number.
6433 * if 'add_backref' is true, also insert a backref from the
6434 * inode to the parent directory.
6436 int btrfs_add_link(struct btrfs_trans_handle *trans,
6437 struct btrfs_inode *parent_inode, struct btrfs_inode *inode,
6438 const char *name, int name_len, int add_backref, u64 index)
6441 struct btrfs_key key;
6442 struct btrfs_root *root = parent_inode->root;
6443 u64 ino = btrfs_ino(inode);
6444 u64 parent_ino = btrfs_ino(parent_inode);
6446 if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
6447 memcpy(&key, &inode->root->root_key, sizeof(key));
6450 key.type = BTRFS_INODE_ITEM_KEY;
6454 if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
6455 ret = btrfs_add_root_ref(trans, key.objectid,
6456 root->root_key.objectid, parent_ino,
6457 index, name, name_len);
6458 } else if (add_backref) {
6459 ret = btrfs_insert_inode_ref(trans, root, name, name_len, ino,
6463 /* Nothing to clean up yet */
6467 ret = btrfs_insert_dir_item(trans, name, name_len, parent_inode, &key,
6468 btrfs_inode_type(&inode->vfs_inode), index);
6469 if (ret == -EEXIST || ret == -EOVERFLOW)
6472 btrfs_abort_transaction(trans, ret);
6476 btrfs_i_size_write(parent_inode, parent_inode->vfs_inode.i_size +
6478 inode_inc_iversion(&parent_inode->vfs_inode);
6480 * If we are replaying a log tree, we do not want to update the mtime
6481 * and ctime of the parent directory with the current time, since the
6482 * log replay procedure is responsible for setting them to their correct
6483 * values (the ones it had when the fsync was done).
6485 if (!test_bit(BTRFS_FS_LOG_RECOVERING, &root->fs_info->flags)) {
6486 struct timespec64 now = current_time(&parent_inode->vfs_inode);
6488 parent_inode->vfs_inode.i_mtime = now;
6489 parent_inode->vfs_inode.i_ctime = now;
6491 ret = btrfs_update_inode(trans, root, &parent_inode->vfs_inode);
6493 btrfs_abort_transaction(trans, ret);
6497 if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
6500 err = btrfs_del_root_ref(trans, key.objectid,
6501 root->root_key.objectid, parent_ino,
6502 &local_index, name, name_len);
6504 btrfs_abort_transaction(trans, err);
6505 } else if (add_backref) {
6509 err = btrfs_del_inode_ref(trans, root, name, name_len,
6510 ino, parent_ino, &local_index);
6512 btrfs_abort_transaction(trans, err);
6515 /* Return the original error code */
6519 static int btrfs_add_nondir(struct btrfs_trans_handle *trans,
6520 struct btrfs_inode *dir, struct dentry *dentry,
6521 struct btrfs_inode *inode, int backref, u64 index)
6523 int err = btrfs_add_link(trans, dir, inode,
6524 dentry->d_name.name, dentry->d_name.len,
6531 static int btrfs_mknod(struct inode *dir, struct dentry *dentry,
6532 umode_t mode, dev_t rdev)
6534 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
6535 struct btrfs_trans_handle *trans;
6536 struct btrfs_root *root = BTRFS_I(dir)->root;
6537 struct inode *inode = NULL;
6543 * 2 for inode item and ref
6545 * 1 for xattr if selinux is on
6547 trans = btrfs_start_transaction(root, 5);
6549 return PTR_ERR(trans);
6551 err = btrfs_find_free_ino(root, &objectid);
6555 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
6556 dentry->d_name.len, btrfs_ino(BTRFS_I(dir)), objectid,
6558 if (IS_ERR(inode)) {
6559 err = PTR_ERR(inode);
6565 * If the active LSM wants to access the inode during
6566 * d_instantiate it needs these. Smack checks to see
6567 * if the filesystem supports xattrs by looking at the
6570 inode->i_op = &btrfs_special_inode_operations;
6571 init_special_inode(inode, inode->i_mode, rdev);
6573 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
6577 err = btrfs_add_nondir(trans, BTRFS_I(dir), dentry, BTRFS_I(inode),
6582 btrfs_update_inode(trans, root, inode);
6583 d_instantiate_new(dentry, inode);
6586 btrfs_end_transaction(trans);
6587 btrfs_btree_balance_dirty(fs_info);
6589 inode_dec_link_count(inode);
6590 discard_new_inode(inode);
6595 static int btrfs_create(struct inode *dir, struct dentry *dentry,
6596 umode_t mode, bool excl)
6598 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
6599 struct btrfs_trans_handle *trans;
6600 struct btrfs_root *root = BTRFS_I(dir)->root;
6601 struct inode *inode = NULL;
6607 * 2 for inode item and ref
6609 * 1 for xattr if selinux is on
6611 trans = btrfs_start_transaction(root, 5);
6613 return PTR_ERR(trans);
6615 err = btrfs_find_free_ino(root, &objectid);
6619 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
6620 dentry->d_name.len, btrfs_ino(BTRFS_I(dir)), objectid,
6622 if (IS_ERR(inode)) {
6623 err = PTR_ERR(inode);
6628 * If the active LSM wants to access the inode during
6629 * d_instantiate it needs these. Smack checks to see
6630 * if the filesystem supports xattrs by looking at the
6633 inode->i_fop = &btrfs_file_operations;
6634 inode->i_op = &btrfs_file_inode_operations;
6635 inode->i_mapping->a_ops = &btrfs_aops;
6637 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
6641 err = btrfs_update_inode(trans, root, inode);
6645 err = btrfs_add_nondir(trans, BTRFS_I(dir), dentry, BTRFS_I(inode),
6650 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
6651 d_instantiate_new(dentry, inode);
6654 btrfs_end_transaction(trans);
6656 inode_dec_link_count(inode);
6657 discard_new_inode(inode);
6659 btrfs_btree_balance_dirty(fs_info);
6663 static int btrfs_link(struct dentry *old_dentry, struct inode *dir,
6664 struct dentry *dentry)
6666 struct btrfs_trans_handle *trans = NULL;
6667 struct btrfs_root *root = BTRFS_I(dir)->root;
6668 struct inode *inode = d_inode(old_dentry);
6669 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
6674 /* do not allow sys_link's with other subvols of the same device */
6675 if (root->root_key.objectid != BTRFS_I(inode)->root->root_key.objectid)
6678 if (inode->i_nlink >= BTRFS_LINK_MAX)
6681 err = btrfs_set_inode_index(BTRFS_I(dir), &index);
6686 * 2 items for inode and inode ref
6687 * 2 items for dir items
6688 * 1 item for parent inode
6689 * 1 item for orphan item deletion if O_TMPFILE
6691 trans = btrfs_start_transaction(root, inode->i_nlink ? 5 : 6);
6692 if (IS_ERR(trans)) {
6693 err = PTR_ERR(trans);
6698 /* There are several dir indexes for this inode, clear the cache. */
6699 BTRFS_I(inode)->dir_index = 0ULL;
6701 inode_inc_iversion(inode);
6702 inode->i_ctime = current_time(inode);
6704 set_bit(BTRFS_INODE_COPY_EVERYTHING, &BTRFS_I(inode)->runtime_flags);
6706 err = btrfs_add_nondir(trans, BTRFS_I(dir), dentry, BTRFS_I(inode),
6712 struct dentry *parent = dentry->d_parent;
6715 err = btrfs_update_inode(trans, root, inode);
6718 if (inode->i_nlink == 1) {
6720 * If new hard link count is 1, it's a file created
6721 * with open(2) O_TMPFILE flag.
6723 err = btrfs_orphan_del(trans, BTRFS_I(inode));
6727 d_instantiate(dentry, inode);
6728 ret = btrfs_log_new_name(trans, BTRFS_I(inode), NULL, parent,
6730 if (ret == BTRFS_NEED_TRANS_COMMIT) {
6731 err = btrfs_commit_transaction(trans);
6738 btrfs_end_transaction(trans);
6740 inode_dec_link_count(inode);
6743 btrfs_btree_balance_dirty(fs_info);
6747 static int btrfs_mkdir(struct inode *dir, struct dentry *dentry, umode_t mode)
6749 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
6750 struct inode *inode = NULL;
6751 struct btrfs_trans_handle *trans;
6752 struct btrfs_root *root = BTRFS_I(dir)->root;
6758 * 2 items for inode and ref
6759 * 2 items for dir items
6760 * 1 for xattr if selinux is on
6762 trans = btrfs_start_transaction(root, 5);
6764 return PTR_ERR(trans);
6766 err = btrfs_find_free_ino(root, &objectid);
6770 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
6771 dentry->d_name.len, btrfs_ino(BTRFS_I(dir)), objectid,
6772 S_IFDIR | mode, &index);
6773 if (IS_ERR(inode)) {
6774 err = PTR_ERR(inode);
6779 /* these must be set before we unlock the inode */
6780 inode->i_op = &btrfs_dir_inode_operations;
6781 inode->i_fop = &btrfs_dir_file_operations;
6783 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
6787 btrfs_i_size_write(BTRFS_I(inode), 0);
6788 err = btrfs_update_inode(trans, root, inode);
6792 err = btrfs_add_link(trans, BTRFS_I(dir), BTRFS_I(inode),
6793 dentry->d_name.name,
6794 dentry->d_name.len, 0, index);
6798 d_instantiate_new(dentry, inode);
6801 btrfs_end_transaction(trans);
6803 inode_dec_link_count(inode);
6804 discard_new_inode(inode);
6806 btrfs_btree_balance_dirty(fs_info);
6810 static noinline int uncompress_inline(struct btrfs_path *path,
6812 size_t pg_offset, u64 extent_offset,
6813 struct btrfs_file_extent_item *item)
6816 struct extent_buffer *leaf = path->nodes[0];
6819 unsigned long inline_size;
6823 WARN_ON(pg_offset != 0);
6824 compress_type = btrfs_file_extent_compression(leaf, item);
6825 max_size = btrfs_file_extent_ram_bytes(leaf, item);
6826 inline_size = btrfs_file_extent_inline_item_len(leaf,
6827 btrfs_item_nr(path->slots[0]));
6828 tmp = kmalloc(inline_size, GFP_NOFS);
6831 ptr = btrfs_file_extent_inline_start(item);
6833 read_extent_buffer(leaf, tmp, ptr, inline_size);
6835 max_size = min_t(unsigned long, PAGE_SIZE, max_size);
6836 ret = btrfs_decompress(compress_type, tmp, page,
6837 extent_offset, inline_size, max_size);
6840 * decompression code contains a memset to fill in any space between the end
6841 * of the uncompressed data and the end of max_size in case the decompressed
6842 * data ends up shorter than ram_bytes. That doesn't cover the hole between
6843 * the end of an inline extent and the beginning of the next block, so we
6844 * cover that region here.
6847 if (max_size + pg_offset < PAGE_SIZE) {
6848 char *map = kmap(page);
6849 memset(map + pg_offset + max_size, 0, PAGE_SIZE - max_size - pg_offset);
6857 * a bit scary, this does extent mapping from logical file offset to the disk.
6858 * the ugly parts come from merging extents from the disk with the in-ram
6859 * representation. This gets more complex because of the data=ordered code,
6860 * where the in-ram extents might be locked pending data=ordered completion.
6862 * This also copies inline extents directly into the page.
6864 struct extent_map *btrfs_get_extent(struct btrfs_inode *inode,
6866 size_t pg_offset, u64 start, u64 len,
6869 struct btrfs_fs_info *fs_info = inode->root->fs_info;
6872 u64 extent_start = 0;
6874 u64 objectid = btrfs_ino(inode);
6875 int extent_type = -1;
6876 struct btrfs_path *path = NULL;
6877 struct btrfs_root *root = inode->root;
6878 struct btrfs_file_extent_item *item;
6879 struct extent_buffer *leaf;
6880 struct btrfs_key found_key;
6881 struct extent_map *em = NULL;
6882 struct extent_map_tree *em_tree = &inode->extent_tree;
6883 struct extent_io_tree *io_tree = &inode->io_tree;
6884 const bool new_inline = !page || create;
6886 read_lock(&em_tree->lock);
6887 em = lookup_extent_mapping(em_tree, start, len);
6889 em->bdev = fs_info->fs_devices->latest_bdev;
6890 read_unlock(&em_tree->lock);
6893 if (em->start > start || em->start + em->len <= start)
6894 free_extent_map(em);
6895 else if (em->block_start == EXTENT_MAP_INLINE && page)
6896 free_extent_map(em);
6900 em = alloc_extent_map();
6905 em->bdev = fs_info->fs_devices->latest_bdev;
6906 em->start = EXTENT_MAP_HOLE;
6907 em->orig_start = EXTENT_MAP_HOLE;
6909 em->block_len = (u64)-1;
6911 path = btrfs_alloc_path();
6917 /* Chances are we'll be called again, so go ahead and do readahead */
6918 path->reada = READA_FORWARD;
6921 * Unless we're going to uncompress the inline extent, no sleep would
6924 path->leave_spinning = 1;
6926 ret = btrfs_lookup_file_extent(NULL, root, path, objectid, start, 0);
6930 } else if (ret > 0) {
6931 if (path->slots[0] == 0)
6936 leaf = path->nodes[0];
6937 item = btrfs_item_ptr(leaf, path->slots[0],
6938 struct btrfs_file_extent_item);
6939 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
6940 if (found_key.objectid != objectid ||
6941 found_key.type != BTRFS_EXTENT_DATA_KEY) {
6943 * If we backup past the first extent we want to move forward
6944 * and see if there is an extent in front of us, otherwise we'll
6945 * say there is a hole for our whole search range which can
6952 extent_type = btrfs_file_extent_type(leaf, item);
6953 extent_start = found_key.offset;
6954 if (extent_type == BTRFS_FILE_EXTENT_REG ||
6955 extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
6956 /* Only regular file could have regular/prealloc extent */
6957 if (!S_ISREG(inode->vfs_inode.i_mode)) {
6960 "regular/prealloc extent found for non-regular inode %llu",
6964 extent_end = extent_start +
6965 btrfs_file_extent_num_bytes(leaf, item);
6967 trace_btrfs_get_extent_show_fi_regular(inode, leaf, item,
6969 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
6972 size = btrfs_file_extent_ram_bytes(leaf, item);
6973 extent_end = ALIGN(extent_start + size,
6974 fs_info->sectorsize);
6976 trace_btrfs_get_extent_show_fi_inline(inode, leaf, item,
6981 if (start >= extent_end) {
6983 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
6984 ret = btrfs_next_leaf(root, path);
6988 } else if (ret > 0) {
6991 leaf = path->nodes[0];
6993 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
6994 if (found_key.objectid != objectid ||
6995 found_key.type != BTRFS_EXTENT_DATA_KEY)
6997 if (start + len <= found_key.offset)
6999 if (start > found_key.offset)
7002 /* New extent overlaps with existing one */
7004 em->orig_start = start;
7005 em->len = found_key.offset - start;
7006 em->block_start = EXTENT_MAP_HOLE;
7010 btrfs_extent_item_to_extent_map(inode, path, item,
7013 if (extent_type == BTRFS_FILE_EXTENT_REG ||
7014 extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
7016 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
7020 size_t extent_offset;
7026 size = btrfs_file_extent_ram_bytes(leaf, item);
7027 extent_offset = page_offset(page) + pg_offset - extent_start;
7028 copy_size = min_t(u64, PAGE_SIZE - pg_offset,
7029 size - extent_offset);
7030 em->start = extent_start + extent_offset;
7031 em->len = ALIGN(copy_size, fs_info->sectorsize);
7032 em->orig_block_len = em->len;
7033 em->orig_start = em->start;
7034 ptr = btrfs_file_extent_inline_start(item) + extent_offset;
7036 btrfs_set_path_blocking(path);
7037 if (!PageUptodate(page)) {
7038 if (btrfs_file_extent_compression(leaf, item) !=
7039 BTRFS_COMPRESS_NONE) {
7040 ret = uncompress_inline(path, page, pg_offset,
7041 extent_offset, item);
7048 read_extent_buffer(leaf, map + pg_offset, ptr,
7050 if (pg_offset + copy_size < PAGE_SIZE) {
7051 memset(map + pg_offset + copy_size, 0,
7052 PAGE_SIZE - pg_offset -
7057 flush_dcache_page(page);
7059 set_extent_uptodate(io_tree, em->start,
7060 extent_map_end(em) - 1, NULL, GFP_NOFS);
7065 em->orig_start = start;
7067 em->block_start = EXTENT_MAP_HOLE;
7069 btrfs_release_path(path);
7070 if (em->start > start || extent_map_end(em) <= start) {
7072 "bad extent! em: [%llu %llu] passed [%llu %llu]",
7073 em->start, em->len, start, len);
7079 write_lock(&em_tree->lock);
7080 err = btrfs_add_extent_mapping(fs_info, em_tree, &em, start, len);
7081 write_unlock(&em_tree->lock);
7083 btrfs_free_path(path);
7085 trace_btrfs_get_extent(root, inode, em);
7088 free_extent_map(em);
7089 return ERR_PTR(err);
7091 BUG_ON(!em); /* Error is always set */
7095 struct extent_map *btrfs_get_extent_fiemap(struct btrfs_inode *inode,
7098 struct extent_map *em;
7099 struct extent_map *hole_em = NULL;
7100 u64 delalloc_start = start;
7106 em = btrfs_get_extent(inode, NULL, 0, start, len, 0);
7110 * If our em maps to:
7112 * - a pre-alloc extent,
7113 * there might actually be delalloc bytes behind it.
7115 if (em->block_start != EXTENT_MAP_HOLE &&
7116 !test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
7121 /* check to see if we've wrapped (len == -1 or similar) */
7130 /* ok, we didn't find anything, lets look for delalloc */
7131 delalloc_len = count_range_bits(&inode->io_tree, &delalloc_start,
7132 end, len, EXTENT_DELALLOC, 1);
7133 delalloc_end = delalloc_start + delalloc_len;
7134 if (delalloc_end < delalloc_start)
7135 delalloc_end = (u64)-1;
7138 * We didn't find anything useful, return the original results from
7141 if (delalloc_start > end || delalloc_end <= start) {
7148 * Adjust the delalloc_start to make sure it doesn't go backwards from
7149 * the start they passed in
7151 delalloc_start = max(start, delalloc_start);
7152 delalloc_len = delalloc_end - delalloc_start;
7154 if (delalloc_len > 0) {
7157 const u64 hole_end = extent_map_end(hole_em);
7159 em = alloc_extent_map();
7168 * When btrfs_get_extent can't find anything it returns one
7171 * Make sure what it found really fits our range, and adjust to
7172 * make sure it is based on the start from the caller
7174 if (hole_end <= start || hole_em->start > end) {
7175 free_extent_map(hole_em);
7178 hole_start = max(hole_em->start, start);
7179 hole_len = hole_end - hole_start;
7182 if (hole_em && delalloc_start > hole_start) {
7184 * Our hole starts before our delalloc, so we have to
7185 * return just the parts of the hole that go until the
7188 em->len = min(hole_len, delalloc_start - hole_start);
7189 em->start = hole_start;
7190 em->orig_start = hole_start;
7192 * Don't adjust block start at all, it is fixed at
7195 em->block_start = hole_em->block_start;
7196 em->block_len = hole_len;
7197 if (test_bit(EXTENT_FLAG_PREALLOC, &hole_em->flags))
7198 set_bit(EXTENT_FLAG_PREALLOC, &em->flags);
7201 * Hole is out of passed range or it starts after
7204 em->start = delalloc_start;
7205 em->len = delalloc_len;
7206 em->orig_start = delalloc_start;
7207 em->block_start = EXTENT_MAP_DELALLOC;
7208 em->block_len = delalloc_len;
7215 free_extent_map(hole_em);
7217 free_extent_map(em);
7218 return ERR_PTR(err);
7223 static struct extent_map *btrfs_create_dio_extent(struct inode *inode,
7226 const u64 orig_start,
7227 const u64 block_start,
7228 const u64 block_len,
7229 const u64 orig_block_len,
7230 const u64 ram_bytes,
7233 struct extent_map *em = NULL;
7236 if (type != BTRFS_ORDERED_NOCOW) {
7237 em = create_io_em(inode, start, len, orig_start,
7238 block_start, block_len, orig_block_len,
7240 BTRFS_COMPRESS_NONE, /* compress_type */
7245 ret = btrfs_add_ordered_extent_dio(inode, start, block_start,
7246 len, block_len, type);
7249 free_extent_map(em);
7250 btrfs_drop_extent_cache(BTRFS_I(inode), start,
7251 start + len - 1, 0);
7260 static struct extent_map *btrfs_new_extent_direct(struct inode *inode,
7263 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7264 struct btrfs_root *root = BTRFS_I(inode)->root;
7265 struct extent_map *em;
7266 struct btrfs_key ins;
7270 alloc_hint = get_extent_allocation_hint(inode, start, len);
7271 ret = btrfs_reserve_extent(root, len, len, fs_info->sectorsize,
7272 0, alloc_hint, &ins, 1, 1);
7274 return ERR_PTR(ret);
7276 em = btrfs_create_dio_extent(inode, start, ins.offset, start,
7277 ins.objectid, ins.offset, ins.offset,
7278 ins.offset, BTRFS_ORDERED_REGULAR);
7279 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
7281 btrfs_free_reserved_extent(fs_info, ins.objectid,
7288 * returns 1 when the nocow is safe, < 1 on error, 0 if the
7289 * block must be cow'd
7291 noinline int can_nocow_extent(struct inode *inode, u64 offset, u64 *len,
7292 u64 *orig_start, u64 *orig_block_len,
7295 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7296 struct btrfs_path *path;
7298 struct extent_buffer *leaf;
7299 struct btrfs_root *root = BTRFS_I(inode)->root;
7300 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
7301 struct btrfs_file_extent_item *fi;
7302 struct btrfs_key key;
7309 bool nocow = (BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW);
7311 path = btrfs_alloc_path();
7315 ret = btrfs_lookup_file_extent(NULL, root, path,
7316 btrfs_ino(BTRFS_I(inode)), offset, 0);
7320 slot = path->slots[0];
7323 /* can't find the item, must cow */
7330 leaf = path->nodes[0];
7331 btrfs_item_key_to_cpu(leaf, &key, slot);
7332 if (key.objectid != btrfs_ino(BTRFS_I(inode)) ||
7333 key.type != BTRFS_EXTENT_DATA_KEY) {
7334 /* not our file or wrong item type, must cow */
7338 if (key.offset > offset) {
7339 /* Wrong offset, must cow */
7343 fi = btrfs_item_ptr(leaf, slot, struct btrfs_file_extent_item);
7344 found_type = btrfs_file_extent_type(leaf, fi);
7345 if (found_type != BTRFS_FILE_EXTENT_REG &&
7346 found_type != BTRFS_FILE_EXTENT_PREALLOC) {
7347 /* not a regular extent, must cow */
7351 if (!nocow && found_type == BTRFS_FILE_EXTENT_REG)
7354 extent_end = key.offset + btrfs_file_extent_num_bytes(leaf, fi);
7355 if (extent_end <= offset)
7358 disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
7359 if (disk_bytenr == 0)
7362 if (btrfs_file_extent_compression(leaf, fi) ||
7363 btrfs_file_extent_encryption(leaf, fi) ||
7364 btrfs_file_extent_other_encoding(leaf, fi))
7368 * Do the same check as in btrfs_cross_ref_exist but without the
7369 * unnecessary search.
7371 if (btrfs_file_extent_generation(leaf, fi) <=
7372 btrfs_root_last_snapshot(&root->root_item))
7375 backref_offset = btrfs_file_extent_offset(leaf, fi);
7378 *orig_start = key.offset - backref_offset;
7379 *orig_block_len = btrfs_file_extent_disk_num_bytes(leaf, fi);
7380 *ram_bytes = btrfs_file_extent_ram_bytes(leaf, fi);
7383 if (btrfs_extent_readonly(fs_info, disk_bytenr))
7386 num_bytes = min(offset + *len, extent_end) - offset;
7387 if (!nocow && found_type == BTRFS_FILE_EXTENT_PREALLOC) {
7390 range_end = round_up(offset + num_bytes,
7391 root->fs_info->sectorsize) - 1;
7392 ret = test_range_bit(io_tree, offset, range_end,
7393 EXTENT_DELALLOC, 0, NULL);
7400 btrfs_release_path(path);
7403 * look for other files referencing this extent, if we
7404 * find any we must cow
7407 ret = btrfs_cross_ref_exist(root, btrfs_ino(BTRFS_I(inode)),
7408 key.offset - backref_offset, disk_bytenr);
7415 * adjust disk_bytenr and num_bytes to cover just the bytes
7416 * in this extent we are about to write. If there
7417 * are any csums in that range we have to cow in order
7418 * to keep the csums correct
7420 disk_bytenr += backref_offset;
7421 disk_bytenr += offset - key.offset;
7422 if (csum_exist_in_range(fs_info, disk_bytenr, num_bytes))
7425 * all of the above have passed, it is safe to overwrite this extent
7431 btrfs_free_path(path);
7435 static int lock_extent_direct(struct inode *inode, u64 lockstart, u64 lockend,
7436 struct extent_state **cached_state, int writing)
7438 struct btrfs_ordered_extent *ordered;
7442 lock_extent_bits(&BTRFS_I(inode)->io_tree, lockstart, lockend,
7445 * We're concerned with the entire range that we're going to be
7446 * doing DIO to, so we need to make sure there's no ordered
7447 * extents in this range.
7449 ordered = btrfs_lookup_ordered_range(BTRFS_I(inode), lockstart,
7450 lockend - lockstart + 1);
7453 * We need to make sure there are no buffered pages in this
7454 * range either, we could have raced between the invalidate in
7455 * generic_file_direct_write and locking the extent. The
7456 * invalidate needs to happen so that reads after a write do not
7460 (!writing || !filemap_range_has_page(inode->i_mapping,
7461 lockstart, lockend)))
7464 unlock_extent_cached(&BTRFS_I(inode)->io_tree, lockstart, lockend,
7469 * If we are doing a DIO read and the ordered extent we
7470 * found is for a buffered write, we can not wait for it
7471 * to complete and retry, because if we do so we can
7472 * deadlock with concurrent buffered writes on page
7473 * locks. This happens only if our DIO read covers more
7474 * than one extent map, if at this point has already
7475 * created an ordered extent for a previous extent map
7476 * and locked its range in the inode's io tree, and a
7477 * concurrent write against that previous extent map's
7478 * range and this range started (we unlock the ranges
7479 * in the io tree only when the bios complete and
7480 * buffered writes always lock pages before attempting
7481 * to lock range in the io tree).
7484 test_bit(BTRFS_ORDERED_DIRECT, &ordered->flags))
7485 btrfs_start_ordered_extent(inode, ordered, 1);
7488 btrfs_put_ordered_extent(ordered);
7491 * We could trigger writeback for this range (and wait
7492 * for it to complete) and then invalidate the pages for
7493 * this range (through invalidate_inode_pages2_range()),
7494 * but that can lead us to a deadlock with a concurrent
7495 * call to readpages() (a buffered read or a defrag call
7496 * triggered a readahead) on a page lock due to an
7497 * ordered dio extent we created before but did not have
7498 * yet a corresponding bio submitted (whence it can not
7499 * complete), which makes readpages() wait for that
7500 * ordered extent to complete while holding a lock on
7515 /* The callers of this must take lock_extent() */
7516 static struct extent_map *create_io_em(struct inode *inode, u64 start, u64 len,
7517 u64 orig_start, u64 block_start,
7518 u64 block_len, u64 orig_block_len,
7519 u64 ram_bytes, int compress_type,
7522 struct extent_map_tree *em_tree;
7523 struct extent_map *em;
7524 struct btrfs_root *root = BTRFS_I(inode)->root;
7527 ASSERT(type == BTRFS_ORDERED_PREALLOC ||
7528 type == BTRFS_ORDERED_COMPRESSED ||
7529 type == BTRFS_ORDERED_NOCOW ||
7530 type == BTRFS_ORDERED_REGULAR);
7532 em_tree = &BTRFS_I(inode)->extent_tree;
7533 em = alloc_extent_map();
7535 return ERR_PTR(-ENOMEM);
7538 em->orig_start = orig_start;
7540 em->block_len = block_len;
7541 em->block_start = block_start;
7542 em->bdev = root->fs_info->fs_devices->latest_bdev;
7543 em->orig_block_len = orig_block_len;
7544 em->ram_bytes = ram_bytes;
7545 em->generation = -1;
7546 set_bit(EXTENT_FLAG_PINNED, &em->flags);
7547 if (type == BTRFS_ORDERED_PREALLOC) {
7548 set_bit(EXTENT_FLAG_FILLING, &em->flags);
7549 } else if (type == BTRFS_ORDERED_COMPRESSED) {
7550 set_bit(EXTENT_FLAG_COMPRESSED, &em->flags);
7551 em->compress_type = compress_type;
7555 btrfs_drop_extent_cache(BTRFS_I(inode), em->start,
7556 em->start + em->len - 1, 0);
7557 write_lock(&em_tree->lock);
7558 ret = add_extent_mapping(em_tree, em, 1);
7559 write_unlock(&em_tree->lock);
7561 * The caller has taken lock_extent(), who could race with us
7564 } while (ret == -EEXIST);
7567 free_extent_map(em);
7568 return ERR_PTR(ret);
7571 /* em got 2 refs now, callers needs to do free_extent_map once. */
7576 static int btrfs_get_blocks_direct_read(struct extent_map *em,
7577 struct buffer_head *bh_result,
7578 struct inode *inode,
7581 if (em->block_start == EXTENT_MAP_HOLE ||
7582 test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
7585 len = min(len, em->len - (start - em->start));
7587 bh_result->b_blocknr = (em->block_start + (start - em->start)) >>
7589 bh_result->b_size = len;
7590 bh_result->b_bdev = em->bdev;
7591 set_buffer_mapped(bh_result);
7596 static int btrfs_get_blocks_direct_write(struct extent_map **map,
7597 struct buffer_head *bh_result,
7598 struct inode *inode,
7599 struct btrfs_dio_data *dio_data,
7602 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7603 struct extent_map *em = *map;
7607 * We don't allocate a new extent in the following cases
7609 * 1) The inode is marked as NODATACOW. In this case we'll just use the
7611 * 2) The extent is marked as PREALLOC. We're good to go here and can
7612 * just use the extent.
7615 if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags) ||
7616 ((BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW) &&
7617 em->block_start != EXTENT_MAP_HOLE)) {
7619 u64 block_start, orig_start, orig_block_len, ram_bytes;
7621 if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
7622 type = BTRFS_ORDERED_PREALLOC;
7624 type = BTRFS_ORDERED_NOCOW;
7625 len = min(len, em->len - (start - em->start));
7626 block_start = em->block_start + (start - em->start);
7628 if (can_nocow_extent(inode, start, &len, &orig_start,
7629 &orig_block_len, &ram_bytes) == 1 &&
7630 btrfs_inc_nocow_writers(fs_info, block_start)) {
7631 struct extent_map *em2;
7633 em2 = btrfs_create_dio_extent(inode, start, len,
7634 orig_start, block_start,
7635 len, orig_block_len,
7637 btrfs_dec_nocow_writers(fs_info, block_start);
7638 if (type == BTRFS_ORDERED_PREALLOC) {
7639 free_extent_map(em);
7643 if (em2 && IS_ERR(em2)) {
7648 * For inode marked NODATACOW or extent marked PREALLOC,
7649 * use the existing or preallocated extent, so does not
7650 * need to adjust btrfs_space_info's bytes_may_use.
7652 btrfs_free_reserved_data_space_noquota(inode, start,
7658 /* this will cow the extent */
7659 len = bh_result->b_size;
7660 free_extent_map(em);
7661 *map = em = btrfs_new_extent_direct(inode, start, len);
7667 len = min(len, em->len - (start - em->start));
7670 bh_result->b_blocknr = (em->block_start + (start - em->start)) >>
7672 bh_result->b_size = len;
7673 bh_result->b_bdev = em->bdev;
7674 set_buffer_mapped(bh_result);
7676 if (!test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
7677 set_buffer_new(bh_result);
7680 * Need to update the i_size under the extent lock so buffered
7681 * readers will get the updated i_size when we unlock.
7683 if (!dio_data->overwrite && start + len > i_size_read(inode))
7684 i_size_write(inode, start + len);
7686 WARN_ON(dio_data->reserve < len);
7687 dio_data->reserve -= len;
7688 dio_data->unsubmitted_oe_range_end = start + len;
7689 current->journal_info = dio_data;
7694 static int btrfs_get_blocks_direct(struct inode *inode, sector_t iblock,
7695 struct buffer_head *bh_result, int create)
7697 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7698 struct extent_map *em;
7699 struct extent_state *cached_state = NULL;
7700 struct btrfs_dio_data *dio_data = NULL;
7701 u64 start = iblock << inode->i_blkbits;
7702 u64 lockstart, lockend;
7703 u64 len = bh_result->b_size;
7704 int unlock_bits = EXTENT_LOCKED;
7708 unlock_bits |= EXTENT_DIRTY;
7710 len = min_t(u64, len, fs_info->sectorsize);
7713 lockend = start + len - 1;
7715 if (current->journal_info) {
7717 * Need to pull our outstanding extents and set journal_info to NULL so
7718 * that anything that needs to check if there's a transaction doesn't get
7721 dio_data = current->journal_info;
7722 current->journal_info = NULL;
7726 * If this errors out it's because we couldn't invalidate pagecache for
7727 * this range and we need to fallback to buffered.
7729 if (lock_extent_direct(inode, lockstart, lockend, &cached_state,
7735 em = btrfs_get_extent(BTRFS_I(inode), NULL, 0, start, len, 0);
7742 * Ok for INLINE and COMPRESSED extents we need to fallback on buffered
7743 * io. INLINE is special, and we could probably kludge it in here, but
7744 * it's still buffered so for safety lets just fall back to the generic
7747 * For COMPRESSED we _have_ to read the entire extent in so we can
7748 * decompress it, so there will be buffering required no matter what we
7749 * do, so go ahead and fallback to buffered.
7751 * We return -ENOTBLK because that's what makes DIO go ahead and go back
7752 * to buffered IO. Don't blame me, this is the price we pay for using
7755 if (test_bit(EXTENT_FLAG_COMPRESSED, &em->flags) ||
7756 em->block_start == EXTENT_MAP_INLINE) {
7757 free_extent_map(em);
7763 ret = btrfs_get_blocks_direct_write(&em, bh_result, inode,
7764 dio_data, start, len);
7768 /* clear and unlock the entire range */
7769 clear_extent_bit(&BTRFS_I(inode)->io_tree, lockstart, lockend,
7770 unlock_bits, 1, 0, &cached_state);
7772 ret = btrfs_get_blocks_direct_read(em, bh_result, inode,
7774 /* Can be negative only if we read from a hole */
7777 free_extent_map(em);
7781 * We need to unlock only the end area that we aren't using.
7782 * The rest is going to be unlocked by the endio routine.
7784 lockstart = start + bh_result->b_size;
7785 if (lockstart < lockend) {
7786 clear_extent_bit(&BTRFS_I(inode)->io_tree, lockstart,
7787 lockend, unlock_bits, 1, 0,
7790 free_extent_state(cached_state);
7794 free_extent_map(em);
7799 clear_extent_bit(&BTRFS_I(inode)->io_tree, lockstart, lockend,
7800 unlock_bits, 1, 0, &cached_state);
7803 current->journal_info = dio_data;
7807 static inline blk_status_t submit_dio_repair_bio(struct inode *inode,
7811 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7814 BUG_ON(bio_op(bio) == REQ_OP_WRITE);
7816 ret = btrfs_bio_wq_end_io(fs_info, bio, BTRFS_WQ_ENDIO_DIO_REPAIR);
7820 ret = btrfs_map_bio(fs_info, bio, mirror_num, 0);
7825 static int btrfs_check_dio_repairable(struct inode *inode,
7826 struct bio *failed_bio,
7827 struct io_failure_record *failrec,
7830 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7833 num_copies = btrfs_num_copies(fs_info, failrec->logical, failrec->len);
7834 if (num_copies == 1) {
7836 * we only have a single copy of the data, so don't bother with
7837 * all the retry and error correction code that follows. no
7838 * matter what the error is, it is very likely to persist.
7840 btrfs_debug(fs_info,
7841 "Check DIO Repairable: cannot repair, num_copies=%d, next_mirror %d, failed_mirror %d",
7842 num_copies, failrec->this_mirror, failed_mirror);
7846 failrec->failed_mirror = failed_mirror;
7847 failrec->this_mirror++;
7848 if (failrec->this_mirror == failed_mirror)
7849 failrec->this_mirror++;
7851 if (failrec->this_mirror > num_copies) {
7852 btrfs_debug(fs_info,
7853 "Check DIO Repairable: (fail) num_copies=%d, next_mirror %d, failed_mirror %d",
7854 num_copies, failrec->this_mirror, failed_mirror);
7861 static blk_status_t dio_read_error(struct inode *inode, struct bio *failed_bio,
7862 struct page *page, unsigned int pgoff,
7863 u64 start, u64 end, int failed_mirror,
7864 bio_end_io_t *repair_endio, void *repair_arg)
7866 struct io_failure_record *failrec;
7867 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
7868 struct extent_io_tree *failure_tree = &BTRFS_I(inode)->io_failure_tree;
7871 unsigned int read_mode = 0;
7874 blk_status_t status;
7875 struct bio_vec bvec;
7877 BUG_ON(bio_op(failed_bio) == REQ_OP_WRITE);
7879 ret = btrfs_get_io_failure_record(inode, start, end, &failrec);
7881 return errno_to_blk_status(ret);
7883 ret = btrfs_check_dio_repairable(inode, failed_bio, failrec,
7886 free_io_failure(failure_tree, io_tree, failrec);
7887 return BLK_STS_IOERR;
7890 segs = bio_segments(failed_bio);
7891 bio_get_first_bvec(failed_bio, &bvec);
7893 (bvec.bv_len > btrfs_inode_sectorsize(inode)))
7894 read_mode |= REQ_FAILFAST_DEV;
7896 isector = start - btrfs_io_bio(failed_bio)->logical;
7897 isector >>= inode->i_sb->s_blocksize_bits;
7898 bio = btrfs_create_repair_bio(inode, failed_bio, failrec, page,
7899 pgoff, isector, repair_endio, repair_arg);
7900 bio->bi_opf = REQ_OP_READ | read_mode;
7902 btrfs_debug(BTRFS_I(inode)->root->fs_info,
7903 "repair DIO read error: submitting new dio read[%#x] to this_mirror=%d, in_validation=%d",
7904 read_mode, failrec->this_mirror, failrec->in_validation);
7906 status = submit_dio_repair_bio(inode, bio, failrec->this_mirror);
7908 free_io_failure(failure_tree, io_tree, failrec);
7915 struct btrfs_retry_complete {
7916 struct completion done;
7917 struct inode *inode;
7922 static void btrfs_retry_endio_nocsum(struct bio *bio)
7924 struct btrfs_retry_complete *done = bio->bi_private;
7925 struct inode *inode = done->inode;
7926 struct bio_vec *bvec;
7927 struct extent_io_tree *io_tree, *failure_tree;
7928 struct bvec_iter_all iter_all;
7933 ASSERT(bio->bi_vcnt == 1);
7934 io_tree = &BTRFS_I(inode)->io_tree;
7935 failure_tree = &BTRFS_I(inode)->io_failure_tree;
7936 ASSERT(bio_first_bvec_all(bio)->bv_len == btrfs_inode_sectorsize(inode));
7939 ASSERT(!bio_flagged(bio, BIO_CLONED));
7940 bio_for_each_segment_all(bvec, bio, iter_all)
7941 clean_io_failure(BTRFS_I(inode)->root->fs_info, failure_tree,
7942 io_tree, done->start, bvec->bv_page,
7943 btrfs_ino(BTRFS_I(inode)), 0);
7945 complete(&done->done);
7949 static blk_status_t __btrfs_correct_data_nocsum(struct inode *inode,
7950 struct btrfs_io_bio *io_bio)
7952 struct btrfs_fs_info *fs_info;
7953 struct bio_vec bvec;
7954 struct bvec_iter iter;
7955 struct btrfs_retry_complete done;
7961 blk_status_t err = BLK_STS_OK;
7963 fs_info = BTRFS_I(inode)->root->fs_info;
7964 sectorsize = fs_info->sectorsize;
7966 start = io_bio->logical;
7968 io_bio->bio.bi_iter = io_bio->iter;
7970 bio_for_each_segment(bvec, &io_bio->bio, iter) {
7971 nr_sectors = BTRFS_BYTES_TO_BLKS(fs_info, bvec.bv_len);
7972 pgoff = bvec.bv_offset;
7974 next_block_or_try_again:
7977 init_completion(&done.done);
7979 ret = dio_read_error(inode, &io_bio->bio, bvec.bv_page,
7980 pgoff, start, start + sectorsize - 1,
7982 btrfs_retry_endio_nocsum, &done);
7988 wait_for_completion_io(&done.done);
7990 if (!done.uptodate) {
7991 /* We might have another mirror, so try again */
7992 goto next_block_or_try_again;
7996 start += sectorsize;
8000 pgoff += sectorsize;
8001 ASSERT(pgoff < PAGE_SIZE);
8002 goto next_block_or_try_again;
8009 static void btrfs_retry_endio(struct bio *bio)
8011 struct btrfs_retry_complete *done = bio->bi_private;
8012 struct btrfs_io_bio *io_bio = btrfs_io_bio(bio);
8013 struct extent_io_tree *io_tree, *failure_tree;
8014 struct inode *inode = done->inode;
8015 struct bio_vec *bvec;
8019 struct bvec_iter_all iter_all;
8026 ASSERT(bio->bi_vcnt == 1);
8027 ASSERT(bio_first_bvec_all(bio)->bv_len == btrfs_inode_sectorsize(done->inode));
8029 io_tree = &BTRFS_I(inode)->io_tree;
8030 failure_tree = &BTRFS_I(inode)->io_failure_tree;
8032 ASSERT(!bio_flagged(bio, BIO_CLONED));
8033 bio_for_each_segment_all(bvec, bio, iter_all) {
8034 ret = __readpage_endio_check(inode, io_bio, i, bvec->bv_page,
8035 bvec->bv_offset, done->start,
8038 clean_io_failure(BTRFS_I(inode)->root->fs_info,
8039 failure_tree, io_tree, done->start,
8041 btrfs_ino(BTRFS_I(inode)),
8048 done->uptodate = uptodate;
8050 complete(&done->done);
8054 static blk_status_t __btrfs_subio_endio_read(struct inode *inode,
8055 struct btrfs_io_bio *io_bio, blk_status_t err)
8057 struct btrfs_fs_info *fs_info;
8058 struct bio_vec bvec;
8059 struct bvec_iter iter;
8060 struct btrfs_retry_complete done;
8067 bool uptodate = (err == 0);
8069 blk_status_t status;
8071 fs_info = BTRFS_I(inode)->root->fs_info;
8072 sectorsize = fs_info->sectorsize;
8075 start = io_bio->logical;
8077 io_bio->bio.bi_iter = io_bio->iter;
8079 bio_for_each_segment(bvec, &io_bio->bio, iter) {
8080 nr_sectors = BTRFS_BYTES_TO_BLKS(fs_info, bvec.bv_len);
8082 pgoff = bvec.bv_offset;
8085 csum_pos = BTRFS_BYTES_TO_BLKS(fs_info, offset);
8086 ret = __readpage_endio_check(inode, io_bio, csum_pos,
8087 bvec.bv_page, pgoff, start, sectorsize);
8094 init_completion(&done.done);
8096 status = dio_read_error(inode, &io_bio->bio, bvec.bv_page,
8097 pgoff, start, start + sectorsize - 1,
8098 io_bio->mirror_num, btrfs_retry_endio,
8105 wait_for_completion_io(&done.done);
8107 if (!done.uptodate) {
8108 /* We might have another mirror, so try again */
8112 offset += sectorsize;
8113 start += sectorsize;
8119 pgoff += sectorsize;
8120 ASSERT(pgoff < PAGE_SIZE);
8128 static blk_status_t btrfs_subio_endio_read(struct inode *inode,
8129 struct btrfs_io_bio *io_bio, blk_status_t err)
8131 bool skip_csum = BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM;
8135 return __btrfs_correct_data_nocsum(inode, io_bio);
8139 return __btrfs_subio_endio_read(inode, io_bio, err);
8143 static void btrfs_endio_direct_read(struct bio *bio)
8145 struct btrfs_dio_private *dip = bio->bi_private;
8146 struct inode *inode = dip->inode;
8147 struct bio *dio_bio;
8148 struct btrfs_io_bio *io_bio = btrfs_io_bio(bio);
8149 blk_status_t err = bio->bi_status;
8151 if (dip->flags & BTRFS_DIO_ORIG_BIO_SUBMITTED)
8152 err = btrfs_subio_endio_read(inode, io_bio, err);
8154 unlock_extent(&BTRFS_I(inode)->io_tree, dip->logical_offset,
8155 dip->logical_offset + dip->bytes - 1);
8156 dio_bio = dip->dio_bio;
8160 dio_bio->bi_status = err;
8161 dio_end_io(dio_bio);
8162 btrfs_io_bio_free_csum(io_bio);
8166 static void __endio_write_update_ordered(struct inode *inode,
8167 const u64 offset, const u64 bytes,
8168 const bool uptodate)
8170 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
8171 struct btrfs_ordered_extent *ordered = NULL;
8172 struct btrfs_workqueue *wq;
8173 btrfs_work_func_t func;
8174 u64 ordered_offset = offset;
8175 u64 ordered_bytes = bytes;
8178 if (btrfs_is_free_space_inode(BTRFS_I(inode))) {
8179 wq = fs_info->endio_freespace_worker;
8180 func = btrfs_freespace_write_helper;
8182 wq = fs_info->endio_write_workers;
8183 func = btrfs_endio_write_helper;
8186 while (ordered_offset < offset + bytes) {
8187 last_offset = ordered_offset;
8188 if (btrfs_dec_test_first_ordered_pending(inode, &ordered,
8192 btrfs_init_work(&ordered->work, func,
8195 btrfs_queue_work(wq, &ordered->work);
8198 * If btrfs_dec_test_ordered_pending does not find any ordered
8199 * extent in the range, we can exit.
8201 if (ordered_offset == last_offset)
8204 * Our bio might span multiple ordered extents. In this case
8205 * we keep going until we have accounted the whole dio.
8207 if (ordered_offset < offset + bytes) {
8208 ordered_bytes = offset + bytes - ordered_offset;
8214 static void btrfs_endio_direct_write(struct bio *bio)
8216 struct btrfs_dio_private *dip = bio->bi_private;
8217 struct bio *dio_bio = dip->dio_bio;
8219 __endio_write_update_ordered(dip->inode, dip->logical_offset,
8220 dip->bytes, !bio->bi_status);
8224 dio_bio->bi_status = bio->bi_status;
8225 dio_end_io(dio_bio);
8229 static blk_status_t btrfs_submit_bio_start_direct_io(void *private_data,
8230 struct bio *bio, u64 offset)
8232 struct inode *inode = private_data;
8234 ret = btrfs_csum_one_bio(inode, bio, offset, 1);
8235 BUG_ON(ret); /* -ENOMEM */
8239 static void btrfs_end_dio_bio(struct bio *bio)
8241 struct btrfs_dio_private *dip = bio->bi_private;
8242 blk_status_t err = bio->bi_status;
8245 btrfs_warn(BTRFS_I(dip->inode)->root->fs_info,
8246 "direct IO failed ino %llu rw %d,%u sector %#Lx len %u err no %d",
8247 btrfs_ino(BTRFS_I(dip->inode)), bio_op(bio),
8249 (unsigned long long)bio->bi_iter.bi_sector,
8250 bio->bi_iter.bi_size, err);
8252 if (dip->subio_endio)
8253 err = dip->subio_endio(dip->inode, btrfs_io_bio(bio), err);
8257 * We want to perceive the errors flag being set before
8258 * decrementing the reference count. We don't need a barrier
8259 * since atomic operations with a return value are fully
8260 * ordered as per atomic_t.txt
8265 /* if there are more bios still pending for this dio, just exit */
8266 if (!atomic_dec_and_test(&dip->pending_bios))
8270 bio_io_error(dip->orig_bio);
8272 dip->dio_bio->bi_status = BLK_STS_OK;
8273 bio_endio(dip->orig_bio);
8279 static inline blk_status_t btrfs_lookup_and_bind_dio_csum(struct inode *inode,
8280 struct btrfs_dio_private *dip,
8284 struct btrfs_io_bio *io_bio = btrfs_io_bio(bio);
8285 struct btrfs_io_bio *orig_io_bio = btrfs_io_bio(dip->orig_bio);
8289 * We load all the csum data we need when we submit
8290 * the first bio to reduce the csum tree search and
8293 if (dip->logical_offset == file_offset) {
8294 ret = btrfs_lookup_bio_sums_dio(inode, dip->orig_bio,
8300 if (bio == dip->orig_bio)
8303 file_offset -= dip->logical_offset;
8304 file_offset >>= inode->i_sb->s_blocksize_bits;
8305 io_bio->csum = (u8 *)(((u32 *)orig_io_bio->csum) + file_offset);
8310 static inline blk_status_t btrfs_submit_dio_bio(struct bio *bio,
8311 struct inode *inode, u64 file_offset, int async_submit)
8313 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
8314 struct btrfs_dio_private *dip = bio->bi_private;
8315 bool write = bio_op(bio) == REQ_OP_WRITE;
8318 /* Check btrfs_submit_bio_hook() for rules about async submit. */
8320 async_submit = !atomic_read(&BTRFS_I(inode)->sync_writers);
8323 ret = btrfs_bio_wq_end_io(fs_info, bio, BTRFS_WQ_ENDIO_DATA);
8328 if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)
8331 if (write && async_submit) {
8332 ret = btrfs_wq_submit_bio(fs_info, bio, 0, 0,
8334 btrfs_submit_bio_start_direct_io);
8338 * If we aren't doing async submit, calculate the csum of the
8341 ret = btrfs_csum_one_bio(inode, bio, file_offset, 1);
8345 ret = btrfs_lookup_and_bind_dio_csum(inode, dip, bio,
8351 ret = btrfs_map_bio(fs_info, bio, 0, 0);
8356 static int btrfs_submit_direct_hook(struct btrfs_dio_private *dip)
8358 struct inode *inode = dip->inode;
8359 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
8361 struct bio *orig_bio = dip->orig_bio;
8362 u64 start_sector = orig_bio->bi_iter.bi_sector;
8363 u64 file_offset = dip->logical_offset;
8364 int async_submit = 0;
8366 int clone_offset = 0;
8369 blk_status_t status;
8370 struct btrfs_io_geometry geom;
8372 submit_len = orig_bio->bi_iter.bi_size;
8373 ret = btrfs_get_io_geometry(fs_info, btrfs_op(orig_bio),
8374 start_sector << 9, submit_len, &geom);
8378 if (geom.len >= submit_len) {
8380 dip->flags |= BTRFS_DIO_ORIG_BIO_SUBMITTED;
8384 /* async crcs make it difficult to collect full stripe writes. */
8385 if (btrfs_data_alloc_profile(fs_info) & BTRFS_BLOCK_GROUP_RAID56_MASK)
8391 ASSERT(geom.len <= INT_MAX);
8392 atomic_inc(&dip->pending_bios);
8394 clone_len = min_t(int, submit_len, geom.len);
8397 * This will never fail as it's passing GPF_NOFS and
8398 * the allocation is backed by btrfs_bioset.
8400 bio = btrfs_bio_clone_partial(orig_bio, clone_offset,
8402 bio->bi_private = dip;
8403 bio->bi_end_io = btrfs_end_dio_bio;
8404 btrfs_io_bio(bio)->logical = file_offset;
8406 ASSERT(submit_len >= clone_len);
8407 submit_len -= clone_len;
8408 if (submit_len == 0)
8412 * Increase the count before we submit the bio so we know
8413 * the end IO handler won't happen before we increase the
8414 * count. Otherwise, the dip might get freed before we're
8415 * done setting it up.
8417 atomic_inc(&dip->pending_bios);
8419 status = btrfs_submit_dio_bio(bio, inode, file_offset,
8423 atomic_dec(&dip->pending_bios);
8427 clone_offset += clone_len;
8428 start_sector += clone_len >> 9;
8429 file_offset += clone_len;
8431 ret = btrfs_get_io_geometry(fs_info, btrfs_op(orig_bio),
8432 start_sector << 9, submit_len, &geom);
8435 } while (submit_len > 0);
8438 status = btrfs_submit_dio_bio(bio, inode, file_offset, async_submit);
8446 * Before atomic variable goto zero, we must make sure dip->errors is
8447 * perceived to be set. This ordering is ensured by the fact that an
8448 * atomic operations with a return value are fully ordered as per
8451 if (atomic_dec_and_test(&dip->pending_bios))
8452 bio_io_error(dip->orig_bio);
8454 /* bio_end_io() will handle error, so we needn't return it */
8458 static void btrfs_submit_direct(struct bio *dio_bio, struct inode *inode,
8461 struct btrfs_dio_private *dip = NULL;
8462 struct bio *bio = NULL;
8463 struct btrfs_io_bio *io_bio;
8464 bool write = (bio_op(dio_bio) == REQ_OP_WRITE);
8467 bio = btrfs_bio_clone(dio_bio);
8469 dip = kzalloc(sizeof(*dip), GFP_NOFS);
8475 dip->private = dio_bio->bi_private;
8477 dip->logical_offset = file_offset;
8478 dip->bytes = dio_bio->bi_iter.bi_size;
8479 dip->disk_bytenr = (u64)dio_bio->bi_iter.bi_sector << 9;
8480 bio->bi_private = dip;
8481 dip->orig_bio = bio;
8482 dip->dio_bio = dio_bio;
8483 atomic_set(&dip->pending_bios, 0);
8484 io_bio = btrfs_io_bio(bio);
8485 io_bio->logical = file_offset;
8488 bio->bi_end_io = btrfs_endio_direct_write;
8490 bio->bi_end_io = btrfs_endio_direct_read;
8491 dip->subio_endio = btrfs_subio_endio_read;
8495 * Reset the range for unsubmitted ordered extents (to a 0 length range)
8496 * even if we fail to submit a bio, because in such case we do the
8497 * corresponding error handling below and it must not be done a second
8498 * time by btrfs_direct_IO().
8501 struct btrfs_dio_data *dio_data = current->journal_info;
8503 dio_data->unsubmitted_oe_range_end = dip->logical_offset +
8505 dio_data->unsubmitted_oe_range_start =
8506 dio_data->unsubmitted_oe_range_end;
8509 ret = btrfs_submit_direct_hook(dip);
8513 btrfs_io_bio_free_csum(io_bio);
8517 * If we arrived here it means either we failed to submit the dip
8518 * or we either failed to clone the dio_bio or failed to allocate the
8519 * dip. If we cloned the dio_bio and allocated the dip, we can just
8520 * call bio_endio against our io_bio so that we get proper resource
8521 * cleanup if we fail to submit the dip, otherwise, we must do the
8522 * same as btrfs_endio_direct_[write|read] because we can't call these
8523 * callbacks - they require an allocated dip and a clone of dio_bio.
8528 * The end io callbacks free our dip, do the final put on bio
8529 * and all the cleanup and final put for dio_bio (through
8536 __endio_write_update_ordered(inode,
8538 dio_bio->bi_iter.bi_size,
8541 unlock_extent(&BTRFS_I(inode)->io_tree, file_offset,
8542 file_offset + dio_bio->bi_iter.bi_size - 1);
8544 dio_bio->bi_status = BLK_STS_IOERR;
8546 * Releases and cleans up our dio_bio, no need to bio_put()
8547 * nor bio_endio()/bio_io_error() against dio_bio.
8549 dio_end_io(dio_bio);
8556 static ssize_t check_direct_IO(struct btrfs_fs_info *fs_info,
8557 const struct iov_iter *iter, loff_t offset)
8561 unsigned int blocksize_mask = fs_info->sectorsize - 1;
8562 ssize_t retval = -EINVAL;
8564 if (offset & blocksize_mask)
8567 if (iov_iter_alignment(iter) & blocksize_mask)
8570 /* If this is a write we don't need to check anymore */
8571 if (iov_iter_rw(iter) != READ || !iter_is_iovec(iter))
8574 * Check to make sure we don't have duplicate iov_base's in this
8575 * iovec, if so return EINVAL, otherwise we'll get csum errors
8576 * when reading back.
8578 for (seg = 0; seg < iter->nr_segs; seg++) {
8579 for (i = seg + 1; i < iter->nr_segs; i++) {
8580 if (iter->iov[seg].iov_base == iter->iov[i].iov_base)
8589 static ssize_t btrfs_direct_IO(struct kiocb *iocb, struct iov_iter *iter)
8591 struct file *file = iocb->ki_filp;
8592 struct inode *inode = file->f_mapping->host;
8593 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
8594 struct btrfs_dio_data dio_data = { 0 };
8595 struct extent_changeset *data_reserved = NULL;
8596 loff_t offset = iocb->ki_pos;
8600 bool relock = false;
8603 if (check_direct_IO(fs_info, iter, offset))
8606 inode_dio_begin(inode);
8609 * The generic stuff only does filemap_write_and_wait_range, which
8610 * isn't enough if we've written compressed pages to this area, so
8611 * we need to flush the dirty pages again to make absolutely sure
8612 * that any outstanding dirty pages are on disk.
8614 count = iov_iter_count(iter);
8615 if (test_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
8616 &BTRFS_I(inode)->runtime_flags))
8617 filemap_fdatawrite_range(inode->i_mapping, offset,
8618 offset + count - 1);
8620 if (iov_iter_rw(iter) == WRITE) {
8622 * If the write DIO is beyond the EOF, we need update
8623 * the isize, but it is protected by i_mutex. So we can
8624 * not unlock the i_mutex at this case.
8626 if (offset + count <= inode->i_size) {
8627 dio_data.overwrite = 1;
8628 inode_unlock(inode);
8630 } else if (iocb->ki_flags & IOCB_NOWAIT) {
8634 ret = btrfs_delalloc_reserve_space(inode, &data_reserved,
8640 * We need to know how many extents we reserved so that we can
8641 * do the accounting properly if we go over the number we
8642 * originally calculated. Abuse current->journal_info for this.
8644 dio_data.reserve = round_up(count,
8645 fs_info->sectorsize);
8646 dio_data.unsubmitted_oe_range_start = (u64)offset;
8647 dio_data.unsubmitted_oe_range_end = (u64)offset;
8648 current->journal_info = &dio_data;
8649 down_read(&BTRFS_I(inode)->dio_sem);
8650 } else if (test_bit(BTRFS_INODE_READDIO_NEED_LOCK,
8651 &BTRFS_I(inode)->runtime_flags)) {
8652 inode_dio_end(inode);
8653 flags = DIO_LOCKING | DIO_SKIP_HOLES;
8657 ret = __blockdev_direct_IO(iocb, inode,
8658 fs_info->fs_devices->latest_bdev,
8659 iter, btrfs_get_blocks_direct, NULL,
8660 btrfs_submit_direct, flags);
8661 if (iov_iter_rw(iter) == WRITE) {
8662 up_read(&BTRFS_I(inode)->dio_sem);
8663 current->journal_info = NULL;
8664 if (ret < 0 && ret != -EIOCBQUEUED) {
8665 if (dio_data.reserve)
8666 btrfs_delalloc_release_space(inode, data_reserved,
8667 offset, dio_data.reserve, true);
8669 * On error we might have left some ordered extents
8670 * without submitting corresponding bios for them, so
8671 * cleanup them up to avoid other tasks getting them
8672 * and waiting for them to complete forever.
8674 if (dio_data.unsubmitted_oe_range_start <
8675 dio_data.unsubmitted_oe_range_end)
8676 __endio_write_update_ordered(inode,
8677 dio_data.unsubmitted_oe_range_start,
8678 dio_data.unsubmitted_oe_range_end -
8679 dio_data.unsubmitted_oe_range_start,
8681 } else if (ret >= 0 && (size_t)ret < count)
8682 btrfs_delalloc_release_space(inode, data_reserved,
8683 offset, count - (size_t)ret, true);
8684 btrfs_delalloc_release_extents(BTRFS_I(inode), count, false);
8688 inode_dio_end(inode);
8692 extent_changeset_free(data_reserved);
8696 #define BTRFS_FIEMAP_FLAGS (FIEMAP_FLAG_SYNC)
8698 static int btrfs_fiemap(struct inode *inode, struct fiemap_extent_info *fieinfo,
8699 __u64 start, __u64 len)
8703 ret = fiemap_check_flags(fieinfo, BTRFS_FIEMAP_FLAGS);
8707 return extent_fiemap(inode, fieinfo, start, len);
8710 int btrfs_readpage(struct file *file, struct page *page)
8712 struct extent_io_tree *tree;
8713 tree = &BTRFS_I(page->mapping->host)->io_tree;
8714 return extent_read_full_page(tree, page, btrfs_get_extent, 0);
8717 static int btrfs_writepage(struct page *page, struct writeback_control *wbc)
8719 struct inode *inode = page->mapping->host;
8722 if (current->flags & PF_MEMALLOC) {
8723 redirty_page_for_writepage(wbc, page);
8729 * If we are under memory pressure we will call this directly from the
8730 * VM, we need to make sure we have the inode referenced for the ordered
8731 * extent. If not just return like we didn't do anything.
8733 if (!igrab(inode)) {
8734 redirty_page_for_writepage(wbc, page);
8735 return AOP_WRITEPAGE_ACTIVATE;
8737 ret = extent_write_full_page(page, wbc);
8738 btrfs_add_delayed_iput(inode);
8742 static int btrfs_writepages(struct address_space *mapping,
8743 struct writeback_control *wbc)
8745 return extent_writepages(mapping, wbc);
8749 btrfs_readpages(struct file *file, struct address_space *mapping,
8750 struct list_head *pages, unsigned nr_pages)
8752 return extent_readpages(mapping, pages, nr_pages);
8755 static int __btrfs_releasepage(struct page *page, gfp_t gfp_flags)
8757 int ret = try_release_extent_mapping(page, gfp_flags);
8759 ClearPagePrivate(page);
8760 set_page_private(page, 0);
8766 static int btrfs_releasepage(struct page *page, gfp_t gfp_flags)
8768 if (PageWriteback(page) || PageDirty(page))
8770 return __btrfs_releasepage(page, gfp_flags);
8773 static void btrfs_invalidatepage(struct page *page, unsigned int offset,
8774 unsigned int length)
8776 struct inode *inode = page->mapping->host;
8777 struct extent_io_tree *tree;
8778 struct btrfs_ordered_extent *ordered;
8779 struct extent_state *cached_state = NULL;
8780 u64 page_start = page_offset(page);
8781 u64 page_end = page_start + PAGE_SIZE - 1;
8784 int inode_evicting = inode->i_state & I_FREEING;
8787 * we have the page locked, so new writeback can't start,
8788 * and the dirty bit won't be cleared while we are here.
8790 * Wait for IO on this page so that we can safely clear
8791 * the PagePrivate2 bit and do ordered accounting
8793 wait_on_page_writeback(page);
8795 tree = &BTRFS_I(inode)->io_tree;
8797 btrfs_releasepage(page, GFP_NOFS);
8801 if (!inode_evicting)
8802 lock_extent_bits(tree, page_start, page_end, &cached_state);
8805 ordered = btrfs_lookup_ordered_range(BTRFS_I(inode), start,
8806 page_end - start + 1);
8808 end = min(page_end, ordered->file_offset + ordered->len - 1);
8810 * IO on this page will never be started, so we need
8811 * to account for any ordered extents now
8813 if (!inode_evicting)
8814 clear_extent_bit(tree, start, end,
8815 EXTENT_DIRTY | EXTENT_DELALLOC |
8816 EXTENT_DELALLOC_NEW |
8817 EXTENT_LOCKED | EXTENT_DO_ACCOUNTING |
8818 EXTENT_DEFRAG, 1, 0, &cached_state);
8820 * whoever cleared the private bit is responsible
8821 * for the finish_ordered_io
8823 if (TestClearPagePrivate2(page)) {
8824 struct btrfs_ordered_inode_tree *tree;
8827 tree = &BTRFS_I(inode)->ordered_tree;
8829 spin_lock_irq(&tree->lock);
8830 set_bit(BTRFS_ORDERED_TRUNCATED, &ordered->flags);
8831 new_len = start - ordered->file_offset;
8832 if (new_len < ordered->truncated_len)
8833 ordered->truncated_len = new_len;
8834 spin_unlock_irq(&tree->lock);
8836 if (btrfs_dec_test_ordered_pending(inode, &ordered,
8838 end - start + 1, 1))
8839 btrfs_finish_ordered_io(ordered);
8841 btrfs_put_ordered_extent(ordered);
8842 if (!inode_evicting) {
8843 cached_state = NULL;
8844 lock_extent_bits(tree, start, end,
8849 if (start < page_end)
8854 * Qgroup reserved space handler
8855 * Page here will be either
8856 * 1) Already written to disk
8857 * In this case, its reserved space is released from data rsv map
8858 * and will be freed by delayed_ref handler finally.
8859 * So even we call qgroup_free_data(), it won't decrease reserved
8861 * 2) Not written to disk
8862 * This means the reserved space should be freed here. However,
8863 * if a truncate invalidates the page (by clearing PageDirty)
8864 * and the page is accounted for while allocating extent
8865 * in btrfs_check_data_free_space() we let delayed_ref to
8866 * free the entire extent.
8868 if (PageDirty(page))
8869 btrfs_qgroup_free_data(inode, NULL, page_start, PAGE_SIZE);
8870 if (!inode_evicting) {
8871 clear_extent_bit(tree, page_start, page_end,
8872 EXTENT_LOCKED | EXTENT_DIRTY |
8873 EXTENT_DELALLOC | EXTENT_DELALLOC_NEW |
8874 EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG, 1, 1,
8877 __btrfs_releasepage(page, GFP_NOFS);
8880 ClearPageChecked(page);
8881 if (PagePrivate(page)) {
8882 ClearPagePrivate(page);
8883 set_page_private(page, 0);
8889 * btrfs_page_mkwrite() is not allowed to change the file size as it gets
8890 * called from a page fault handler when a page is first dirtied. Hence we must
8891 * be careful to check for EOF conditions here. We set the page up correctly
8892 * for a written page which means we get ENOSPC checking when writing into
8893 * holes and correct delalloc and unwritten extent mapping on filesystems that
8894 * support these features.
8896 * We are not allowed to take the i_mutex here so we have to play games to
8897 * protect against truncate races as the page could now be beyond EOF. Because
8898 * truncate_setsize() writes the inode size before removing pages, once we have
8899 * the page lock we can determine safely if the page is beyond EOF. If it is not
8900 * beyond EOF, then the page is guaranteed safe against truncation until we
8903 vm_fault_t btrfs_page_mkwrite(struct vm_fault *vmf)
8905 struct page *page = vmf->page;
8906 struct inode *inode = file_inode(vmf->vma->vm_file);
8907 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
8908 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
8909 struct btrfs_ordered_extent *ordered;
8910 struct extent_state *cached_state = NULL;
8911 struct extent_changeset *data_reserved = NULL;
8913 unsigned long zero_start;
8923 reserved_space = PAGE_SIZE;
8925 sb_start_pagefault(inode->i_sb);
8926 page_start = page_offset(page);
8927 page_end = page_start + PAGE_SIZE - 1;
8931 * Reserving delalloc space after obtaining the page lock can lead to
8932 * deadlock. For example, if a dirty page is locked by this function
8933 * and the call to btrfs_delalloc_reserve_space() ends up triggering
8934 * dirty page write out, then the btrfs_writepage() function could
8935 * end up waiting indefinitely to get a lock on the page currently
8936 * being processed by btrfs_page_mkwrite() function.
8938 ret2 = btrfs_delalloc_reserve_space(inode, &data_reserved, page_start,
8941 ret2 = file_update_time(vmf->vma->vm_file);
8945 ret = vmf_error(ret2);
8951 ret = VM_FAULT_NOPAGE; /* make the VM retry the fault */
8954 size = i_size_read(inode);
8956 if ((page->mapping != inode->i_mapping) ||
8957 (page_start >= size)) {
8958 /* page got truncated out from underneath us */
8961 wait_on_page_writeback(page);
8963 lock_extent_bits(io_tree, page_start, page_end, &cached_state);
8964 set_page_extent_mapped(page);
8967 * we can't set the delalloc bits if there are pending ordered
8968 * extents. Drop our locks and wait for them to finish
8970 ordered = btrfs_lookup_ordered_range(BTRFS_I(inode), page_start,
8973 unlock_extent_cached(io_tree, page_start, page_end,
8976 btrfs_start_ordered_extent(inode, ordered, 1);
8977 btrfs_put_ordered_extent(ordered);
8981 if (page->index == ((size - 1) >> PAGE_SHIFT)) {
8982 reserved_space = round_up(size - page_start,
8983 fs_info->sectorsize);
8984 if (reserved_space < PAGE_SIZE) {
8985 end = page_start + reserved_space - 1;
8986 btrfs_delalloc_release_space(inode, data_reserved,
8987 page_start, PAGE_SIZE - reserved_space,
8993 * page_mkwrite gets called when the page is firstly dirtied after it's
8994 * faulted in, but write(2) could also dirty a page and set delalloc
8995 * bits, thus in this case for space account reason, we still need to
8996 * clear any delalloc bits within this page range since we have to
8997 * reserve data&meta space before lock_page() (see above comments).
8999 clear_extent_bit(&BTRFS_I(inode)->io_tree, page_start, end,
9000 EXTENT_DIRTY | EXTENT_DELALLOC |
9001 EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG,
9002 0, 0, &cached_state);
9004 ret2 = btrfs_set_extent_delalloc(inode, page_start, end, 0,
9007 unlock_extent_cached(io_tree, page_start, page_end,
9009 ret = VM_FAULT_SIGBUS;
9014 /* page is wholly or partially inside EOF */
9015 if (page_start + PAGE_SIZE > size)
9016 zero_start = offset_in_page(size);
9018 zero_start = PAGE_SIZE;
9020 if (zero_start != PAGE_SIZE) {
9022 memset(kaddr + zero_start, 0, PAGE_SIZE - zero_start);
9023 flush_dcache_page(page);
9026 ClearPageChecked(page);
9027 set_page_dirty(page);
9028 SetPageUptodate(page);
9030 BTRFS_I(inode)->last_trans = fs_info->generation;
9031 BTRFS_I(inode)->last_sub_trans = BTRFS_I(inode)->root->log_transid;
9032 BTRFS_I(inode)->last_log_commit = BTRFS_I(inode)->root->last_log_commit;
9034 unlock_extent_cached(io_tree, page_start, page_end, &cached_state);
9037 btrfs_delalloc_release_extents(BTRFS_I(inode), PAGE_SIZE, true);
9038 sb_end_pagefault(inode->i_sb);
9039 extent_changeset_free(data_reserved);
9040 return VM_FAULT_LOCKED;
9046 btrfs_delalloc_release_extents(BTRFS_I(inode), PAGE_SIZE, (ret != 0));
9047 btrfs_delalloc_release_space(inode, data_reserved, page_start,
9048 reserved_space, (ret != 0));
9050 sb_end_pagefault(inode->i_sb);
9051 extent_changeset_free(data_reserved);
9055 static int btrfs_truncate(struct inode *inode, bool skip_writeback)
9057 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
9058 struct btrfs_root *root = BTRFS_I(inode)->root;
9059 struct btrfs_block_rsv *rsv;
9061 struct btrfs_trans_handle *trans;
9062 u64 mask = fs_info->sectorsize - 1;
9063 u64 min_size = btrfs_calc_trunc_metadata_size(fs_info, 1);
9065 if (!skip_writeback) {
9066 ret = btrfs_wait_ordered_range(inode, inode->i_size & (~mask),
9073 * Yes ladies and gentlemen, this is indeed ugly. We have a couple of
9074 * things going on here:
9076 * 1) We need to reserve space to update our inode.
9078 * 2) We need to have something to cache all the space that is going to
9079 * be free'd up by the truncate operation, but also have some slack
9080 * space reserved in case it uses space during the truncate (thank you
9081 * very much snapshotting).
9083 * And we need these to be separate. The fact is we can use a lot of
9084 * space doing the truncate, and we have no earthly idea how much space
9085 * we will use, so we need the truncate reservation to be separate so it
9086 * doesn't end up using space reserved for updating the inode. We also
9087 * need to be able to stop the transaction and start a new one, which
9088 * means we need to be able to update the inode several times, and we
9089 * have no idea of knowing how many times that will be, so we can't just
9090 * reserve 1 item for the entirety of the operation, so that has to be
9091 * done separately as well.
9093 * So that leaves us with
9095 * 1) rsv - for the truncate reservation, which we will steal from the
9096 * transaction reservation.
9097 * 2) fs_info->trans_block_rsv - this will have 1 items worth left for
9098 * updating the inode.
9100 rsv = btrfs_alloc_block_rsv(fs_info, BTRFS_BLOCK_RSV_TEMP);
9103 rsv->size = min_size;
9107 * 1 for the truncate slack space
9108 * 1 for updating the inode.
9110 trans = btrfs_start_transaction(root, 2);
9111 if (IS_ERR(trans)) {
9112 ret = PTR_ERR(trans);
9116 /* Migrate the slack space for the truncate to our reserve */
9117 ret = btrfs_block_rsv_migrate(&fs_info->trans_block_rsv, rsv,
9122 * So if we truncate and then write and fsync we normally would just
9123 * write the extents that changed, which is a problem if we need to
9124 * first truncate that entire inode. So set this flag so we write out
9125 * all of the extents in the inode to the sync log so we're completely
9128 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &BTRFS_I(inode)->runtime_flags);
9129 trans->block_rsv = rsv;
9132 ret = btrfs_truncate_inode_items(trans, root, inode,
9134 BTRFS_EXTENT_DATA_KEY);
9135 trans->block_rsv = &fs_info->trans_block_rsv;
9136 if (ret != -ENOSPC && ret != -EAGAIN)
9139 ret = btrfs_update_inode(trans, root, inode);
9143 btrfs_end_transaction(trans);
9144 btrfs_btree_balance_dirty(fs_info);
9146 trans = btrfs_start_transaction(root, 2);
9147 if (IS_ERR(trans)) {
9148 ret = PTR_ERR(trans);
9153 btrfs_block_rsv_release(fs_info, rsv, -1);
9154 ret = btrfs_block_rsv_migrate(&fs_info->trans_block_rsv,
9155 rsv, min_size, false);
9156 BUG_ON(ret); /* shouldn't happen */
9157 trans->block_rsv = rsv;
9161 * We can't call btrfs_truncate_block inside a trans handle as we could
9162 * deadlock with freeze, if we got NEED_TRUNCATE_BLOCK then we know
9163 * we've truncated everything except the last little bit, and can do
9164 * btrfs_truncate_block and then update the disk_i_size.
9166 if (ret == NEED_TRUNCATE_BLOCK) {
9167 btrfs_end_transaction(trans);
9168 btrfs_btree_balance_dirty(fs_info);
9170 ret = btrfs_truncate_block(inode, inode->i_size, 0, 0);
9173 trans = btrfs_start_transaction(root, 1);
9174 if (IS_ERR(trans)) {
9175 ret = PTR_ERR(trans);
9178 btrfs_ordered_update_i_size(inode, inode->i_size, NULL);
9184 trans->block_rsv = &fs_info->trans_block_rsv;
9185 ret2 = btrfs_update_inode(trans, root, inode);
9189 ret2 = btrfs_end_transaction(trans);
9192 btrfs_btree_balance_dirty(fs_info);
9195 btrfs_free_block_rsv(fs_info, rsv);
9201 * create a new subvolume directory/inode (helper for the ioctl).
9203 int btrfs_create_subvol_root(struct btrfs_trans_handle *trans,
9204 struct btrfs_root *new_root,
9205 struct btrfs_root *parent_root,
9208 struct inode *inode;
9212 inode = btrfs_new_inode(trans, new_root, NULL, "..", 2,
9213 new_dirid, new_dirid,
9214 S_IFDIR | (~current_umask() & S_IRWXUGO),
9217 return PTR_ERR(inode);
9218 inode->i_op = &btrfs_dir_inode_operations;
9219 inode->i_fop = &btrfs_dir_file_operations;
9221 set_nlink(inode, 1);
9222 btrfs_i_size_write(BTRFS_I(inode), 0);
9223 unlock_new_inode(inode);
9225 err = btrfs_subvol_inherit_props(trans, new_root, parent_root);
9227 btrfs_err(new_root->fs_info,
9228 "error inheriting subvolume %llu properties: %d",
9229 new_root->root_key.objectid, err);
9231 err = btrfs_update_inode(trans, new_root, inode);
9237 struct inode *btrfs_alloc_inode(struct super_block *sb)
9239 struct btrfs_fs_info *fs_info = btrfs_sb(sb);
9240 struct btrfs_inode *ei;
9241 struct inode *inode;
9243 ei = kmem_cache_alloc(btrfs_inode_cachep, GFP_KERNEL);
9250 ei->last_sub_trans = 0;
9251 ei->logged_trans = 0;
9252 ei->delalloc_bytes = 0;
9253 ei->new_delalloc_bytes = 0;
9254 ei->defrag_bytes = 0;
9255 ei->disk_i_size = 0;
9258 ei->index_cnt = (u64)-1;
9260 ei->last_unlink_trans = 0;
9261 ei->last_log_commit = 0;
9263 spin_lock_init(&ei->lock);
9264 ei->outstanding_extents = 0;
9265 if (sb->s_magic != BTRFS_TEST_MAGIC)
9266 btrfs_init_metadata_block_rsv(fs_info, &ei->block_rsv,
9267 BTRFS_BLOCK_RSV_DELALLOC);
9268 ei->runtime_flags = 0;
9269 ei->prop_compress = BTRFS_COMPRESS_NONE;
9270 ei->defrag_compress = BTRFS_COMPRESS_NONE;
9272 ei->delayed_node = NULL;
9274 ei->i_otime.tv_sec = 0;
9275 ei->i_otime.tv_nsec = 0;
9277 inode = &ei->vfs_inode;
9278 extent_map_tree_init(&ei->extent_tree);
9279 extent_io_tree_init(fs_info, &ei->io_tree, IO_TREE_INODE_IO, inode);
9280 extent_io_tree_init(fs_info, &ei->io_failure_tree,
9281 IO_TREE_INODE_IO_FAILURE, inode);
9282 ei->io_tree.track_uptodate = true;
9283 ei->io_failure_tree.track_uptodate = true;
9284 atomic_set(&ei->sync_writers, 0);
9285 mutex_init(&ei->log_mutex);
9286 mutex_init(&ei->delalloc_mutex);
9287 btrfs_ordered_inode_tree_init(&ei->ordered_tree);
9288 INIT_LIST_HEAD(&ei->delalloc_inodes);
9289 INIT_LIST_HEAD(&ei->delayed_iput);
9290 RB_CLEAR_NODE(&ei->rb_node);
9291 init_rwsem(&ei->dio_sem);
9296 #ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
9297 void btrfs_test_destroy_inode(struct inode *inode)
9299 btrfs_drop_extent_cache(BTRFS_I(inode), 0, (u64)-1, 0);
9300 kmem_cache_free(btrfs_inode_cachep, BTRFS_I(inode));
9304 void btrfs_free_inode(struct inode *inode)
9306 kmem_cache_free(btrfs_inode_cachep, BTRFS_I(inode));
9309 void btrfs_destroy_inode(struct inode *inode)
9311 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
9312 struct btrfs_ordered_extent *ordered;
9313 struct btrfs_root *root = BTRFS_I(inode)->root;
9315 WARN_ON(!hlist_empty(&inode->i_dentry));
9316 WARN_ON(inode->i_data.nrpages);
9317 WARN_ON(BTRFS_I(inode)->block_rsv.reserved);
9318 WARN_ON(BTRFS_I(inode)->block_rsv.size);
9319 WARN_ON(BTRFS_I(inode)->outstanding_extents);
9320 WARN_ON(BTRFS_I(inode)->delalloc_bytes);
9321 WARN_ON(BTRFS_I(inode)->new_delalloc_bytes);
9322 WARN_ON(BTRFS_I(inode)->csum_bytes);
9323 WARN_ON(BTRFS_I(inode)->defrag_bytes);
9326 * This can happen where we create an inode, but somebody else also
9327 * created the same inode and we need to destroy the one we already
9334 ordered = btrfs_lookup_first_ordered_extent(inode, (u64)-1);
9339 "found ordered extent %llu %llu on inode cleanup",
9340 ordered->file_offset, ordered->len);
9341 btrfs_remove_ordered_extent(inode, ordered);
9342 btrfs_put_ordered_extent(ordered);
9343 btrfs_put_ordered_extent(ordered);
9346 btrfs_qgroup_check_reserved_leak(inode);
9347 inode_tree_del(inode);
9348 btrfs_drop_extent_cache(BTRFS_I(inode), 0, (u64)-1, 0);
9351 int btrfs_drop_inode(struct inode *inode)
9353 struct btrfs_root *root = BTRFS_I(inode)->root;
9358 /* the snap/subvol tree is on deleting */
9359 if (btrfs_root_refs(&root->root_item) == 0)
9362 return generic_drop_inode(inode);
9365 static void init_once(void *foo)
9367 struct btrfs_inode *ei = (struct btrfs_inode *) foo;
9369 inode_init_once(&ei->vfs_inode);
9372 void __cold btrfs_destroy_cachep(void)
9375 * Make sure all delayed rcu free inodes are flushed before we
9379 kmem_cache_destroy(btrfs_inode_cachep);
9380 kmem_cache_destroy(btrfs_trans_handle_cachep);
9381 kmem_cache_destroy(btrfs_path_cachep);
9382 kmem_cache_destroy(btrfs_free_space_cachep);
9385 int __init btrfs_init_cachep(void)
9387 btrfs_inode_cachep = kmem_cache_create("btrfs_inode",
9388 sizeof(struct btrfs_inode), 0,
9389 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD | SLAB_ACCOUNT,
9391 if (!btrfs_inode_cachep)
9394 btrfs_trans_handle_cachep = kmem_cache_create("btrfs_trans_handle",
9395 sizeof(struct btrfs_trans_handle), 0,
9396 SLAB_TEMPORARY | SLAB_MEM_SPREAD, NULL);
9397 if (!btrfs_trans_handle_cachep)
9400 btrfs_path_cachep = kmem_cache_create("btrfs_path",
9401 sizeof(struct btrfs_path), 0,
9402 SLAB_MEM_SPREAD, NULL);
9403 if (!btrfs_path_cachep)
9406 btrfs_free_space_cachep = kmem_cache_create("btrfs_free_space",
9407 sizeof(struct btrfs_free_space), 0,
9408 SLAB_MEM_SPREAD, NULL);
9409 if (!btrfs_free_space_cachep)
9414 btrfs_destroy_cachep();
9418 static int btrfs_getattr(const struct path *path, struct kstat *stat,
9419 u32 request_mask, unsigned int flags)
9422 struct inode *inode = d_inode(path->dentry);
9423 u32 blocksize = inode->i_sb->s_blocksize;
9424 u32 bi_flags = BTRFS_I(inode)->flags;
9426 stat->result_mask |= STATX_BTIME;
9427 stat->btime.tv_sec = BTRFS_I(inode)->i_otime.tv_sec;
9428 stat->btime.tv_nsec = BTRFS_I(inode)->i_otime.tv_nsec;
9429 if (bi_flags & BTRFS_INODE_APPEND)
9430 stat->attributes |= STATX_ATTR_APPEND;
9431 if (bi_flags & BTRFS_INODE_COMPRESS)
9432 stat->attributes |= STATX_ATTR_COMPRESSED;
9433 if (bi_flags & BTRFS_INODE_IMMUTABLE)
9434 stat->attributes |= STATX_ATTR_IMMUTABLE;
9435 if (bi_flags & BTRFS_INODE_NODUMP)
9436 stat->attributes |= STATX_ATTR_NODUMP;
9438 stat->attributes_mask |= (STATX_ATTR_APPEND |
9439 STATX_ATTR_COMPRESSED |
9440 STATX_ATTR_IMMUTABLE |
9443 generic_fillattr(inode, stat);
9444 stat->dev = BTRFS_I(inode)->root->anon_dev;
9446 spin_lock(&BTRFS_I(inode)->lock);
9447 delalloc_bytes = BTRFS_I(inode)->new_delalloc_bytes;
9448 spin_unlock(&BTRFS_I(inode)->lock);
9449 stat->blocks = (ALIGN(inode_get_bytes(inode), blocksize) +
9450 ALIGN(delalloc_bytes, blocksize)) >> 9;
9454 static int btrfs_rename_exchange(struct inode *old_dir,
9455 struct dentry *old_dentry,
9456 struct inode *new_dir,
9457 struct dentry *new_dentry)
9459 struct btrfs_fs_info *fs_info = btrfs_sb(old_dir->i_sb);
9460 struct btrfs_trans_handle *trans;
9461 struct btrfs_root *root = BTRFS_I(old_dir)->root;
9462 struct btrfs_root *dest = BTRFS_I(new_dir)->root;
9463 struct inode *new_inode = new_dentry->d_inode;
9464 struct inode *old_inode = old_dentry->d_inode;
9465 struct timespec64 ctime = current_time(old_inode);
9466 struct dentry *parent;
9467 u64 old_ino = btrfs_ino(BTRFS_I(old_inode));
9468 u64 new_ino = btrfs_ino(BTRFS_I(new_inode));
9473 bool root_log_pinned = false;
9474 bool dest_log_pinned = false;
9475 struct btrfs_log_ctx ctx_root;
9476 struct btrfs_log_ctx ctx_dest;
9477 bool sync_log_root = false;
9478 bool sync_log_dest = false;
9479 bool commit_transaction = false;
9481 /* we only allow rename subvolume link between subvolumes */
9482 if (old_ino != BTRFS_FIRST_FREE_OBJECTID && root != dest)
9485 btrfs_init_log_ctx(&ctx_root, old_inode);
9486 btrfs_init_log_ctx(&ctx_dest, new_inode);
9488 /* close the race window with snapshot create/destroy ioctl */
9489 if (old_ino == BTRFS_FIRST_FREE_OBJECTID)
9490 down_read(&fs_info->subvol_sem);
9491 if (new_ino == BTRFS_FIRST_FREE_OBJECTID)
9492 down_read(&fs_info->subvol_sem);
9495 * We want to reserve the absolute worst case amount of items. So if
9496 * both inodes are subvols and we need to unlink them then that would
9497 * require 4 item modifications, but if they are both normal inodes it
9498 * would require 5 item modifications, so we'll assume their normal
9499 * inodes. So 5 * 2 is 10, plus 2 for the new links, so 12 total items
9500 * should cover the worst case number of items we'll modify.
9502 trans = btrfs_start_transaction(root, 12);
9503 if (IS_ERR(trans)) {
9504 ret = PTR_ERR(trans);
9509 * We need to find a free sequence number both in the source and
9510 * in the destination directory for the exchange.
9512 ret = btrfs_set_inode_index(BTRFS_I(new_dir), &old_idx);
9515 ret = btrfs_set_inode_index(BTRFS_I(old_dir), &new_idx);
9519 BTRFS_I(old_inode)->dir_index = 0ULL;
9520 BTRFS_I(new_inode)->dir_index = 0ULL;
9522 /* Reference for the source. */
9523 if (old_ino == BTRFS_FIRST_FREE_OBJECTID) {
9524 /* force full log commit if subvolume involved. */
9525 btrfs_set_log_full_commit(trans);
9527 btrfs_pin_log_trans(root);
9528 root_log_pinned = true;
9529 ret = btrfs_insert_inode_ref(trans, dest,
9530 new_dentry->d_name.name,
9531 new_dentry->d_name.len,
9533 btrfs_ino(BTRFS_I(new_dir)),
9539 /* And now for the dest. */
9540 if (new_ino == BTRFS_FIRST_FREE_OBJECTID) {
9541 /* force full log commit if subvolume involved. */
9542 btrfs_set_log_full_commit(trans);
9544 btrfs_pin_log_trans(dest);
9545 dest_log_pinned = true;
9546 ret = btrfs_insert_inode_ref(trans, root,
9547 old_dentry->d_name.name,
9548 old_dentry->d_name.len,
9550 btrfs_ino(BTRFS_I(old_dir)),
9556 /* Update inode version and ctime/mtime. */
9557 inode_inc_iversion(old_dir);
9558 inode_inc_iversion(new_dir);
9559 inode_inc_iversion(old_inode);
9560 inode_inc_iversion(new_inode);
9561 old_dir->i_ctime = old_dir->i_mtime = ctime;
9562 new_dir->i_ctime = new_dir->i_mtime = ctime;
9563 old_inode->i_ctime = ctime;
9564 new_inode->i_ctime = ctime;
9566 if (old_dentry->d_parent != new_dentry->d_parent) {
9567 btrfs_record_unlink_dir(trans, BTRFS_I(old_dir),
9568 BTRFS_I(old_inode), 1);
9569 btrfs_record_unlink_dir(trans, BTRFS_I(new_dir),
9570 BTRFS_I(new_inode), 1);
9573 /* src is a subvolume */
9574 if (old_ino == BTRFS_FIRST_FREE_OBJECTID) {
9575 root_objectid = BTRFS_I(old_inode)->root->root_key.objectid;
9576 ret = btrfs_unlink_subvol(trans, old_dir, root_objectid,
9577 old_dentry->d_name.name,
9578 old_dentry->d_name.len);
9579 } else { /* src is an inode */
9580 ret = __btrfs_unlink_inode(trans, root, BTRFS_I(old_dir),
9581 BTRFS_I(old_dentry->d_inode),
9582 old_dentry->d_name.name,
9583 old_dentry->d_name.len);
9585 ret = btrfs_update_inode(trans, root, old_inode);
9588 btrfs_abort_transaction(trans, ret);
9592 /* dest is a subvolume */
9593 if (new_ino == BTRFS_FIRST_FREE_OBJECTID) {
9594 root_objectid = BTRFS_I(new_inode)->root->root_key.objectid;
9595 ret = btrfs_unlink_subvol(trans, new_dir, root_objectid,
9596 new_dentry->d_name.name,
9597 new_dentry->d_name.len);
9598 } else { /* dest is an inode */
9599 ret = __btrfs_unlink_inode(trans, dest, BTRFS_I(new_dir),
9600 BTRFS_I(new_dentry->d_inode),
9601 new_dentry->d_name.name,
9602 new_dentry->d_name.len);
9604 ret = btrfs_update_inode(trans, dest, new_inode);
9607 btrfs_abort_transaction(trans, ret);
9611 ret = btrfs_add_link(trans, BTRFS_I(new_dir), BTRFS_I(old_inode),
9612 new_dentry->d_name.name,
9613 new_dentry->d_name.len, 0, old_idx);
9615 btrfs_abort_transaction(trans, ret);
9619 ret = btrfs_add_link(trans, BTRFS_I(old_dir), BTRFS_I(new_inode),
9620 old_dentry->d_name.name,
9621 old_dentry->d_name.len, 0, new_idx);
9623 btrfs_abort_transaction(trans, ret);
9627 if (old_inode->i_nlink == 1)
9628 BTRFS_I(old_inode)->dir_index = old_idx;
9629 if (new_inode->i_nlink == 1)
9630 BTRFS_I(new_inode)->dir_index = new_idx;
9632 if (root_log_pinned) {
9633 parent = new_dentry->d_parent;
9634 ret = btrfs_log_new_name(trans, BTRFS_I(old_inode),
9635 BTRFS_I(old_dir), parent,
9637 if (ret == BTRFS_NEED_LOG_SYNC)
9638 sync_log_root = true;
9639 else if (ret == BTRFS_NEED_TRANS_COMMIT)
9640 commit_transaction = true;
9642 btrfs_end_log_trans(root);
9643 root_log_pinned = false;
9645 if (dest_log_pinned) {
9646 if (!commit_transaction) {
9647 parent = old_dentry->d_parent;
9648 ret = btrfs_log_new_name(trans, BTRFS_I(new_inode),
9649 BTRFS_I(new_dir), parent,
9651 if (ret == BTRFS_NEED_LOG_SYNC)
9652 sync_log_dest = true;
9653 else if (ret == BTRFS_NEED_TRANS_COMMIT)
9654 commit_transaction = true;
9657 btrfs_end_log_trans(dest);
9658 dest_log_pinned = false;
9662 * If we have pinned a log and an error happened, we unpin tasks
9663 * trying to sync the log and force them to fallback to a transaction
9664 * commit if the log currently contains any of the inodes involved in
9665 * this rename operation (to ensure we do not persist a log with an
9666 * inconsistent state for any of these inodes or leading to any
9667 * inconsistencies when replayed). If the transaction was aborted, the
9668 * abortion reason is propagated to userspace when attempting to commit
9669 * the transaction. If the log does not contain any of these inodes, we
9670 * allow the tasks to sync it.
9672 if (ret && (root_log_pinned || dest_log_pinned)) {
9673 if (btrfs_inode_in_log(BTRFS_I(old_dir), fs_info->generation) ||
9674 btrfs_inode_in_log(BTRFS_I(new_dir), fs_info->generation) ||
9675 btrfs_inode_in_log(BTRFS_I(old_inode), fs_info->generation) ||
9677 btrfs_inode_in_log(BTRFS_I(new_inode), fs_info->generation)))
9678 btrfs_set_log_full_commit(trans);
9680 if (root_log_pinned) {
9681 btrfs_end_log_trans(root);
9682 root_log_pinned = false;
9684 if (dest_log_pinned) {
9685 btrfs_end_log_trans(dest);
9686 dest_log_pinned = false;
9689 if (!ret && sync_log_root && !commit_transaction) {
9690 ret = btrfs_sync_log(trans, BTRFS_I(old_inode)->root,
9693 commit_transaction = true;
9695 if (!ret && sync_log_dest && !commit_transaction) {
9696 ret = btrfs_sync_log(trans, BTRFS_I(new_inode)->root,
9699 commit_transaction = true;
9701 if (commit_transaction) {
9702 ret = btrfs_commit_transaction(trans);
9706 ret2 = btrfs_end_transaction(trans);
9707 ret = ret ? ret : ret2;
9710 if (new_ino == BTRFS_FIRST_FREE_OBJECTID)
9711 up_read(&fs_info->subvol_sem);
9712 if (old_ino == BTRFS_FIRST_FREE_OBJECTID)
9713 up_read(&fs_info->subvol_sem);
9718 static int btrfs_whiteout_for_rename(struct btrfs_trans_handle *trans,
9719 struct btrfs_root *root,
9721 struct dentry *dentry)
9724 struct inode *inode;
9728 ret = btrfs_find_free_ino(root, &objectid);
9732 inode = btrfs_new_inode(trans, root, dir,
9733 dentry->d_name.name,
9735 btrfs_ino(BTRFS_I(dir)),
9737 S_IFCHR | WHITEOUT_MODE,
9740 if (IS_ERR(inode)) {
9741 ret = PTR_ERR(inode);
9745 inode->i_op = &btrfs_special_inode_operations;
9746 init_special_inode(inode, inode->i_mode,
9749 ret = btrfs_init_inode_security(trans, inode, dir,
9754 ret = btrfs_add_nondir(trans, BTRFS_I(dir), dentry,
9755 BTRFS_I(inode), 0, index);
9759 ret = btrfs_update_inode(trans, root, inode);
9761 unlock_new_inode(inode);
9763 inode_dec_link_count(inode);
9769 static int btrfs_rename(struct inode *old_dir, struct dentry *old_dentry,
9770 struct inode *new_dir, struct dentry *new_dentry,
9773 struct btrfs_fs_info *fs_info = btrfs_sb(old_dir->i_sb);
9774 struct btrfs_trans_handle *trans;
9775 unsigned int trans_num_items;
9776 struct btrfs_root *root = BTRFS_I(old_dir)->root;
9777 struct btrfs_root *dest = BTRFS_I(new_dir)->root;
9778 struct inode *new_inode = d_inode(new_dentry);
9779 struct inode *old_inode = d_inode(old_dentry);
9783 u64 old_ino = btrfs_ino(BTRFS_I(old_inode));
9784 bool log_pinned = false;
9785 struct btrfs_log_ctx ctx;
9786 bool sync_log = false;
9787 bool commit_transaction = false;
9789 if (btrfs_ino(BTRFS_I(new_dir)) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)
9792 /* we only allow rename subvolume link between subvolumes */
9793 if (old_ino != BTRFS_FIRST_FREE_OBJECTID && root != dest)
9796 if (old_ino == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID ||
9797 (new_inode && btrfs_ino(BTRFS_I(new_inode)) == BTRFS_FIRST_FREE_OBJECTID))
9800 if (S_ISDIR(old_inode->i_mode) && new_inode &&
9801 new_inode->i_size > BTRFS_EMPTY_DIR_SIZE)
9805 /* check for collisions, even if the name isn't there */
9806 ret = btrfs_check_dir_item_collision(dest, new_dir->i_ino,
9807 new_dentry->d_name.name,
9808 new_dentry->d_name.len);
9811 if (ret == -EEXIST) {
9813 * eexist without a new_inode */
9814 if (WARN_ON(!new_inode)) {
9818 /* maybe -EOVERFLOW */
9825 * we're using rename to replace one file with another. Start IO on it
9826 * now so we don't add too much work to the end of the transaction
9828 if (new_inode && S_ISREG(old_inode->i_mode) && new_inode->i_size)
9829 filemap_flush(old_inode->i_mapping);
9831 /* close the racy window with snapshot create/destroy ioctl */
9832 if (old_ino == BTRFS_FIRST_FREE_OBJECTID)
9833 down_read(&fs_info->subvol_sem);
9835 * We want to reserve the absolute worst case amount of items. So if
9836 * both inodes are subvols and we need to unlink them then that would
9837 * require 4 item modifications, but if they are both normal inodes it
9838 * would require 5 item modifications, so we'll assume they are normal
9839 * inodes. So 5 * 2 is 10, plus 1 for the new link, so 11 total items
9840 * should cover the worst case number of items we'll modify.
9841 * If our rename has the whiteout flag, we need more 5 units for the
9842 * new inode (1 inode item, 1 inode ref, 2 dir items and 1 xattr item
9843 * when selinux is enabled).
9845 trans_num_items = 11;
9846 if (flags & RENAME_WHITEOUT)
9847 trans_num_items += 5;
9848 trans = btrfs_start_transaction(root, trans_num_items);
9849 if (IS_ERR(trans)) {
9850 ret = PTR_ERR(trans);
9855 btrfs_record_root_in_trans(trans, dest);
9857 ret = btrfs_set_inode_index(BTRFS_I(new_dir), &index);
9861 BTRFS_I(old_inode)->dir_index = 0ULL;
9862 if (unlikely(old_ino == BTRFS_FIRST_FREE_OBJECTID)) {
9863 /* force full log commit if subvolume involved. */
9864 btrfs_set_log_full_commit(trans);
9866 btrfs_pin_log_trans(root);
9868 ret = btrfs_insert_inode_ref(trans, dest,
9869 new_dentry->d_name.name,
9870 new_dentry->d_name.len,
9872 btrfs_ino(BTRFS_I(new_dir)), index);
9877 inode_inc_iversion(old_dir);
9878 inode_inc_iversion(new_dir);
9879 inode_inc_iversion(old_inode);
9880 old_dir->i_ctime = old_dir->i_mtime =
9881 new_dir->i_ctime = new_dir->i_mtime =
9882 old_inode->i_ctime = current_time(old_dir);
9884 if (old_dentry->d_parent != new_dentry->d_parent)
9885 btrfs_record_unlink_dir(trans, BTRFS_I(old_dir),
9886 BTRFS_I(old_inode), 1);
9888 if (unlikely(old_ino == BTRFS_FIRST_FREE_OBJECTID)) {
9889 root_objectid = BTRFS_I(old_inode)->root->root_key.objectid;
9890 ret = btrfs_unlink_subvol(trans, old_dir, root_objectid,
9891 old_dentry->d_name.name,
9892 old_dentry->d_name.len);
9894 ret = __btrfs_unlink_inode(trans, root, BTRFS_I(old_dir),
9895 BTRFS_I(d_inode(old_dentry)),
9896 old_dentry->d_name.name,
9897 old_dentry->d_name.len);
9899 ret = btrfs_update_inode(trans, root, old_inode);
9902 btrfs_abort_transaction(trans, ret);
9907 inode_inc_iversion(new_inode);
9908 new_inode->i_ctime = current_time(new_inode);
9909 if (unlikely(btrfs_ino(BTRFS_I(new_inode)) ==
9910 BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)) {
9911 root_objectid = BTRFS_I(new_inode)->location.objectid;
9912 ret = btrfs_unlink_subvol(trans, new_dir, root_objectid,
9913 new_dentry->d_name.name,
9914 new_dentry->d_name.len);
9915 BUG_ON(new_inode->i_nlink == 0);
9917 ret = btrfs_unlink_inode(trans, dest, BTRFS_I(new_dir),
9918 BTRFS_I(d_inode(new_dentry)),
9919 new_dentry->d_name.name,
9920 new_dentry->d_name.len);
9922 if (!ret && new_inode->i_nlink == 0)
9923 ret = btrfs_orphan_add(trans,
9924 BTRFS_I(d_inode(new_dentry)));
9926 btrfs_abort_transaction(trans, ret);
9931 ret = btrfs_add_link(trans, BTRFS_I(new_dir), BTRFS_I(old_inode),
9932 new_dentry->d_name.name,
9933 new_dentry->d_name.len, 0, index);
9935 btrfs_abort_transaction(trans, ret);
9939 if (old_inode->i_nlink == 1)
9940 BTRFS_I(old_inode)->dir_index = index;
9943 struct dentry *parent = new_dentry->d_parent;
9945 btrfs_init_log_ctx(&ctx, old_inode);
9946 ret = btrfs_log_new_name(trans, BTRFS_I(old_inode),
9947 BTRFS_I(old_dir), parent,
9949 if (ret == BTRFS_NEED_LOG_SYNC)
9951 else if (ret == BTRFS_NEED_TRANS_COMMIT)
9952 commit_transaction = true;
9954 btrfs_end_log_trans(root);
9958 if (flags & RENAME_WHITEOUT) {
9959 ret = btrfs_whiteout_for_rename(trans, root, old_dir,
9963 btrfs_abort_transaction(trans, ret);
9969 * If we have pinned the log and an error happened, we unpin tasks
9970 * trying to sync the log and force them to fallback to a transaction
9971 * commit if the log currently contains any of the inodes involved in
9972 * this rename operation (to ensure we do not persist a log with an
9973 * inconsistent state for any of these inodes or leading to any
9974 * inconsistencies when replayed). If the transaction was aborted, the
9975 * abortion reason is propagated to userspace when attempting to commit
9976 * the transaction. If the log does not contain any of these inodes, we
9977 * allow the tasks to sync it.
9979 if (ret && log_pinned) {
9980 if (btrfs_inode_in_log(BTRFS_I(old_dir), fs_info->generation) ||
9981 btrfs_inode_in_log(BTRFS_I(new_dir), fs_info->generation) ||
9982 btrfs_inode_in_log(BTRFS_I(old_inode), fs_info->generation) ||
9984 btrfs_inode_in_log(BTRFS_I(new_inode), fs_info->generation)))
9985 btrfs_set_log_full_commit(trans);
9987 btrfs_end_log_trans(root);
9990 if (!ret && sync_log) {
9991 ret = btrfs_sync_log(trans, BTRFS_I(old_inode)->root, &ctx);
9993 commit_transaction = true;
9995 if (commit_transaction) {
9996 ret = btrfs_commit_transaction(trans);
10000 ret2 = btrfs_end_transaction(trans);
10001 ret = ret ? ret : ret2;
10004 if (old_ino == BTRFS_FIRST_FREE_OBJECTID)
10005 up_read(&fs_info->subvol_sem);
10010 static int btrfs_rename2(struct inode *old_dir, struct dentry *old_dentry,
10011 struct inode *new_dir, struct dentry *new_dentry,
10012 unsigned int flags)
10014 if (flags & ~(RENAME_NOREPLACE | RENAME_EXCHANGE | RENAME_WHITEOUT))
10017 if (flags & RENAME_EXCHANGE)
10018 return btrfs_rename_exchange(old_dir, old_dentry, new_dir,
10021 return btrfs_rename(old_dir, old_dentry, new_dir, new_dentry, flags);
10024 struct btrfs_delalloc_work {
10025 struct inode *inode;
10026 struct completion completion;
10027 struct list_head list;
10028 struct btrfs_work work;
10031 static void btrfs_run_delalloc_work(struct btrfs_work *work)
10033 struct btrfs_delalloc_work *delalloc_work;
10034 struct inode *inode;
10036 delalloc_work = container_of(work, struct btrfs_delalloc_work,
10038 inode = delalloc_work->inode;
10039 filemap_flush(inode->i_mapping);
10040 if (test_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
10041 &BTRFS_I(inode)->runtime_flags))
10042 filemap_flush(inode->i_mapping);
10045 complete(&delalloc_work->completion);
10048 static struct btrfs_delalloc_work *btrfs_alloc_delalloc_work(struct inode *inode)
10050 struct btrfs_delalloc_work *work;
10052 work = kmalloc(sizeof(*work), GFP_NOFS);
10056 init_completion(&work->completion);
10057 INIT_LIST_HEAD(&work->list);
10058 work->inode = inode;
10059 btrfs_init_work(&work->work, btrfs_flush_delalloc_helper,
10060 btrfs_run_delalloc_work, NULL, NULL);
10066 * some fairly slow code that needs optimization. This walks the list
10067 * of all the inodes with pending delalloc and forces them to disk.
10069 static int start_delalloc_inodes(struct btrfs_root *root, int nr, bool snapshot)
10071 struct btrfs_inode *binode;
10072 struct inode *inode;
10073 struct btrfs_delalloc_work *work, *next;
10074 struct list_head works;
10075 struct list_head splice;
10078 INIT_LIST_HEAD(&works);
10079 INIT_LIST_HEAD(&splice);
10081 mutex_lock(&root->delalloc_mutex);
10082 spin_lock(&root->delalloc_lock);
10083 list_splice_init(&root->delalloc_inodes, &splice);
10084 while (!list_empty(&splice)) {
10085 binode = list_entry(splice.next, struct btrfs_inode,
10088 list_move_tail(&binode->delalloc_inodes,
10089 &root->delalloc_inodes);
10090 inode = igrab(&binode->vfs_inode);
10092 cond_resched_lock(&root->delalloc_lock);
10095 spin_unlock(&root->delalloc_lock);
10098 set_bit(BTRFS_INODE_SNAPSHOT_FLUSH,
10099 &binode->runtime_flags);
10100 work = btrfs_alloc_delalloc_work(inode);
10106 list_add_tail(&work->list, &works);
10107 btrfs_queue_work(root->fs_info->flush_workers,
10110 if (nr != -1 && ret >= nr)
10113 spin_lock(&root->delalloc_lock);
10115 spin_unlock(&root->delalloc_lock);
10118 list_for_each_entry_safe(work, next, &works, list) {
10119 list_del_init(&work->list);
10120 wait_for_completion(&work->completion);
10124 if (!list_empty(&splice)) {
10125 spin_lock(&root->delalloc_lock);
10126 list_splice_tail(&splice, &root->delalloc_inodes);
10127 spin_unlock(&root->delalloc_lock);
10129 mutex_unlock(&root->delalloc_mutex);
10133 int btrfs_start_delalloc_snapshot(struct btrfs_root *root)
10135 struct btrfs_fs_info *fs_info = root->fs_info;
10138 if (test_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state))
10141 ret = start_delalloc_inodes(root, -1, true);
10147 int btrfs_start_delalloc_roots(struct btrfs_fs_info *fs_info, int nr)
10149 struct btrfs_root *root;
10150 struct list_head splice;
10153 if (test_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state))
10156 INIT_LIST_HEAD(&splice);
10158 mutex_lock(&fs_info->delalloc_root_mutex);
10159 spin_lock(&fs_info->delalloc_root_lock);
10160 list_splice_init(&fs_info->delalloc_roots, &splice);
10161 while (!list_empty(&splice) && nr) {
10162 root = list_first_entry(&splice, struct btrfs_root,
10164 root = btrfs_grab_fs_root(root);
10166 list_move_tail(&root->delalloc_root,
10167 &fs_info->delalloc_roots);
10168 spin_unlock(&fs_info->delalloc_root_lock);
10170 ret = start_delalloc_inodes(root, nr, false);
10171 btrfs_put_fs_root(root);
10179 spin_lock(&fs_info->delalloc_root_lock);
10181 spin_unlock(&fs_info->delalloc_root_lock);
10185 if (!list_empty(&splice)) {
10186 spin_lock(&fs_info->delalloc_root_lock);
10187 list_splice_tail(&splice, &fs_info->delalloc_roots);
10188 spin_unlock(&fs_info->delalloc_root_lock);
10190 mutex_unlock(&fs_info->delalloc_root_mutex);
10194 static int btrfs_symlink(struct inode *dir, struct dentry *dentry,
10195 const char *symname)
10197 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
10198 struct btrfs_trans_handle *trans;
10199 struct btrfs_root *root = BTRFS_I(dir)->root;
10200 struct btrfs_path *path;
10201 struct btrfs_key key;
10202 struct inode *inode = NULL;
10209 struct btrfs_file_extent_item *ei;
10210 struct extent_buffer *leaf;
10212 name_len = strlen(symname);
10213 if (name_len > BTRFS_MAX_INLINE_DATA_SIZE(fs_info))
10214 return -ENAMETOOLONG;
10217 * 2 items for inode item and ref
10218 * 2 items for dir items
10219 * 1 item for updating parent inode item
10220 * 1 item for the inline extent item
10221 * 1 item for xattr if selinux is on
10223 trans = btrfs_start_transaction(root, 7);
10225 return PTR_ERR(trans);
10227 err = btrfs_find_free_ino(root, &objectid);
10231 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
10232 dentry->d_name.len, btrfs_ino(BTRFS_I(dir)),
10233 objectid, S_IFLNK|S_IRWXUGO, &index);
10234 if (IS_ERR(inode)) {
10235 err = PTR_ERR(inode);
10241 * If the active LSM wants to access the inode during
10242 * d_instantiate it needs these. Smack checks to see
10243 * if the filesystem supports xattrs by looking at the
10246 inode->i_fop = &btrfs_file_operations;
10247 inode->i_op = &btrfs_file_inode_operations;
10248 inode->i_mapping->a_ops = &btrfs_aops;
10249 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
10251 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
10255 path = btrfs_alloc_path();
10260 key.objectid = btrfs_ino(BTRFS_I(inode));
10262 key.type = BTRFS_EXTENT_DATA_KEY;
10263 datasize = btrfs_file_extent_calc_inline_size(name_len);
10264 err = btrfs_insert_empty_item(trans, root, path, &key,
10267 btrfs_free_path(path);
10270 leaf = path->nodes[0];
10271 ei = btrfs_item_ptr(leaf, path->slots[0],
10272 struct btrfs_file_extent_item);
10273 btrfs_set_file_extent_generation(leaf, ei, trans->transid);
10274 btrfs_set_file_extent_type(leaf, ei,
10275 BTRFS_FILE_EXTENT_INLINE);
10276 btrfs_set_file_extent_encryption(leaf, ei, 0);
10277 btrfs_set_file_extent_compression(leaf, ei, 0);
10278 btrfs_set_file_extent_other_encoding(leaf, ei, 0);
10279 btrfs_set_file_extent_ram_bytes(leaf, ei, name_len);
10281 ptr = btrfs_file_extent_inline_start(ei);
10282 write_extent_buffer(leaf, symname, ptr, name_len);
10283 btrfs_mark_buffer_dirty(leaf);
10284 btrfs_free_path(path);
10286 inode->i_op = &btrfs_symlink_inode_operations;
10287 inode_nohighmem(inode);
10288 inode_set_bytes(inode, name_len);
10289 btrfs_i_size_write(BTRFS_I(inode), name_len);
10290 err = btrfs_update_inode(trans, root, inode);
10292 * Last step, add directory indexes for our symlink inode. This is the
10293 * last step to avoid extra cleanup of these indexes if an error happens
10297 err = btrfs_add_nondir(trans, BTRFS_I(dir), dentry,
10298 BTRFS_I(inode), 0, index);
10302 d_instantiate_new(dentry, inode);
10305 btrfs_end_transaction(trans);
10306 if (err && inode) {
10307 inode_dec_link_count(inode);
10308 discard_new_inode(inode);
10310 btrfs_btree_balance_dirty(fs_info);
10314 static int __btrfs_prealloc_file_range(struct inode *inode, int mode,
10315 u64 start, u64 num_bytes, u64 min_size,
10316 loff_t actual_len, u64 *alloc_hint,
10317 struct btrfs_trans_handle *trans)
10319 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
10320 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
10321 struct extent_map *em;
10322 struct btrfs_root *root = BTRFS_I(inode)->root;
10323 struct btrfs_key ins;
10324 u64 cur_offset = start;
10327 u64 last_alloc = (u64)-1;
10329 bool own_trans = true;
10330 u64 end = start + num_bytes - 1;
10334 while (num_bytes > 0) {
10336 trans = btrfs_start_transaction(root, 3);
10337 if (IS_ERR(trans)) {
10338 ret = PTR_ERR(trans);
10343 cur_bytes = min_t(u64, num_bytes, SZ_256M);
10344 cur_bytes = max(cur_bytes, min_size);
10346 * If we are severely fragmented we could end up with really
10347 * small allocations, so if the allocator is returning small
10348 * chunks lets make its job easier by only searching for those
10351 cur_bytes = min(cur_bytes, last_alloc);
10352 ret = btrfs_reserve_extent(root, cur_bytes, cur_bytes,
10353 min_size, 0, *alloc_hint, &ins, 1, 0);
10356 btrfs_end_transaction(trans);
10359 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
10361 last_alloc = ins.offset;
10362 ret = insert_reserved_file_extent(trans, inode,
10363 cur_offset, ins.objectid,
10364 ins.offset, ins.offset,
10365 ins.offset, 0, 0, 0,
10366 BTRFS_FILE_EXTENT_PREALLOC);
10368 btrfs_free_reserved_extent(fs_info, ins.objectid,
10370 btrfs_abort_transaction(trans, ret);
10372 btrfs_end_transaction(trans);
10376 btrfs_drop_extent_cache(BTRFS_I(inode), cur_offset,
10377 cur_offset + ins.offset -1, 0);
10379 em = alloc_extent_map();
10381 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
10382 &BTRFS_I(inode)->runtime_flags);
10386 em->start = cur_offset;
10387 em->orig_start = cur_offset;
10388 em->len = ins.offset;
10389 em->block_start = ins.objectid;
10390 em->block_len = ins.offset;
10391 em->orig_block_len = ins.offset;
10392 em->ram_bytes = ins.offset;
10393 em->bdev = fs_info->fs_devices->latest_bdev;
10394 set_bit(EXTENT_FLAG_PREALLOC, &em->flags);
10395 em->generation = trans->transid;
10398 write_lock(&em_tree->lock);
10399 ret = add_extent_mapping(em_tree, em, 1);
10400 write_unlock(&em_tree->lock);
10401 if (ret != -EEXIST)
10403 btrfs_drop_extent_cache(BTRFS_I(inode), cur_offset,
10404 cur_offset + ins.offset - 1,
10407 free_extent_map(em);
10409 num_bytes -= ins.offset;
10410 cur_offset += ins.offset;
10411 *alloc_hint = ins.objectid + ins.offset;
10413 inode_inc_iversion(inode);
10414 inode->i_ctime = current_time(inode);
10415 BTRFS_I(inode)->flags |= BTRFS_INODE_PREALLOC;
10416 if (!(mode & FALLOC_FL_KEEP_SIZE) &&
10417 (actual_len > inode->i_size) &&
10418 (cur_offset > inode->i_size)) {
10419 if (cur_offset > actual_len)
10420 i_size = actual_len;
10422 i_size = cur_offset;
10423 i_size_write(inode, i_size);
10424 btrfs_ordered_update_i_size(inode, i_size, NULL);
10427 ret = btrfs_update_inode(trans, root, inode);
10430 btrfs_abort_transaction(trans, ret);
10432 btrfs_end_transaction(trans);
10437 btrfs_end_transaction(trans);
10439 if (cur_offset < end)
10440 btrfs_free_reserved_data_space(inode, NULL, cur_offset,
10441 end - cur_offset + 1);
10445 int btrfs_prealloc_file_range(struct inode *inode, int mode,
10446 u64 start, u64 num_bytes, u64 min_size,
10447 loff_t actual_len, u64 *alloc_hint)
10449 return __btrfs_prealloc_file_range(inode, mode, start, num_bytes,
10450 min_size, actual_len, alloc_hint,
10454 int btrfs_prealloc_file_range_trans(struct inode *inode,
10455 struct btrfs_trans_handle *trans, int mode,
10456 u64 start, u64 num_bytes, u64 min_size,
10457 loff_t actual_len, u64 *alloc_hint)
10459 return __btrfs_prealloc_file_range(inode, mode, start, num_bytes,
10460 min_size, actual_len, alloc_hint, trans);
10463 static int btrfs_set_page_dirty(struct page *page)
10465 return __set_page_dirty_nobuffers(page);
10468 static int btrfs_permission(struct inode *inode, int mask)
10470 struct btrfs_root *root = BTRFS_I(inode)->root;
10471 umode_t mode = inode->i_mode;
10473 if (mask & MAY_WRITE &&
10474 (S_ISREG(mode) || S_ISDIR(mode) || S_ISLNK(mode))) {
10475 if (btrfs_root_readonly(root))
10477 if (BTRFS_I(inode)->flags & BTRFS_INODE_READONLY)
10480 return generic_permission(inode, mask);
10483 static int btrfs_tmpfile(struct inode *dir, struct dentry *dentry, umode_t mode)
10485 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
10486 struct btrfs_trans_handle *trans;
10487 struct btrfs_root *root = BTRFS_I(dir)->root;
10488 struct inode *inode = NULL;
10494 * 5 units required for adding orphan entry
10496 trans = btrfs_start_transaction(root, 5);
10498 return PTR_ERR(trans);
10500 ret = btrfs_find_free_ino(root, &objectid);
10504 inode = btrfs_new_inode(trans, root, dir, NULL, 0,
10505 btrfs_ino(BTRFS_I(dir)), objectid, mode, &index);
10506 if (IS_ERR(inode)) {
10507 ret = PTR_ERR(inode);
10512 inode->i_fop = &btrfs_file_operations;
10513 inode->i_op = &btrfs_file_inode_operations;
10515 inode->i_mapping->a_ops = &btrfs_aops;
10516 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
10518 ret = btrfs_init_inode_security(trans, inode, dir, NULL);
10522 ret = btrfs_update_inode(trans, root, inode);
10525 ret = btrfs_orphan_add(trans, BTRFS_I(inode));
10530 * We set number of links to 0 in btrfs_new_inode(), and here we set
10531 * it to 1 because d_tmpfile() will issue a warning if the count is 0,
10534 * d_tmpfile() -> inode_dec_link_count() -> drop_nlink()
10536 set_nlink(inode, 1);
10537 d_tmpfile(dentry, inode);
10538 unlock_new_inode(inode);
10539 mark_inode_dirty(inode);
10541 btrfs_end_transaction(trans);
10543 discard_new_inode(inode);
10544 btrfs_btree_balance_dirty(fs_info);
10548 void btrfs_set_range_writeback(struct extent_io_tree *tree, u64 start, u64 end)
10550 struct inode *inode = tree->private_data;
10551 unsigned long index = start >> PAGE_SHIFT;
10552 unsigned long end_index = end >> PAGE_SHIFT;
10555 while (index <= end_index) {
10556 page = find_get_page(inode->i_mapping, index);
10557 ASSERT(page); /* Pages should be in the extent_io_tree */
10558 set_page_writeback(page);
10566 * Add an entry indicating a block group or device which is pinned by a
10567 * swapfile. Returns 0 on success, 1 if there is already an entry for it, or a
10568 * negative errno on failure.
10570 static int btrfs_add_swapfile_pin(struct inode *inode, void *ptr,
10571 bool is_block_group)
10573 struct btrfs_fs_info *fs_info = BTRFS_I(inode)->root->fs_info;
10574 struct btrfs_swapfile_pin *sp, *entry;
10575 struct rb_node **p;
10576 struct rb_node *parent = NULL;
10578 sp = kmalloc(sizeof(*sp), GFP_NOFS);
10583 sp->is_block_group = is_block_group;
10585 spin_lock(&fs_info->swapfile_pins_lock);
10586 p = &fs_info->swapfile_pins.rb_node;
10589 entry = rb_entry(parent, struct btrfs_swapfile_pin, node);
10590 if (sp->ptr < entry->ptr ||
10591 (sp->ptr == entry->ptr && sp->inode < entry->inode)) {
10592 p = &(*p)->rb_left;
10593 } else if (sp->ptr > entry->ptr ||
10594 (sp->ptr == entry->ptr && sp->inode > entry->inode)) {
10595 p = &(*p)->rb_right;
10597 spin_unlock(&fs_info->swapfile_pins_lock);
10602 rb_link_node(&sp->node, parent, p);
10603 rb_insert_color(&sp->node, &fs_info->swapfile_pins);
10604 spin_unlock(&fs_info->swapfile_pins_lock);
10608 /* Free all of the entries pinned by this swapfile. */
10609 static void btrfs_free_swapfile_pins(struct inode *inode)
10611 struct btrfs_fs_info *fs_info = BTRFS_I(inode)->root->fs_info;
10612 struct btrfs_swapfile_pin *sp;
10613 struct rb_node *node, *next;
10615 spin_lock(&fs_info->swapfile_pins_lock);
10616 node = rb_first(&fs_info->swapfile_pins);
10618 next = rb_next(node);
10619 sp = rb_entry(node, struct btrfs_swapfile_pin, node);
10620 if (sp->inode == inode) {
10621 rb_erase(&sp->node, &fs_info->swapfile_pins);
10622 if (sp->is_block_group)
10623 btrfs_put_block_group(sp->ptr);
10628 spin_unlock(&fs_info->swapfile_pins_lock);
10631 struct btrfs_swap_info {
10637 unsigned long nr_pages;
10641 static int btrfs_add_swap_extent(struct swap_info_struct *sis,
10642 struct btrfs_swap_info *bsi)
10644 unsigned long nr_pages;
10645 u64 first_ppage, first_ppage_reported, next_ppage;
10648 first_ppage = ALIGN(bsi->block_start, PAGE_SIZE) >> PAGE_SHIFT;
10649 next_ppage = ALIGN_DOWN(bsi->block_start + bsi->block_len,
10650 PAGE_SIZE) >> PAGE_SHIFT;
10652 if (first_ppage >= next_ppage)
10654 nr_pages = next_ppage - first_ppage;
10656 first_ppage_reported = first_ppage;
10657 if (bsi->start == 0)
10658 first_ppage_reported++;
10659 if (bsi->lowest_ppage > first_ppage_reported)
10660 bsi->lowest_ppage = first_ppage_reported;
10661 if (bsi->highest_ppage < (next_ppage - 1))
10662 bsi->highest_ppage = next_ppage - 1;
10664 ret = add_swap_extent(sis, bsi->nr_pages, nr_pages, first_ppage);
10667 bsi->nr_extents += ret;
10668 bsi->nr_pages += nr_pages;
10672 static void btrfs_swap_deactivate(struct file *file)
10674 struct inode *inode = file_inode(file);
10676 btrfs_free_swapfile_pins(inode);
10677 atomic_dec(&BTRFS_I(inode)->root->nr_swapfiles);
10680 static int btrfs_swap_activate(struct swap_info_struct *sis, struct file *file,
10683 struct inode *inode = file_inode(file);
10684 struct btrfs_fs_info *fs_info = BTRFS_I(inode)->root->fs_info;
10685 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
10686 struct extent_state *cached_state = NULL;
10687 struct extent_map *em = NULL;
10688 struct btrfs_device *device = NULL;
10689 struct btrfs_swap_info bsi = {
10690 .lowest_ppage = (sector_t)-1ULL,
10697 * If the swap file was just created, make sure delalloc is done. If the
10698 * file changes again after this, the user is doing something stupid and
10699 * we don't really care.
10701 ret = btrfs_wait_ordered_range(inode, 0, (u64)-1);
10706 * The inode is locked, so these flags won't change after we check them.
10708 if (BTRFS_I(inode)->flags & BTRFS_INODE_COMPRESS) {
10709 btrfs_warn(fs_info, "swapfile must not be compressed");
10712 if (!(BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW)) {
10713 btrfs_warn(fs_info, "swapfile must not be copy-on-write");
10716 if (!(BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)) {
10717 btrfs_warn(fs_info, "swapfile must not be checksummed");
10722 * Balance or device remove/replace/resize can move stuff around from
10723 * under us. The EXCL_OP flag makes sure they aren't running/won't run
10724 * concurrently while we are mapping the swap extents, and
10725 * fs_info->swapfile_pins prevents them from running while the swap file
10726 * is active and moving the extents. Note that this also prevents a
10727 * concurrent device add which isn't actually necessary, but it's not
10728 * really worth the trouble to allow it.
10730 if (test_and_set_bit(BTRFS_FS_EXCL_OP, &fs_info->flags)) {
10731 btrfs_warn(fs_info,
10732 "cannot activate swapfile while exclusive operation is running");
10736 * Snapshots can create extents which require COW even if NODATACOW is
10737 * set. We use this counter to prevent snapshots. We must increment it
10738 * before walking the extents because we don't want a concurrent
10739 * snapshot to run after we've already checked the extents.
10741 atomic_inc(&BTRFS_I(inode)->root->nr_swapfiles);
10743 isize = ALIGN_DOWN(inode->i_size, fs_info->sectorsize);
10745 lock_extent_bits(io_tree, 0, isize - 1, &cached_state);
10747 while (start < isize) {
10748 u64 logical_block_start, physical_block_start;
10749 struct btrfs_block_group_cache *bg;
10750 u64 len = isize - start;
10752 em = btrfs_get_extent(BTRFS_I(inode), NULL, 0, start, len, 0);
10758 if (em->block_start == EXTENT_MAP_HOLE) {
10759 btrfs_warn(fs_info, "swapfile must not have holes");
10763 if (em->block_start == EXTENT_MAP_INLINE) {
10765 * It's unlikely we'll ever actually find ourselves
10766 * here, as a file small enough to fit inline won't be
10767 * big enough to store more than the swap header, but in
10768 * case something changes in the future, let's catch it
10769 * here rather than later.
10771 btrfs_warn(fs_info, "swapfile must not be inline");
10775 if (test_bit(EXTENT_FLAG_COMPRESSED, &em->flags)) {
10776 btrfs_warn(fs_info, "swapfile must not be compressed");
10781 logical_block_start = em->block_start + (start - em->start);
10782 len = min(len, em->len - (start - em->start));
10783 free_extent_map(em);
10786 ret = can_nocow_extent(inode, start, &len, NULL, NULL, NULL);
10792 btrfs_warn(fs_info,
10793 "swapfile must not be copy-on-write");
10798 em = btrfs_get_chunk_map(fs_info, logical_block_start, len);
10804 if (em->map_lookup->type & BTRFS_BLOCK_GROUP_PROFILE_MASK) {
10805 btrfs_warn(fs_info,
10806 "swapfile must have single data profile");
10811 if (device == NULL) {
10812 device = em->map_lookup->stripes[0].dev;
10813 ret = btrfs_add_swapfile_pin(inode, device, false);
10818 } else if (device != em->map_lookup->stripes[0].dev) {
10819 btrfs_warn(fs_info, "swapfile must be on one device");
10824 physical_block_start = (em->map_lookup->stripes[0].physical +
10825 (logical_block_start - em->start));
10826 len = min(len, em->len - (logical_block_start - em->start));
10827 free_extent_map(em);
10830 bg = btrfs_lookup_block_group(fs_info, logical_block_start);
10832 btrfs_warn(fs_info,
10833 "could not find block group containing swapfile");
10838 ret = btrfs_add_swapfile_pin(inode, bg, true);
10840 btrfs_put_block_group(bg);
10847 if (bsi.block_len &&
10848 bsi.block_start + bsi.block_len == physical_block_start) {
10849 bsi.block_len += len;
10851 if (bsi.block_len) {
10852 ret = btrfs_add_swap_extent(sis, &bsi);
10857 bsi.block_start = physical_block_start;
10858 bsi.block_len = len;
10865 ret = btrfs_add_swap_extent(sis, &bsi);
10868 if (!IS_ERR_OR_NULL(em))
10869 free_extent_map(em);
10871 unlock_extent_cached(io_tree, 0, isize - 1, &cached_state);
10874 btrfs_swap_deactivate(file);
10876 clear_bit(BTRFS_FS_EXCL_OP, &fs_info->flags);
10882 sis->bdev = device->bdev;
10883 *span = bsi.highest_ppage - bsi.lowest_ppage + 1;
10884 sis->max = bsi.nr_pages;
10885 sis->pages = bsi.nr_pages - 1;
10886 sis->highest_bit = bsi.nr_pages - 1;
10887 return bsi.nr_extents;
10890 static void btrfs_swap_deactivate(struct file *file)
10894 static int btrfs_swap_activate(struct swap_info_struct *sis, struct file *file,
10897 return -EOPNOTSUPP;
10901 static const struct inode_operations btrfs_dir_inode_operations = {
10902 .getattr = btrfs_getattr,
10903 .lookup = btrfs_lookup,
10904 .create = btrfs_create,
10905 .unlink = btrfs_unlink,
10906 .link = btrfs_link,
10907 .mkdir = btrfs_mkdir,
10908 .rmdir = btrfs_rmdir,
10909 .rename = btrfs_rename2,
10910 .symlink = btrfs_symlink,
10911 .setattr = btrfs_setattr,
10912 .mknod = btrfs_mknod,
10913 .listxattr = btrfs_listxattr,
10914 .permission = btrfs_permission,
10915 .get_acl = btrfs_get_acl,
10916 .set_acl = btrfs_set_acl,
10917 .update_time = btrfs_update_time,
10918 .tmpfile = btrfs_tmpfile,
10920 static const struct inode_operations btrfs_dir_ro_inode_operations = {
10921 .lookup = btrfs_lookup,
10922 .permission = btrfs_permission,
10923 .update_time = btrfs_update_time,
10926 static const struct file_operations btrfs_dir_file_operations = {
10927 .llseek = generic_file_llseek,
10928 .read = generic_read_dir,
10929 .iterate_shared = btrfs_real_readdir,
10930 .open = btrfs_opendir,
10931 .unlocked_ioctl = btrfs_ioctl,
10932 #ifdef CONFIG_COMPAT
10933 .compat_ioctl = btrfs_compat_ioctl,
10935 .release = btrfs_release_file,
10936 .fsync = btrfs_sync_file,
10939 static const struct extent_io_ops btrfs_extent_io_ops = {
10940 /* mandatory callbacks */
10941 .submit_bio_hook = btrfs_submit_bio_hook,
10942 .readpage_end_io_hook = btrfs_readpage_end_io_hook,
10946 * btrfs doesn't support the bmap operation because swapfiles
10947 * use bmap to make a mapping of extents in the file. They assume
10948 * these extents won't change over the life of the file and they
10949 * use the bmap result to do IO directly to the drive.
10951 * the btrfs bmap call would return logical addresses that aren't
10952 * suitable for IO and they also will change frequently as COW
10953 * operations happen. So, swapfile + btrfs == corruption.
10955 * For now we're avoiding this by dropping bmap.
10957 static const struct address_space_operations btrfs_aops = {
10958 .readpage = btrfs_readpage,
10959 .writepage = btrfs_writepage,
10960 .writepages = btrfs_writepages,
10961 .readpages = btrfs_readpages,
10962 .direct_IO = btrfs_direct_IO,
10963 .invalidatepage = btrfs_invalidatepage,
10964 .releasepage = btrfs_releasepage,
10965 .set_page_dirty = btrfs_set_page_dirty,
10966 .error_remove_page = generic_error_remove_page,
10967 .swap_activate = btrfs_swap_activate,
10968 .swap_deactivate = btrfs_swap_deactivate,
10971 static const struct inode_operations btrfs_file_inode_operations = {
10972 .getattr = btrfs_getattr,
10973 .setattr = btrfs_setattr,
10974 .listxattr = btrfs_listxattr,
10975 .permission = btrfs_permission,
10976 .fiemap = btrfs_fiemap,
10977 .get_acl = btrfs_get_acl,
10978 .set_acl = btrfs_set_acl,
10979 .update_time = btrfs_update_time,
10981 static const struct inode_operations btrfs_special_inode_operations = {
10982 .getattr = btrfs_getattr,
10983 .setattr = btrfs_setattr,
10984 .permission = btrfs_permission,
10985 .listxattr = btrfs_listxattr,
10986 .get_acl = btrfs_get_acl,
10987 .set_acl = btrfs_set_acl,
10988 .update_time = btrfs_update_time,
10990 static const struct inode_operations btrfs_symlink_inode_operations = {
10991 .get_link = page_get_link,
10992 .getattr = btrfs_getattr,
10993 .setattr = btrfs_setattr,
10994 .permission = btrfs_permission,
10995 .listxattr = btrfs_listxattr,
10996 .update_time = btrfs_update_time,
10999 const struct dentry_operations btrfs_dentry_operations = {
11000 .d_delete = btrfs_dentry_delete,