1 // SPDX-License-Identifier: GPL-2.0
3 * Copyright (C) 2007 Oracle. All rights reserved.
6 #include <linux/kernel.h>
8 #include <linux/file.h>
10 #include <linux/pagemap.h>
11 #include <linux/highmem.h>
12 #include <linux/time.h>
13 #include <linux/init.h>
14 #include <linux/string.h>
15 #include <linux/backing-dev.h>
16 #include <linux/writeback.h>
17 #include <linux/compat.h>
18 #include <linux/xattr.h>
19 #include <linux/posix_acl.h>
20 #include <linux/falloc.h>
21 #include <linux/slab.h>
22 #include <linux/ratelimit.h>
23 #include <linux/btrfs.h>
24 #include <linux/blkdev.h>
25 #include <linux/posix_acl_xattr.h>
26 #include <linux/uio.h>
27 #include <linux/magic.h>
28 #include <linux/iversion.h>
29 #include <linux/swap.h>
30 #include <linux/migrate.h>
31 #include <linux/sched/mm.h>
32 #include <linux/iomap.h>
33 #include <asm/unaligned.h>
37 #include "transaction.h"
38 #include "btrfs_inode.h"
39 #include "print-tree.h"
40 #include "ordered-data.h"
44 #include "compression.h"
46 #include "free-space-cache.h"
47 #include "inode-map.h"
50 #include "delalloc-space.h"
51 #include "block-group.h"
53 struct btrfs_iget_args {
55 struct btrfs_root *root;
58 struct btrfs_dio_data {
62 struct extent_changeset *data_reserved;
65 static const struct inode_operations btrfs_dir_inode_operations;
66 static const struct inode_operations btrfs_symlink_inode_operations;
67 static const struct inode_operations btrfs_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;
77 struct kmem_cache *btrfs_free_space_bitmap_cachep;
79 static int btrfs_setsize(struct inode *inode, struct iattr *attr);
80 static int btrfs_truncate(struct inode *inode, bool skip_writeback);
81 static int btrfs_finish_ordered_io(struct btrfs_ordered_extent *ordered_extent);
82 static noinline int cow_file_range(struct inode *inode,
83 struct page *locked_page,
84 u64 start, u64 end, int *page_started,
85 unsigned long *nr_written, int unlock);
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 ASSERT((compressed_size > 0 && compressed_pages) ||
182 (compressed_size == 0 && !compressed_pages));
184 if (compressed_size && compressed_pages)
185 cur_size = compressed_size;
187 inode_add_bytes(inode, size);
189 if (!extent_inserted) {
190 struct btrfs_key key;
193 key.objectid = btrfs_ino(BTRFS_I(inode));
195 key.type = BTRFS_EXTENT_DATA_KEY;
197 datasize = btrfs_file_extent_calc_inline_size(cur_size);
198 path->leave_spinning = 1;
199 ret = btrfs_insert_empty_item(trans, root, path, &key,
204 leaf = path->nodes[0];
205 ei = btrfs_item_ptr(leaf, path->slots[0],
206 struct btrfs_file_extent_item);
207 btrfs_set_file_extent_generation(leaf, ei, trans->transid);
208 btrfs_set_file_extent_type(leaf, ei, BTRFS_FILE_EXTENT_INLINE);
209 btrfs_set_file_extent_encryption(leaf, ei, 0);
210 btrfs_set_file_extent_other_encoding(leaf, ei, 0);
211 btrfs_set_file_extent_ram_bytes(leaf, ei, size);
212 ptr = btrfs_file_extent_inline_start(ei);
214 if (compress_type != BTRFS_COMPRESS_NONE) {
217 while (compressed_size > 0) {
218 cpage = compressed_pages[i];
219 cur_size = min_t(unsigned long, compressed_size,
222 kaddr = kmap_atomic(cpage);
223 write_extent_buffer(leaf, kaddr, ptr, cur_size);
224 kunmap_atomic(kaddr);
228 compressed_size -= cur_size;
230 btrfs_set_file_extent_compression(leaf, ei,
233 page = find_get_page(inode->i_mapping,
234 start >> PAGE_SHIFT);
235 btrfs_set_file_extent_compression(leaf, ei, 0);
236 kaddr = kmap_atomic(page);
237 offset = offset_in_page(start);
238 write_extent_buffer(leaf, kaddr + offset, ptr, size);
239 kunmap_atomic(kaddr);
242 btrfs_mark_buffer_dirty(leaf);
243 btrfs_release_path(path);
246 * We align size to sectorsize for inline extents just for simplicity
249 size = ALIGN(size, root->fs_info->sectorsize);
250 ret = btrfs_inode_set_file_extent_range(BTRFS_I(inode), start, size);
255 * we're an inline extent, so nobody can
256 * extend the file past i_size without locking
257 * a page we already have locked.
259 * We must do any isize and inode updates
260 * before we unlock the pages. Otherwise we
261 * could end up racing with unlink.
263 BTRFS_I(inode)->disk_i_size = inode->i_size;
264 ret = btrfs_update_inode(trans, root, inode);
272 * conditionally insert an inline extent into the file. This
273 * does the checks required to make sure the data is small enough
274 * to fit as an inline extent.
276 static noinline int cow_file_range_inline(struct inode *inode, u64 start,
277 u64 end, size_t compressed_size,
279 struct page **compressed_pages)
281 struct btrfs_root *root = BTRFS_I(inode)->root;
282 struct btrfs_fs_info *fs_info = root->fs_info;
283 struct btrfs_trans_handle *trans;
284 u64 isize = i_size_read(inode);
285 u64 actual_end = min(end + 1, isize);
286 u64 inline_len = actual_end - start;
287 u64 aligned_end = ALIGN(end, fs_info->sectorsize);
288 u64 data_len = inline_len;
290 struct btrfs_path *path;
291 int extent_inserted = 0;
292 u32 extent_item_size;
295 data_len = compressed_size;
298 actual_end > fs_info->sectorsize ||
299 data_len > BTRFS_MAX_INLINE_DATA_SIZE(fs_info) ||
301 (actual_end & (fs_info->sectorsize - 1)) == 0) ||
303 data_len > fs_info->max_inline) {
307 path = btrfs_alloc_path();
311 trans = btrfs_join_transaction(root);
313 btrfs_free_path(path);
314 return PTR_ERR(trans);
316 trans->block_rsv = &BTRFS_I(inode)->block_rsv;
318 if (compressed_size && compressed_pages)
319 extent_item_size = btrfs_file_extent_calc_inline_size(
322 extent_item_size = btrfs_file_extent_calc_inline_size(
325 ret = __btrfs_drop_extents(trans, root, inode, path,
326 start, aligned_end, NULL,
327 1, 1, extent_item_size, &extent_inserted);
329 btrfs_abort_transaction(trans, ret);
333 if (isize > actual_end)
334 inline_len = min_t(u64, isize, actual_end);
335 ret = insert_inline_extent(trans, path, extent_inserted,
337 inline_len, compressed_size,
338 compress_type, compressed_pages);
339 if (ret && ret != -ENOSPC) {
340 btrfs_abort_transaction(trans, ret);
342 } else if (ret == -ENOSPC) {
347 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &BTRFS_I(inode)->runtime_flags);
348 btrfs_drop_extent_cache(BTRFS_I(inode), start, aligned_end - 1, 0);
351 * Don't forget to free the reserved space, as for inlined extent
352 * it won't count as data extent, free them directly here.
353 * And at reserve time, it's always aligned to page size, so
354 * just free one page here.
356 btrfs_qgroup_free_data(inode, NULL, 0, PAGE_SIZE);
357 btrfs_free_path(path);
358 btrfs_end_transaction(trans);
362 struct async_extent {
367 unsigned long nr_pages;
369 struct list_head list;
374 struct page *locked_page;
377 unsigned int write_flags;
378 struct list_head extents;
379 struct cgroup_subsys_state *blkcg_css;
380 struct btrfs_work work;
385 /* Number of chunks in flight; must be first in the structure */
387 struct async_chunk chunks[];
390 static noinline int add_async_extent(struct async_chunk *cow,
391 u64 start, u64 ram_size,
394 unsigned long nr_pages,
397 struct async_extent *async_extent;
399 async_extent = kmalloc(sizeof(*async_extent), GFP_NOFS);
400 BUG_ON(!async_extent); /* -ENOMEM */
401 async_extent->start = start;
402 async_extent->ram_size = ram_size;
403 async_extent->compressed_size = compressed_size;
404 async_extent->pages = pages;
405 async_extent->nr_pages = nr_pages;
406 async_extent->compress_type = compress_type;
407 list_add_tail(&async_extent->list, &cow->extents);
412 * Check if the inode has flags compatible with compression
414 static inline bool inode_can_compress(struct inode *inode)
416 if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW ||
417 BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)
423 * Check if the inode needs to be submitted to compression, based on mount
424 * options, defragmentation, properties or heuristics.
426 static inline int inode_need_compress(struct inode *inode, u64 start, u64 end)
428 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
430 if (!inode_can_compress(inode)) {
431 WARN(IS_ENABLED(CONFIG_BTRFS_DEBUG),
432 KERN_ERR "BTRFS: unexpected compression for ino %llu\n",
433 btrfs_ino(BTRFS_I(inode)));
437 if (btrfs_test_opt(fs_info, FORCE_COMPRESS))
440 if (BTRFS_I(inode)->defrag_compress)
442 /* bad compression ratios */
443 if (BTRFS_I(inode)->flags & BTRFS_INODE_NOCOMPRESS)
445 if (btrfs_test_opt(fs_info, COMPRESS) ||
446 BTRFS_I(inode)->flags & BTRFS_INODE_COMPRESS ||
447 BTRFS_I(inode)->prop_compress)
448 return btrfs_compress_heuristic(inode, start, end);
452 static inline void inode_should_defrag(struct btrfs_inode *inode,
453 u64 start, u64 end, u64 num_bytes, u64 small_write)
455 /* If this is a small write inside eof, kick off a defrag */
456 if (num_bytes < small_write &&
457 (start > 0 || end + 1 < inode->disk_i_size))
458 btrfs_add_inode_defrag(NULL, inode);
462 * we create compressed extents in two phases. The first
463 * phase compresses a range of pages that have already been
464 * locked (both pages and state bits are locked).
466 * This is done inside an ordered work queue, and the compression
467 * is spread across many cpus. The actual IO submission is step
468 * two, and the ordered work queue takes care of making sure that
469 * happens in the same order things were put onto the queue by
470 * writepages and friends.
472 * If this code finds it can't get good compression, it puts an
473 * entry onto the work queue to write the uncompressed bytes. This
474 * makes sure that both compressed inodes and uncompressed inodes
475 * are written in the same order that the flusher thread sent them
478 static noinline int compress_file_range(struct async_chunk *async_chunk)
480 struct inode *inode = async_chunk->inode;
481 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
482 u64 blocksize = fs_info->sectorsize;
483 u64 start = async_chunk->start;
484 u64 end = async_chunk->end;
488 struct page **pages = NULL;
489 unsigned long nr_pages;
490 unsigned long total_compressed = 0;
491 unsigned long total_in = 0;
494 int compress_type = fs_info->compress_type;
495 int compressed_extents = 0;
498 inode_should_defrag(BTRFS_I(inode), start, end, end - start + 1,
502 * We need to save i_size before now because it could change in between
503 * us evaluating the size and assigning it. This is because we lock and
504 * unlock the page in truncate and fallocate, and then modify the i_size
507 * The barriers are to emulate READ_ONCE, remove that once i_size_read
511 i_size = i_size_read(inode);
513 actual_end = min_t(u64, i_size, end + 1);
516 nr_pages = (end >> PAGE_SHIFT) - (start >> PAGE_SHIFT) + 1;
517 BUILD_BUG_ON((BTRFS_MAX_COMPRESSED % PAGE_SIZE) != 0);
518 nr_pages = min_t(unsigned long, nr_pages,
519 BTRFS_MAX_COMPRESSED / PAGE_SIZE);
522 * we don't want to send crud past the end of i_size through
523 * compression, that's just a waste of CPU time. So, if the
524 * end of the file is before the start of our current
525 * requested range of bytes, we bail out to the uncompressed
526 * cleanup code that can deal with all of this.
528 * It isn't really the fastest way to fix things, but this is a
529 * very uncommon corner.
531 if (actual_end <= start)
532 goto cleanup_and_bail_uncompressed;
534 total_compressed = actual_end - start;
537 * skip compression for a small file range(<=blocksize) that
538 * isn't an inline extent, since it doesn't save disk space at all.
540 if (total_compressed <= blocksize &&
541 (start > 0 || end + 1 < BTRFS_I(inode)->disk_i_size))
542 goto cleanup_and_bail_uncompressed;
544 total_compressed = min_t(unsigned long, total_compressed,
545 BTRFS_MAX_UNCOMPRESSED);
550 * we do compression for mount -o compress and when the
551 * inode has not been flagged as nocompress. This flag can
552 * change at any time if we discover bad compression ratios.
554 if (inode_need_compress(inode, start, end)) {
556 pages = kcalloc(nr_pages, sizeof(struct page *), GFP_NOFS);
558 /* just bail out to the uncompressed code */
563 if (BTRFS_I(inode)->defrag_compress)
564 compress_type = BTRFS_I(inode)->defrag_compress;
565 else if (BTRFS_I(inode)->prop_compress)
566 compress_type = BTRFS_I(inode)->prop_compress;
569 * we need to call clear_page_dirty_for_io on each
570 * page in the range. Otherwise applications with the file
571 * mmap'd can wander in and change the page contents while
572 * we are compressing them.
574 * If the compression fails for any reason, we set the pages
575 * dirty again later on.
577 * Note that the remaining part is redirtied, the start pointer
578 * has moved, the end is the original one.
581 extent_range_clear_dirty_for_io(inode, start, end);
585 /* Compression level is applied here and only here */
586 ret = btrfs_compress_pages(
587 compress_type | (fs_info->compress_level << 4),
588 inode->i_mapping, start,
595 unsigned long offset = offset_in_page(total_compressed);
596 struct page *page = pages[nr_pages - 1];
599 /* zero the tail end of the last page, we might be
600 * sending it down to disk
603 kaddr = kmap_atomic(page);
604 memset(kaddr + offset, 0,
606 kunmap_atomic(kaddr);
613 /* lets try to make an inline extent */
614 if (ret || total_in < actual_end) {
615 /* we didn't compress the entire range, try
616 * to make an uncompressed inline extent.
618 ret = cow_file_range_inline(inode, start, end, 0,
619 BTRFS_COMPRESS_NONE, NULL);
621 /* try making a compressed inline extent */
622 ret = cow_file_range_inline(inode, start, end,
624 compress_type, pages);
627 unsigned long clear_flags = EXTENT_DELALLOC |
628 EXTENT_DELALLOC_NEW | EXTENT_DEFRAG |
629 EXTENT_DO_ACCOUNTING;
630 unsigned long page_error_op;
632 page_error_op = ret < 0 ? PAGE_SET_ERROR : 0;
635 * inline extent creation worked or returned error,
636 * we don't need to create any more async work items.
637 * Unlock and free up our temp pages.
639 * We use DO_ACCOUNTING here because we need the
640 * delalloc_release_metadata to be done _after_ we drop
641 * our outstanding extent for clearing delalloc for this
644 extent_clear_unlock_delalloc(inode, start, end, NULL,
652 for (i = 0; i < nr_pages; i++) {
653 WARN_ON(pages[i]->mapping);
664 * we aren't doing an inline extent round the compressed size
665 * up to a block size boundary so the allocator does sane
668 total_compressed = ALIGN(total_compressed, blocksize);
671 * one last check to make sure the compression is really a
672 * win, compare the page count read with the blocks on disk,
673 * compression must free at least one sector size
675 total_in = ALIGN(total_in, PAGE_SIZE);
676 if (total_compressed + blocksize <= total_in) {
677 compressed_extents++;
680 * The async work queues will take care of doing actual
681 * allocation on disk for these compressed pages, and
682 * will submit them to the elevator.
684 add_async_extent(async_chunk, start, total_in,
685 total_compressed, pages, nr_pages,
688 if (start + total_in < end) {
694 return compressed_extents;
699 * the compression code ran but failed to make things smaller,
700 * free any pages it allocated and our page pointer array
702 for (i = 0; i < nr_pages; i++) {
703 WARN_ON(pages[i]->mapping);
708 total_compressed = 0;
711 /* flag the file so we don't compress in the future */
712 if (!btrfs_test_opt(fs_info, FORCE_COMPRESS) &&
713 !(BTRFS_I(inode)->prop_compress)) {
714 BTRFS_I(inode)->flags |= BTRFS_INODE_NOCOMPRESS;
717 cleanup_and_bail_uncompressed:
719 * No compression, but we still need to write the pages in the file
720 * we've been given so far. redirty the locked page if it corresponds
721 * to our extent and set things up for the async work queue to run
722 * cow_file_range to do the normal delalloc dance.
724 if (async_chunk->locked_page &&
725 (page_offset(async_chunk->locked_page) >= start &&
726 page_offset(async_chunk->locked_page)) <= end) {
727 __set_page_dirty_nobuffers(async_chunk->locked_page);
728 /* unlocked later on in the async handlers */
732 extent_range_redirty_for_io(inode, start, end);
733 add_async_extent(async_chunk, start, end - start + 1, 0, NULL, 0,
734 BTRFS_COMPRESS_NONE);
735 compressed_extents++;
737 return compressed_extents;
740 static void free_async_extent_pages(struct async_extent *async_extent)
744 if (!async_extent->pages)
747 for (i = 0; i < async_extent->nr_pages; i++) {
748 WARN_ON(async_extent->pages[i]->mapping);
749 put_page(async_extent->pages[i]);
751 kfree(async_extent->pages);
752 async_extent->nr_pages = 0;
753 async_extent->pages = NULL;
757 * phase two of compressed writeback. This is the ordered portion
758 * of the code, which only gets called in the order the work was
759 * queued. We walk all the async extents created by compress_file_range
760 * and send them down to the disk.
762 static noinline void submit_compressed_extents(struct async_chunk *async_chunk)
764 struct inode *inode = async_chunk->inode;
765 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
766 struct async_extent *async_extent;
768 struct btrfs_key ins;
769 struct extent_map *em;
770 struct btrfs_root *root = BTRFS_I(inode)->root;
771 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
775 while (!list_empty(&async_chunk->extents)) {
776 async_extent = list_entry(async_chunk->extents.next,
777 struct async_extent, list);
778 list_del(&async_extent->list);
781 lock_extent(io_tree, async_extent->start,
782 async_extent->start + async_extent->ram_size - 1);
783 /* did the compression code fall back to uncompressed IO? */
784 if (!async_extent->pages) {
785 int page_started = 0;
786 unsigned long nr_written = 0;
788 /* allocate blocks */
789 ret = cow_file_range(inode, async_chunk->locked_page,
791 async_extent->start +
792 async_extent->ram_size - 1,
793 &page_started, &nr_written, 0);
798 * if page_started, cow_file_range inserted an
799 * inline extent and took care of all the unlocking
800 * and IO for us. Otherwise, we need to submit
801 * all those pages down to the drive.
803 if (!page_started && !ret)
804 extent_write_locked_range(inode,
806 async_extent->start +
807 async_extent->ram_size - 1,
809 else if (ret && async_chunk->locked_page)
810 unlock_page(async_chunk->locked_page);
816 ret = btrfs_reserve_extent(root, async_extent->ram_size,
817 async_extent->compressed_size,
818 async_extent->compressed_size,
819 0, alloc_hint, &ins, 1, 1);
821 free_async_extent_pages(async_extent);
823 if (ret == -ENOSPC) {
824 unlock_extent(io_tree, async_extent->start,
825 async_extent->start +
826 async_extent->ram_size - 1);
829 * we need to redirty the pages if we decide to
830 * fallback to uncompressed IO, otherwise we
831 * will not submit these pages down to lower
834 extent_range_redirty_for_io(inode,
836 async_extent->start +
837 async_extent->ram_size - 1);
844 * here we're doing allocation and writeback of the
847 em = create_io_em(inode, async_extent->start,
848 async_extent->ram_size, /* len */
849 async_extent->start, /* orig_start */
850 ins.objectid, /* block_start */
851 ins.offset, /* block_len */
852 ins.offset, /* orig_block_len */
853 async_extent->ram_size, /* ram_bytes */
854 async_extent->compress_type,
855 BTRFS_ORDERED_COMPRESSED);
857 /* ret value is not necessary due to void function */
858 goto out_free_reserve;
861 ret = btrfs_add_ordered_extent_compress(inode,
864 async_extent->ram_size,
866 BTRFS_ORDERED_COMPRESSED,
867 async_extent->compress_type);
869 btrfs_drop_extent_cache(BTRFS_I(inode),
871 async_extent->start +
872 async_extent->ram_size - 1, 0);
873 goto out_free_reserve;
875 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
878 * clear dirty, set writeback and unlock the pages.
880 extent_clear_unlock_delalloc(inode, async_extent->start,
881 async_extent->start +
882 async_extent->ram_size - 1,
883 NULL, EXTENT_LOCKED | EXTENT_DELALLOC,
884 PAGE_UNLOCK | PAGE_CLEAR_DIRTY |
886 if (btrfs_submit_compressed_write(inode,
888 async_extent->ram_size,
890 ins.offset, async_extent->pages,
891 async_extent->nr_pages,
892 async_chunk->write_flags,
893 async_chunk->blkcg_css)) {
894 struct page *p = async_extent->pages[0];
895 const u64 start = async_extent->start;
896 const u64 end = start + async_extent->ram_size - 1;
898 p->mapping = inode->i_mapping;
899 btrfs_writepage_endio_finish_ordered(p, start, end, 0);
902 extent_clear_unlock_delalloc(inode, start, end,
906 free_async_extent_pages(async_extent);
908 alloc_hint = ins.objectid + ins.offset;
914 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
915 btrfs_free_reserved_extent(fs_info, ins.objectid, ins.offset, 1);
917 extent_clear_unlock_delalloc(inode, async_extent->start,
918 async_extent->start +
919 async_extent->ram_size - 1,
920 NULL, EXTENT_LOCKED | EXTENT_DELALLOC |
921 EXTENT_DELALLOC_NEW |
922 EXTENT_DEFRAG | EXTENT_DO_ACCOUNTING,
923 PAGE_UNLOCK | PAGE_CLEAR_DIRTY |
924 PAGE_SET_WRITEBACK | PAGE_END_WRITEBACK |
926 free_async_extent_pages(async_extent);
931 static u64 get_extent_allocation_hint(struct inode *inode, u64 start,
934 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
935 struct extent_map *em;
938 read_lock(&em_tree->lock);
939 em = search_extent_mapping(em_tree, start, num_bytes);
942 * if block start isn't an actual block number then find the
943 * first block in this inode and use that as a hint. If that
944 * block is also bogus then just don't worry about it.
946 if (em->block_start >= EXTENT_MAP_LAST_BYTE) {
948 em = search_extent_mapping(em_tree, 0, 0);
949 if (em && em->block_start < EXTENT_MAP_LAST_BYTE)
950 alloc_hint = em->block_start;
954 alloc_hint = em->block_start;
958 read_unlock(&em_tree->lock);
964 * when extent_io.c finds a delayed allocation range in the file,
965 * the call backs end up in this code. The basic idea is to
966 * allocate extents on disk for the range, and create ordered data structs
967 * in ram to track those extents.
969 * locked_page is the page that writepage had locked already. We use
970 * it to make sure we don't do extra locks or unlocks.
972 * *page_started is set to one if we unlock locked_page and do everything
973 * required to start IO on it. It may be clean and already done with
976 static noinline int cow_file_range(struct inode *inode,
977 struct page *locked_page,
978 u64 start, u64 end, int *page_started,
979 unsigned long *nr_written, int unlock)
981 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
982 struct btrfs_root *root = BTRFS_I(inode)->root;
985 unsigned long ram_size;
986 u64 cur_alloc_size = 0;
987 u64 blocksize = fs_info->sectorsize;
988 struct btrfs_key ins;
989 struct extent_map *em;
991 unsigned long page_ops;
992 bool extent_reserved = false;
995 if (btrfs_is_free_space_inode(BTRFS_I(inode))) {
1001 num_bytes = ALIGN(end - start + 1, blocksize);
1002 num_bytes = max(blocksize, num_bytes);
1003 ASSERT(num_bytes <= btrfs_super_total_bytes(fs_info->super_copy));
1005 inode_should_defrag(BTRFS_I(inode), start, end, num_bytes, SZ_64K);
1008 /* lets try to make an inline extent */
1009 ret = cow_file_range_inline(inode, start, end, 0,
1010 BTRFS_COMPRESS_NONE, NULL);
1013 * We use DO_ACCOUNTING here because we need the
1014 * delalloc_release_metadata to be run _after_ we drop
1015 * our outstanding extent for clearing delalloc for this
1018 extent_clear_unlock_delalloc(inode, start, end, NULL,
1019 EXTENT_LOCKED | EXTENT_DELALLOC |
1020 EXTENT_DELALLOC_NEW | EXTENT_DEFRAG |
1021 EXTENT_DO_ACCOUNTING, PAGE_UNLOCK |
1022 PAGE_CLEAR_DIRTY | PAGE_SET_WRITEBACK |
1023 PAGE_END_WRITEBACK);
1024 *nr_written = *nr_written +
1025 (end - start + PAGE_SIZE) / PAGE_SIZE;
1028 } else if (ret < 0) {
1033 alloc_hint = get_extent_allocation_hint(inode, start, num_bytes);
1034 btrfs_drop_extent_cache(BTRFS_I(inode), start,
1035 start + num_bytes - 1, 0);
1037 while (num_bytes > 0) {
1038 cur_alloc_size = num_bytes;
1039 ret = btrfs_reserve_extent(root, cur_alloc_size, cur_alloc_size,
1040 fs_info->sectorsize, 0, alloc_hint,
1044 cur_alloc_size = ins.offset;
1045 extent_reserved = true;
1047 ram_size = ins.offset;
1048 em = create_io_em(inode, start, ins.offset, /* len */
1049 start, /* orig_start */
1050 ins.objectid, /* block_start */
1051 ins.offset, /* block_len */
1052 ins.offset, /* orig_block_len */
1053 ram_size, /* ram_bytes */
1054 BTRFS_COMPRESS_NONE, /* compress_type */
1055 BTRFS_ORDERED_REGULAR /* type */);
1060 free_extent_map(em);
1062 ret = btrfs_add_ordered_extent(inode, start, ins.objectid,
1063 ram_size, cur_alloc_size, 0);
1065 goto out_drop_extent_cache;
1067 if (root->root_key.objectid ==
1068 BTRFS_DATA_RELOC_TREE_OBJECTID) {
1069 ret = btrfs_reloc_clone_csums(inode, start,
1072 * Only drop cache here, and process as normal.
1074 * We must not allow extent_clear_unlock_delalloc()
1075 * at out_unlock label to free meta of this ordered
1076 * extent, as its meta should be freed by
1077 * btrfs_finish_ordered_io().
1079 * So we must continue until @start is increased to
1080 * skip current ordered extent.
1083 btrfs_drop_extent_cache(BTRFS_I(inode), start,
1084 start + ram_size - 1, 0);
1087 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
1089 /* we're not doing compressed IO, don't unlock the first
1090 * page (which the caller expects to stay locked), don't
1091 * clear any dirty bits and don't set any writeback bits
1093 * Do set the Private2 bit so we know this page was properly
1094 * setup for writepage
1096 page_ops = unlock ? PAGE_UNLOCK : 0;
1097 page_ops |= PAGE_SET_PRIVATE2;
1099 extent_clear_unlock_delalloc(inode, start,
1100 start + ram_size - 1,
1102 EXTENT_LOCKED | EXTENT_DELALLOC,
1104 if (num_bytes < cur_alloc_size)
1107 num_bytes -= cur_alloc_size;
1108 alloc_hint = ins.objectid + ins.offset;
1109 start += cur_alloc_size;
1110 extent_reserved = false;
1113 * btrfs_reloc_clone_csums() error, since start is increased
1114 * extent_clear_unlock_delalloc() at out_unlock label won't
1115 * free metadata of current ordered extent, we're OK to exit.
1123 out_drop_extent_cache:
1124 btrfs_drop_extent_cache(BTRFS_I(inode), start, start + ram_size - 1, 0);
1126 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
1127 btrfs_free_reserved_extent(fs_info, ins.objectid, ins.offset, 1);
1129 clear_bits = EXTENT_LOCKED | EXTENT_DELALLOC | EXTENT_DELALLOC_NEW |
1130 EXTENT_DEFRAG | EXTENT_CLEAR_META_RESV;
1131 page_ops = PAGE_UNLOCK | PAGE_CLEAR_DIRTY | PAGE_SET_WRITEBACK |
1134 * If we reserved an extent for our delalloc range (or a subrange) and
1135 * failed to create the respective ordered extent, then it means that
1136 * when we reserved the extent we decremented the extent's size from
1137 * the data space_info's bytes_may_use counter and incremented the
1138 * space_info's bytes_reserved counter by the same amount. We must make
1139 * sure extent_clear_unlock_delalloc() does not try to decrement again
1140 * the data space_info's bytes_may_use counter, therefore we do not pass
1141 * it the flag EXTENT_CLEAR_DATA_RESV.
1143 if (extent_reserved) {
1144 extent_clear_unlock_delalloc(inode, start,
1145 start + cur_alloc_size,
1149 start += cur_alloc_size;
1153 extent_clear_unlock_delalloc(inode, start, end, locked_page,
1154 clear_bits | EXTENT_CLEAR_DATA_RESV,
1160 * work queue call back to started compression on a file and pages
1162 static noinline void async_cow_start(struct btrfs_work *work)
1164 struct async_chunk *async_chunk;
1165 int compressed_extents;
1167 async_chunk = container_of(work, struct async_chunk, work);
1169 compressed_extents = compress_file_range(async_chunk);
1170 if (compressed_extents == 0) {
1171 btrfs_add_delayed_iput(async_chunk->inode);
1172 async_chunk->inode = NULL;
1177 * work queue call back to submit previously compressed pages
1179 static noinline void async_cow_submit(struct btrfs_work *work)
1181 struct async_chunk *async_chunk = container_of(work, struct async_chunk,
1183 struct btrfs_fs_info *fs_info = btrfs_work_owner(work);
1184 unsigned long nr_pages;
1186 nr_pages = (async_chunk->end - async_chunk->start + PAGE_SIZE) >>
1189 /* atomic_sub_return implies a barrier */
1190 if (atomic_sub_return(nr_pages, &fs_info->async_delalloc_pages) <
1192 cond_wake_up_nomb(&fs_info->async_submit_wait);
1195 * ->inode could be NULL if async_chunk_start has failed to compress,
1196 * in which case we don't have anything to submit, yet we need to
1197 * always adjust ->async_delalloc_pages as its paired with the init
1198 * happening in cow_file_range_async
1200 if (async_chunk->inode)
1201 submit_compressed_extents(async_chunk);
1204 static noinline void async_cow_free(struct btrfs_work *work)
1206 struct async_chunk *async_chunk;
1208 async_chunk = container_of(work, struct async_chunk, work);
1209 if (async_chunk->inode)
1210 btrfs_add_delayed_iput(async_chunk->inode);
1211 if (async_chunk->blkcg_css)
1212 css_put(async_chunk->blkcg_css);
1214 * Since the pointer to 'pending' is at the beginning of the array of
1215 * async_chunk's, freeing it ensures the whole array has been freed.
1217 if (atomic_dec_and_test(async_chunk->pending))
1218 kvfree(async_chunk->pending);
1221 static int cow_file_range_async(struct inode *inode,
1222 struct writeback_control *wbc,
1223 struct page *locked_page,
1224 u64 start, u64 end, int *page_started,
1225 unsigned long *nr_written)
1227 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1228 struct cgroup_subsys_state *blkcg_css = wbc_blkcg_css(wbc);
1229 struct async_cow *ctx;
1230 struct async_chunk *async_chunk;
1231 unsigned long nr_pages;
1233 u64 num_chunks = DIV_ROUND_UP(end - start, SZ_512K);
1235 bool should_compress;
1237 const unsigned int write_flags = wbc_to_write_flags(wbc);
1239 unlock_extent(&BTRFS_I(inode)->io_tree, start, end);
1241 if (BTRFS_I(inode)->flags & BTRFS_INODE_NOCOMPRESS &&
1242 !btrfs_test_opt(fs_info, FORCE_COMPRESS)) {
1244 should_compress = false;
1246 should_compress = true;
1249 nofs_flag = memalloc_nofs_save();
1250 ctx = kvmalloc(struct_size(ctx, chunks, num_chunks), GFP_KERNEL);
1251 memalloc_nofs_restore(nofs_flag);
1254 unsigned clear_bits = EXTENT_LOCKED | EXTENT_DELALLOC |
1255 EXTENT_DELALLOC_NEW | EXTENT_DEFRAG |
1256 EXTENT_DO_ACCOUNTING;
1257 unsigned long page_ops = PAGE_UNLOCK | PAGE_CLEAR_DIRTY |
1258 PAGE_SET_WRITEBACK | PAGE_END_WRITEBACK |
1261 extent_clear_unlock_delalloc(inode, start, end, locked_page,
1262 clear_bits, page_ops);
1266 async_chunk = ctx->chunks;
1267 atomic_set(&ctx->num_chunks, num_chunks);
1269 for (i = 0; i < num_chunks; i++) {
1270 if (should_compress)
1271 cur_end = min(end, start + SZ_512K - 1);
1276 * igrab is called higher up in the call chain, take only the
1277 * lightweight reference for the callback lifetime
1280 async_chunk[i].pending = &ctx->num_chunks;
1281 async_chunk[i].inode = inode;
1282 async_chunk[i].start = start;
1283 async_chunk[i].end = cur_end;
1284 async_chunk[i].write_flags = write_flags;
1285 INIT_LIST_HEAD(&async_chunk[i].extents);
1288 * The locked_page comes all the way from writepage and its
1289 * the original page we were actually given. As we spread
1290 * this large delalloc region across multiple async_chunk
1291 * structs, only the first struct needs a pointer to locked_page
1293 * This way we don't need racey decisions about who is supposed
1298 * Depending on the compressibility, the pages might or
1299 * might not go through async. We want all of them to
1300 * be accounted against wbc once. Let's do it here
1301 * before the paths diverge. wbc accounting is used
1302 * only for foreign writeback detection and doesn't
1303 * need full accuracy. Just account the whole thing
1304 * against the first page.
1306 wbc_account_cgroup_owner(wbc, locked_page,
1308 async_chunk[i].locked_page = locked_page;
1311 async_chunk[i].locked_page = NULL;
1314 if (blkcg_css != blkcg_root_css) {
1316 async_chunk[i].blkcg_css = blkcg_css;
1318 async_chunk[i].blkcg_css = NULL;
1321 btrfs_init_work(&async_chunk[i].work, async_cow_start,
1322 async_cow_submit, async_cow_free);
1324 nr_pages = DIV_ROUND_UP(cur_end - start, PAGE_SIZE);
1325 atomic_add(nr_pages, &fs_info->async_delalloc_pages);
1327 btrfs_queue_work(fs_info->delalloc_workers, &async_chunk[i].work);
1329 *nr_written += nr_pages;
1330 start = cur_end + 1;
1336 static noinline int csum_exist_in_range(struct btrfs_fs_info *fs_info,
1337 u64 bytenr, u64 num_bytes)
1340 struct btrfs_ordered_sum *sums;
1343 ret = btrfs_lookup_csums_range(fs_info->csum_root, bytenr,
1344 bytenr + num_bytes - 1, &list, 0);
1345 if (ret == 0 && list_empty(&list))
1348 while (!list_empty(&list)) {
1349 sums = list_entry(list.next, struct btrfs_ordered_sum, list);
1350 list_del(&sums->list);
1359 * when nowcow writeback call back. This checks for snapshots or COW copies
1360 * of the extents that exist in the file, and COWs the file as required.
1362 * If no cow copies or snapshots exist, we write directly to the existing
1365 static noinline int run_delalloc_nocow(struct inode *inode,
1366 struct page *locked_page,
1367 const u64 start, const u64 end,
1368 int *page_started, int force,
1369 unsigned long *nr_written)
1371 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1372 struct btrfs_root *root = BTRFS_I(inode)->root;
1373 struct btrfs_path *path;
1374 u64 cow_start = (u64)-1;
1375 u64 cur_offset = start;
1377 bool check_prev = true;
1378 const bool freespace_inode = btrfs_is_free_space_inode(BTRFS_I(inode));
1379 u64 ino = btrfs_ino(BTRFS_I(inode));
1381 u64 disk_bytenr = 0;
1383 path = btrfs_alloc_path();
1385 extent_clear_unlock_delalloc(inode, start, end, locked_page,
1386 EXTENT_LOCKED | EXTENT_DELALLOC |
1387 EXTENT_DO_ACCOUNTING |
1388 EXTENT_DEFRAG, PAGE_UNLOCK |
1390 PAGE_SET_WRITEBACK |
1391 PAGE_END_WRITEBACK);
1396 struct btrfs_key found_key;
1397 struct btrfs_file_extent_item *fi;
1398 struct extent_buffer *leaf;
1408 ret = btrfs_lookup_file_extent(NULL, root, path, ino,
1414 * If there is no extent for our range when doing the initial
1415 * search, then go back to the previous slot as it will be the
1416 * one containing the search offset
1418 if (ret > 0 && path->slots[0] > 0 && check_prev) {
1419 leaf = path->nodes[0];
1420 btrfs_item_key_to_cpu(leaf, &found_key,
1421 path->slots[0] - 1);
1422 if (found_key.objectid == ino &&
1423 found_key.type == BTRFS_EXTENT_DATA_KEY)
1428 /* Go to next leaf if we have exhausted the current one */
1429 leaf = path->nodes[0];
1430 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
1431 ret = btrfs_next_leaf(root, path);
1433 if (cow_start != (u64)-1)
1434 cur_offset = cow_start;
1439 leaf = path->nodes[0];
1442 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
1444 /* Didn't find anything for our INO */
1445 if (found_key.objectid > ino)
1448 * Keep searching until we find an EXTENT_ITEM or there are no
1449 * more extents for this inode
1451 if (WARN_ON_ONCE(found_key.objectid < ino) ||
1452 found_key.type < BTRFS_EXTENT_DATA_KEY) {
1457 /* Found key is not EXTENT_DATA_KEY or starts after req range */
1458 if (found_key.type > BTRFS_EXTENT_DATA_KEY ||
1459 found_key.offset > end)
1463 * If the found extent starts after requested offset, then
1464 * adjust extent_end to be right before this extent begins
1466 if (found_key.offset > cur_offset) {
1467 extent_end = found_key.offset;
1473 * Found extent which begins before our range and potentially
1476 fi = btrfs_item_ptr(leaf, path->slots[0],
1477 struct btrfs_file_extent_item);
1478 extent_type = btrfs_file_extent_type(leaf, fi);
1480 ram_bytes = btrfs_file_extent_ram_bytes(leaf, fi);
1481 if (extent_type == BTRFS_FILE_EXTENT_REG ||
1482 extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
1483 disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
1484 extent_offset = btrfs_file_extent_offset(leaf, fi);
1485 extent_end = found_key.offset +
1486 btrfs_file_extent_num_bytes(leaf, fi);
1488 btrfs_file_extent_disk_num_bytes(leaf, fi);
1490 * If the extent we got ends before our current offset,
1491 * skip to the next extent.
1493 if (extent_end <= cur_offset) {
1498 if (disk_bytenr == 0)
1500 /* Skip compressed/encrypted/encoded extents */
1501 if (btrfs_file_extent_compression(leaf, fi) ||
1502 btrfs_file_extent_encryption(leaf, fi) ||
1503 btrfs_file_extent_other_encoding(leaf, fi))
1506 * If extent is created before the last volume's snapshot
1507 * this implies the extent is shared, hence we can't do
1508 * nocow. This is the same check as in
1509 * btrfs_cross_ref_exist but without calling
1510 * btrfs_search_slot.
1512 if (!freespace_inode &&
1513 btrfs_file_extent_generation(leaf, fi) <=
1514 btrfs_root_last_snapshot(&root->root_item))
1516 if (extent_type == BTRFS_FILE_EXTENT_REG && !force)
1518 /* If extent is RO, we must COW it */
1519 if (btrfs_extent_readonly(fs_info, disk_bytenr))
1521 ret = btrfs_cross_ref_exist(root, ino,
1523 extent_offset, disk_bytenr);
1526 * ret could be -EIO if the above fails to read
1530 if (cow_start != (u64)-1)
1531 cur_offset = cow_start;
1535 WARN_ON_ONCE(freespace_inode);
1538 disk_bytenr += extent_offset;
1539 disk_bytenr += cur_offset - found_key.offset;
1540 num_bytes = min(end + 1, extent_end) - cur_offset;
1542 * If there are pending snapshots for this root, we
1543 * fall into common COW way
1545 if (!freespace_inode && atomic_read(&root->snapshot_force_cow))
1548 * force cow if csum exists in the range.
1549 * this ensure that csum for a given extent are
1550 * either valid or do not exist.
1552 ret = csum_exist_in_range(fs_info, disk_bytenr,
1556 * ret could be -EIO if the above fails to read
1560 if (cow_start != (u64)-1)
1561 cur_offset = cow_start;
1564 WARN_ON_ONCE(freespace_inode);
1567 if (!btrfs_inc_nocow_writers(fs_info, disk_bytenr))
1570 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
1571 extent_end = found_key.offset + ram_bytes;
1572 extent_end = ALIGN(extent_end, fs_info->sectorsize);
1573 /* Skip extents outside of our requested range */
1574 if (extent_end <= start) {
1579 /* If this triggers then we have a memory corruption */
1584 * If nocow is false then record the beginning of the range
1585 * that needs to be COWed
1588 if (cow_start == (u64)-1)
1589 cow_start = cur_offset;
1590 cur_offset = extent_end;
1591 if (cur_offset > end)
1597 btrfs_release_path(path);
1600 * COW range from cow_start to found_key.offset - 1. As the key
1601 * will contain the beginning of the first extent that can be
1602 * NOCOW, following one which needs to be COW'ed
1604 if (cow_start != (u64)-1) {
1605 ret = cow_file_range(inode, locked_page,
1606 cow_start, found_key.offset - 1,
1607 page_started, nr_written, 1);
1610 btrfs_dec_nocow_writers(fs_info,
1614 cow_start = (u64)-1;
1617 if (extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
1618 u64 orig_start = found_key.offset - extent_offset;
1619 struct extent_map *em;
1621 em = create_io_em(inode, cur_offset, num_bytes,
1623 disk_bytenr, /* block_start */
1624 num_bytes, /* block_len */
1625 disk_num_bytes, /* orig_block_len */
1626 ram_bytes, BTRFS_COMPRESS_NONE,
1627 BTRFS_ORDERED_PREALLOC);
1630 btrfs_dec_nocow_writers(fs_info,
1635 free_extent_map(em);
1636 ret = btrfs_add_ordered_extent(inode, cur_offset,
1637 disk_bytenr, num_bytes,
1639 BTRFS_ORDERED_PREALLOC);
1641 btrfs_drop_extent_cache(BTRFS_I(inode),
1643 cur_offset + num_bytes - 1,
1648 ret = btrfs_add_ordered_extent(inode, cur_offset,
1649 disk_bytenr, num_bytes,
1651 BTRFS_ORDERED_NOCOW);
1657 btrfs_dec_nocow_writers(fs_info, disk_bytenr);
1660 if (root->root_key.objectid ==
1661 BTRFS_DATA_RELOC_TREE_OBJECTID)
1663 * Error handled later, as we must prevent
1664 * extent_clear_unlock_delalloc() in error handler
1665 * from freeing metadata of created ordered extent.
1667 ret = btrfs_reloc_clone_csums(inode, cur_offset,
1670 extent_clear_unlock_delalloc(inode, cur_offset,
1671 cur_offset + num_bytes - 1,
1672 locked_page, EXTENT_LOCKED |
1674 EXTENT_CLEAR_DATA_RESV,
1675 PAGE_UNLOCK | PAGE_SET_PRIVATE2);
1677 cur_offset = extent_end;
1680 * btrfs_reloc_clone_csums() error, now we're OK to call error
1681 * handler, as metadata for created ordered extent will only
1682 * be freed by btrfs_finish_ordered_io().
1686 if (cur_offset > end)
1689 btrfs_release_path(path);
1691 if (cur_offset <= end && cow_start == (u64)-1)
1692 cow_start = cur_offset;
1694 if (cow_start != (u64)-1) {
1696 ret = cow_file_range(inode, locked_page, cow_start, end,
1697 page_started, nr_written, 1);
1704 btrfs_dec_nocow_writers(fs_info, disk_bytenr);
1706 if (ret && cur_offset < end)
1707 extent_clear_unlock_delalloc(inode, cur_offset, end,
1708 locked_page, EXTENT_LOCKED |
1709 EXTENT_DELALLOC | EXTENT_DEFRAG |
1710 EXTENT_DO_ACCOUNTING, PAGE_UNLOCK |
1712 PAGE_SET_WRITEBACK |
1713 PAGE_END_WRITEBACK);
1714 btrfs_free_path(path);
1718 static inline int need_force_cow(struct inode *inode, u64 start, u64 end)
1721 if (!(BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW) &&
1722 !(BTRFS_I(inode)->flags & BTRFS_INODE_PREALLOC))
1726 * @defrag_bytes is a hint value, no spinlock held here,
1727 * if is not zero, it means the file is defragging.
1728 * Force cow if given extent needs to be defragged.
1730 if (BTRFS_I(inode)->defrag_bytes &&
1731 test_range_bit(&BTRFS_I(inode)->io_tree, start, end,
1732 EXTENT_DEFRAG, 0, NULL))
1739 * Function to process delayed allocation (create CoW) for ranges which are
1740 * being touched for the first time.
1742 int btrfs_run_delalloc_range(struct inode *inode, struct page *locked_page,
1743 u64 start, u64 end, int *page_started, unsigned long *nr_written,
1744 struct writeback_control *wbc)
1747 int force_cow = need_force_cow(inode, start, end);
1749 if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW && !force_cow) {
1750 ret = run_delalloc_nocow(inode, locked_page, start, end,
1751 page_started, 1, nr_written);
1752 } else if (BTRFS_I(inode)->flags & BTRFS_INODE_PREALLOC && !force_cow) {
1753 ret = run_delalloc_nocow(inode, locked_page, start, end,
1754 page_started, 0, nr_written);
1755 } else if (!inode_can_compress(inode) ||
1756 !inode_need_compress(inode, start, end)) {
1757 ret = cow_file_range(inode, locked_page, start, end,
1758 page_started, nr_written, 1);
1760 set_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
1761 &BTRFS_I(inode)->runtime_flags);
1762 ret = cow_file_range_async(inode, wbc, locked_page, start, end,
1763 page_started, nr_written);
1766 btrfs_cleanup_ordered_extents(inode, locked_page, start,
1771 void btrfs_split_delalloc_extent(struct inode *inode,
1772 struct extent_state *orig, u64 split)
1776 /* not delalloc, ignore it */
1777 if (!(orig->state & EXTENT_DELALLOC))
1780 size = orig->end - orig->start + 1;
1781 if (size > BTRFS_MAX_EXTENT_SIZE) {
1786 * See the explanation in btrfs_merge_delalloc_extent, the same
1787 * applies here, just in reverse.
1789 new_size = orig->end - split + 1;
1790 num_extents = count_max_extents(new_size);
1791 new_size = split - orig->start;
1792 num_extents += count_max_extents(new_size);
1793 if (count_max_extents(size) >= num_extents)
1797 spin_lock(&BTRFS_I(inode)->lock);
1798 btrfs_mod_outstanding_extents(BTRFS_I(inode), 1);
1799 spin_unlock(&BTRFS_I(inode)->lock);
1803 * Handle merged delayed allocation extents so we can keep track of new extents
1804 * that are just merged onto old extents, such as when we are doing sequential
1805 * writes, so we can properly account for the metadata space we'll need.
1807 void btrfs_merge_delalloc_extent(struct inode *inode, struct extent_state *new,
1808 struct extent_state *other)
1810 u64 new_size, old_size;
1813 /* not delalloc, ignore it */
1814 if (!(other->state & EXTENT_DELALLOC))
1817 if (new->start > other->start)
1818 new_size = new->end - other->start + 1;
1820 new_size = other->end - new->start + 1;
1822 /* we're not bigger than the max, unreserve the space and go */
1823 if (new_size <= BTRFS_MAX_EXTENT_SIZE) {
1824 spin_lock(&BTRFS_I(inode)->lock);
1825 btrfs_mod_outstanding_extents(BTRFS_I(inode), -1);
1826 spin_unlock(&BTRFS_I(inode)->lock);
1831 * We have to add up either side to figure out how many extents were
1832 * accounted for before we merged into one big extent. If the number of
1833 * extents we accounted for is <= the amount we need for the new range
1834 * then we can return, otherwise drop. Think of it like this
1838 * So we've grown the extent by a MAX_SIZE extent, this would mean we
1839 * need 2 outstanding extents, on one side we have 1 and the other side
1840 * we have 1 so they are == and we can return. But in this case
1842 * [MAX_SIZE+4k][MAX_SIZE+4k]
1844 * Each range on their own accounts for 2 extents, but merged together
1845 * they are only 3 extents worth of accounting, so we need to drop in
1848 old_size = other->end - other->start + 1;
1849 num_extents = count_max_extents(old_size);
1850 old_size = new->end - new->start + 1;
1851 num_extents += count_max_extents(old_size);
1852 if (count_max_extents(new_size) >= num_extents)
1855 spin_lock(&BTRFS_I(inode)->lock);
1856 btrfs_mod_outstanding_extents(BTRFS_I(inode), -1);
1857 spin_unlock(&BTRFS_I(inode)->lock);
1860 static void btrfs_add_delalloc_inodes(struct btrfs_root *root,
1861 struct inode *inode)
1863 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1865 spin_lock(&root->delalloc_lock);
1866 if (list_empty(&BTRFS_I(inode)->delalloc_inodes)) {
1867 list_add_tail(&BTRFS_I(inode)->delalloc_inodes,
1868 &root->delalloc_inodes);
1869 set_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1870 &BTRFS_I(inode)->runtime_flags);
1871 root->nr_delalloc_inodes++;
1872 if (root->nr_delalloc_inodes == 1) {
1873 spin_lock(&fs_info->delalloc_root_lock);
1874 BUG_ON(!list_empty(&root->delalloc_root));
1875 list_add_tail(&root->delalloc_root,
1876 &fs_info->delalloc_roots);
1877 spin_unlock(&fs_info->delalloc_root_lock);
1880 spin_unlock(&root->delalloc_lock);
1884 void __btrfs_del_delalloc_inode(struct btrfs_root *root,
1885 struct btrfs_inode *inode)
1887 struct btrfs_fs_info *fs_info = root->fs_info;
1889 if (!list_empty(&inode->delalloc_inodes)) {
1890 list_del_init(&inode->delalloc_inodes);
1891 clear_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1892 &inode->runtime_flags);
1893 root->nr_delalloc_inodes--;
1894 if (!root->nr_delalloc_inodes) {
1895 ASSERT(list_empty(&root->delalloc_inodes));
1896 spin_lock(&fs_info->delalloc_root_lock);
1897 BUG_ON(list_empty(&root->delalloc_root));
1898 list_del_init(&root->delalloc_root);
1899 spin_unlock(&fs_info->delalloc_root_lock);
1904 static void btrfs_del_delalloc_inode(struct btrfs_root *root,
1905 struct btrfs_inode *inode)
1907 spin_lock(&root->delalloc_lock);
1908 __btrfs_del_delalloc_inode(root, inode);
1909 spin_unlock(&root->delalloc_lock);
1913 * Properly track delayed allocation bytes in the inode and to maintain the
1914 * list of inodes that have pending delalloc work to be done.
1916 void btrfs_set_delalloc_extent(struct inode *inode, struct extent_state *state,
1919 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1921 if ((*bits & EXTENT_DEFRAG) && !(*bits & EXTENT_DELALLOC))
1924 * set_bit and clear bit hooks normally require _irqsave/restore
1925 * but in this case, we are only testing for the DELALLOC
1926 * bit, which is only set or cleared with irqs on
1928 if (!(state->state & EXTENT_DELALLOC) && (*bits & EXTENT_DELALLOC)) {
1929 struct btrfs_root *root = BTRFS_I(inode)->root;
1930 u64 len = state->end + 1 - state->start;
1931 u32 num_extents = count_max_extents(len);
1932 bool do_list = !btrfs_is_free_space_inode(BTRFS_I(inode));
1934 spin_lock(&BTRFS_I(inode)->lock);
1935 btrfs_mod_outstanding_extents(BTRFS_I(inode), num_extents);
1936 spin_unlock(&BTRFS_I(inode)->lock);
1938 /* For sanity tests */
1939 if (btrfs_is_testing(fs_info))
1942 percpu_counter_add_batch(&fs_info->delalloc_bytes, len,
1943 fs_info->delalloc_batch);
1944 spin_lock(&BTRFS_I(inode)->lock);
1945 BTRFS_I(inode)->delalloc_bytes += len;
1946 if (*bits & EXTENT_DEFRAG)
1947 BTRFS_I(inode)->defrag_bytes += len;
1948 if (do_list && !test_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1949 &BTRFS_I(inode)->runtime_flags))
1950 btrfs_add_delalloc_inodes(root, inode);
1951 spin_unlock(&BTRFS_I(inode)->lock);
1954 if (!(state->state & EXTENT_DELALLOC_NEW) &&
1955 (*bits & EXTENT_DELALLOC_NEW)) {
1956 spin_lock(&BTRFS_I(inode)->lock);
1957 BTRFS_I(inode)->new_delalloc_bytes += state->end + 1 -
1959 spin_unlock(&BTRFS_I(inode)->lock);
1964 * Once a range is no longer delalloc this function ensures that proper
1965 * accounting happens.
1967 void btrfs_clear_delalloc_extent(struct inode *vfs_inode,
1968 struct extent_state *state, unsigned *bits)
1970 struct btrfs_inode *inode = BTRFS_I(vfs_inode);
1971 struct btrfs_fs_info *fs_info = btrfs_sb(vfs_inode->i_sb);
1972 u64 len = state->end + 1 - state->start;
1973 u32 num_extents = count_max_extents(len);
1975 if ((state->state & EXTENT_DEFRAG) && (*bits & EXTENT_DEFRAG)) {
1976 spin_lock(&inode->lock);
1977 inode->defrag_bytes -= len;
1978 spin_unlock(&inode->lock);
1982 * set_bit and clear bit hooks normally require _irqsave/restore
1983 * but in this case, we are only testing for the DELALLOC
1984 * bit, which is only set or cleared with irqs on
1986 if ((state->state & EXTENT_DELALLOC) && (*bits & EXTENT_DELALLOC)) {
1987 struct btrfs_root *root = inode->root;
1988 bool do_list = !btrfs_is_free_space_inode(inode);
1990 spin_lock(&inode->lock);
1991 btrfs_mod_outstanding_extents(inode, -num_extents);
1992 spin_unlock(&inode->lock);
1995 * We don't reserve metadata space for space cache inodes so we
1996 * don't need to call delalloc_release_metadata if there is an
1999 if (*bits & EXTENT_CLEAR_META_RESV &&
2000 root != fs_info->tree_root)
2001 btrfs_delalloc_release_metadata(inode, len, false);
2003 /* For sanity tests. */
2004 if (btrfs_is_testing(fs_info))
2007 if (root->root_key.objectid != BTRFS_DATA_RELOC_TREE_OBJECTID &&
2008 do_list && !(state->state & EXTENT_NORESERVE) &&
2009 (*bits & EXTENT_CLEAR_DATA_RESV))
2010 btrfs_free_reserved_data_space_noquota(
2014 percpu_counter_add_batch(&fs_info->delalloc_bytes, -len,
2015 fs_info->delalloc_batch);
2016 spin_lock(&inode->lock);
2017 inode->delalloc_bytes -= len;
2018 if (do_list && inode->delalloc_bytes == 0 &&
2019 test_bit(BTRFS_INODE_IN_DELALLOC_LIST,
2020 &inode->runtime_flags))
2021 btrfs_del_delalloc_inode(root, inode);
2022 spin_unlock(&inode->lock);
2025 if ((state->state & EXTENT_DELALLOC_NEW) &&
2026 (*bits & EXTENT_DELALLOC_NEW)) {
2027 spin_lock(&inode->lock);
2028 ASSERT(inode->new_delalloc_bytes >= len);
2029 inode->new_delalloc_bytes -= len;
2030 spin_unlock(&inode->lock);
2035 * btrfs_bio_fits_in_stripe - Checks whether the size of the given bio will fit
2036 * in a chunk's stripe. This function ensures that bios do not span a
2039 * @page - The page we are about to add to the bio
2040 * @size - size we want to add to the bio
2041 * @bio - bio we want to ensure is smaller than a stripe
2042 * @bio_flags - flags of the bio
2044 * return 1 if page cannot be added to the bio
2045 * return 0 if page can be added to the bio
2046 * return error otherwise
2048 int btrfs_bio_fits_in_stripe(struct page *page, size_t size, struct bio *bio,
2049 unsigned long bio_flags)
2051 struct inode *inode = page->mapping->host;
2052 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2053 u64 logical = (u64)bio->bi_iter.bi_sector << 9;
2057 struct btrfs_io_geometry geom;
2059 if (bio_flags & EXTENT_BIO_COMPRESSED)
2062 length = bio->bi_iter.bi_size;
2063 map_length = length;
2064 ret = btrfs_get_io_geometry(fs_info, btrfs_op(bio), logical, map_length,
2069 if (geom.len < length + size)
2075 * in order to insert checksums into the metadata in large chunks,
2076 * we wait until bio submission time. All the pages in the bio are
2077 * checksummed and sums are attached onto the ordered extent record.
2079 * At IO completion time the cums attached on the ordered extent record
2080 * are inserted into the btree
2082 static blk_status_t btrfs_submit_bio_start(void *private_data, struct bio *bio,
2085 struct inode *inode = private_data;
2086 blk_status_t ret = 0;
2088 ret = btrfs_csum_one_bio(inode, bio, 0, 0);
2089 BUG_ON(ret); /* -ENOMEM */
2094 * extent_io.c submission hook. This does the right thing for csum calculation
2095 * on write, or reading the csums from the tree before a read.
2097 * Rules about async/sync submit,
2098 * a) read: sync submit
2100 * b) write without checksum: sync submit
2102 * c) write with checksum:
2103 * c-1) if bio is issued by fsync: sync submit
2104 * (sync_writers != 0)
2106 * c-2) if root is reloc root: sync submit
2107 * (only in case of buffered IO)
2109 * c-3) otherwise: async submit
2111 static blk_status_t btrfs_submit_bio_hook(struct inode *inode, struct bio *bio,
2113 unsigned long bio_flags)
2116 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2117 struct btrfs_root *root = BTRFS_I(inode)->root;
2118 enum btrfs_wq_endio_type metadata = BTRFS_WQ_ENDIO_DATA;
2119 blk_status_t ret = 0;
2121 int async = !atomic_read(&BTRFS_I(inode)->sync_writers);
2123 skip_sum = BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM;
2125 if (btrfs_is_free_space_inode(BTRFS_I(inode)))
2126 metadata = BTRFS_WQ_ENDIO_FREE_SPACE;
2128 if (bio_op(bio) != REQ_OP_WRITE) {
2129 ret = btrfs_bio_wq_end_io(fs_info, bio, metadata);
2133 if (bio_flags & EXTENT_BIO_COMPRESSED) {
2134 ret = btrfs_submit_compressed_read(inode, bio,
2138 } else if (!skip_sum) {
2139 ret = btrfs_lookup_bio_sums(inode, bio, (u64)-1, NULL);
2144 } else if (async && !skip_sum) {
2145 /* csum items have already been cloned */
2146 if (root->root_key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID)
2148 /* we're doing a write, do the async checksumming */
2149 ret = btrfs_wq_submit_bio(fs_info, bio, mirror_num, bio_flags,
2150 0, inode, btrfs_submit_bio_start);
2152 } else if (!skip_sum) {
2153 ret = btrfs_csum_one_bio(inode, bio, 0, 0);
2159 ret = btrfs_map_bio(fs_info, bio, mirror_num);
2163 bio->bi_status = ret;
2170 * given a list of ordered sums record them in the inode. This happens
2171 * at IO completion time based on sums calculated at bio submission time.
2173 static noinline int add_pending_csums(struct btrfs_trans_handle *trans,
2174 struct inode *inode, struct list_head *list)
2176 struct btrfs_ordered_sum *sum;
2179 list_for_each_entry(sum, list, list) {
2180 trans->adding_csums = true;
2181 ret = btrfs_csum_file_blocks(trans,
2182 BTRFS_I(inode)->root->fs_info->csum_root, sum);
2183 trans->adding_csums = false;
2190 int btrfs_set_extent_delalloc(struct inode *inode, u64 start, u64 end,
2191 unsigned int extra_bits,
2192 struct extent_state **cached_state)
2194 WARN_ON(PAGE_ALIGNED(end));
2195 return set_extent_delalloc(&BTRFS_I(inode)->io_tree, start, end,
2196 extra_bits, cached_state);
2199 /* see btrfs_writepage_start_hook for details on why this is required */
2200 struct btrfs_writepage_fixup {
2202 struct inode *inode;
2203 struct btrfs_work work;
2206 static void btrfs_writepage_fixup_worker(struct btrfs_work *work)
2208 struct btrfs_writepage_fixup *fixup;
2209 struct btrfs_ordered_extent *ordered;
2210 struct extent_state *cached_state = NULL;
2211 struct extent_changeset *data_reserved = NULL;
2213 struct inode *inode;
2217 bool free_delalloc_space = true;
2219 fixup = container_of(work, struct btrfs_writepage_fixup, work);
2221 inode = fixup->inode;
2222 page_start = page_offset(page);
2223 page_end = page_offset(page) + PAGE_SIZE - 1;
2226 * This is similar to page_mkwrite, we need to reserve the space before
2227 * we take the page lock.
2229 ret = btrfs_delalloc_reserve_space(inode, &data_reserved, page_start,
2235 * Before we queued this fixup, we took a reference on the page.
2236 * page->mapping may go NULL, but it shouldn't be moved to a different
2239 if (!page->mapping || !PageDirty(page) || !PageChecked(page)) {
2241 * Unfortunately this is a little tricky, either
2243 * 1) We got here and our page had already been dealt with and
2244 * we reserved our space, thus ret == 0, so we need to just
2245 * drop our space reservation and bail. This can happen the
2246 * first time we come into the fixup worker, or could happen
2247 * while waiting for the ordered extent.
2248 * 2) Our page was already dealt with, but we happened to get an
2249 * ENOSPC above from the btrfs_delalloc_reserve_space. In
2250 * this case we obviously don't have anything to release, but
2251 * because the page was already dealt with we don't want to
2252 * mark the page with an error, so make sure we're resetting
2253 * ret to 0. This is why we have this check _before_ the ret
2254 * check, because we do not want to have a surprise ENOSPC
2255 * when the page was already properly dealt with.
2258 btrfs_delalloc_release_extents(BTRFS_I(inode),
2260 btrfs_delalloc_release_space(inode, data_reserved,
2261 page_start, PAGE_SIZE,
2269 * We can't mess with the page state unless it is locked, so now that
2270 * it is locked bail if we failed to make our space reservation.
2275 lock_extent_bits(&BTRFS_I(inode)->io_tree, page_start, page_end,
2278 /* already ordered? We're done */
2279 if (PagePrivate2(page))
2282 ordered = btrfs_lookup_ordered_range(BTRFS_I(inode), page_start,
2285 unlock_extent_cached(&BTRFS_I(inode)->io_tree, page_start,
2286 page_end, &cached_state);
2288 btrfs_start_ordered_extent(inode, ordered, 1);
2289 btrfs_put_ordered_extent(ordered);
2293 ret = btrfs_set_extent_delalloc(inode, page_start, page_end, 0,
2299 * Everything went as planned, we're now the owner of a dirty page with
2300 * delayed allocation bits set and space reserved for our COW
2303 * The page was dirty when we started, nothing should have cleaned it.
2305 BUG_ON(!PageDirty(page));
2306 free_delalloc_space = false;
2308 btrfs_delalloc_release_extents(BTRFS_I(inode), PAGE_SIZE);
2309 if (free_delalloc_space)
2310 btrfs_delalloc_release_space(inode, data_reserved, page_start,
2312 unlock_extent_cached(&BTRFS_I(inode)->io_tree, page_start, page_end,
2317 * We hit ENOSPC or other errors. Update the mapping and page
2318 * to reflect the errors and clean the page.
2320 mapping_set_error(page->mapping, ret);
2321 end_extent_writepage(page, ret, page_start, page_end);
2322 clear_page_dirty_for_io(page);
2325 ClearPageChecked(page);
2329 extent_changeset_free(data_reserved);
2331 * As a precaution, do a delayed iput in case it would be the last iput
2332 * that could need flushing space. Recursing back to fixup worker would
2335 btrfs_add_delayed_iput(inode);
2339 * There are a few paths in the higher layers of the kernel that directly
2340 * set the page dirty bit without asking the filesystem if it is a
2341 * good idea. This causes problems because we want to make sure COW
2342 * properly happens and the data=ordered rules are followed.
2344 * In our case any range that doesn't have the ORDERED bit set
2345 * hasn't been properly setup for IO. We kick off an async process
2346 * to fix it up. The async helper will wait for ordered extents, set
2347 * the delalloc bit and make it safe to write the page.
2349 int btrfs_writepage_cow_fixup(struct page *page, u64 start, u64 end)
2351 struct inode *inode = page->mapping->host;
2352 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2353 struct btrfs_writepage_fixup *fixup;
2355 /* this page is properly in the ordered list */
2356 if (TestClearPagePrivate2(page))
2360 * PageChecked is set below when we create a fixup worker for this page,
2361 * don't try to create another one if we're already PageChecked()
2363 * The extent_io writepage code will redirty the page if we send back
2366 if (PageChecked(page))
2369 fixup = kzalloc(sizeof(*fixup), GFP_NOFS);
2374 * We are already holding a reference to this inode from
2375 * write_cache_pages. We need to hold it because the space reservation
2376 * takes place outside of the page lock, and we can't trust
2377 * page->mapping outside of the page lock.
2380 SetPageChecked(page);
2382 btrfs_init_work(&fixup->work, btrfs_writepage_fixup_worker, NULL, NULL);
2384 fixup->inode = inode;
2385 btrfs_queue_work(fs_info->fixup_workers, &fixup->work);
2390 static int insert_reserved_file_extent(struct btrfs_trans_handle *trans,
2391 struct inode *inode, u64 file_pos,
2392 u64 disk_bytenr, u64 disk_num_bytes,
2393 u64 num_bytes, u64 ram_bytes,
2394 u8 compression, u8 encryption,
2395 u16 other_encoding, int extent_type)
2397 struct btrfs_root *root = BTRFS_I(inode)->root;
2398 struct btrfs_file_extent_item *fi;
2399 struct btrfs_path *path;
2400 struct extent_buffer *leaf;
2401 struct btrfs_key ins;
2403 int extent_inserted = 0;
2406 path = btrfs_alloc_path();
2411 * we may be replacing one extent in the tree with another.
2412 * The new extent is pinned in the extent map, and we don't want
2413 * to drop it from the cache until it is completely in the btree.
2415 * So, tell btrfs_drop_extents to leave this extent in the cache.
2416 * the caller is expected to unpin it and allow it to be merged
2419 ret = __btrfs_drop_extents(trans, root, inode, path, file_pos,
2420 file_pos + num_bytes, NULL, 0,
2421 1, sizeof(*fi), &extent_inserted);
2425 if (!extent_inserted) {
2426 ins.objectid = btrfs_ino(BTRFS_I(inode));
2427 ins.offset = file_pos;
2428 ins.type = BTRFS_EXTENT_DATA_KEY;
2430 path->leave_spinning = 1;
2431 ret = btrfs_insert_empty_item(trans, root, path, &ins,
2436 leaf = path->nodes[0];
2437 fi = btrfs_item_ptr(leaf, path->slots[0],
2438 struct btrfs_file_extent_item);
2439 btrfs_set_file_extent_generation(leaf, fi, trans->transid);
2440 btrfs_set_file_extent_type(leaf, fi, extent_type);
2441 btrfs_set_file_extent_disk_bytenr(leaf, fi, disk_bytenr);
2442 btrfs_set_file_extent_disk_num_bytes(leaf, fi, disk_num_bytes);
2443 btrfs_set_file_extent_offset(leaf, fi, 0);
2444 btrfs_set_file_extent_num_bytes(leaf, fi, num_bytes);
2445 btrfs_set_file_extent_ram_bytes(leaf, fi, ram_bytes);
2446 btrfs_set_file_extent_compression(leaf, fi, compression);
2447 btrfs_set_file_extent_encryption(leaf, fi, encryption);
2448 btrfs_set_file_extent_other_encoding(leaf, fi, other_encoding);
2450 btrfs_mark_buffer_dirty(leaf);
2451 btrfs_release_path(path);
2453 inode_add_bytes(inode, num_bytes);
2455 ins.objectid = disk_bytenr;
2456 ins.offset = disk_num_bytes;
2457 ins.type = BTRFS_EXTENT_ITEM_KEY;
2459 ret = btrfs_inode_set_file_extent_range(BTRFS_I(inode), file_pos,
2465 * Release the reserved range from inode dirty range map, as it is
2466 * already moved into delayed_ref_head
2468 ret = btrfs_qgroup_release_data(inode, file_pos, ram_bytes);
2472 ret = btrfs_alloc_reserved_file_extent(trans, root,
2473 btrfs_ino(BTRFS_I(inode)),
2474 file_pos, qg_released, &ins);
2476 btrfs_free_path(path);
2481 static void btrfs_release_delalloc_bytes(struct btrfs_fs_info *fs_info,
2484 struct btrfs_block_group *cache;
2486 cache = btrfs_lookup_block_group(fs_info, start);
2489 spin_lock(&cache->lock);
2490 cache->delalloc_bytes -= len;
2491 spin_unlock(&cache->lock);
2493 btrfs_put_block_group(cache);
2496 /* as ordered data IO finishes, this gets called so we can finish
2497 * an ordered extent if the range of bytes in the file it covers are
2500 static int btrfs_finish_ordered_io(struct btrfs_ordered_extent *ordered_extent)
2502 struct inode *inode = ordered_extent->inode;
2503 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2504 struct btrfs_root *root = BTRFS_I(inode)->root;
2505 struct btrfs_trans_handle *trans = NULL;
2506 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
2507 struct extent_state *cached_state = NULL;
2509 int compress_type = 0;
2511 u64 logical_len = ordered_extent->num_bytes;
2512 bool freespace_inode;
2513 bool truncated = false;
2514 bool range_locked = false;
2515 bool clear_new_delalloc_bytes = false;
2516 bool clear_reserved_extent = true;
2517 unsigned int clear_bits;
2519 start = ordered_extent->file_offset;
2520 end = start + ordered_extent->num_bytes - 1;
2522 if (!test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags) &&
2523 !test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags) &&
2524 !test_bit(BTRFS_ORDERED_DIRECT, &ordered_extent->flags))
2525 clear_new_delalloc_bytes = true;
2527 freespace_inode = btrfs_is_free_space_inode(BTRFS_I(inode));
2529 if (test_bit(BTRFS_ORDERED_IOERR, &ordered_extent->flags)) {
2534 btrfs_free_io_failure_record(BTRFS_I(inode), start, end);
2536 if (test_bit(BTRFS_ORDERED_TRUNCATED, &ordered_extent->flags)) {
2538 logical_len = ordered_extent->truncated_len;
2539 /* Truncated the entire extent, don't bother adding */
2544 if (test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags)) {
2545 BUG_ON(!list_empty(&ordered_extent->list)); /* Logic error */
2548 * For mwrite(mmap + memset to write) case, we still reserve
2549 * space for NOCOW range.
2550 * As NOCOW won't cause a new delayed ref, just free the space
2552 btrfs_qgroup_free_data(inode, NULL, start,
2553 ordered_extent->num_bytes);
2554 btrfs_inode_safe_disk_i_size_write(inode, 0);
2555 if (freespace_inode)
2556 trans = btrfs_join_transaction_spacecache(root);
2558 trans = btrfs_join_transaction(root);
2559 if (IS_ERR(trans)) {
2560 ret = PTR_ERR(trans);
2564 trans->block_rsv = &BTRFS_I(inode)->block_rsv;
2565 ret = btrfs_update_inode_fallback(trans, root, inode);
2566 if (ret) /* -ENOMEM or corruption */
2567 btrfs_abort_transaction(trans, ret);
2571 range_locked = true;
2572 lock_extent_bits(io_tree, start, end, &cached_state);
2574 if (freespace_inode)
2575 trans = btrfs_join_transaction_spacecache(root);
2577 trans = btrfs_join_transaction(root);
2578 if (IS_ERR(trans)) {
2579 ret = PTR_ERR(trans);
2584 trans->block_rsv = &BTRFS_I(inode)->block_rsv;
2586 if (test_bit(BTRFS_ORDERED_COMPRESSED, &ordered_extent->flags))
2587 compress_type = ordered_extent->compress_type;
2588 if (test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags)) {
2589 BUG_ON(compress_type);
2590 btrfs_qgroup_free_data(inode, NULL, start,
2591 ordered_extent->num_bytes);
2592 ret = btrfs_mark_extent_written(trans, BTRFS_I(inode),
2593 ordered_extent->file_offset,
2594 ordered_extent->file_offset +
2597 BUG_ON(root == fs_info->tree_root);
2598 ret = insert_reserved_file_extent(trans, inode, start,
2599 ordered_extent->disk_bytenr,
2600 ordered_extent->disk_num_bytes,
2601 logical_len, logical_len,
2602 compress_type, 0, 0,
2603 BTRFS_FILE_EXTENT_REG);
2605 clear_reserved_extent = false;
2606 btrfs_release_delalloc_bytes(fs_info,
2607 ordered_extent->disk_bytenr,
2608 ordered_extent->disk_num_bytes);
2611 unpin_extent_cache(&BTRFS_I(inode)->extent_tree,
2612 ordered_extent->file_offset,
2613 ordered_extent->num_bytes, trans->transid);
2615 btrfs_abort_transaction(trans, ret);
2619 ret = add_pending_csums(trans, inode, &ordered_extent->list);
2621 btrfs_abort_transaction(trans, ret);
2625 btrfs_inode_safe_disk_i_size_write(inode, 0);
2626 ret = btrfs_update_inode_fallback(trans, root, inode);
2627 if (ret) { /* -ENOMEM or corruption */
2628 btrfs_abort_transaction(trans, ret);
2633 clear_bits = EXTENT_DEFRAG;
2635 clear_bits |= EXTENT_LOCKED;
2636 if (clear_new_delalloc_bytes)
2637 clear_bits |= EXTENT_DELALLOC_NEW;
2638 clear_extent_bit(&BTRFS_I(inode)->io_tree, start, end, clear_bits,
2639 (clear_bits & EXTENT_LOCKED) ? 1 : 0, 0,
2643 btrfs_end_transaction(trans);
2645 if (ret || truncated) {
2646 u64 unwritten_start = start;
2649 unwritten_start += logical_len;
2650 clear_extent_uptodate(io_tree, unwritten_start, end, NULL);
2652 /* Drop the cache for the part of the extent we didn't write. */
2653 btrfs_drop_extent_cache(BTRFS_I(inode), unwritten_start, end, 0);
2656 * If the ordered extent had an IOERR or something else went
2657 * wrong we need to return the space for this ordered extent
2658 * back to the allocator. We only free the extent in the
2659 * truncated case if we didn't write out the extent at all.
2661 * If we made it past insert_reserved_file_extent before we
2662 * errored out then we don't need to do this as the accounting
2663 * has already been done.
2665 if ((ret || !logical_len) &&
2666 clear_reserved_extent &&
2667 !test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags) &&
2668 !test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags)) {
2670 * Discard the range before returning it back to the
2673 if (ret && btrfs_test_opt(fs_info, DISCARD_SYNC))
2674 btrfs_discard_extent(fs_info,
2675 ordered_extent->disk_bytenr,
2676 ordered_extent->disk_num_bytes,
2678 btrfs_free_reserved_extent(fs_info,
2679 ordered_extent->disk_bytenr,
2680 ordered_extent->disk_num_bytes, 1);
2685 * This needs to be done to make sure anybody waiting knows we are done
2686 * updating everything for this ordered extent.
2688 btrfs_remove_ordered_extent(inode, ordered_extent);
2691 btrfs_put_ordered_extent(ordered_extent);
2692 /* once for the tree */
2693 btrfs_put_ordered_extent(ordered_extent);
2698 static void finish_ordered_fn(struct btrfs_work *work)
2700 struct btrfs_ordered_extent *ordered_extent;
2701 ordered_extent = container_of(work, struct btrfs_ordered_extent, work);
2702 btrfs_finish_ordered_io(ordered_extent);
2705 void btrfs_writepage_endio_finish_ordered(struct page *page, u64 start,
2706 u64 end, int uptodate)
2708 struct inode *inode = page->mapping->host;
2709 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2710 struct btrfs_ordered_extent *ordered_extent = NULL;
2711 struct btrfs_workqueue *wq;
2713 trace_btrfs_writepage_end_io_hook(page, start, end, uptodate);
2715 ClearPagePrivate2(page);
2716 if (!btrfs_dec_test_ordered_pending(inode, &ordered_extent, start,
2717 end - start + 1, uptodate))
2720 if (btrfs_is_free_space_inode(BTRFS_I(inode)))
2721 wq = fs_info->endio_freespace_worker;
2723 wq = fs_info->endio_write_workers;
2725 btrfs_init_work(&ordered_extent->work, finish_ordered_fn, NULL, NULL);
2726 btrfs_queue_work(wq, &ordered_extent->work);
2729 static int check_data_csum(struct inode *inode, struct btrfs_io_bio *io_bio,
2730 int icsum, struct page *page, int pgoff, u64 start,
2733 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2734 SHASH_DESC_ON_STACK(shash, fs_info->csum_shash);
2736 u16 csum_size = btrfs_super_csum_size(fs_info->super_copy);
2738 u8 csum[BTRFS_CSUM_SIZE];
2740 csum_expected = ((u8 *)io_bio->csum) + icsum * csum_size;
2742 kaddr = kmap_atomic(page);
2743 shash->tfm = fs_info->csum_shash;
2745 crypto_shash_digest(shash, kaddr + pgoff, len, csum);
2747 if (memcmp(csum, csum_expected, csum_size))
2750 kunmap_atomic(kaddr);
2753 btrfs_print_data_csum_error(BTRFS_I(inode), start, csum, csum_expected,
2754 io_bio->mirror_num);
2755 memset(kaddr + pgoff, 1, len);
2756 flush_dcache_page(page);
2757 kunmap_atomic(kaddr);
2762 * when reads are done, we need to check csums to verify the data is correct
2763 * if there's a match, we allow the bio to finish. If not, the code in
2764 * extent_io.c will try to find good copies for us.
2766 static int btrfs_readpage_end_io_hook(struct btrfs_io_bio *io_bio,
2767 u64 phy_offset, struct page *page,
2768 u64 start, u64 end, int mirror)
2770 size_t offset = start - page_offset(page);
2771 struct inode *inode = page->mapping->host;
2772 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
2773 struct btrfs_root *root = BTRFS_I(inode)->root;
2775 if (PageChecked(page)) {
2776 ClearPageChecked(page);
2780 if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)
2783 if (root->root_key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID &&
2784 test_range_bit(io_tree, start, end, EXTENT_NODATASUM, 1, NULL)) {
2785 clear_extent_bits(io_tree, start, end, EXTENT_NODATASUM);
2789 phy_offset >>= inode->i_sb->s_blocksize_bits;
2790 return check_data_csum(inode, io_bio, phy_offset, page, offset, start,
2791 (size_t)(end - start + 1));
2795 * btrfs_add_delayed_iput - perform a delayed iput on @inode
2797 * @inode: The inode we want to perform iput on
2799 * This function uses the generic vfs_inode::i_count to track whether we should
2800 * just decrement it (in case it's > 1) or if this is the last iput then link
2801 * the inode to the delayed iput machinery. Delayed iputs are processed at
2802 * transaction commit time/superblock commit/cleaner kthread.
2804 void btrfs_add_delayed_iput(struct inode *inode)
2806 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2807 struct btrfs_inode *binode = BTRFS_I(inode);
2809 if (atomic_add_unless(&inode->i_count, -1, 1))
2812 atomic_inc(&fs_info->nr_delayed_iputs);
2813 spin_lock(&fs_info->delayed_iput_lock);
2814 ASSERT(list_empty(&binode->delayed_iput));
2815 list_add_tail(&binode->delayed_iput, &fs_info->delayed_iputs);
2816 spin_unlock(&fs_info->delayed_iput_lock);
2817 if (!test_bit(BTRFS_FS_CLEANER_RUNNING, &fs_info->flags))
2818 wake_up_process(fs_info->cleaner_kthread);
2821 static void run_delayed_iput_locked(struct btrfs_fs_info *fs_info,
2822 struct btrfs_inode *inode)
2824 list_del_init(&inode->delayed_iput);
2825 spin_unlock(&fs_info->delayed_iput_lock);
2826 iput(&inode->vfs_inode);
2827 if (atomic_dec_and_test(&fs_info->nr_delayed_iputs))
2828 wake_up(&fs_info->delayed_iputs_wait);
2829 spin_lock(&fs_info->delayed_iput_lock);
2832 static void btrfs_run_delayed_iput(struct btrfs_fs_info *fs_info,
2833 struct btrfs_inode *inode)
2835 if (!list_empty(&inode->delayed_iput)) {
2836 spin_lock(&fs_info->delayed_iput_lock);
2837 if (!list_empty(&inode->delayed_iput))
2838 run_delayed_iput_locked(fs_info, inode);
2839 spin_unlock(&fs_info->delayed_iput_lock);
2843 void btrfs_run_delayed_iputs(struct btrfs_fs_info *fs_info)
2846 spin_lock(&fs_info->delayed_iput_lock);
2847 while (!list_empty(&fs_info->delayed_iputs)) {
2848 struct btrfs_inode *inode;
2850 inode = list_first_entry(&fs_info->delayed_iputs,
2851 struct btrfs_inode, delayed_iput);
2852 run_delayed_iput_locked(fs_info, inode);
2854 spin_unlock(&fs_info->delayed_iput_lock);
2858 * btrfs_wait_on_delayed_iputs - wait on the delayed iputs to be done running
2859 * @fs_info - the fs_info for this fs
2860 * @return - EINTR if we were killed, 0 if nothing's pending
2862 * This will wait on any delayed iputs that are currently running with KILLABLE
2863 * set. Once they are all done running we will return, unless we are killed in
2864 * which case we return EINTR. This helps in user operations like fallocate etc
2865 * that might get blocked on the iputs.
2867 int btrfs_wait_on_delayed_iputs(struct btrfs_fs_info *fs_info)
2869 int ret = wait_event_killable(fs_info->delayed_iputs_wait,
2870 atomic_read(&fs_info->nr_delayed_iputs) == 0);
2877 * This creates an orphan entry for the given inode in case something goes wrong
2878 * in the middle of an unlink.
2880 int btrfs_orphan_add(struct btrfs_trans_handle *trans,
2881 struct btrfs_inode *inode)
2885 ret = btrfs_insert_orphan_item(trans, inode->root, btrfs_ino(inode));
2886 if (ret && ret != -EEXIST) {
2887 btrfs_abort_transaction(trans, ret);
2895 * We have done the delete so we can go ahead and remove the orphan item for
2896 * this particular inode.
2898 static int btrfs_orphan_del(struct btrfs_trans_handle *trans,
2899 struct btrfs_inode *inode)
2901 return btrfs_del_orphan_item(trans, inode->root, btrfs_ino(inode));
2905 * this cleans up any orphans that may be left on the list from the last use
2908 int btrfs_orphan_cleanup(struct btrfs_root *root)
2910 struct btrfs_fs_info *fs_info = root->fs_info;
2911 struct btrfs_path *path;
2912 struct extent_buffer *leaf;
2913 struct btrfs_key key, found_key;
2914 struct btrfs_trans_handle *trans;
2915 struct inode *inode;
2916 u64 last_objectid = 0;
2917 int ret = 0, nr_unlink = 0;
2919 if (cmpxchg(&root->orphan_cleanup_state, 0, ORPHAN_CLEANUP_STARTED))
2922 path = btrfs_alloc_path();
2927 path->reada = READA_BACK;
2929 key.objectid = BTRFS_ORPHAN_OBJECTID;
2930 key.type = BTRFS_ORPHAN_ITEM_KEY;
2931 key.offset = (u64)-1;
2934 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2939 * if ret == 0 means we found what we were searching for, which
2940 * is weird, but possible, so only screw with path if we didn't
2941 * find the key and see if we have stuff that matches
2945 if (path->slots[0] == 0)
2950 /* pull out the item */
2951 leaf = path->nodes[0];
2952 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
2954 /* make sure the item matches what we want */
2955 if (found_key.objectid != BTRFS_ORPHAN_OBJECTID)
2957 if (found_key.type != BTRFS_ORPHAN_ITEM_KEY)
2960 /* release the path since we're done with it */
2961 btrfs_release_path(path);
2964 * this is where we are basically btrfs_lookup, without the
2965 * crossing root thing. we store the inode number in the
2966 * offset of the orphan item.
2969 if (found_key.offset == last_objectid) {
2971 "Error removing orphan entry, stopping orphan cleanup");
2976 last_objectid = found_key.offset;
2978 found_key.objectid = found_key.offset;
2979 found_key.type = BTRFS_INODE_ITEM_KEY;
2980 found_key.offset = 0;
2981 inode = btrfs_iget(fs_info->sb, last_objectid, root);
2982 ret = PTR_ERR_OR_ZERO(inode);
2983 if (ret && ret != -ENOENT)
2986 if (ret == -ENOENT && root == fs_info->tree_root) {
2987 struct btrfs_root *dead_root;
2988 struct btrfs_fs_info *fs_info = root->fs_info;
2989 int is_dead_root = 0;
2992 * this is an orphan in the tree root. Currently these
2993 * could come from 2 sources:
2994 * a) a snapshot deletion in progress
2995 * b) a free space cache inode
2996 * We need to distinguish those two, as the snapshot
2997 * orphan must not get deleted.
2998 * find_dead_roots already ran before us, so if this
2999 * is a snapshot deletion, we should find the root
3000 * in the fs_roots radix tree.
3003 spin_lock(&fs_info->fs_roots_radix_lock);
3004 dead_root = radix_tree_lookup(&fs_info->fs_roots_radix,
3005 (unsigned long)found_key.objectid);
3006 if (dead_root && btrfs_root_refs(&dead_root->root_item) == 0)
3008 spin_unlock(&fs_info->fs_roots_radix_lock);
3011 /* prevent this orphan from being found again */
3012 key.offset = found_key.objectid - 1;
3019 * If we have an inode with links, there are a couple of
3020 * possibilities. Old kernels (before v3.12) used to create an
3021 * orphan item for truncate indicating that there were possibly
3022 * extent items past i_size that needed to be deleted. In v3.12,
3023 * truncate was changed to update i_size in sync with the extent
3024 * items, but the (useless) orphan item was still created. Since
3025 * v4.18, we don't create the orphan item for truncate at all.
3027 * So, this item could mean that we need to do a truncate, but
3028 * only if this filesystem was last used on a pre-v3.12 kernel
3029 * and was not cleanly unmounted. The odds of that are quite
3030 * slim, and it's a pain to do the truncate now, so just delete
3033 * It's also possible that this orphan item was supposed to be
3034 * deleted but wasn't. The inode number may have been reused,
3035 * but either way, we can delete the orphan item.
3037 if (ret == -ENOENT || inode->i_nlink) {
3040 trans = btrfs_start_transaction(root, 1);
3041 if (IS_ERR(trans)) {
3042 ret = PTR_ERR(trans);
3045 btrfs_debug(fs_info, "auto deleting %Lu",
3046 found_key.objectid);
3047 ret = btrfs_del_orphan_item(trans, root,
3048 found_key.objectid);
3049 btrfs_end_transaction(trans);
3057 /* this will do delete_inode and everything for us */
3060 /* release the path since we're done with it */
3061 btrfs_release_path(path);
3063 root->orphan_cleanup_state = ORPHAN_CLEANUP_DONE;
3065 if (test_bit(BTRFS_ROOT_ORPHAN_ITEM_INSERTED, &root->state)) {
3066 trans = btrfs_join_transaction(root);
3068 btrfs_end_transaction(trans);
3072 btrfs_debug(fs_info, "unlinked %d orphans", nr_unlink);
3076 btrfs_err(fs_info, "could not do orphan cleanup %d", ret);
3077 btrfs_free_path(path);
3082 * very simple check to peek ahead in the leaf looking for xattrs. If we
3083 * don't find any xattrs, we know there can't be any acls.
3085 * slot is the slot the inode is in, objectid is the objectid of the inode
3087 static noinline int acls_after_inode_item(struct extent_buffer *leaf,
3088 int slot, u64 objectid,
3089 int *first_xattr_slot)
3091 u32 nritems = btrfs_header_nritems(leaf);
3092 struct btrfs_key found_key;
3093 static u64 xattr_access = 0;
3094 static u64 xattr_default = 0;
3097 if (!xattr_access) {
3098 xattr_access = btrfs_name_hash(XATTR_NAME_POSIX_ACL_ACCESS,
3099 strlen(XATTR_NAME_POSIX_ACL_ACCESS));
3100 xattr_default = btrfs_name_hash(XATTR_NAME_POSIX_ACL_DEFAULT,
3101 strlen(XATTR_NAME_POSIX_ACL_DEFAULT));
3105 *first_xattr_slot = -1;
3106 while (slot < nritems) {
3107 btrfs_item_key_to_cpu(leaf, &found_key, slot);
3109 /* we found a different objectid, there must not be acls */
3110 if (found_key.objectid != objectid)
3113 /* we found an xattr, assume we've got an acl */
3114 if (found_key.type == BTRFS_XATTR_ITEM_KEY) {
3115 if (*first_xattr_slot == -1)
3116 *first_xattr_slot = slot;
3117 if (found_key.offset == xattr_access ||
3118 found_key.offset == xattr_default)
3123 * we found a key greater than an xattr key, there can't
3124 * be any acls later on
3126 if (found_key.type > BTRFS_XATTR_ITEM_KEY)
3133 * it goes inode, inode backrefs, xattrs, extents,
3134 * so if there are a ton of hard links to an inode there can
3135 * be a lot of backrefs. Don't waste time searching too hard,
3136 * this is just an optimization
3141 /* we hit the end of the leaf before we found an xattr or
3142 * something larger than an xattr. We have to assume the inode
3145 if (*first_xattr_slot == -1)
3146 *first_xattr_slot = slot;
3151 * read an inode from the btree into the in-memory inode
3153 static int btrfs_read_locked_inode(struct inode *inode,
3154 struct btrfs_path *in_path)
3156 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
3157 struct btrfs_path *path = in_path;
3158 struct extent_buffer *leaf;
3159 struct btrfs_inode_item *inode_item;
3160 struct btrfs_root *root = BTRFS_I(inode)->root;
3161 struct btrfs_key location;
3166 bool filled = false;
3167 int first_xattr_slot;
3169 ret = btrfs_fill_inode(inode, &rdev);
3174 path = btrfs_alloc_path();
3179 memcpy(&location, &BTRFS_I(inode)->location, sizeof(location));
3181 ret = btrfs_lookup_inode(NULL, root, path, &location, 0);
3183 if (path != in_path)
3184 btrfs_free_path(path);
3188 leaf = path->nodes[0];
3193 inode_item = btrfs_item_ptr(leaf, path->slots[0],
3194 struct btrfs_inode_item);
3195 inode->i_mode = btrfs_inode_mode(leaf, inode_item);
3196 set_nlink(inode, btrfs_inode_nlink(leaf, inode_item));
3197 i_uid_write(inode, btrfs_inode_uid(leaf, inode_item));
3198 i_gid_write(inode, btrfs_inode_gid(leaf, inode_item));
3199 btrfs_i_size_write(BTRFS_I(inode), btrfs_inode_size(leaf, inode_item));
3200 btrfs_inode_set_file_extent_range(BTRFS_I(inode), 0,
3201 round_up(i_size_read(inode), fs_info->sectorsize));
3203 inode->i_atime.tv_sec = btrfs_timespec_sec(leaf, &inode_item->atime);
3204 inode->i_atime.tv_nsec = btrfs_timespec_nsec(leaf, &inode_item->atime);
3206 inode->i_mtime.tv_sec = btrfs_timespec_sec(leaf, &inode_item->mtime);
3207 inode->i_mtime.tv_nsec = btrfs_timespec_nsec(leaf, &inode_item->mtime);
3209 inode->i_ctime.tv_sec = btrfs_timespec_sec(leaf, &inode_item->ctime);
3210 inode->i_ctime.tv_nsec = btrfs_timespec_nsec(leaf, &inode_item->ctime);
3212 BTRFS_I(inode)->i_otime.tv_sec =
3213 btrfs_timespec_sec(leaf, &inode_item->otime);
3214 BTRFS_I(inode)->i_otime.tv_nsec =
3215 btrfs_timespec_nsec(leaf, &inode_item->otime);
3217 inode_set_bytes(inode, btrfs_inode_nbytes(leaf, inode_item));
3218 BTRFS_I(inode)->generation = btrfs_inode_generation(leaf, inode_item);
3219 BTRFS_I(inode)->last_trans = btrfs_inode_transid(leaf, inode_item);
3221 inode_set_iversion_queried(inode,
3222 btrfs_inode_sequence(leaf, inode_item));
3223 inode->i_generation = BTRFS_I(inode)->generation;
3225 rdev = btrfs_inode_rdev(leaf, inode_item);
3227 BTRFS_I(inode)->index_cnt = (u64)-1;
3228 BTRFS_I(inode)->flags = btrfs_inode_flags(leaf, inode_item);
3232 * If we were modified in the current generation and evicted from memory
3233 * and then re-read we need to do a full sync since we don't have any
3234 * idea about which extents were modified before we were evicted from
3237 * This is required for both inode re-read from disk and delayed inode
3238 * in delayed_nodes_tree.
3240 if (BTRFS_I(inode)->last_trans == fs_info->generation)
3241 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
3242 &BTRFS_I(inode)->runtime_flags);
3245 * We don't persist the id of the transaction where an unlink operation
3246 * against the inode was last made. So here we assume the inode might
3247 * have been evicted, and therefore the exact value of last_unlink_trans
3248 * lost, and set it to last_trans to avoid metadata inconsistencies
3249 * between the inode and its parent if the inode is fsync'ed and the log
3250 * replayed. For example, in the scenario:
3253 * ln mydir/foo mydir/bar
3256 * echo 2 > /proc/sys/vm/drop_caches # evicts inode
3257 * xfs_io -c fsync mydir/foo
3259 * mount fs, triggers fsync log replay
3261 * We must make sure that when we fsync our inode foo we also log its
3262 * parent inode, otherwise after log replay the parent still has the
3263 * dentry with the "bar" name but our inode foo has a link count of 1
3264 * and doesn't have an inode ref with the name "bar" anymore.
3266 * Setting last_unlink_trans to last_trans is a pessimistic approach,
3267 * but it guarantees correctness at the expense of occasional full
3268 * transaction commits on fsync if our inode is a directory, or if our
3269 * inode is not a directory, logging its parent unnecessarily.
3271 BTRFS_I(inode)->last_unlink_trans = BTRFS_I(inode)->last_trans;
3274 if (inode->i_nlink != 1 ||
3275 path->slots[0] >= btrfs_header_nritems(leaf))
3278 btrfs_item_key_to_cpu(leaf, &location, path->slots[0]);
3279 if (location.objectid != btrfs_ino(BTRFS_I(inode)))
3282 ptr = btrfs_item_ptr_offset(leaf, path->slots[0]);
3283 if (location.type == BTRFS_INODE_REF_KEY) {
3284 struct btrfs_inode_ref *ref;
3286 ref = (struct btrfs_inode_ref *)ptr;
3287 BTRFS_I(inode)->dir_index = btrfs_inode_ref_index(leaf, ref);
3288 } else if (location.type == BTRFS_INODE_EXTREF_KEY) {
3289 struct btrfs_inode_extref *extref;
3291 extref = (struct btrfs_inode_extref *)ptr;
3292 BTRFS_I(inode)->dir_index = btrfs_inode_extref_index(leaf,
3297 * try to precache a NULL acl entry for files that don't have
3298 * any xattrs or acls
3300 maybe_acls = acls_after_inode_item(leaf, path->slots[0],
3301 btrfs_ino(BTRFS_I(inode)), &first_xattr_slot);
3302 if (first_xattr_slot != -1) {
3303 path->slots[0] = first_xattr_slot;
3304 ret = btrfs_load_inode_props(inode, path);
3307 "error loading props for ino %llu (root %llu): %d",
3308 btrfs_ino(BTRFS_I(inode)),
3309 root->root_key.objectid, ret);
3311 if (path != in_path)
3312 btrfs_free_path(path);
3315 cache_no_acl(inode);
3317 switch (inode->i_mode & S_IFMT) {
3319 inode->i_mapping->a_ops = &btrfs_aops;
3320 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
3321 inode->i_fop = &btrfs_file_operations;
3322 inode->i_op = &btrfs_file_inode_operations;
3325 inode->i_fop = &btrfs_dir_file_operations;
3326 inode->i_op = &btrfs_dir_inode_operations;
3329 inode->i_op = &btrfs_symlink_inode_operations;
3330 inode_nohighmem(inode);
3331 inode->i_mapping->a_ops = &btrfs_aops;
3334 inode->i_op = &btrfs_special_inode_operations;
3335 init_special_inode(inode, inode->i_mode, rdev);
3339 btrfs_sync_inode_flags_to_i_flags(inode);
3344 * given a leaf and an inode, copy the inode fields into the leaf
3346 static void fill_inode_item(struct btrfs_trans_handle *trans,
3347 struct extent_buffer *leaf,
3348 struct btrfs_inode_item *item,
3349 struct inode *inode)
3351 struct btrfs_map_token token;
3353 btrfs_init_map_token(&token, leaf);
3355 btrfs_set_token_inode_uid(&token, item, i_uid_read(inode));
3356 btrfs_set_token_inode_gid(&token, item, i_gid_read(inode));
3357 btrfs_set_token_inode_size(&token, item, BTRFS_I(inode)->disk_i_size);
3358 btrfs_set_token_inode_mode(&token, item, inode->i_mode);
3359 btrfs_set_token_inode_nlink(&token, item, inode->i_nlink);
3361 btrfs_set_token_timespec_sec(&token, &item->atime,
3362 inode->i_atime.tv_sec);
3363 btrfs_set_token_timespec_nsec(&token, &item->atime,
3364 inode->i_atime.tv_nsec);
3366 btrfs_set_token_timespec_sec(&token, &item->mtime,
3367 inode->i_mtime.tv_sec);
3368 btrfs_set_token_timespec_nsec(&token, &item->mtime,
3369 inode->i_mtime.tv_nsec);
3371 btrfs_set_token_timespec_sec(&token, &item->ctime,
3372 inode->i_ctime.tv_sec);
3373 btrfs_set_token_timespec_nsec(&token, &item->ctime,
3374 inode->i_ctime.tv_nsec);
3376 btrfs_set_token_timespec_sec(&token, &item->otime,
3377 BTRFS_I(inode)->i_otime.tv_sec);
3378 btrfs_set_token_timespec_nsec(&token, &item->otime,
3379 BTRFS_I(inode)->i_otime.tv_nsec);
3381 btrfs_set_token_inode_nbytes(&token, item, inode_get_bytes(inode));
3382 btrfs_set_token_inode_generation(&token, item,
3383 BTRFS_I(inode)->generation);
3384 btrfs_set_token_inode_sequence(&token, item, inode_peek_iversion(inode));
3385 btrfs_set_token_inode_transid(&token, item, trans->transid);
3386 btrfs_set_token_inode_rdev(&token, item, inode->i_rdev);
3387 btrfs_set_token_inode_flags(&token, item, BTRFS_I(inode)->flags);
3388 btrfs_set_token_inode_block_group(&token, item, 0);
3392 * copy everything in the in-memory inode into the btree.
3394 static noinline int btrfs_update_inode_item(struct btrfs_trans_handle *trans,
3395 struct btrfs_root *root, struct inode *inode)
3397 struct btrfs_inode_item *inode_item;
3398 struct btrfs_path *path;
3399 struct extent_buffer *leaf;
3402 path = btrfs_alloc_path();
3406 path->leave_spinning = 1;
3407 ret = btrfs_lookup_inode(trans, root, path, &BTRFS_I(inode)->location,
3415 leaf = path->nodes[0];
3416 inode_item = btrfs_item_ptr(leaf, path->slots[0],
3417 struct btrfs_inode_item);
3419 fill_inode_item(trans, leaf, inode_item, inode);
3420 btrfs_mark_buffer_dirty(leaf);
3421 btrfs_set_inode_last_trans(trans, inode);
3424 btrfs_free_path(path);
3429 * copy everything in the in-memory inode into the btree.
3431 noinline int btrfs_update_inode(struct btrfs_trans_handle *trans,
3432 struct btrfs_root *root, struct inode *inode)
3434 struct btrfs_fs_info *fs_info = root->fs_info;
3438 * If the inode is a free space inode, we can deadlock during commit
3439 * if we put it into the delayed code.
3441 * The data relocation inode should also be directly updated
3444 if (!btrfs_is_free_space_inode(BTRFS_I(inode))
3445 && root->root_key.objectid != BTRFS_DATA_RELOC_TREE_OBJECTID
3446 && !test_bit(BTRFS_FS_LOG_RECOVERING, &fs_info->flags)) {
3447 btrfs_update_root_times(trans, root);
3449 ret = btrfs_delayed_update_inode(trans, root, inode);
3451 btrfs_set_inode_last_trans(trans, inode);
3455 return btrfs_update_inode_item(trans, root, inode);
3458 noinline int btrfs_update_inode_fallback(struct btrfs_trans_handle *trans,
3459 struct btrfs_root *root,
3460 struct inode *inode)
3464 ret = btrfs_update_inode(trans, root, inode);
3466 return btrfs_update_inode_item(trans, root, inode);
3471 * unlink helper that gets used here in inode.c and in the tree logging
3472 * recovery code. It remove a link in a directory with a given name, and
3473 * also drops the back refs in the inode to the directory
3475 static int __btrfs_unlink_inode(struct btrfs_trans_handle *trans,
3476 struct btrfs_root *root,
3477 struct btrfs_inode *dir,
3478 struct btrfs_inode *inode,
3479 const char *name, int name_len)
3481 struct btrfs_fs_info *fs_info = root->fs_info;
3482 struct btrfs_path *path;
3484 struct btrfs_dir_item *di;
3486 u64 ino = btrfs_ino(inode);
3487 u64 dir_ino = btrfs_ino(dir);
3489 path = btrfs_alloc_path();
3495 path->leave_spinning = 1;
3496 di = btrfs_lookup_dir_item(trans, root, path, dir_ino,
3497 name, name_len, -1);
3498 if (IS_ERR_OR_NULL(di)) {
3499 ret = di ? PTR_ERR(di) : -ENOENT;
3502 ret = btrfs_delete_one_dir_name(trans, root, path, di);
3505 btrfs_release_path(path);
3508 * If we don't have dir index, we have to get it by looking up
3509 * the inode ref, since we get the inode ref, remove it directly,
3510 * it is unnecessary to do delayed deletion.
3512 * But if we have dir index, needn't search inode ref to get it.
3513 * Since the inode ref is close to the inode item, it is better
3514 * that we delay to delete it, and just do this deletion when
3515 * we update the inode item.
3517 if (inode->dir_index) {
3518 ret = btrfs_delayed_delete_inode_ref(inode);
3520 index = inode->dir_index;
3525 ret = btrfs_del_inode_ref(trans, root, name, name_len, ino,
3529 "failed to delete reference to %.*s, inode %llu parent %llu",
3530 name_len, name, ino, dir_ino);
3531 btrfs_abort_transaction(trans, ret);
3535 ret = btrfs_delete_delayed_dir_index(trans, dir, index);
3537 btrfs_abort_transaction(trans, ret);
3541 ret = btrfs_del_inode_ref_in_log(trans, root, name, name_len, inode,
3543 if (ret != 0 && ret != -ENOENT) {
3544 btrfs_abort_transaction(trans, ret);
3548 ret = btrfs_del_dir_entries_in_log(trans, root, name, name_len, dir,
3553 btrfs_abort_transaction(trans, ret);
3556 * If we have a pending delayed iput we could end up with the final iput
3557 * being run in btrfs-cleaner context. If we have enough of these built
3558 * up we can end up burning a lot of time in btrfs-cleaner without any
3559 * way to throttle the unlinks. Since we're currently holding a ref on
3560 * the inode we can run the delayed iput here without any issues as the
3561 * final iput won't be done until after we drop the ref we're currently
3564 btrfs_run_delayed_iput(fs_info, inode);
3566 btrfs_free_path(path);
3570 btrfs_i_size_write(dir, dir->vfs_inode.i_size - name_len * 2);
3571 inode_inc_iversion(&inode->vfs_inode);
3572 inode_inc_iversion(&dir->vfs_inode);
3573 inode->vfs_inode.i_ctime = dir->vfs_inode.i_mtime =
3574 dir->vfs_inode.i_ctime = current_time(&inode->vfs_inode);
3575 ret = btrfs_update_inode(trans, root, &dir->vfs_inode);
3580 int btrfs_unlink_inode(struct btrfs_trans_handle *trans,
3581 struct btrfs_root *root,
3582 struct btrfs_inode *dir, struct btrfs_inode *inode,
3583 const char *name, int name_len)
3586 ret = __btrfs_unlink_inode(trans, root, dir, inode, name, name_len);
3588 drop_nlink(&inode->vfs_inode);
3589 ret = btrfs_update_inode(trans, root, &inode->vfs_inode);
3595 * helper to start transaction for unlink and rmdir.
3597 * unlink and rmdir are special in btrfs, they do not always free space, so
3598 * if we cannot make our reservations the normal way try and see if there is
3599 * plenty of slack room in the global reserve to migrate, otherwise we cannot
3600 * allow the unlink to occur.
3602 static struct btrfs_trans_handle *__unlink_start_trans(struct inode *dir)
3604 struct btrfs_root *root = BTRFS_I(dir)->root;
3607 * 1 for the possible orphan item
3608 * 1 for the dir item
3609 * 1 for the dir index
3610 * 1 for the inode ref
3613 return btrfs_start_transaction_fallback_global_rsv(root, 5);
3616 static int btrfs_unlink(struct inode *dir, struct dentry *dentry)
3618 struct btrfs_root *root = BTRFS_I(dir)->root;
3619 struct btrfs_trans_handle *trans;
3620 struct inode *inode = d_inode(dentry);
3623 trans = __unlink_start_trans(dir);
3625 return PTR_ERR(trans);
3627 btrfs_record_unlink_dir(trans, BTRFS_I(dir), BTRFS_I(d_inode(dentry)),
3630 ret = btrfs_unlink_inode(trans, root, BTRFS_I(dir),
3631 BTRFS_I(d_inode(dentry)), dentry->d_name.name,
3632 dentry->d_name.len);
3636 if (inode->i_nlink == 0) {
3637 ret = btrfs_orphan_add(trans, BTRFS_I(inode));
3643 btrfs_end_transaction(trans);
3644 btrfs_btree_balance_dirty(root->fs_info);
3648 static int btrfs_unlink_subvol(struct btrfs_trans_handle *trans,
3649 struct inode *dir, struct dentry *dentry)
3651 struct btrfs_root *root = BTRFS_I(dir)->root;
3652 struct btrfs_inode *inode = BTRFS_I(d_inode(dentry));
3653 struct btrfs_path *path;
3654 struct extent_buffer *leaf;
3655 struct btrfs_dir_item *di;
3656 struct btrfs_key key;
3657 const char *name = dentry->d_name.name;
3658 int name_len = dentry->d_name.len;
3662 u64 dir_ino = btrfs_ino(BTRFS_I(dir));
3664 if (btrfs_ino(inode) == BTRFS_FIRST_FREE_OBJECTID) {
3665 objectid = inode->root->root_key.objectid;
3666 } else if (btrfs_ino(inode) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID) {
3667 objectid = inode->location.objectid;
3673 path = btrfs_alloc_path();
3677 di = btrfs_lookup_dir_item(trans, root, path, dir_ino,
3678 name, name_len, -1);
3679 if (IS_ERR_OR_NULL(di)) {
3680 ret = di ? PTR_ERR(di) : -ENOENT;
3684 leaf = path->nodes[0];
3685 btrfs_dir_item_key_to_cpu(leaf, di, &key);
3686 WARN_ON(key.type != BTRFS_ROOT_ITEM_KEY || key.objectid != objectid);
3687 ret = btrfs_delete_one_dir_name(trans, root, path, di);
3689 btrfs_abort_transaction(trans, ret);
3692 btrfs_release_path(path);
3695 * This is a placeholder inode for a subvolume we didn't have a
3696 * reference to at the time of the snapshot creation. In the meantime
3697 * we could have renamed the real subvol link into our snapshot, so
3698 * depending on btrfs_del_root_ref to return -ENOENT here is incorret.
3699 * Instead simply lookup the dir_index_item for this entry so we can
3700 * remove it. Otherwise we know we have a ref to the root and we can
3701 * call btrfs_del_root_ref, and it _shouldn't_ fail.
3703 if (btrfs_ino(inode) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID) {
3704 di = btrfs_search_dir_index_item(root, path, dir_ino,
3706 if (IS_ERR_OR_NULL(di)) {
3711 btrfs_abort_transaction(trans, ret);
3715 leaf = path->nodes[0];
3716 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
3718 btrfs_release_path(path);
3720 ret = btrfs_del_root_ref(trans, objectid,
3721 root->root_key.objectid, dir_ino,
3722 &index, name, name_len);
3724 btrfs_abort_transaction(trans, ret);
3729 ret = btrfs_delete_delayed_dir_index(trans, BTRFS_I(dir), index);
3731 btrfs_abort_transaction(trans, ret);
3735 btrfs_i_size_write(BTRFS_I(dir), dir->i_size - name_len * 2);
3736 inode_inc_iversion(dir);
3737 dir->i_mtime = dir->i_ctime = current_time(dir);
3738 ret = btrfs_update_inode_fallback(trans, root, dir);
3740 btrfs_abort_transaction(trans, ret);
3742 btrfs_free_path(path);
3747 * Helper to check if the subvolume references other subvolumes or if it's
3750 static noinline int may_destroy_subvol(struct btrfs_root *root)
3752 struct btrfs_fs_info *fs_info = root->fs_info;
3753 struct btrfs_path *path;
3754 struct btrfs_dir_item *di;
3755 struct btrfs_key key;
3759 path = btrfs_alloc_path();
3763 /* Make sure this root isn't set as the default subvol */
3764 dir_id = btrfs_super_root_dir(fs_info->super_copy);
3765 di = btrfs_lookup_dir_item(NULL, fs_info->tree_root, path,
3766 dir_id, "default", 7, 0);
3767 if (di && !IS_ERR(di)) {
3768 btrfs_dir_item_key_to_cpu(path->nodes[0], di, &key);
3769 if (key.objectid == root->root_key.objectid) {
3772 "deleting default subvolume %llu is not allowed",
3776 btrfs_release_path(path);
3779 key.objectid = root->root_key.objectid;
3780 key.type = BTRFS_ROOT_REF_KEY;
3781 key.offset = (u64)-1;
3783 ret = btrfs_search_slot(NULL, fs_info->tree_root, &key, path, 0, 0);
3789 if (path->slots[0] > 0) {
3791 btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
3792 if (key.objectid == root->root_key.objectid &&
3793 key.type == BTRFS_ROOT_REF_KEY)
3797 btrfs_free_path(path);
3801 /* Delete all dentries for inodes belonging to the root */
3802 static void btrfs_prune_dentries(struct btrfs_root *root)
3804 struct btrfs_fs_info *fs_info = root->fs_info;
3805 struct rb_node *node;
3806 struct rb_node *prev;
3807 struct btrfs_inode *entry;
3808 struct inode *inode;
3811 if (!test_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state))
3812 WARN_ON(btrfs_root_refs(&root->root_item) != 0);
3814 spin_lock(&root->inode_lock);
3816 node = root->inode_tree.rb_node;
3820 entry = rb_entry(node, struct btrfs_inode, rb_node);
3822 if (objectid < btrfs_ino(entry))
3823 node = node->rb_left;
3824 else if (objectid > btrfs_ino(entry))
3825 node = node->rb_right;
3831 entry = rb_entry(prev, struct btrfs_inode, rb_node);
3832 if (objectid <= btrfs_ino(entry)) {
3836 prev = rb_next(prev);
3840 entry = rb_entry(node, struct btrfs_inode, rb_node);
3841 objectid = btrfs_ino(entry) + 1;
3842 inode = igrab(&entry->vfs_inode);
3844 spin_unlock(&root->inode_lock);
3845 if (atomic_read(&inode->i_count) > 1)
3846 d_prune_aliases(inode);
3848 * btrfs_drop_inode will have it removed from the inode
3849 * cache when its usage count hits zero.
3853 spin_lock(&root->inode_lock);
3857 if (cond_resched_lock(&root->inode_lock))
3860 node = rb_next(node);
3862 spin_unlock(&root->inode_lock);
3865 int btrfs_delete_subvolume(struct inode *dir, struct dentry *dentry)
3867 struct btrfs_fs_info *fs_info = btrfs_sb(dentry->d_sb);
3868 struct btrfs_root *root = BTRFS_I(dir)->root;
3869 struct inode *inode = d_inode(dentry);
3870 struct btrfs_root *dest = BTRFS_I(inode)->root;
3871 struct btrfs_trans_handle *trans;
3872 struct btrfs_block_rsv block_rsv;
3878 * Don't allow to delete a subvolume with send in progress. This is
3879 * inside the inode lock so the error handling that has to drop the bit
3880 * again is not run concurrently.
3882 spin_lock(&dest->root_item_lock);
3883 if (dest->send_in_progress) {
3884 spin_unlock(&dest->root_item_lock);
3886 "attempt to delete subvolume %llu during send",
3887 dest->root_key.objectid);
3890 root_flags = btrfs_root_flags(&dest->root_item);
3891 btrfs_set_root_flags(&dest->root_item,
3892 root_flags | BTRFS_ROOT_SUBVOL_DEAD);
3893 spin_unlock(&dest->root_item_lock);
3895 down_write(&fs_info->subvol_sem);
3897 err = may_destroy_subvol(dest);
3901 btrfs_init_block_rsv(&block_rsv, BTRFS_BLOCK_RSV_TEMP);
3903 * One for dir inode,
3904 * two for dir entries,
3905 * two for root ref/backref.
3907 err = btrfs_subvolume_reserve_metadata(root, &block_rsv, 5, true);
3911 trans = btrfs_start_transaction(root, 0);
3912 if (IS_ERR(trans)) {
3913 err = PTR_ERR(trans);
3916 trans->block_rsv = &block_rsv;
3917 trans->bytes_reserved = block_rsv.size;
3919 btrfs_record_snapshot_destroy(trans, BTRFS_I(dir));
3921 ret = btrfs_unlink_subvol(trans, dir, dentry);
3924 btrfs_abort_transaction(trans, ret);
3928 btrfs_record_root_in_trans(trans, dest);
3930 memset(&dest->root_item.drop_progress, 0,
3931 sizeof(dest->root_item.drop_progress));
3932 dest->root_item.drop_level = 0;
3933 btrfs_set_root_refs(&dest->root_item, 0);
3935 if (!test_and_set_bit(BTRFS_ROOT_ORPHAN_ITEM_INSERTED, &dest->state)) {
3936 ret = btrfs_insert_orphan_item(trans,
3938 dest->root_key.objectid);
3940 btrfs_abort_transaction(trans, ret);
3946 ret = btrfs_uuid_tree_remove(trans, dest->root_item.uuid,
3947 BTRFS_UUID_KEY_SUBVOL,
3948 dest->root_key.objectid);
3949 if (ret && ret != -ENOENT) {
3950 btrfs_abort_transaction(trans, ret);
3954 if (!btrfs_is_empty_uuid(dest->root_item.received_uuid)) {
3955 ret = btrfs_uuid_tree_remove(trans,
3956 dest->root_item.received_uuid,
3957 BTRFS_UUID_KEY_RECEIVED_SUBVOL,
3958 dest->root_key.objectid);
3959 if (ret && ret != -ENOENT) {
3960 btrfs_abort_transaction(trans, ret);
3967 trans->block_rsv = NULL;
3968 trans->bytes_reserved = 0;
3969 ret = btrfs_end_transaction(trans);
3972 inode->i_flags |= S_DEAD;
3974 btrfs_subvolume_release_metadata(fs_info, &block_rsv);
3976 up_write(&fs_info->subvol_sem);
3978 spin_lock(&dest->root_item_lock);
3979 root_flags = btrfs_root_flags(&dest->root_item);
3980 btrfs_set_root_flags(&dest->root_item,
3981 root_flags & ~BTRFS_ROOT_SUBVOL_DEAD);
3982 spin_unlock(&dest->root_item_lock);
3984 d_invalidate(dentry);
3985 btrfs_prune_dentries(dest);
3986 ASSERT(dest->send_in_progress == 0);
3989 if (dest->ino_cache_inode) {
3990 iput(dest->ino_cache_inode);
3991 dest->ino_cache_inode = NULL;
3998 static int btrfs_rmdir(struct inode *dir, struct dentry *dentry)
4000 struct inode *inode = d_inode(dentry);
4002 struct btrfs_root *root = BTRFS_I(dir)->root;
4003 struct btrfs_trans_handle *trans;
4004 u64 last_unlink_trans;
4006 if (inode->i_size > BTRFS_EMPTY_DIR_SIZE)
4008 if (btrfs_ino(BTRFS_I(inode)) == BTRFS_FIRST_FREE_OBJECTID)
4009 return btrfs_delete_subvolume(dir, dentry);
4011 trans = __unlink_start_trans(dir);
4013 return PTR_ERR(trans);
4015 if (unlikely(btrfs_ino(BTRFS_I(inode)) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)) {
4016 err = btrfs_unlink_subvol(trans, dir, dentry);
4020 err = btrfs_orphan_add(trans, BTRFS_I(inode));
4024 last_unlink_trans = BTRFS_I(inode)->last_unlink_trans;
4026 /* now the directory is empty */
4027 err = btrfs_unlink_inode(trans, root, BTRFS_I(dir),
4028 BTRFS_I(d_inode(dentry)), dentry->d_name.name,
4029 dentry->d_name.len);
4031 btrfs_i_size_write(BTRFS_I(inode), 0);
4033 * Propagate the last_unlink_trans value of the deleted dir to
4034 * its parent directory. This is to prevent an unrecoverable
4035 * log tree in the case we do something like this:
4037 * 2) create snapshot under dir foo
4038 * 3) delete the snapshot
4041 * 6) fsync foo or some file inside foo
4043 if (last_unlink_trans >= trans->transid)
4044 BTRFS_I(dir)->last_unlink_trans = last_unlink_trans;
4047 btrfs_end_transaction(trans);
4048 btrfs_btree_balance_dirty(root->fs_info);
4054 * Return this if we need to call truncate_block for the last bit of the
4057 #define NEED_TRUNCATE_BLOCK 1
4060 * this can truncate away extent items, csum items and directory items.
4061 * It starts at a high offset and removes keys until it can't find
4062 * any higher than new_size
4064 * csum items that cross the new i_size are truncated to the new size
4067 * min_type is the minimum key type to truncate down to. If set to 0, this
4068 * will kill all the items on this inode, including the INODE_ITEM_KEY.
4070 int btrfs_truncate_inode_items(struct btrfs_trans_handle *trans,
4071 struct btrfs_root *root,
4072 struct inode *inode,
4073 u64 new_size, u32 min_type)
4075 struct btrfs_fs_info *fs_info = root->fs_info;
4076 struct btrfs_path *path;
4077 struct extent_buffer *leaf;
4078 struct btrfs_file_extent_item *fi;
4079 struct btrfs_key key;
4080 struct btrfs_key found_key;
4081 u64 extent_start = 0;
4082 u64 extent_num_bytes = 0;
4083 u64 extent_offset = 0;
4085 u64 last_size = new_size;
4086 u32 found_type = (u8)-1;
4089 int pending_del_nr = 0;
4090 int pending_del_slot = 0;
4091 int extent_type = -1;
4093 u64 ino = btrfs_ino(BTRFS_I(inode));
4094 u64 bytes_deleted = 0;
4095 bool be_nice = false;
4096 bool should_throttle = false;
4097 const u64 lock_start = ALIGN_DOWN(new_size, fs_info->sectorsize);
4098 struct extent_state *cached_state = NULL;
4100 BUG_ON(new_size > 0 && min_type != BTRFS_EXTENT_DATA_KEY);
4103 * For non-free space inodes and non-shareable roots, we want to back
4104 * off from time to time. This means all inodes in subvolume roots,
4105 * reloc roots, and data reloc roots.
4107 if (!btrfs_is_free_space_inode(BTRFS_I(inode)) &&
4108 test_bit(BTRFS_ROOT_SHAREABLE, &root->state))
4111 path = btrfs_alloc_path();
4114 path->reada = READA_BACK;
4116 if (root->root_key.objectid != BTRFS_TREE_LOG_OBJECTID) {
4117 lock_extent_bits(&BTRFS_I(inode)->io_tree, lock_start, (u64)-1,
4121 * We want to drop from the next block forward in case this
4122 * new size is not block aligned since we will be keeping the
4123 * last block of the extent just the way it is.
4125 btrfs_drop_extent_cache(BTRFS_I(inode), ALIGN(new_size,
4126 fs_info->sectorsize),
4131 * This function is also used to drop the items in the log tree before
4132 * we relog the inode, so if root != BTRFS_I(inode)->root, it means
4133 * it is used to drop the logged items. So we shouldn't kill the delayed
4136 if (min_type == 0 && root == BTRFS_I(inode)->root)
4137 btrfs_kill_delayed_inode_items(BTRFS_I(inode));
4140 key.offset = (u64)-1;
4145 * with a 16K leaf size and 128MB extents, you can actually queue
4146 * up a huge file in a single leaf. Most of the time that
4147 * bytes_deleted is > 0, it will be huge by the time we get here
4149 if (be_nice && bytes_deleted > SZ_32M &&
4150 btrfs_should_end_transaction(trans)) {
4155 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
4161 /* there are no items in the tree for us to truncate, we're
4164 if (path->slots[0] == 0)
4170 u64 clear_start = 0, clear_len = 0;
4173 leaf = path->nodes[0];
4174 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
4175 found_type = found_key.type;
4177 if (found_key.objectid != ino)
4180 if (found_type < min_type)
4183 item_end = found_key.offset;
4184 if (found_type == BTRFS_EXTENT_DATA_KEY) {
4185 fi = btrfs_item_ptr(leaf, path->slots[0],
4186 struct btrfs_file_extent_item);
4187 extent_type = btrfs_file_extent_type(leaf, fi);
4188 if (extent_type != BTRFS_FILE_EXTENT_INLINE) {
4190 btrfs_file_extent_num_bytes(leaf, fi);
4192 trace_btrfs_truncate_show_fi_regular(
4193 BTRFS_I(inode), leaf, fi,
4195 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
4196 item_end += btrfs_file_extent_ram_bytes(leaf,
4199 trace_btrfs_truncate_show_fi_inline(
4200 BTRFS_I(inode), leaf, fi, path->slots[0],
4205 if (found_type > min_type) {
4208 if (item_end < new_size)
4210 if (found_key.offset >= new_size)
4216 /* FIXME, shrink the extent if the ref count is only 1 */
4217 if (found_type != BTRFS_EXTENT_DATA_KEY)
4220 if (extent_type != BTRFS_FILE_EXTENT_INLINE) {
4223 clear_start = found_key.offset;
4224 extent_start = btrfs_file_extent_disk_bytenr(leaf, fi);
4226 u64 orig_num_bytes =
4227 btrfs_file_extent_num_bytes(leaf, fi);
4228 extent_num_bytes = ALIGN(new_size -
4230 fs_info->sectorsize);
4231 clear_start = ALIGN(new_size, fs_info->sectorsize);
4232 btrfs_set_file_extent_num_bytes(leaf, fi,
4234 num_dec = (orig_num_bytes -
4236 if (test_bit(BTRFS_ROOT_SHAREABLE,
4239 inode_sub_bytes(inode, num_dec);
4240 btrfs_mark_buffer_dirty(leaf);
4243 btrfs_file_extent_disk_num_bytes(leaf,
4245 extent_offset = found_key.offset -
4246 btrfs_file_extent_offset(leaf, fi);
4248 /* FIXME blocksize != 4096 */
4249 num_dec = btrfs_file_extent_num_bytes(leaf, fi);
4250 if (extent_start != 0) {
4252 if (test_bit(BTRFS_ROOT_SHAREABLE,
4254 inode_sub_bytes(inode, num_dec);
4257 clear_len = num_dec;
4258 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
4260 * we can't truncate inline items that have had
4264 btrfs_file_extent_encryption(leaf, fi) == 0 &&
4265 btrfs_file_extent_other_encoding(leaf, fi) == 0 &&
4266 btrfs_file_extent_compression(leaf, fi) == 0) {
4267 u32 size = (u32)(new_size - found_key.offset);
4269 btrfs_set_file_extent_ram_bytes(leaf, fi, size);
4270 size = btrfs_file_extent_calc_inline_size(size);
4271 btrfs_truncate_item(path, size, 1);
4272 } else if (!del_item) {
4274 * We have to bail so the last_size is set to
4275 * just before this extent.
4277 ret = NEED_TRUNCATE_BLOCK;
4281 * Inline extents are special, we just treat
4282 * them as a full sector worth in the file
4283 * extent tree just for simplicity sake.
4285 clear_len = fs_info->sectorsize;
4288 if (test_bit(BTRFS_ROOT_SHAREABLE, &root->state))
4289 inode_sub_bytes(inode, item_end + 1 - new_size);
4293 * We use btrfs_truncate_inode_items() to clean up log trees for
4294 * multiple fsyncs, and in this case we don't want to clear the
4295 * file extent range because it's just the log.
4297 if (root == BTRFS_I(inode)->root) {
4298 ret = btrfs_inode_clear_file_extent_range(BTRFS_I(inode),
4299 clear_start, clear_len);
4301 btrfs_abort_transaction(trans, ret);
4307 last_size = found_key.offset;
4309 last_size = new_size;
4311 if (!pending_del_nr) {
4312 /* no pending yet, add ourselves */
4313 pending_del_slot = path->slots[0];
4315 } else if (pending_del_nr &&
4316 path->slots[0] + 1 == pending_del_slot) {
4317 /* hop on the pending chunk */
4319 pending_del_slot = path->slots[0];
4326 should_throttle = false;
4329 root->root_key.objectid != BTRFS_TREE_LOG_OBJECTID) {
4330 struct btrfs_ref ref = { 0 };
4332 bytes_deleted += extent_num_bytes;
4334 btrfs_init_generic_ref(&ref, BTRFS_DROP_DELAYED_REF,
4335 extent_start, extent_num_bytes, 0);
4336 ref.real_root = root->root_key.objectid;
4337 btrfs_init_data_ref(&ref, btrfs_header_owner(leaf),
4338 ino, extent_offset);
4339 ret = btrfs_free_extent(trans, &ref);
4341 btrfs_abort_transaction(trans, ret);
4345 if (btrfs_should_throttle_delayed_refs(trans))
4346 should_throttle = true;
4350 if (found_type == BTRFS_INODE_ITEM_KEY)
4353 if (path->slots[0] == 0 ||
4354 path->slots[0] != pending_del_slot ||
4356 if (pending_del_nr) {
4357 ret = btrfs_del_items(trans, root, path,
4361 btrfs_abort_transaction(trans, ret);
4366 btrfs_release_path(path);
4369 * We can generate a lot of delayed refs, so we need to
4370 * throttle every once and a while and make sure we're
4371 * adding enough space to keep up with the work we are
4372 * generating. Since we hold a transaction here we
4373 * can't flush, and we don't want to FLUSH_LIMIT because
4374 * we could have generated too many delayed refs to
4375 * actually allocate, so just bail if we're short and
4376 * let the normal reservation dance happen higher up.
4378 if (should_throttle) {
4379 ret = btrfs_delayed_refs_rsv_refill(fs_info,
4380 BTRFS_RESERVE_NO_FLUSH);
4392 if (ret >= 0 && pending_del_nr) {
4395 err = btrfs_del_items(trans, root, path, pending_del_slot,
4398 btrfs_abort_transaction(trans, err);
4402 if (root->root_key.objectid != BTRFS_TREE_LOG_OBJECTID) {
4403 ASSERT(last_size >= new_size);
4404 if (!ret && last_size > new_size)
4405 last_size = new_size;
4406 btrfs_inode_safe_disk_i_size_write(inode, last_size);
4407 unlock_extent_cached(&BTRFS_I(inode)->io_tree, lock_start,
4408 (u64)-1, &cached_state);
4411 btrfs_free_path(path);
4416 * btrfs_truncate_block - read, zero a chunk and write a block
4417 * @inode - inode that we're zeroing
4418 * @from - the offset to start zeroing
4419 * @len - the length to zero, 0 to zero the entire range respective to the
4421 * @front - zero up to the offset instead of from the offset on
4423 * This will find the block for the "from" offset and cow the block and zero the
4424 * part we want to zero. This is used with truncate and hole punching.
4426 int btrfs_truncate_block(struct inode *inode, loff_t from, loff_t len,
4429 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
4430 struct address_space *mapping = inode->i_mapping;
4431 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
4432 struct btrfs_ordered_extent *ordered;
4433 struct extent_state *cached_state = NULL;
4434 struct extent_changeset *data_reserved = NULL;
4436 u32 blocksize = fs_info->sectorsize;
4437 pgoff_t index = from >> PAGE_SHIFT;
4438 unsigned offset = from & (blocksize - 1);
4440 gfp_t mask = btrfs_alloc_write_mask(mapping);
4445 if (IS_ALIGNED(offset, blocksize) &&
4446 (!len || IS_ALIGNED(len, blocksize)))
4449 block_start = round_down(from, blocksize);
4450 block_end = block_start + blocksize - 1;
4452 ret = btrfs_delalloc_reserve_space(inode, &data_reserved,
4453 block_start, blocksize);
4458 page = find_or_create_page(mapping, index, mask);
4460 btrfs_delalloc_release_space(inode, data_reserved,
4461 block_start, blocksize, true);
4462 btrfs_delalloc_release_extents(BTRFS_I(inode), blocksize);
4467 if (!PageUptodate(page)) {
4468 ret = btrfs_readpage(NULL, page);
4470 if (page->mapping != mapping) {
4475 if (!PageUptodate(page)) {
4480 wait_on_page_writeback(page);
4482 lock_extent_bits(io_tree, block_start, block_end, &cached_state);
4483 set_page_extent_mapped(page);
4485 ordered = btrfs_lookup_ordered_extent(inode, block_start);
4487 unlock_extent_cached(io_tree, block_start, block_end,
4491 btrfs_start_ordered_extent(inode, ordered, 1);
4492 btrfs_put_ordered_extent(ordered);
4496 clear_extent_bit(&BTRFS_I(inode)->io_tree, block_start, block_end,
4497 EXTENT_DELALLOC | EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG,
4498 0, 0, &cached_state);
4500 ret = btrfs_set_extent_delalloc(inode, block_start, block_end, 0,
4503 unlock_extent_cached(io_tree, block_start, block_end,
4508 if (offset != blocksize) {
4510 len = blocksize - offset;
4513 memset(kaddr + (block_start - page_offset(page)),
4516 memset(kaddr + (block_start - page_offset(page)) + offset,
4518 flush_dcache_page(page);
4521 ClearPageChecked(page);
4522 set_page_dirty(page);
4523 unlock_extent_cached(io_tree, block_start, block_end, &cached_state);
4527 btrfs_delalloc_release_space(inode, data_reserved, block_start,
4529 btrfs_delalloc_release_extents(BTRFS_I(inode), blocksize);
4533 extent_changeset_free(data_reserved);
4537 static int maybe_insert_hole(struct btrfs_root *root, struct inode *inode,
4538 u64 offset, u64 len)
4540 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
4541 struct btrfs_trans_handle *trans;
4545 * Still need to make sure the inode looks like it's been updated so
4546 * that any holes get logged if we fsync.
4548 if (btrfs_fs_incompat(fs_info, NO_HOLES)) {
4549 BTRFS_I(inode)->last_trans = fs_info->generation;
4550 BTRFS_I(inode)->last_sub_trans = root->log_transid;
4551 BTRFS_I(inode)->last_log_commit = root->last_log_commit;
4556 * 1 - for the one we're dropping
4557 * 1 - for the one we're adding
4558 * 1 - for updating the inode.
4560 trans = btrfs_start_transaction(root, 3);
4562 return PTR_ERR(trans);
4564 ret = btrfs_drop_extents(trans, root, inode, offset, offset + len, 1);
4566 btrfs_abort_transaction(trans, ret);
4567 btrfs_end_transaction(trans);
4571 ret = btrfs_insert_file_extent(trans, root, btrfs_ino(BTRFS_I(inode)),
4572 offset, 0, 0, len, 0, len, 0, 0, 0);
4574 btrfs_abort_transaction(trans, ret);
4576 btrfs_update_inode(trans, root, inode);
4577 btrfs_end_transaction(trans);
4582 * This function puts in dummy file extents for the area we're creating a hole
4583 * for. So if we are truncating this file to a larger size we need to insert
4584 * these file extents so that btrfs_get_extent will return a EXTENT_MAP_HOLE for
4585 * the range between oldsize and size
4587 int btrfs_cont_expand(struct inode *inode, loff_t oldsize, loff_t size)
4589 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
4590 struct btrfs_root *root = BTRFS_I(inode)->root;
4591 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
4592 struct extent_map *em = NULL;
4593 struct extent_state *cached_state = NULL;
4594 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
4595 u64 hole_start = ALIGN(oldsize, fs_info->sectorsize);
4596 u64 block_end = ALIGN(size, fs_info->sectorsize);
4603 * If our size started in the middle of a block we need to zero out the
4604 * rest of the block before we expand the i_size, otherwise we could
4605 * expose stale data.
4607 err = btrfs_truncate_block(inode, oldsize, 0, 0);
4611 if (size <= hole_start)
4614 btrfs_lock_and_flush_ordered_range(BTRFS_I(inode), hole_start,
4615 block_end - 1, &cached_state);
4616 cur_offset = hole_start;
4618 em = btrfs_get_extent(BTRFS_I(inode), NULL, 0, cur_offset,
4619 block_end - cur_offset);
4625 last_byte = min(extent_map_end(em), block_end);
4626 last_byte = ALIGN(last_byte, fs_info->sectorsize);
4627 hole_size = last_byte - cur_offset;
4629 if (!test_bit(EXTENT_FLAG_PREALLOC, &em->flags)) {
4630 struct extent_map *hole_em;
4632 err = maybe_insert_hole(root, inode, cur_offset,
4637 err = btrfs_inode_set_file_extent_range(BTRFS_I(inode),
4638 cur_offset, hole_size);
4642 btrfs_drop_extent_cache(BTRFS_I(inode), cur_offset,
4643 cur_offset + hole_size - 1, 0);
4644 hole_em = alloc_extent_map();
4646 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
4647 &BTRFS_I(inode)->runtime_flags);
4650 hole_em->start = cur_offset;
4651 hole_em->len = hole_size;
4652 hole_em->orig_start = cur_offset;
4654 hole_em->block_start = EXTENT_MAP_HOLE;
4655 hole_em->block_len = 0;
4656 hole_em->orig_block_len = 0;
4657 hole_em->ram_bytes = hole_size;
4658 hole_em->compress_type = BTRFS_COMPRESS_NONE;
4659 hole_em->generation = fs_info->generation;
4662 write_lock(&em_tree->lock);
4663 err = add_extent_mapping(em_tree, hole_em, 1);
4664 write_unlock(&em_tree->lock);
4667 btrfs_drop_extent_cache(BTRFS_I(inode),
4672 free_extent_map(hole_em);
4674 err = btrfs_inode_set_file_extent_range(BTRFS_I(inode),
4675 cur_offset, hole_size);
4680 free_extent_map(em);
4682 cur_offset = last_byte;
4683 if (cur_offset >= block_end)
4686 free_extent_map(em);
4687 unlock_extent_cached(io_tree, hole_start, block_end - 1, &cached_state);
4691 static int btrfs_setsize(struct inode *inode, struct iattr *attr)
4693 struct btrfs_root *root = BTRFS_I(inode)->root;
4694 struct btrfs_trans_handle *trans;
4695 loff_t oldsize = i_size_read(inode);
4696 loff_t newsize = attr->ia_size;
4697 int mask = attr->ia_valid;
4701 * The regular truncate() case without ATTR_CTIME and ATTR_MTIME is a
4702 * special case where we need to update the times despite not having
4703 * these flags set. For all other operations the VFS set these flags
4704 * explicitly if it wants a timestamp update.
4706 if (newsize != oldsize) {
4707 inode_inc_iversion(inode);
4708 if (!(mask & (ATTR_CTIME | ATTR_MTIME)))
4709 inode->i_ctime = inode->i_mtime =
4710 current_time(inode);
4713 if (newsize > oldsize) {
4715 * Don't do an expanding truncate while snapshotting is ongoing.
4716 * This is to ensure the snapshot captures a fully consistent
4717 * state of this file - if the snapshot captures this expanding
4718 * truncation, it must capture all writes that happened before
4721 btrfs_drew_write_lock(&root->snapshot_lock);
4722 ret = btrfs_cont_expand(inode, oldsize, newsize);
4724 btrfs_drew_write_unlock(&root->snapshot_lock);
4728 trans = btrfs_start_transaction(root, 1);
4729 if (IS_ERR(trans)) {
4730 btrfs_drew_write_unlock(&root->snapshot_lock);
4731 return PTR_ERR(trans);
4734 i_size_write(inode, newsize);
4735 btrfs_inode_safe_disk_i_size_write(inode, 0);
4736 pagecache_isize_extended(inode, oldsize, newsize);
4737 ret = btrfs_update_inode(trans, root, inode);
4738 btrfs_drew_write_unlock(&root->snapshot_lock);
4739 btrfs_end_transaction(trans);
4743 * We're truncating a file that used to have good data down to
4744 * zero. Make sure it gets into the ordered flush list so that
4745 * any new writes get down to disk quickly.
4748 set_bit(BTRFS_INODE_ORDERED_DATA_CLOSE,
4749 &BTRFS_I(inode)->runtime_flags);
4751 truncate_setsize(inode, newsize);
4753 /* Disable nonlocked read DIO to avoid the endless truncate */
4754 btrfs_inode_block_unlocked_dio(BTRFS_I(inode));
4755 inode_dio_wait(inode);
4756 btrfs_inode_resume_unlocked_dio(BTRFS_I(inode));
4758 ret = btrfs_truncate(inode, newsize == oldsize);
4759 if (ret && inode->i_nlink) {
4763 * Truncate failed, so fix up the in-memory size. We
4764 * adjusted disk_i_size down as we removed extents, so
4765 * wait for disk_i_size to be stable and then update the
4766 * in-memory size to match.
4768 err = btrfs_wait_ordered_range(inode, 0, (u64)-1);
4771 i_size_write(inode, BTRFS_I(inode)->disk_i_size);
4778 static int btrfs_setattr(struct dentry *dentry, struct iattr *attr)
4780 struct inode *inode = d_inode(dentry);
4781 struct btrfs_root *root = BTRFS_I(inode)->root;
4784 if (btrfs_root_readonly(root))
4787 err = setattr_prepare(dentry, attr);
4791 if (S_ISREG(inode->i_mode) && (attr->ia_valid & ATTR_SIZE)) {
4792 err = btrfs_setsize(inode, attr);
4797 if (attr->ia_valid) {
4798 setattr_copy(inode, attr);
4799 inode_inc_iversion(inode);
4800 err = btrfs_dirty_inode(inode);
4802 if (!err && attr->ia_valid & ATTR_MODE)
4803 err = posix_acl_chmod(inode, inode->i_mode);
4810 * While truncating the inode pages during eviction, we get the VFS calling
4811 * btrfs_invalidatepage() against each page of the inode. This is slow because
4812 * the calls to btrfs_invalidatepage() result in a huge amount of calls to
4813 * lock_extent_bits() and clear_extent_bit(), which keep merging and splitting
4814 * extent_state structures over and over, wasting lots of time.
4816 * Therefore if the inode is being evicted, let btrfs_invalidatepage() skip all
4817 * those expensive operations on a per page basis and do only the ordered io
4818 * finishing, while we release here the extent_map and extent_state structures,
4819 * without the excessive merging and splitting.
4821 static void evict_inode_truncate_pages(struct inode *inode)
4823 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
4824 struct extent_map_tree *map_tree = &BTRFS_I(inode)->extent_tree;
4825 struct rb_node *node;
4827 ASSERT(inode->i_state & I_FREEING);
4828 truncate_inode_pages_final(&inode->i_data);
4830 write_lock(&map_tree->lock);
4831 while (!RB_EMPTY_ROOT(&map_tree->map.rb_root)) {
4832 struct extent_map *em;
4834 node = rb_first_cached(&map_tree->map);
4835 em = rb_entry(node, struct extent_map, rb_node);
4836 clear_bit(EXTENT_FLAG_PINNED, &em->flags);
4837 clear_bit(EXTENT_FLAG_LOGGING, &em->flags);
4838 remove_extent_mapping(map_tree, em);
4839 free_extent_map(em);
4840 if (need_resched()) {
4841 write_unlock(&map_tree->lock);
4843 write_lock(&map_tree->lock);
4846 write_unlock(&map_tree->lock);
4849 * Keep looping until we have no more ranges in the io tree.
4850 * We can have ongoing bios started by readpages (called from readahead)
4851 * that have their endio callback (extent_io.c:end_bio_extent_readpage)
4852 * still in progress (unlocked the pages in the bio but did not yet
4853 * unlocked the ranges in the io tree). Therefore this means some
4854 * ranges can still be locked and eviction started because before
4855 * submitting those bios, which are executed by a separate task (work
4856 * queue kthread), inode references (inode->i_count) were not taken
4857 * (which would be dropped in the end io callback of each bio).
4858 * Therefore here we effectively end up waiting for those bios and
4859 * anyone else holding locked ranges without having bumped the inode's
4860 * reference count - if we don't do it, when they access the inode's
4861 * io_tree to unlock a range it may be too late, leading to an
4862 * use-after-free issue.
4864 spin_lock(&io_tree->lock);
4865 while (!RB_EMPTY_ROOT(&io_tree->state)) {
4866 struct extent_state *state;
4867 struct extent_state *cached_state = NULL;
4870 unsigned state_flags;
4872 node = rb_first(&io_tree->state);
4873 state = rb_entry(node, struct extent_state, rb_node);
4874 start = state->start;
4876 state_flags = state->state;
4877 spin_unlock(&io_tree->lock);
4879 lock_extent_bits(io_tree, start, end, &cached_state);
4882 * If still has DELALLOC flag, the extent didn't reach disk,
4883 * and its reserved space won't be freed by delayed_ref.
4884 * So we need to free its reserved space here.
4885 * (Refer to comment in btrfs_invalidatepage, case 2)
4887 * Note, end is the bytenr of last byte, so we need + 1 here.
4889 if (state_flags & EXTENT_DELALLOC)
4890 btrfs_qgroup_free_data(inode, NULL, start, end - start + 1);
4892 clear_extent_bit(io_tree, start, end,
4893 EXTENT_LOCKED | EXTENT_DELALLOC |
4894 EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG, 1, 1,
4898 spin_lock(&io_tree->lock);
4900 spin_unlock(&io_tree->lock);
4903 static struct btrfs_trans_handle *evict_refill_and_join(struct btrfs_root *root,
4904 struct btrfs_block_rsv *rsv)
4906 struct btrfs_fs_info *fs_info = root->fs_info;
4907 struct btrfs_block_rsv *global_rsv = &fs_info->global_block_rsv;
4908 struct btrfs_trans_handle *trans;
4909 u64 delayed_refs_extra = btrfs_calc_insert_metadata_size(fs_info, 1);
4913 * Eviction should be taking place at some place safe because of our
4914 * delayed iputs. However the normal flushing code will run delayed
4915 * iputs, so we cannot use FLUSH_ALL otherwise we'll deadlock.
4917 * We reserve the delayed_refs_extra here again because we can't use
4918 * btrfs_start_transaction(root, 0) for the same deadlocky reason as
4919 * above. We reserve our extra bit here because we generate a ton of
4920 * delayed refs activity by truncating.
4922 * If we cannot make our reservation we'll attempt to steal from the
4923 * global reserve, because we really want to be able to free up space.
4925 ret = btrfs_block_rsv_refill(root, rsv, rsv->size + delayed_refs_extra,
4926 BTRFS_RESERVE_FLUSH_EVICT);
4929 * Try to steal from the global reserve if there is space for
4932 if (btrfs_check_space_for_delayed_refs(fs_info) ||
4933 btrfs_block_rsv_migrate(global_rsv, rsv, rsv->size, 0)) {
4935 "could not allocate space for delete; will truncate on mount");
4936 return ERR_PTR(-ENOSPC);
4938 delayed_refs_extra = 0;
4941 trans = btrfs_join_transaction(root);
4945 if (delayed_refs_extra) {
4946 trans->block_rsv = &fs_info->trans_block_rsv;
4947 trans->bytes_reserved = delayed_refs_extra;
4948 btrfs_block_rsv_migrate(rsv, trans->block_rsv,
4949 delayed_refs_extra, 1);
4954 void btrfs_evict_inode(struct inode *inode)
4956 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
4957 struct btrfs_trans_handle *trans;
4958 struct btrfs_root *root = BTRFS_I(inode)->root;
4959 struct btrfs_block_rsv *rsv;
4962 trace_btrfs_inode_evict(inode);
4969 evict_inode_truncate_pages(inode);
4971 if (inode->i_nlink &&
4972 ((btrfs_root_refs(&root->root_item) != 0 &&
4973 root->root_key.objectid != BTRFS_ROOT_TREE_OBJECTID) ||
4974 btrfs_is_free_space_inode(BTRFS_I(inode))))
4977 if (is_bad_inode(inode))
4980 btrfs_free_io_failure_record(BTRFS_I(inode), 0, (u64)-1);
4982 if (test_bit(BTRFS_FS_LOG_RECOVERING, &fs_info->flags))
4985 if (inode->i_nlink > 0) {
4986 BUG_ON(btrfs_root_refs(&root->root_item) != 0 &&
4987 root->root_key.objectid != BTRFS_ROOT_TREE_OBJECTID);
4991 ret = btrfs_commit_inode_delayed_inode(BTRFS_I(inode));
4995 rsv = btrfs_alloc_block_rsv(fs_info, BTRFS_BLOCK_RSV_TEMP);
4998 rsv->size = btrfs_calc_metadata_size(fs_info, 1);
5001 btrfs_i_size_write(BTRFS_I(inode), 0);
5004 trans = evict_refill_and_join(root, rsv);
5008 trans->block_rsv = rsv;
5010 ret = btrfs_truncate_inode_items(trans, root, inode, 0, 0);
5011 trans->block_rsv = &fs_info->trans_block_rsv;
5012 btrfs_end_transaction(trans);
5013 btrfs_btree_balance_dirty(fs_info);
5014 if (ret && ret != -ENOSPC && ret != -EAGAIN)
5021 * Errors here aren't a big deal, it just means we leave orphan items in
5022 * the tree. They will be cleaned up on the next mount. If the inode
5023 * number gets reused, cleanup deletes the orphan item without doing
5024 * anything, and unlink reuses the existing orphan item.
5026 * If it turns out that we are dropping too many of these, we might want
5027 * to add a mechanism for retrying these after a commit.
5029 trans = evict_refill_and_join(root, rsv);
5030 if (!IS_ERR(trans)) {
5031 trans->block_rsv = rsv;
5032 btrfs_orphan_del(trans, BTRFS_I(inode));
5033 trans->block_rsv = &fs_info->trans_block_rsv;
5034 btrfs_end_transaction(trans);
5037 if (!(root == fs_info->tree_root ||
5038 root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID))
5039 btrfs_return_ino(root, btrfs_ino(BTRFS_I(inode)));
5042 btrfs_free_block_rsv(fs_info, rsv);
5045 * If we didn't successfully delete, the orphan item will still be in
5046 * the tree and we'll retry on the next mount. Again, we might also want
5047 * to retry these periodically in the future.
5049 btrfs_remove_delayed_node(BTRFS_I(inode));
5054 * Return the key found in the dir entry in the location pointer, fill @type
5055 * with BTRFS_FT_*, and return 0.
5057 * If no dir entries were found, returns -ENOENT.
5058 * If found a corrupted location in dir entry, returns -EUCLEAN.
5060 static int btrfs_inode_by_name(struct inode *dir, struct dentry *dentry,
5061 struct btrfs_key *location, u8 *type)
5063 const char *name = dentry->d_name.name;
5064 int namelen = dentry->d_name.len;
5065 struct btrfs_dir_item *di;
5066 struct btrfs_path *path;
5067 struct btrfs_root *root = BTRFS_I(dir)->root;
5070 path = btrfs_alloc_path();
5074 di = btrfs_lookup_dir_item(NULL, root, path, btrfs_ino(BTRFS_I(dir)),
5076 if (IS_ERR_OR_NULL(di)) {
5077 ret = di ? PTR_ERR(di) : -ENOENT;
5081 btrfs_dir_item_key_to_cpu(path->nodes[0], di, location);
5082 if (location->type != BTRFS_INODE_ITEM_KEY &&
5083 location->type != BTRFS_ROOT_ITEM_KEY) {
5085 btrfs_warn(root->fs_info,
5086 "%s gets something invalid in DIR_ITEM (name %s, directory ino %llu, location(%llu %u %llu))",
5087 __func__, name, btrfs_ino(BTRFS_I(dir)),
5088 location->objectid, location->type, location->offset);
5091 *type = btrfs_dir_type(path->nodes[0], di);
5093 btrfs_free_path(path);
5098 * when we hit a tree root in a directory, the btrfs part of the inode
5099 * needs to be changed to reflect the root directory of the tree root. This
5100 * is kind of like crossing a mount point.
5102 static int fixup_tree_root_location(struct btrfs_fs_info *fs_info,
5104 struct dentry *dentry,
5105 struct btrfs_key *location,
5106 struct btrfs_root **sub_root)
5108 struct btrfs_path *path;
5109 struct btrfs_root *new_root;
5110 struct btrfs_root_ref *ref;
5111 struct extent_buffer *leaf;
5112 struct btrfs_key key;
5116 path = btrfs_alloc_path();
5123 key.objectid = BTRFS_I(dir)->root->root_key.objectid;
5124 key.type = BTRFS_ROOT_REF_KEY;
5125 key.offset = location->objectid;
5127 ret = btrfs_search_slot(NULL, fs_info->tree_root, &key, path, 0, 0);
5134 leaf = path->nodes[0];
5135 ref = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_root_ref);
5136 if (btrfs_root_ref_dirid(leaf, ref) != btrfs_ino(BTRFS_I(dir)) ||
5137 btrfs_root_ref_name_len(leaf, ref) != dentry->d_name.len)
5140 ret = memcmp_extent_buffer(leaf, dentry->d_name.name,
5141 (unsigned long)(ref + 1),
5142 dentry->d_name.len);
5146 btrfs_release_path(path);
5148 new_root = btrfs_get_fs_root(fs_info, location->objectid, true);
5149 if (IS_ERR(new_root)) {
5150 err = PTR_ERR(new_root);
5154 *sub_root = new_root;
5155 location->objectid = btrfs_root_dirid(&new_root->root_item);
5156 location->type = BTRFS_INODE_ITEM_KEY;
5157 location->offset = 0;
5160 btrfs_free_path(path);
5164 static void inode_tree_add(struct inode *inode)
5166 struct btrfs_root *root = BTRFS_I(inode)->root;
5167 struct btrfs_inode *entry;
5169 struct rb_node *parent;
5170 struct rb_node *new = &BTRFS_I(inode)->rb_node;
5171 u64 ino = btrfs_ino(BTRFS_I(inode));
5173 if (inode_unhashed(inode))
5176 spin_lock(&root->inode_lock);
5177 p = &root->inode_tree.rb_node;
5180 entry = rb_entry(parent, struct btrfs_inode, rb_node);
5182 if (ino < btrfs_ino(entry))
5183 p = &parent->rb_left;
5184 else if (ino > btrfs_ino(entry))
5185 p = &parent->rb_right;
5187 WARN_ON(!(entry->vfs_inode.i_state &
5188 (I_WILL_FREE | I_FREEING)));
5189 rb_replace_node(parent, new, &root->inode_tree);
5190 RB_CLEAR_NODE(parent);
5191 spin_unlock(&root->inode_lock);
5195 rb_link_node(new, parent, p);
5196 rb_insert_color(new, &root->inode_tree);
5197 spin_unlock(&root->inode_lock);
5200 static void inode_tree_del(struct inode *inode)
5202 struct btrfs_root *root = BTRFS_I(inode)->root;
5205 spin_lock(&root->inode_lock);
5206 if (!RB_EMPTY_NODE(&BTRFS_I(inode)->rb_node)) {
5207 rb_erase(&BTRFS_I(inode)->rb_node, &root->inode_tree);
5208 RB_CLEAR_NODE(&BTRFS_I(inode)->rb_node);
5209 empty = RB_EMPTY_ROOT(&root->inode_tree);
5211 spin_unlock(&root->inode_lock);
5213 if (empty && btrfs_root_refs(&root->root_item) == 0) {
5214 spin_lock(&root->inode_lock);
5215 empty = RB_EMPTY_ROOT(&root->inode_tree);
5216 spin_unlock(&root->inode_lock);
5218 btrfs_add_dead_root(root);
5223 static int btrfs_init_locked_inode(struct inode *inode, void *p)
5225 struct btrfs_iget_args *args = p;
5227 inode->i_ino = args->ino;
5228 BTRFS_I(inode)->location.objectid = args->ino;
5229 BTRFS_I(inode)->location.type = BTRFS_INODE_ITEM_KEY;
5230 BTRFS_I(inode)->location.offset = 0;
5231 BTRFS_I(inode)->root = btrfs_grab_root(args->root);
5232 BUG_ON(args->root && !BTRFS_I(inode)->root);
5236 static int btrfs_find_actor(struct inode *inode, void *opaque)
5238 struct btrfs_iget_args *args = opaque;
5240 return args->ino == BTRFS_I(inode)->location.objectid &&
5241 args->root == BTRFS_I(inode)->root;
5244 static struct inode *btrfs_iget_locked(struct super_block *s, u64 ino,
5245 struct btrfs_root *root)
5247 struct inode *inode;
5248 struct btrfs_iget_args args;
5249 unsigned long hashval = btrfs_inode_hash(ino, root);
5254 inode = iget5_locked(s, hashval, btrfs_find_actor,
5255 btrfs_init_locked_inode,
5261 * Get an inode object given its inode number and corresponding root.
5262 * Path can be preallocated to prevent recursing back to iget through
5263 * allocator. NULL is also valid but may require an additional allocation
5266 struct inode *btrfs_iget_path(struct super_block *s, u64 ino,
5267 struct btrfs_root *root, struct btrfs_path *path)
5269 struct inode *inode;
5271 inode = btrfs_iget_locked(s, ino, root);
5273 return ERR_PTR(-ENOMEM);
5275 if (inode->i_state & I_NEW) {
5278 ret = btrfs_read_locked_inode(inode, path);
5280 inode_tree_add(inode);
5281 unlock_new_inode(inode);
5285 * ret > 0 can come from btrfs_search_slot called by
5286 * btrfs_read_locked_inode, this means the inode item
5291 inode = ERR_PTR(ret);
5298 struct inode *btrfs_iget(struct super_block *s, u64 ino, struct btrfs_root *root)
5300 return btrfs_iget_path(s, ino, root, NULL);
5303 static struct inode *new_simple_dir(struct super_block *s,
5304 struct btrfs_key *key,
5305 struct btrfs_root *root)
5307 struct inode *inode = new_inode(s);
5310 return ERR_PTR(-ENOMEM);
5312 BTRFS_I(inode)->root = btrfs_grab_root(root);
5313 memcpy(&BTRFS_I(inode)->location, key, sizeof(*key));
5314 set_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags);
5316 inode->i_ino = BTRFS_EMPTY_SUBVOL_DIR_OBJECTID;
5318 * We only need lookup, the rest is read-only and there's no inode
5319 * associated with the dentry
5321 inode->i_op = &simple_dir_inode_operations;
5322 inode->i_opflags &= ~IOP_XATTR;
5323 inode->i_fop = &simple_dir_operations;
5324 inode->i_mode = S_IFDIR | S_IRUGO | S_IWUSR | S_IXUGO;
5325 inode->i_mtime = current_time(inode);
5326 inode->i_atime = inode->i_mtime;
5327 inode->i_ctime = inode->i_mtime;
5328 BTRFS_I(inode)->i_otime = inode->i_mtime;
5333 static inline u8 btrfs_inode_type(struct inode *inode)
5336 * Compile-time asserts that generic FT_* types still match
5339 BUILD_BUG_ON(BTRFS_FT_UNKNOWN != FT_UNKNOWN);
5340 BUILD_BUG_ON(BTRFS_FT_REG_FILE != FT_REG_FILE);
5341 BUILD_BUG_ON(BTRFS_FT_DIR != FT_DIR);
5342 BUILD_BUG_ON(BTRFS_FT_CHRDEV != FT_CHRDEV);
5343 BUILD_BUG_ON(BTRFS_FT_BLKDEV != FT_BLKDEV);
5344 BUILD_BUG_ON(BTRFS_FT_FIFO != FT_FIFO);
5345 BUILD_BUG_ON(BTRFS_FT_SOCK != FT_SOCK);
5346 BUILD_BUG_ON(BTRFS_FT_SYMLINK != FT_SYMLINK);
5348 return fs_umode_to_ftype(inode->i_mode);
5351 struct inode *btrfs_lookup_dentry(struct inode *dir, struct dentry *dentry)
5353 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
5354 struct inode *inode;
5355 struct btrfs_root *root = BTRFS_I(dir)->root;
5356 struct btrfs_root *sub_root = root;
5357 struct btrfs_key location;
5361 if (dentry->d_name.len > BTRFS_NAME_LEN)
5362 return ERR_PTR(-ENAMETOOLONG);
5364 ret = btrfs_inode_by_name(dir, dentry, &location, &di_type);
5366 return ERR_PTR(ret);
5368 if (location.type == BTRFS_INODE_ITEM_KEY) {
5369 inode = btrfs_iget(dir->i_sb, location.objectid, root);
5373 /* Do extra check against inode mode with di_type */
5374 if (btrfs_inode_type(inode) != di_type) {
5376 "inode mode mismatch with dir: inode mode=0%o btrfs type=%u dir type=%u",
5377 inode->i_mode, btrfs_inode_type(inode),
5380 return ERR_PTR(-EUCLEAN);
5385 ret = fixup_tree_root_location(fs_info, dir, dentry,
5386 &location, &sub_root);
5389 inode = ERR_PTR(ret);
5391 inode = new_simple_dir(dir->i_sb, &location, sub_root);
5393 inode = btrfs_iget(dir->i_sb, location.objectid, sub_root);
5395 if (root != sub_root)
5396 btrfs_put_root(sub_root);
5398 if (!IS_ERR(inode) && root != sub_root) {
5399 down_read(&fs_info->cleanup_work_sem);
5400 if (!sb_rdonly(inode->i_sb))
5401 ret = btrfs_orphan_cleanup(sub_root);
5402 up_read(&fs_info->cleanup_work_sem);
5405 inode = ERR_PTR(ret);
5412 static int btrfs_dentry_delete(const struct dentry *dentry)
5414 struct btrfs_root *root;
5415 struct inode *inode = d_inode(dentry);
5417 if (!inode && !IS_ROOT(dentry))
5418 inode = d_inode(dentry->d_parent);
5421 root = BTRFS_I(inode)->root;
5422 if (btrfs_root_refs(&root->root_item) == 0)
5425 if (btrfs_ino(BTRFS_I(inode)) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)
5431 static struct dentry *btrfs_lookup(struct inode *dir, struct dentry *dentry,
5434 struct inode *inode = btrfs_lookup_dentry(dir, dentry);
5436 if (inode == ERR_PTR(-ENOENT))
5438 return d_splice_alias(inode, dentry);
5442 * All this infrastructure exists because dir_emit can fault, and we are holding
5443 * the tree lock when doing readdir. For now just allocate a buffer and copy
5444 * our information into that, and then dir_emit from the buffer. This is
5445 * similar to what NFS does, only we don't keep the buffer around in pagecache
5446 * because I'm afraid I'll mess that up. Long term we need to make filldir do
5447 * copy_to_user_inatomic so we don't have to worry about page faulting under the
5450 static int btrfs_opendir(struct inode *inode, struct file *file)
5452 struct btrfs_file_private *private;
5454 private = kzalloc(sizeof(struct btrfs_file_private), GFP_KERNEL);
5457 private->filldir_buf = kzalloc(PAGE_SIZE, GFP_KERNEL);
5458 if (!private->filldir_buf) {
5462 file->private_data = private;
5473 static int btrfs_filldir(void *addr, int entries, struct dir_context *ctx)
5476 struct dir_entry *entry = addr;
5477 char *name = (char *)(entry + 1);
5479 ctx->pos = get_unaligned(&entry->offset);
5480 if (!dir_emit(ctx, name, get_unaligned(&entry->name_len),
5481 get_unaligned(&entry->ino),
5482 get_unaligned(&entry->type)))
5484 addr += sizeof(struct dir_entry) +
5485 get_unaligned(&entry->name_len);
5491 static int btrfs_real_readdir(struct file *file, struct dir_context *ctx)
5493 struct inode *inode = file_inode(file);
5494 struct btrfs_root *root = BTRFS_I(inode)->root;
5495 struct btrfs_file_private *private = file->private_data;
5496 struct btrfs_dir_item *di;
5497 struct btrfs_key key;
5498 struct btrfs_key found_key;
5499 struct btrfs_path *path;
5501 struct list_head ins_list;
5502 struct list_head del_list;
5504 struct extent_buffer *leaf;
5511 struct btrfs_key location;
5513 if (!dir_emit_dots(file, ctx))
5516 path = btrfs_alloc_path();
5520 addr = private->filldir_buf;
5521 path->reada = READA_FORWARD;
5523 INIT_LIST_HEAD(&ins_list);
5524 INIT_LIST_HEAD(&del_list);
5525 put = btrfs_readdir_get_delayed_items(inode, &ins_list, &del_list);
5528 key.type = BTRFS_DIR_INDEX_KEY;
5529 key.offset = ctx->pos;
5530 key.objectid = btrfs_ino(BTRFS_I(inode));
5532 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
5537 struct dir_entry *entry;
5539 leaf = path->nodes[0];
5540 slot = path->slots[0];
5541 if (slot >= btrfs_header_nritems(leaf)) {
5542 ret = btrfs_next_leaf(root, path);
5550 btrfs_item_key_to_cpu(leaf, &found_key, slot);
5552 if (found_key.objectid != key.objectid)
5554 if (found_key.type != BTRFS_DIR_INDEX_KEY)
5556 if (found_key.offset < ctx->pos)
5558 if (btrfs_should_delete_dir_index(&del_list, found_key.offset))
5560 di = btrfs_item_ptr(leaf, slot, struct btrfs_dir_item);
5561 name_len = btrfs_dir_name_len(leaf, di);
5562 if ((total_len + sizeof(struct dir_entry) + name_len) >=
5564 btrfs_release_path(path);
5565 ret = btrfs_filldir(private->filldir_buf, entries, ctx);
5568 addr = private->filldir_buf;
5575 put_unaligned(name_len, &entry->name_len);
5576 name_ptr = (char *)(entry + 1);
5577 read_extent_buffer(leaf, name_ptr, (unsigned long)(di + 1),
5579 put_unaligned(fs_ftype_to_dtype(btrfs_dir_type(leaf, di)),
5581 btrfs_dir_item_key_to_cpu(leaf, di, &location);
5582 put_unaligned(location.objectid, &entry->ino);
5583 put_unaligned(found_key.offset, &entry->offset);
5585 addr += sizeof(struct dir_entry) + name_len;
5586 total_len += sizeof(struct dir_entry) + name_len;
5590 btrfs_release_path(path);
5592 ret = btrfs_filldir(private->filldir_buf, entries, ctx);
5596 ret = btrfs_readdir_delayed_dir_index(ctx, &ins_list);
5601 * Stop new entries from being returned after we return the last
5604 * New directory entries are assigned a strictly increasing
5605 * offset. This means that new entries created during readdir
5606 * are *guaranteed* to be seen in the future by that readdir.
5607 * This has broken buggy programs which operate on names as
5608 * they're returned by readdir. Until we re-use freed offsets
5609 * we have this hack to stop new entries from being returned
5610 * under the assumption that they'll never reach this huge
5613 * This is being careful not to overflow 32bit loff_t unless the
5614 * last entry requires it because doing so has broken 32bit apps
5617 if (ctx->pos >= INT_MAX)
5618 ctx->pos = LLONG_MAX;
5625 btrfs_readdir_put_delayed_items(inode, &ins_list, &del_list);
5626 btrfs_free_path(path);
5631 * This is somewhat expensive, updating the tree every time the
5632 * inode changes. But, it is most likely to find the inode in cache.
5633 * FIXME, needs more benchmarking...there are no reasons other than performance
5634 * to keep or drop this code.
5636 static int btrfs_dirty_inode(struct inode *inode)
5638 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
5639 struct btrfs_root *root = BTRFS_I(inode)->root;
5640 struct btrfs_trans_handle *trans;
5643 if (test_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags))
5646 trans = btrfs_join_transaction(root);
5648 return PTR_ERR(trans);
5650 ret = btrfs_update_inode(trans, root, inode);
5651 if (ret && ret == -ENOSPC) {
5652 /* whoops, lets try again with the full transaction */
5653 btrfs_end_transaction(trans);
5654 trans = btrfs_start_transaction(root, 1);
5656 return PTR_ERR(trans);
5658 ret = btrfs_update_inode(trans, root, inode);
5660 btrfs_end_transaction(trans);
5661 if (BTRFS_I(inode)->delayed_node)
5662 btrfs_balance_delayed_items(fs_info);
5668 * This is a copy of file_update_time. We need this so we can return error on
5669 * ENOSPC for updating the inode in the case of file write and mmap writes.
5671 static int btrfs_update_time(struct inode *inode, struct timespec64 *now,
5674 struct btrfs_root *root = BTRFS_I(inode)->root;
5675 bool dirty = flags & ~S_VERSION;
5677 if (btrfs_root_readonly(root))
5680 if (flags & S_VERSION)
5681 dirty |= inode_maybe_inc_iversion(inode, dirty);
5682 if (flags & S_CTIME)
5683 inode->i_ctime = *now;
5684 if (flags & S_MTIME)
5685 inode->i_mtime = *now;
5686 if (flags & S_ATIME)
5687 inode->i_atime = *now;
5688 return dirty ? btrfs_dirty_inode(inode) : 0;
5692 * find the highest existing sequence number in a directory
5693 * and then set the in-memory index_cnt variable to reflect
5694 * free sequence numbers
5696 static int btrfs_set_inode_index_count(struct btrfs_inode *inode)
5698 struct btrfs_root *root = inode->root;
5699 struct btrfs_key key, found_key;
5700 struct btrfs_path *path;
5701 struct extent_buffer *leaf;
5704 key.objectid = btrfs_ino(inode);
5705 key.type = BTRFS_DIR_INDEX_KEY;
5706 key.offset = (u64)-1;
5708 path = btrfs_alloc_path();
5712 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
5715 /* FIXME: we should be able to handle this */
5721 * MAGIC NUMBER EXPLANATION:
5722 * since we search a directory based on f_pos we have to start at 2
5723 * since '.' and '..' have f_pos of 0 and 1 respectively, so everybody
5724 * else has to start at 2
5726 if (path->slots[0] == 0) {
5727 inode->index_cnt = 2;
5733 leaf = path->nodes[0];
5734 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
5736 if (found_key.objectid != btrfs_ino(inode) ||
5737 found_key.type != BTRFS_DIR_INDEX_KEY) {
5738 inode->index_cnt = 2;
5742 inode->index_cnt = found_key.offset + 1;
5744 btrfs_free_path(path);
5749 * helper to find a free sequence number in a given directory. This current
5750 * code is very simple, later versions will do smarter things in the btree
5752 int btrfs_set_inode_index(struct btrfs_inode *dir, u64 *index)
5756 if (dir->index_cnt == (u64)-1) {
5757 ret = btrfs_inode_delayed_dir_index_count(dir);
5759 ret = btrfs_set_inode_index_count(dir);
5765 *index = dir->index_cnt;
5771 static int btrfs_insert_inode_locked(struct inode *inode)
5773 struct btrfs_iget_args args;
5775 args.ino = BTRFS_I(inode)->location.objectid;
5776 args.root = BTRFS_I(inode)->root;
5778 return insert_inode_locked4(inode,
5779 btrfs_inode_hash(inode->i_ino, BTRFS_I(inode)->root),
5780 btrfs_find_actor, &args);
5784 * Inherit flags from the parent inode.
5786 * Currently only the compression flags and the cow flags are inherited.
5788 static void btrfs_inherit_iflags(struct inode *inode, struct inode *dir)
5795 flags = BTRFS_I(dir)->flags;
5797 if (flags & BTRFS_INODE_NOCOMPRESS) {
5798 BTRFS_I(inode)->flags &= ~BTRFS_INODE_COMPRESS;
5799 BTRFS_I(inode)->flags |= BTRFS_INODE_NOCOMPRESS;
5800 } else if (flags & BTRFS_INODE_COMPRESS) {
5801 BTRFS_I(inode)->flags &= ~BTRFS_INODE_NOCOMPRESS;
5802 BTRFS_I(inode)->flags |= BTRFS_INODE_COMPRESS;
5805 if (flags & BTRFS_INODE_NODATACOW) {
5806 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATACOW;
5807 if (S_ISREG(inode->i_mode))
5808 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATASUM;
5811 btrfs_sync_inode_flags_to_i_flags(inode);
5814 static struct inode *btrfs_new_inode(struct btrfs_trans_handle *trans,
5815 struct btrfs_root *root,
5817 const char *name, int name_len,
5818 u64 ref_objectid, u64 objectid,
5819 umode_t mode, u64 *index)
5821 struct btrfs_fs_info *fs_info = root->fs_info;
5822 struct inode *inode;
5823 struct btrfs_inode_item *inode_item;
5824 struct btrfs_key *location;
5825 struct btrfs_path *path;
5826 struct btrfs_inode_ref *ref;
5827 struct btrfs_key key[2];
5829 int nitems = name ? 2 : 1;
5831 unsigned int nofs_flag;
5834 path = btrfs_alloc_path();
5836 return ERR_PTR(-ENOMEM);
5838 nofs_flag = memalloc_nofs_save();
5839 inode = new_inode(fs_info->sb);
5840 memalloc_nofs_restore(nofs_flag);
5842 btrfs_free_path(path);
5843 return ERR_PTR(-ENOMEM);
5847 * O_TMPFILE, set link count to 0, so that after this point,
5848 * we fill in an inode item with the correct link count.
5851 set_nlink(inode, 0);
5854 * we have to initialize this early, so we can reclaim the inode
5855 * number if we fail afterwards in this function.
5857 inode->i_ino = objectid;
5860 trace_btrfs_inode_request(dir);
5862 ret = btrfs_set_inode_index(BTRFS_I(dir), index);
5864 btrfs_free_path(path);
5866 return ERR_PTR(ret);
5872 * index_cnt is ignored for everything but a dir,
5873 * btrfs_set_inode_index_count has an explanation for the magic
5876 BTRFS_I(inode)->index_cnt = 2;
5877 BTRFS_I(inode)->dir_index = *index;
5878 BTRFS_I(inode)->root = btrfs_grab_root(root);
5879 BTRFS_I(inode)->generation = trans->transid;
5880 inode->i_generation = BTRFS_I(inode)->generation;
5883 * We could have gotten an inode number from somebody who was fsynced
5884 * and then removed in this same transaction, so let's just set full
5885 * sync since it will be a full sync anyway and this will blow away the
5886 * old info in the log.
5888 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &BTRFS_I(inode)->runtime_flags);
5890 key[0].objectid = objectid;
5891 key[0].type = BTRFS_INODE_ITEM_KEY;
5894 sizes[0] = sizeof(struct btrfs_inode_item);
5898 * Start new inodes with an inode_ref. This is slightly more
5899 * efficient for small numbers of hard links since they will
5900 * be packed into one item. Extended refs will kick in if we
5901 * add more hard links than can fit in the ref item.
5903 key[1].objectid = objectid;
5904 key[1].type = BTRFS_INODE_REF_KEY;
5905 key[1].offset = ref_objectid;
5907 sizes[1] = name_len + sizeof(*ref);
5910 location = &BTRFS_I(inode)->location;
5911 location->objectid = objectid;
5912 location->offset = 0;
5913 location->type = BTRFS_INODE_ITEM_KEY;
5915 ret = btrfs_insert_inode_locked(inode);
5921 path->leave_spinning = 1;
5922 ret = btrfs_insert_empty_items(trans, root, path, key, sizes, nitems);
5926 inode_init_owner(inode, dir, mode);
5927 inode_set_bytes(inode, 0);
5929 inode->i_mtime = current_time(inode);
5930 inode->i_atime = inode->i_mtime;
5931 inode->i_ctime = inode->i_mtime;
5932 BTRFS_I(inode)->i_otime = inode->i_mtime;
5934 inode_item = btrfs_item_ptr(path->nodes[0], path->slots[0],
5935 struct btrfs_inode_item);
5936 memzero_extent_buffer(path->nodes[0], (unsigned long)inode_item,
5937 sizeof(*inode_item));
5938 fill_inode_item(trans, path->nodes[0], inode_item, inode);
5941 ref = btrfs_item_ptr(path->nodes[0], path->slots[0] + 1,
5942 struct btrfs_inode_ref);
5943 btrfs_set_inode_ref_name_len(path->nodes[0], ref, name_len);
5944 btrfs_set_inode_ref_index(path->nodes[0], ref, *index);
5945 ptr = (unsigned long)(ref + 1);
5946 write_extent_buffer(path->nodes[0], name, ptr, name_len);
5949 btrfs_mark_buffer_dirty(path->nodes[0]);
5950 btrfs_free_path(path);
5952 btrfs_inherit_iflags(inode, dir);
5954 if (S_ISREG(mode)) {
5955 if (btrfs_test_opt(fs_info, NODATASUM))
5956 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATASUM;
5957 if (btrfs_test_opt(fs_info, NODATACOW))
5958 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATACOW |
5959 BTRFS_INODE_NODATASUM;
5962 inode_tree_add(inode);
5964 trace_btrfs_inode_new(inode);
5965 btrfs_set_inode_last_trans(trans, inode);
5967 btrfs_update_root_times(trans, root);
5969 ret = btrfs_inode_inherit_props(trans, inode, dir);
5972 "error inheriting props for ino %llu (root %llu): %d",
5973 btrfs_ino(BTRFS_I(inode)), root->root_key.objectid, ret);
5978 discard_new_inode(inode);
5981 BTRFS_I(dir)->index_cnt--;
5982 btrfs_free_path(path);
5983 return ERR_PTR(ret);
5987 * utility function to add 'inode' into 'parent_inode' with
5988 * a give name and a given sequence number.
5989 * if 'add_backref' is true, also insert a backref from the
5990 * inode to the parent directory.
5992 int btrfs_add_link(struct btrfs_trans_handle *trans,
5993 struct btrfs_inode *parent_inode, struct btrfs_inode *inode,
5994 const char *name, int name_len, int add_backref, u64 index)
5997 struct btrfs_key key;
5998 struct btrfs_root *root = parent_inode->root;
5999 u64 ino = btrfs_ino(inode);
6000 u64 parent_ino = btrfs_ino(parent_inode);
6002 if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
6003 memcpy(&key, &inode->root->root_key, sizeof(key));
6006 key.type = BTRFS_INODE_ITEM_KEY;
6010 if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
6011 ret = btrfs_add_root_ref(trans, key.objectid,
6012 root->root_key.objectid, parent_ino,
6013 index, name, name_len);
6014 } else if (add_backref) {
6015 ret = btrfs_insert_inode_ref(trans, root, name, name_len, ino,
6019 /* Nothing to clean up yet */
6023 ret = btrfs_insert_dir_item(trans, name, name_len, parent_inode, &key,
6024 btrfs_inode_type(&inode->vfs_inode), index);
6025 if (ret == -EEXIST || ret == -EOVERFLOW)
6028 btrfs_abort_transaction(trans, ret);
6032 btrfs_i_size_write(parent_inode, parent_inode->vfs_inode.i_size +
6034 inode_inc_iversion(&parent_inode->vfs_inode);
6036 * If we are replaying a log tree, we do not want to update the mtime
6037 * and ctime of the parent directory with the current time, since the
6038 * log replay procedure is responsible for setting them to their correct
6039 * values (the ones it had when the fsync was done).
6041 if (!test_bit(BTRFS_FS_LOG_RECOVERING, &root->fs_info->flags)) {
6042 struct timespec64 now = current_time(&parent_inode->vfs_inode);
6044 parent_inode->vfs_inode.i_mtime = now;
6045 parent_inode->vfs_inode.i_ctime = now;
6047 ret = btrfs_update_inode(trans, root, &parent_inode->vfs_inode);
6049 btrfs_abort_transaction(trans, ret);
6053 if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
6056 err = btrfs_del_root_ref(trans, key.objectid,
6057 root->root_key.objectid, parent_ino,
6058 &local_index, name, name_len);
6060 btrfs_abort_transaction(trans, err);
6061 } else if (add_backref) {
6065 err = btrfs_del_inode_ref(trans, root, name, name_len,
6066 ino, parent_ino, &local_index);
6068 btrfs_abort_transaction(trans, err);
6071 /* Return the original error code */
6075 static int btrfs_add_nondir(struct btrfs_trans_handle *trans,
6076 struct btrfs_inode *dir, struct dentry *dentry,
6077 struct btrfs_inode *inode, int backref, u64 index)
6079 int err = btrfs_add_link(trans, dir, inode,
6080 dentry->d_name.name, dentry->d_name.len,
6087 static int btrfs_mknod(struct inode *dir, struct dentry *dentry,
6088 umode_t mode, dev_t rdev)
6090 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
6091 struct btrfs_trans_handle *trans;
6092 struct btrfs_root *root = BTRFS_I(dir)->root;
6093 struct inode *inode = NULL;
6099 * 2 for inode item and ref
6101 * 1 for xattr if selinux is on
6103 trans = btrfs_start_transaction(root, 5);
6105 return PTR_ERR(trans);
6107 err = btrfs_find_free_ino(root, &objectid);
6111 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
6112 dentry->d_name.len, btrfs_ino(BTRFS_I(dir)), objectid,
6114 if (IS_ERR(inode)) {
6115 err = PTR_ERR(inode);
6121 * If the active LSM wants to access the inode during
6122 * d_instantiate it needs these. Smack checks to see
6123 * if the filesystem supports xattrs by looking at the
6126 inode->i_op = &btrfs_special_inode_operations;
6127 init_special_inode(inode, inode->i_mode, rdev);
6129 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
6133 err = btrfs_add_nondir(trans, BTRFS_I(dir), dentry, BTRFS_I(inode),
6138 btrfs_update_inode(trans, root, inode);
6139 d_instantiate_new(dentry, inode);
6142 btrfs_end_transaction(trans);
6143 btrfs_btree_balance_dirty(fs_info);
6145 inode_dec_link_count(inode);
6146 discard_new_inode(inode);
6151 static int btrfs_create(struct inode *dir, struct dentry *dentry,
6152 umode_t mode, bool excl)
6154 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
6155 struct btrfs_trans_handle *trans;
6156 struct btrfs_root *root = BTRFS_I(dir)->root;
6157 struct inode *inode = NULL;
6163 * 2 for inode item and ref
6165 * 1 for xattr if selinux is on
6167 trans = btrfs_start_transaction(root, 5);
6169 return PTR_ERR(trans);
6171 err = btrfs_find_free_ino(root, &objectid);
6175 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
6176 dentry->d_name.len, btrfs_ino(BTRFS_I(dir)), objectid,
6178 if (IS_ERR(inode)) {
6179 err = PTR_ERR(inode);
6184 * If the active LSM wants to access the inode during
6185 * d_instantiate it needs these. Smack checks to see
6186 * if the filesystem supports xattrs by looking at the
6189 inode->i_fop = &btrfs_file_operations;
6190 inode->i_op = &btrfs_file_inode_operations;
6191 inode->i_mapping->a_ops = &btrfs_aops;
6193 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
6197 err = btrfs_update_inode(trans, root, inode);
6201 err = btrfs_add_nondir(trans, BTRFS_I(dir), dentry, BTRFS_I(inode),
6206 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
6207 d_instantiate_new(dentry, inode);
6210 btrfs_end_transaction(trans);
6212 inode_dec_link_count(inode);
6213 discard_new_inode(inode);
6215 btrfs_btree_balance_dirty(fs_info);
6219 static int btrfs_link(struct dentry *old_dentry, struct inode *dir,
6220 struct dentry *dentry)
6222 struct btrfs_trans_handle *trans = NULL;
6223 struct btrfs_root *root = BTRFS_I(dir)->root;
6224 struct inode *inode = d_inode(old_dentry);
6225 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
6230 /* do not allow sys_link's with other subvols of the same device */
6231 if (root->root_key.objectid != BTRFS_I(inode)->root->root_key.objectid)
6234 if (inode->i_nlink >= BTRFS_LINK_MAX)
6237 err = btrfs_set_inode_index(BTRFS_I(dir), &index);
6242 * 2 items for inode and inode ref
6243 * 2 items for dir items
6244 * 1 item for parent inode
6245 * 1 item for orphan item deletion if O_TMPFILE
6247 trans = btrfs_start_transaction(root, inode->i_nlink ? 5 : 6);
6248 if (IS_ERR(trans)) {
6249 err = PTR_ERR(trans);
6254 /* There are several dir indexes for this inode, clear the cache. */
6255 BTRFS_I(inode)->dir_index = 0ULL;
6257 inode_inc_iversion(inode);
6258 inode->i_ctime = current_time(inode);
6260 set_bit(BTRFS_INODE_COPY_EVERYTHING, &BTRFS_I(inode)->runtime_flags);
6262 err = btrfs_add_nondir(trans, BTRFS_I(dir), dentry, BTRFS_I(inode),
6268 struct dentry *parent = dentry->d_parent;
6271 err = btrfs_update_inode(trans, root, inode);
6274 if (inode->i_nlink == 1) {
6276 * If new hard link count is 1, it's a file created
6277 * with open(2) O_TMPFILE flag.
6279 err = btrfs_orphan_del(trans, BTRFS_I(inode));
6283 d_instantiate(dentry, inode);
6284 ret = btrfs_log_new_name(trans, BTRFS_I(inode), NULL, parent,
6286 if (ret == BTRFS_NEED_TRANS_COMMIT) {
6287 err = btrfs_commit_transaction(trans);
6294 btrfs_end_transaction(trans);
6296 inode_dec_link_count(inode);
6299 btrfs_btree_balance_dirty(fs_info);
6303 static int btrfs_mkdir(struct inode *dir, struct dentry *dentry, umode_t mode)
6305 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
6306 struct inode *inode = NULL;
6307 struct btrfs_trans_handle *trans;
6308 struct btrfs_root *root = BTRFS_I(dir)->root;
6314 * 2 items for inode and ref
6315 * 2 items for dir items
6316 * 1 for xattr if selinux is on
6318 trans = btrfs_start_transaction(root, 5);
6320 return PTR_ERR(trans);
6322 err = btrfs_find_free_ino(root, &objectid);
6326 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
6327 dentry->d_name.len, btrfs_ino(BTRFS_I(dir)), objectid,
6328 S_IFDIR | mode, &index);
6329 if (IS_ERR(inode)) {
6330 err = PTR_ERR(inode);
6335 /* these must be set before we unlock the inode */
6336 inode->i_op = &btrfs_dir_inode_operations;
6337 inode->i_fop = &btrfs_dir_file_operations;
6339 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
6343 btrfs_i_size_write(BTRFS_I(inode), 0);
6344 err = btrfs_update_inode(trans, root, inode);
6348 err = btrfs_add_link(trans, BTRFS_I(dir), BTRFS_I(inode),
6349 dentry->d_name.name,
6350 dentry->d_name.len, 0, index);
6354 d_instantiate_new(dentry, inode);
6357 btrfs_end_transaction(trans);
6359 inode_dec_link_count(inode);
6360 discard_new_inode(inode);
6362 btrfs_btree_balance_dirty(fs_info);
6366 static noinline int uncompress_inline(struct btrfs_path *path,
6368 size_t pg_offset, u64 extent_offset,
6369 struct btrfs_file_extent_item *item)
6372 struct extent_buffer *leaf = path->nodes[0];
6375 unsigned long inline_size;
6379 WARN_ON(pg_offset != 0);
6380 compress_type = btrfs_file_extent_compression(leaf, item);
6381 max_size = btrfs_file_extent_ram_bytes(leaf, item);
6382 inline_size = btrfs_file_extent_inline_item_len(leaf,
6383 btrfs_item_nr(path->slots[0]));
6384 tmp = kmalloc(inline_size, GFP_NOFS);
6387 ptr = btrfs_file_extent_inline_start(item);
6389 read_extent_buffer(leaf, tmp, ptr, inline_size);
6391 max_size = min_t(unsigned long, PAGE_SIZE, max_size);
6392 ret = btrfs_decompress(compress_type, tmp, page,
6393 extent_offset, inline_size, max_size);
6396 * decompression code contains a memset to fill in any space between the end
6397 * of the uncompressed data and the end of max_size in case the decompressed
6398 * data ends up shorter than ram_bytes. That doesn't cover the hole between
6399 * the end of an inline extent and the beginning of the next block, so we
6400 * cover that region here.
6403 if (max_size + pg_offset < PAGE_SIZE) {
6404 char *map = kmap(page);
6405 memset(map + pg_offset + max_size, 0, PAGE_SIZE - max_size - pg_offset);
6413 * btrfs_get_extent - Lookup the first extent overlapping a range in a file.
6414 * @inode: file to search in
6415 * @page: page to read extent data into if the extent is inline
6416 * @pg_offset: offset into @page to copy to
6417 * @start: file offset
6418 * @len: length of range starting at @start
6420 * This returns the first &struct extent_map which overlaps with the given
6421 * range, reading it from the B-tree and caching it if necessary. Note that
6422 * there may be more extents which overlap the given range after the returned
6425 * If @page is not NULL and the extent is inline, this also reads the extent
6426 * data directly into the page and marks the extent up to date in the io_tree.
6428 * Return: ERR_PTR on error, non-NULL extent_map on success.
6430 struct extent_map *btrfs_get_extent(struct btrfs_inode *inode,
6431 struct page *page, size_t pg_offset,
6434 struct btrfs_fs_info *fs_info = inode->root->fs_info;
6437 u64 extent_start = 0;
6439 u64 objectid = btrfs_ino(inode);
6440 int extent_type = -1;
6441 struct btrfs_path *path = NULL;
6442 struct btrfs_root *root = inode->root;
6443 struct btrfs_file_extent_item *item;
6444 struct extent_buffer *leaf;
6445 struct btrfs_key found_key;
6446 struct extent_map *em = NULL;
6447 struct extent_map_tree *em_tree = &inode->extent_tree;
6448 struct extent_io_tree *io_tree = &inode->io_tree;
6450 read_lock(&em_tree->lock);
6451 em = lookup_extent_mapping(em_tree, start, len);
6452 read_unlock(&em_tree->lock);
6455 if (em->start > start || em->start + em->len <= start)
6456 free_extent_map(em);
6457 else if (em->block_start == EXTENT_MAP_INLINE && page)
6458 free_extent_map(em);
6462 em = alloc_extent_map();
6467 em->start = EXTENT_MAP_HOLE;
6468 em->orig_start = EXTENT_MAP_HOLE;
6470 em->block_len = (u64)-1;
6472 path = btrfs_alloc_path();
6478 /* Chances are we'll be called again, so go ahead and do readahead */
6479 path->reada = READA_FORWARD;
6482 * Unless we're going to uncompress the inline extent, no sleep would
6485 path->leave_spinning = 1;
6487 ret = btrfs_lookup_file_extent(NULL, root, path, objectid, start, 0);
6491 } else if (ret > 0) {
6492 if (path->slots[0] == 0)
6497 leaf = path->nodes[0];
6498 item = btrfs_item_ptr(leaf, path->slots[0],
6499 struct btrfs_file_extent_item);
6500 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
6501 if (found_key.objectid != objectid ||
6502 found_key.type != BTRFS_EXTENT_DATA_KEY) {
6504 * If we backup past the first extent we want to move forward
6505 * and see if there is an extent in front of us, otherwise we'll
6506 * say there is a hole for our whole search range which can
6513 extent_type = btrfs_file_extent_type(leaf, item);
6514 extent_start = found_key.offset;
6515 extent_end = btrfs_file_extent_end(path);
6516 if (extent_type == BTRFS_FILE_EXTENT_REG ||
6517 extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
6518 /* Only regular file could have regular/prealloc extent */
6519 if (!S_ISREG(inode->vfs_inode.i_mode)) {
6522 "regular/prealloc extent found for non-regular inode %llu",
6526 trace_btrfs_get_extent_show_fi_regular(inode, leaf, item,
6528 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
6529 trace_btrfs_get_extent_show_fi_inline(inode, leaf, item,
6534 if (start >= extent_end) {
6536 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
6537 ret = btrfs_next_leaf(root, path);
6541 } else if (ret > 0) {
6544 leaf = path->nodes[0];
6546 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
6547 if (found_key.objectid != objectid ||
6548 found_key.type != BTRFS_EXTENT_DATA_KEY)
6550 if (start + len <= found_key.offset)
6552 if (start > found_key.offset)
6555 /* New extent overlaps with existing one */
6557 em->orig_start = start;
6558 em->len = found_key.offset - start;
6559 em->block_start = EXTENT_MAP_HOLE;
6563 btrfs_extent_item_to_extent_map(inode, path, item, !page, em);
6565 if (extent_type == BTRFS_FILE_EXTENT_REG ||
6566 extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
6568 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
6572 size_t extent_offset;
6578 size = btrfs_file_extent_ram_bytes(leaf, item);
6579 extent_offset = page_offset(page) + pg_offset - extent_start;
6580 copy_size = min_t(u64, PAGE_SIZE - pg_offset,
6581 size - extent_offset);
6582 em->start = extent_start + extent_offset;
6583 em->len = ALIGN(copy_size, fs_info->sectorsize);
6584 em->orig_block_len = em->len;
6585 em->orig_start = em->start;
6586 ptr = btrfs_file_extent_inline_start(item) + extent_offset;
6588 btrfs_set_path_blocking(path);
6589 if (!PageUptodate(page)) {
6590 if (btrfs_file_extent_compression(leaf, item) !=
6591 BTRFS_COMPRESS_NONE) {
6592 ret = uncompress_inline(path, page, pg_offset,
6593 extent_offset, item);
6600 read_extent_buffer(leaf, map + pg_offset, ptr,
6602 if (pg_offset + copy_size < PAGE_SIZE) {
6603 memset(map + pg_offset + copy_size, 0,
6604 PAGE_SIZE - pg_offset -
6609 flush_dcache_page(page);
6611 set_extent_uptodate(io_tree, em->start,
6612 extent_map_end(em) - 1, NULL, GFP_NOFS);
6617 em->orig_start = start;
6619 em->block_start = EXTENT_MAP_HOLE;
6621 btrfs_release_path(path);
6622 if (em->start > start || extent_map_end(em) <= start) {
6624 "bad extent! em: [%llu %llu] passed [%llu %llu]",
6625 em->start, em->len, start, len);
6631 write_lock(&em_tree->lock);
6632 err = btrfs_add_extent_mapping(fs_info, em_tree, &em, start, len);
6633 write_unlock(&em_tree->lock);
6635 btrfs_free_path(path);
6637 trace_btrfs_get_extent(root, inode, em);
6640 free_extent_map(em);
6641 return ERR_PTR(err);
6643 BUG_ON(!em); /* Error is always set */
6647 struct extent_map *btrfs_get_extent_fiemap(struct btrfs_inode *inode,
6650 struct extent_map *em;
6651 struct extent_map *hole_em = NULL;
6652 u64 delalloc_start = start;
6658 em = btrfs_get_extent(inode, NULL, 0, start, len);
6662 * If our em maps to:
6664 * - a pre-alloc extent,
6665 * there might actually be delalloc bytes behind it.
6667 if (em->block_start != EXTENT_MAP_HOLE &&
6668 !test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
6673 /* check to see if we've wrapped (len == -1 or similar) */
6682 /* ok, we didn't find anything, lets look for delalloc */
6683 delalloc_len = count_range_bits(&inode->io_tree, &delalloc_start,
6684 end, len, EXTENT_DELALLOC, 1);
6685 delalloc_end = delalloc_start + delalloc_len;
6686 if (delalloc_end < delalloc_start)
6687 delalloc_end = (u64)-1;
6690 * We didn't find anything useful, return the original results from
6693 if (delalloc_start > end || delalloc_end <= start) {
6700 * Adjust the delalloc_start to make sure it doesn't go backwards from
6701 * the start they passed in
6703 delalloc_start = max(start, delalloc_start);
6704 delalloc_len = delalloc_end - delalloc_start;
6706 if (delalloc_len > 0) {
6709 const u64 hole_end = extent_map_end(hole_em);
6711 em = alloc_extent_map();
6719 * When btrfs_get_extent can't find anything it returns one
6722 * Make sure what it found really fits our range, and adjust to
6723 * make sure it is based on the start from the caller
6725 if (hole_end <= start || hole_em->start > end) {
6726 free_extent_map(hole_em);
6729 hole_start = max(hole_em->start, start);
6730 hole_len = hole_end - hole_start;
6733 if (hole_em && delalloc_start > hole_start) {
6735 * Our hole starts before our delalloc, so we have to
6736 * return just the parts of the hole that go until the
6739 em->len = min(hole_len, delalloc_start - hole_start);
6740 em->start = hole_start;
6741 em->orig_start = hole_start;
6743 * Don't adjust block start at all, it is fixed at
6746 em->block_start = hole_em->block_start;
6747 em->block_len = hole_len;
6748 if (test_bit(EXTENT_FLAG_PREALLOC, &hole_em->flags))
6749 set_bit(EXTENT_FLAG_PREALLOC, &em->flags);
6752 * Hole is out of passed range or it starts after
6755 em->start = delalloc_start;
6756 em->len = delalloc_len;
6757 em->orig_start = delalloc_start;
6758 em->block_start = EXTENT_MAP_DELALLOC;
6759 em->block_len = delalloc_len;
6766 free_extent_map(hole_em);
6768 free_extent_map(em);
6769 return ERR_PTR(err);
6774 static struct extent_map *btrfs_create_dio_extent(struct inode *inode,
6777 const u64 orig_start,
6778 const u64 block_start,
6779 const u64 block_len,
6780 const u64 orig_block_len,
6781 const u64 ram_bytes,
6784 struct extent_map *em = NULL;
6787 if (type != BTRFS_ORDERED_NOCOW) {
6788 em = create_io_em(inode, start, len, orig_start,
6789 block_start, block_len, orig_block_len,
6791 BTRFS_COMPRESS_NONE, /* compress_type */
6796 ret = btrfs_add_ordered_extent_dio(inode, start, block_start,
6797 len, block_len, type);
6800 free_extent_map(em);
6801 btrfs_drop_extent_cache(BTRFS_I(inode), start,
6802 start + len - 1, 0);
6811 static struct extent_map *btrfs_new_extent_direct(struct inode *inode,
6814 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
6815 struct btrfs_root *root = BTRFS_I(inode)->root;
6816 struct extent_map *em;
6817 struct btrfs_key ins;
6821 alloc_hint = get_extent_allocation_hint(inode, start, len);
6822 ret = btrfs_reserve_extent(root, len, len, fs_info->sectorsize,
6823 0, alloc_hint, &ins, 1, 1);
6825 return ERR_PTR(ret);
6827 em = btrfs_create_dio_extent(inode, start, ins.offset, start,
6828 ins.objectid, ins.offset, ins.offset,
6829 ins.offset, BTRFS_ORDERED_REGULAR);
6830 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
6832 btrfs_free_reserved_extent(fs_info, ins.objectid,
6839 * returns 1 when the nocow is safe, < 1 on error, 0 if the
6840 * block must be cow'd
6842 noinline int can_nocow_extent(struct inode *inode, u64 offset, u64 *len,
6843 u64 *orig_start, u64 *orig_block_len,
6846 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
6847 struct btrfs_path *path;
6849 struct extent_buffer *leaf;
6850 struct btrfs_root *root = BTRFS_I(inode)->root;
6851 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
6852 struct btrfs_file_extent_item *fi;
6853 struct btrfs_key key;
6860 bool nocow = (BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW);
6862 path = btrfs_alloc_path();
6866 ret = btrfs_lookup_file_extent(NULL, root, path,
6867 btrfs_ino(BTRFS_I(inode)), offset, 0);
6871 slot = path->slots[0];
6874 /* can't find the item, must cow */
6881 leaf = path->nodes[0];
6882 btrfs_item_key_to_cpu(leaf, &key, slot);
6883 if (key.objectid != btrfs_ino(BTRFS_I(inode)) ||
6884 key.type != BTRFS_EXTENT_DATA_KEY) {
6885 /* not our file or wrong item type, must cow */
6889 if (key.offset > offset) {
6890 /* Wrong offset, must cow */
6894 fi = btrfs_item_ptr(leaf, slot, struct btrfs_file_extent_item);
6895 found_type = btrfs_file_extent_type(leaf, fi);
6896 if (found_type != BTRFS_FILE_EXTENT_REG &&
6897 found_type != BTRFS_FILE_EXTENT_PREALLOC) {
6898 /* not a regular extent, must cow */
6902 if (!nocow && found_type == BTRFS_FILE_EXTENT_REG)
6905 extent_end = key.offset + btrfs_file_extent_num_bytes(leaf, fi);
6906 if (extent_end <= offset)
6909 disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
6910 if (disk_bytenr == 0)
6913 if (btrfs_file_extent_compression(leaf, fi) ||
6914 btrfs_file_extent_encryption(leaf, fi) ||
6915 btrfs_file_extent_other_encoding(leaf, fi))
6919 * Do the same check as in btrfs_cross_ref_exist but without the
6920 * unnecessary search.
6922 if (btrfs_file_extent_generation(leaf, fi) <=
6923 btrfs_root_last_snapshot(&root->root_item))
6926 backref_offset = btrfs_file_extent_offset(leaf, fi);
6929 *orig_start = key.offset - backref_offset;
6930 *orig_block_len = btrfs_file_extent_disk_num_bytes(leaf, fi);
6931 *ram_bytes = btrfs_file_extent_ram_bytes(leaf, fi);
6934 if (btrfs_extent_readonly(fs_info, disk_bytenr))
6937 num_bytes = min(offset + *len, extent_end) - offset;
6938 if (!nocow && found_type == BTRFS_FILE_EXTENT_PREALLOC) {
6941 range_end = round_up(offset + num_bytes,
6942 root->fs_info->sectorsize) - 1;
6943 ret = test_range_bit(io_tree, offset, range_end,
6944 EXTENT_DELALLOC, 0, NULL);
6951 btrfs_release_path(path);
6954 * look for other files referencing this extent, if we
6955 * find any we must cow
6958 ret = btrfs_cross_ref_exist(root, btrfs_ino(BTRFS_I(inode)),
6959 key.offset - backref_offset, disk_bytenr);
6966 * adjust disk_bytenr and num_bytes to cover just the bytes
6967 * in this extent we are about to write. If there
6968 * are any csums in that range we have to cow in order
6969 * to keep the csums correct
6971 disk_bytenr += backref_offset;
6972 disk_bytenr += offset - key.offset;
6973 if (csum_exist_in_range(fs_info, disk_bytenr, num_bytes))
6976 * all of the above have passed, it is safe to overwrite this extent
6982 btrfs_free_path(path);
6986 static int lock_extent_direct(struct inode *inode, u64 lockstart, u64 lockend,
6987 struct extent_state **cached_state, bool writing)
6989 struct btrfs_ordered_extent *ordered;
6993 lock_extent_bits(&BTRFS_I(inode)->io_tree, lockstart, lockend,
6996 * We're concerned with the entire range that we're going to be
6997 * doing DIO to, so we need to make sure there's no ordered
6998 * extents in this range.
7000 ordered = btrfs_lookup_ordered_range(BTRFS_I(inode), lockstart,
7001 lockend - lockstart + 1);
7004 * We need to make sure there are no buffered pages in this
7005 * range either, we could have raced between the invalidate in
7006 * generic_file_direct_write and locking the extent. The
7007 * invalidate needs to happen so that reads after a write do not
7011 (!writing || !filemap_range_has_page(inode->i_mapping,
7012 lockstart, lockend)))
7015 unlock_extent_cached(&BTRFS_I(inode)->io_tree, lockstart, lockend,
7020 * If we are doing a DIO read and the ordered extent we
7021 * found is for a buffered write, we can not wait for it
7022 * to complete and retry, because if we do so we can
7023 * deadlock with concurrent buffered writes on page
7024 * locks. This happens only if our DIO read covers more
7025 * than one extent map, if at this point has already
7026 * created an ordered extent for a previous extent map
7027 * and locked its range in the inode's io tree, and a
7028 * concurrent write against that previous extent map's
7029 * range and this range started (we unlock the ranges
7030 * in the io tree only when the bios complete and
7031 * buffered writes always lock pages before attempting
7032 * to lock range in the io tree).
7035 test_bit(BTRFS_ORDERED_DIRECT, &ordered->flags))
7036 btrfs_start_ordered_extent(inode, ordered, 1);
7039 btrfs_put_ordered_extent(ordered);
7042 * We could trigger writeback for this range (and wait
7043 * for it to complete) and then invalidate the pages for
7044 * this range (through invalidate_inode_pages2_range()),
7045 * but that can lead us to a deadlock with a concurrent
7046 * call to readpages() (a buffered read or a defrag call
7047 * triggered a readahead) on a page lock due to an
7048 * ordered dio extent we created before but did not have
7049 * yet a corresponding bio submitted (whence it can not
7050 * complete), which makes readpages() wait for that
7051 * ordered extent to complete while holding a lock on
7066 /* The callers of this must take lock_extent() */
7067 static struct extent_map *create_io_em(struct inode *inode, u64 start, u64 len,
7068 u64 orig_start, u64 block_start,
7069 u64 block_len, u64 orig_block_len,
7070 u64 ram_bytes, int compress_type,
7073 struct extent_map_tree *em_tree;
7074 struct extent_map *em;
7077 ASSERT(type == BTRFS_ORDERED_PREALLOC ||
7078 type == BTRFS_ORDERED_COMPRESSED ||
7079 type == BTRFS_ORDERED_NOCOW ||
7080 type == BTRFS_ORDERED_REGULAR);
7082 em_tree = &BTRFS_I(inode)->extent_tree;
7083 em = alloc_extent_map();
7085 return ERR_PTR(-ENOMEM);
7088 em->orig_start = orig_start;
7090 em->block_len = block_len;
7091 em->block_start = block_start;
7092 em->orig_block_len = orig_block_len;
7093 em->ram_bytes = ram_bytes;
7094 em->generation = -1;
7095 set_bit(EXTENT_FLAG_PINNED, &em->flags);
7096 if (type == BTRFS_ORDERED_PREALLOC) {
7097 set_bit(EXTENT_FLAG_FILLING, &em->flags);
7098 } else if (type == BTRFS_ORDERED_COMPRESSED) {
7099 set_bit(EXTENT_FLAG_COMPRESSED, &em->flags);
7100 em->compress_type = compress_type;
7104 btrfs_drop_extent_cache(BTRFS_I(inode), em->start,
7105 em->start + em->len - 1, 0);
7106 write_lock(&em_tree->lock);
7107 ret = add_extent_mapping(em_tree, em, 1);
7108 write_unlock(&em_tree->lock);
7110 * The caller has taken lock_extent(), who could race with us
7113 } while (ret == -EEXIST);
7116 free_extent_map(em);
7117 return ERR_PTR(ret);
7120 /* em got 2 refs now, callers needs to do free_extent_map once. */
7125 static int btrfs_get_blocks_direct_write(struct extent_map **map,
7126 struct inode *inode,
7127 struct btrfs_dio_data *dio_data,
7130 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7131 struct extent_map *em = *map;
7135 * We don't allocate a new extent in the following cases
7137 * 1) The inode is marked as NODATACOW. In this case we'll just use the
7139 * 2) The extent is marked as PREALLOC. We're good to go here and can
7140 * just use the extent.
7143 if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags) ||
7144 ((BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW) &&
7145 em->block_start != EXTENT_MAP_HOLE)) {
7147 u64 block_start, orig_start, orig_block_len, ram_bytes;
7149 if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
7150 type = BTRFS_ORDERED_PREALLOC;
7152 type = BTRFS_ORDERED_NOCOW;
7153 len = min(len, em->len - (start - em->start));
7154 block_start = em->block_start + (start - em->start);
7156 if (can_nocow_extent(inode, start, &len, &orig_start,
7157 &orig_block_len, &ram_bytes) == 1 &&
7158 btrfs_inc_nocow_writers(fs_info, block_start)) {
7159 struct extent_map *em2;
7161 em2 = btrfs_create_dio_extent(inode, start, len,
7162 orig_start, block_start,
7163 len, orig_block_len,
7165 btrfs_dec_nocow_writers(fs_info, block_start);
7166 if (type == BTRFS_ORDERED_PREALLOC) {
7167 free_extent_map(em);
7171 if (em2 && IS_ERR(em2)) {
7176 * For inode marked NODATACOW or extent marked PREALLOC,
7177 * use the existing or preallocated extent, so does not
7178 * need to adjust btrfs_space_info's bytes_may_use.
7180 btrfs_free_reserved_data_space_noquota(inode, start,
7186 /* this will cow the extent */
7187 free_extent_map(em);
7188 *map = em = btrfs_new_extent_direct(inode, start, len);
7194 len = min(len, em->len - (start - em->start));
7198 * Need to update the i_size under the extent lock so buffered
7199 * readers will get the updated i_size when we unlock.
7201 if (start + len > i_size_read(inode))
7202 i_size_write(inode, start + len);
7204 dio_data->reserve -= len;
7209 static int btrfs_dio_iomap_begin(struct inode *inode, loff_t start,
7210 loff_t length, unsigned flags, struct iomap *iomap,
7211 struct iomap *srcmap)
7213 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7214 struct extent_map *em;
7215 struct extent_state *cached_state = NULL;
7216 struct btrfs_dio_data *dio_data = NULL;
7217 u64 lockstart, lockend;
7218 const bool write = !!(flags & IOMAP_WRITE);
7221 bool unlock_extents = false;
7224 len = min_t(u64, len, fs_info->sectorsize);
7227 lockend = start + len - 1;
7230 * The generic stuff only does filemap_write_and_wait_range, which
7231 * isn't enough if we've written compressed pages to this area, so we
7232 * need to flush the dirty pages again to make absolutely sure that any
7233 * outstanding dirty pages are on disk.
7235 if (test_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
7236 &BTRFS_I(inode)->runtime_flags))
7237 ret = filemap_fdatawrite_range(inode->i_mapping, start,
7238 start + length - 1);
7240 dio_data = kzalloc(sizeof(*dio_data), GFP_NOFS);
7244 dio_data->length = length;
7246 dio_data->reserve = round_up(length, fs_info->sectorsize);
7247 ret = btrfs_delalloc_reserve_space(inode,
7248 &dio_data->data_reserved,
7249 start, dio_data->reserve);
7251 extent_changeset_free(dio_data->data_reserved);
7256 iomap->private = dio_data;
7260 * If this errors out it's because we couldn't invalidate pagecache for
7261 * this range and we need to fallback to buffered.
7263 if (lock_extent_direct(inode, lockstart, lockend, &cached_state, write)) {
7268 em = btrfs_get_extent(BTRFS_I(inode), NULL, 0, start, len);
7275 * Ok for INLINE and COMPRESSED extents we need to fallback on buffered
7276 * io. INLINE is special, and we could probably kludge it in here, but
7277 * it's still buffered so for safety lets just fall back to the generic
7280 * For COMPRESSED we _have_ to read the entire extent in so we can
7281 * decompress it, so there will be buffering required no matter what we
7282 * do, so go ahead and fallback to buffered.
7284 * We return -ENOTBLK because that's what makes DIO go ahead and go back
7285 * to buffered IO. Don't blame me, this is the price we pay for using
7288 if (test_bit(EXTENT_FLAG_COMPRESSED, &em->flags) ||
7289 em->block_start == EXTENT_MAP_INLINE) {
7290 free_extent_map(em);
7295 len = min(len, em->len - (start - em->start));
7297 ret = btrfs_get_blocks_direct_write(&em, inode, dio_data,
7301 unlock_extents = true;
7302 /* Recalc len in case the new em is smaller than requested */
7303 len = min(len, em->len - (start - em->start));
7306 * We need to unlock only the end area that we aren't using.
7307 * The rest is going to be unlocked by the endio routine.
7309 lockstart = start + len;
7310 if (lockstart < lockend)
7311 unlock_extents = true;
7315 unlock_extent_cached(&BTRFS_I(inode)->io_tree,
7316 lockstart, lockend, &cached_state);
7318 free_extent_state(cached_state);
7321 * Translate extent map information to iomap.
7322 * We trim the extents (and move the addr) even though iomap code does
7323 * that, since we have locked only the parts we are performing I/O in.
7325 if ((em->block_start == EXTENT_MAP_HOLE) ||
7326 (test_bit(EXTENT_FLAG_PREALLOC, &em->flags) && !write)) {
7327 iomap->addr = IOMAP_NULL_ADDR;
7328 iomap->type = IOMAP_HOLE;
7330 iomap->addr = em->block_start + (start - em->start);
7331 iomap->type = IOMAP_MAPPED;
7333 iomap->offset = start;
7334 iomap->bdev = fs_info->fs_devices->latest_bdev;
7335 iomap->length = len;
7337 free_extent_map(em);
7342 unlock_extent_cached(&BTRFS_I(inode)->io_tree, lockstart, lockend,
7346 btrfs_delalloc_release_space(inode, dio_data->data_reserved,
7347 start, dio_data->reserve, true);
7348 btrfs_delalloc_release_extents(BTRFS_I(inode), dio_data->reserve);
7349 extent_changeset_free(dio_data->data_reserved);
7355 static int btrfs_dio_iomap_end(struct inode *inode, loff_t pos, loff_t length,
7356 ssize_t written, unsigned flags, struct iomap *iomap)
7359 struct btrfs_dio_data *dio_data = iomap->private;
7360 size_t submitted = dio_data->submitted;
7361 const bool write = !!(flags & IOMAP_WRITE);
7363 if (!write && (iomap->type == IOMAP_HOLE)) {
7364 /* If reading from a hole, unlock and return */
7365 unlock_extent(&BTRFS_I(inode)->io_tree, pos, pos + length - 1);
7369 if (submitted < length) {
7371 length -= submitted;
7373 __endio_write_update_ordered(inode, pos, length, false);
7375 unlock_extent(&BTRFS_I(inode)->io_tree, pos,
7381 if (dio_data->reserve)
7382 btrfs_delalloc_release_space(inode,
7383 dio_data->data_reserved, pos,
7384 dio_data->reserve, true);
7385 btrfs_delalloc_release_extents(BTRFS_I(inode), dio_data->length);
7386 extent_changeset_free(dio_data->data_reserved);
7390 iomap->private = NULL;
7395 static void btrfs_dio_private_put(struct btrfs_dio_private *dip)
7398 * This implies a barrier so that stores to dio_bio->bi_status before
7399 * this and loads of dio_bio->bi_status after this are fully ordered.
7401 if (!refcount_dec_and_test(&dip->refs))
7404 if (bio_op(dip->dio_bio) == REQ_OP_WRITE) {
7405 __endio_write_update_ordered(dip->inode, dip->logical_offset,
7407 !dip->dio_bio->bi_status);
7409 unlock_extent(&BTRFS_I(dip->inode)->io_tree,
7410 dip->logical_offset,
7411 dip->logical_offset + dip->bytes - 1);
7414 bio_endio(dip->dio_bio);
7418 static blk_status_t submit_dio_repair_bio(struct inode *inode, struct bio *bio,
7420 unsigned long bio_flags)
7422 struct btrfs_dio_private *dip = bio->bi_private;
7423 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7426 BUG_ON(bio_op(bio) == REQ_OP_WRITE);
7428 ret = btrfs_bio_wq_end_io(fs_info, bio, BTRFS_WQ_ENDIO_DATA);
7432 refcount_inc(&dip->refs);
7433 ret = btrfs_map_bio(fs_info, bio, mirror_num);
7435 refcount_dec(&dip->refs);
7439 static blk_status_t btrfs_check_read_dio_bio(struct inode *inode,
7440 struct btrfs_io_bio *io_bio,
7441 const bool uptodate)
7443 struct btrfs_fs_info *fs_info = BTRFS_I(inode)->root->fs_info;
7444 const u32 sectorsize = fs_info->sectorsize;
7445 struct extent_io_tree *failure_tree = &BTRFS_I(inode)->io_failure_tree;
7446 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
7447 const bool csum = !(BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM);
7448 struct bio_vec bvec;
7449 struct bvec_iter iter;
7450 u64 start = io_bio->logical;
7452 blk_status_t err = BLK_STS_OK;
7454 __bio_for_each_segment(bvec, &io_bio->bio, iter, io_bio->iter) {
7455 unsigned int i, nr_sectors, pgoff;
7457 nr_sectors = BTRFS_BYTES_TO_BLKS(fs_info, bvec.bv_len);
7458 pgoff = bvec.bv_offset;
7459 for (i = 0; i < nr_sectors; i++) {
7460 ASSERT(pgoff < PAGE_SIZE);
7462 (!csum || !check_data_csum(inode, io_bio, icsum,
7463 bvec.bv_page, pgoff,
7464 start, sectorsize))) {
7465 clean_io_failure(fs_info, failure_tree, io_tree,
7466 start, bvec.bv_page,
7467 btrfs_ino(BTRFS_I(inode)),
7470 blk_status_t status;
7472 status = btrfs_submit_read_repair(inode,
7474 start - io_bio->logical,
7475 bvec.bv_page, pgoff,
7477 start + sectorsize - 1,
7479 submit_dio_repair_bio);
7483 start += sectorsize;
7485 pgoff += sectorsize;
7491 static void __endio_write_update_ordered(struct inode *inode,
7492 const u64 offset, const u64 bytes,
7493 const bool uptodate)
7495 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7496 struct btrfs_ordered_extent *ordered = NULL;
7497 struct btrfs_workqueue *wq;
7498 u64 ordered_offset = offset;
7499 u64 ordered_bytes = bytes;
7502 if (btrfs_is_free_space_inode(BTRFS_I(inode)))
7503 wq = fs_info->endio_freespace_worker;
7505 wq = fs_info->endio_write_workers;
7507 while (ordered_offset < offset + bytes) {
7508 last_offset = ordered_offset;
7509 if (btrfs_dec_test_first_ordered_pending(inode, &ordered,
7513 btrfs_init_work(&ordered->work, finish_ordered_fn, NULL,
7515 btrfs_queue_work(wq, &ordered->work);
7518 * If btrfs_dec_test_ordered_pending does not find any ordered
7519 * extent in the range, we can exit.
7521 if (ordered_offset == last_offset)
7524 * Our bio might span multiple ordered extents. In this case
7525 * we keep going until we have accounted the whole dio.
7527 if (ordered_offset < offset + bytes) {
7528 ordered_bytes = offset + bytes - ordered_offset;
7534 static blk_status_t btrfs_submit_bio_start_direct_io(void *private_data,
7535 struct bio *bio, u64 offset)
7537 struct inode *inode = private_data;
7539 ret = btrfs_csum_one_bio(inode, bio, offset, 1);
7540 BUG_ON(ret); /* -ENOMEM */
7544 static void btrfs_end_dio_bio(struct bio *bio)
7546 struct btrfs_dio_private *dip = bio->bi_private;
7547 blk_status_t err = bio->bi_status;
7550 btrfs_warn(BTRFS_I(dip->inode)->root->fs_info,
7551 "direct IO failed ino %llu rw %d,%u sector %#Lx len %u err no %d",
7552 btrfs_ino(BTRFS_I(dip->inode)), bio_op(bio),
7554 (unsigned long long)bio->bi_iter.bi_sector,
7555 bio->bi_iter.bi_size, err);
7557 if (bio_op(bio) == REQ_OP_READ) {
7558 err = btrfs_check_read_dio_bio(dip->inode, btrfs_io_bio(bio),
7563 dip->dio_bio->bi_status = err;
7566 btrfs_dio_private_put(dip);
7569 static inline blk_status_t btrfs_submit_dio_bio(struct bio *bio,
7570 struct inode *inode, u64 file_offset, int async_submit)
7572 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7573 struct btrfs_dio_private *dip = bio->bi_private;
7574 bool write = bio_op(bio) == REQ_OP_WRITE;
7577 /* Check btrfs_submit_bio_hook() for rules about async submit. */
7579 async_submit = !atomic_read(&BTRFS_I(inode)->sync_writers);
7582 ret = btrfs_bio_wq_end_io(fs_info, bio, BTRFS_WQ_ENDIO_DATA);
7587 if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)
7590 if (write && async_submit) {
7591 ret = btrfs_wq_submit_bio(fs_info, bio, 0, 0,
7593 btrfs_submit_bio_start_direct_io);
7597 * If we aren't doing async submit, calculate the csum of the
7600 ret = btrfs_csum_one_bio(inode, bio, file_offset, 1);
7606 csum_offset = file_offset - dip->logical_offset;
7607 csum_offset >>= inode->i_sb->s_blocksize_bits;
7608 csum_offset *= btrfs_super_csum_size(fs_info->super_copy);
7609 btrfs_io_bio(bio)->csum = dip->csums + csum_offset;
7612 ret = btrfs_map_bio(fs_info, bio, 0);
7618 * If this succeeds, the btrfs_dio_private is responsible for cleaning up locked
7619 * or ordered extents whether or not we submit any bios.
7621 static struct btrfs_dio_private *btrfs_create_dio_private(struct bio *dio_bio,
7622 struct inode *inode,
7625 const bool write = (bio_op(dio_bio) == REQ_OP_WRITE);
7626 const bool csum = !(BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM);
7628 struct btrfs_dio_private *dip;
7630 dip_size = sizeof(*dip);
7631 if (!write && csum) {
7632 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7633 const u16 csum_size = btrfs_super_csum_size(fs_info->super_copy);
7636 nblocks = dio_bio->bi_iter.bi_size >> inode->i_sb->s_blocksize_bits;
7637 dip_size += csum_size * nblocks;
7640 dip = kzalloc(dip_size, GFP_NOFS);
7645 dip->logical_offset = file_offset;
7646 dip->bytes = dio_bio->bi_iter.bi_size;
7647 dip->disk_bytenr = (u64)dio_bio->bi_iter.bi_sector << 9;
7648 dip->dio_bio = dio_bio;
7649 refcount_set(&dip->refs, 1);
7653 static blk_qc_t btrfs_submit_direct(struct inode *inode, struct iomap *iomap,
7654 struct bio *dio_bio, loff_t file_offset)
7656 const bool write = (bio_op(dio_bio) == REQ_OP_WRITE);
7657 const bool csum = !(BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM);
7658 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7659 const bool raid56 = (btrfs_data_alloc_profile(fs_info) &
7660 BTRFS_BLOCK_GROUP_RAID56_MASK);
7661 struct btrfs_dio_private *dip;
7664 int async_submit = 0;
7666 int clone_offset = 0;
7669 blk_status_t status;
7670 struct btrfs_io_geometry geom;
7671 struct btrfs_dio_data *dio_data = iomap->private;
7673 dip = btrfs_create_dio_private(dio_bio, inode, file_offset);
7676 unlock_extent(&BTRFS_I(inode)->io_tree, file_offset,
7677 file_offset + dio_bio->bi_iter.bi_size - 1);
7679 dio_bio->bi_status = BLK_STS_RESOURCE;
7681 return BLK_QC_T_NONE;
7684 if (!write && csum) {
7686 * Load the csums up front to reduce csum tree searches and
7687 * contention when submitting bios.
7689 status = btrfs_lookup_bio_sums(inode, dio_bio, file_offset,
7691 if (status != BLK_STS_OK)
7695 start_sector = dio_bio->bi_iter.bi_sector;
7696 submit_len = dio_bio->bi_iter.bi_size;
7699 ret = btrfs_get_io_geometry(fs_info, btrfs_op(dio_bio),
7700 start_sector << 9, submit_len,
7703 status = errno_to_blk_status(ret);
7706 ASSERT(geom.len <= INT_MAX);
7708 clone_len = min_t(int, submit_len, geom.len);
7711 * This will never fail as it's passing GPF_NOFS and
7712 * the allocation is backed by btrfs_bioset.
7714 bio = btrfs_bio_clone_partial(dio_bio, clone_offset, clone_len);
7715 bio->bi_private = dip;
7716 bio->bi_end_io = btrfs_end_dio_bio;
7717 btrfs_io_bio(bio)->logical = file_offset;
7719 ASSERT(submit_len >= clone_len);
7720 submit_len -= clone_len;
7723 * Increase the count before we submit the bio so we know
7724 * the end IO handler won't happen before we increase the
7725 * count. Otherwise, the dip might get freed before we're
7726 * done setting it up.
7728 * We transfer the initial reference to the last bio, so we
7729 * don't need to increment the reference count for the last one.
7731 if (submit_len > 0) {
7732 refcount_inc(&dip->refs);
7734 * If we are submitting more than one bio, submit them
7735 * all asynchronously. The exception is RAID 5 or 6, as
7736 * asynchronous checksums make it difficult to collect
7737 * full stripe writes.
7743 status = btrfs_submit_dio_bio(bio, inode, file_offset,
7748 refcount_dec(&dip->refs);
7752 dio_data->submitted += clone_len;
7753 clone_offset += clone_len;
7754 start_sector += clone_len >> 9;
7755 file_offset += clone_len;
7756 } while (submit_len > 0);
7757 return BLK_QC_T_NONE;
7760 dip->dio_bio->bi_status = status;
7761 btrfs_dio_private_put(dip);
7762 return BLK_QC_T_NONE;
7765 static ssize_t check_direct_IO(struct btrfs_fs_info *fs_info,
7766 const struct iov_iter *iter, loff_t offset)
7770 unsigned int blocksize_mask = fs_info->sectorsize - 1;
7771 ssize_t retval = -EINVAL;
7773 if (offset & blocksize_mask)
7776 if (iov_iter_alignment(iter) & blocksize_mask)
7779 /* If this is a write we don't need to check anymore */
7780 if (iov_iter_rw(iter) != READ || !iter_is_iovec(iter))
7783 * Check to make sure we don't have duplicate iov_base's in this
7784 * iovec, if so return EINVAL, otherwise we'll get csum errors
7785 * when reading back.
7787 for (seg = 0; seg < iter->nr_segs; seg++) {
7788 for (i = seg + 1; i < iter->nr_segs; i++) {
7789 if (iter->iov[seg].iov_base == iter->iov[i].iov_base)
7798 static const struct iomap_ops btrfs_dio_iomap_ops = {
7799 .iomap_begin = btrfs_dio_iomap_begin,
7800 .iomap_end = btrfs_dio_iomap_end,
7803 static const struct iomap_dio_ops btrfs_dops = {
7804 .submit_io = btrfs_submit_direct,
7807 ssize_t btrfs_direct_IO(struct kiocb *iocb, struct iov_iter *iter)
7809 struct file *file = iocb->ki_filp;
7810 struct inode *inode = file->f_mapping->host;
7811 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7812 struct extent_changeset *data_reserved = NULL;
7813 loff_t offset = iocb->ki_pos;
7815 bool relock = false;
7818 if (check_direct_IO(fs_info, iter, offset))
7821 count = iov_iter_count(iter);
7822 if (iov_iter_rw(iter) == WRITE) {
7824 * If the write DIO is beyond the EOF, we need update
7825 * the isize, but it is protected by i_mutex. So we can
7826 * not unlock the i_mutex at this case.
7828 if (offset + count <= inode->i_size) {
7829 inode_unlock(inode);
7831 } else if (iocb->ki_flags & IOCB_NOWAIT) {
7835 down_read(&BTRFS_I(inode)->dio_sem);
7838 ret = iomap_dio_rw(iocb, iter, &btrfs_dio_iomap_ops, &btrfs_dops,
7839 is_sync_kiocb(iocb));
7841 if (iov_iter_rw(iter) == WRITE) {
7842 up_read(&BTRFS_I(inode)->dio_sem);
7847 extent_changeset_free(data_reserved);
7851 #define BTRFS_FIEMAP_FLAGS (FIEMAP_FLAG_SYNC)
7853 static int btrfs_fiemap(struct inode *inode, struct fiemap_extent_info *fieinfo,
7854 __u64 start, __u64 len)
7858 ret = fiemap_check_flags(fieinfo, BTRFS_FIEMAP_FLAGS);
7862 return extent_fiemap(inode, fieinfo, start, len);
7865 int btrfs_readpage(struct file *file, struct page *page)
7867 return extent_read_full_page(page, btrfs_get_extent, 0);
7870 static int btrfs_writepage(struct page *page, struct writeback_control *wbc)
7872 struct inode *inode = page->mapping->host;
7875 if (current->flags & PF_MEMALLOC) {
7876 redirty_page_for_writepage(wbc, page);
7882 * If we are under memory pressure we will call this directly from the
7883 * VM, we need to make sure we have the inode referenced for the ordered
7884 * extent. If not just return like we didn't do anything.
7886 if (!igrab(inode)) {
7887 redirty_page_for_writepage(wbc, page);
7888 return AOP_WRITEPAGE_ACTIVATE;
7890 ret = extent_write_full_page(page, wbc);
7891 btrfs_add_delayed_iput(inode);
7895 static int btrfs_writepages(struct address_space *mapping,
7896 struct writeback_control *wbc)
7898 return extent_writepages(mapping, wbc);
7902 btrfs_readpages(struct file *file, struct address_space *mapping,
7903 struct list_head *pages, unsigned nr_pages)
7905 return extent_readpages(mapping, pages, nr_pages);
7908 static int __btrfs_releasepage(struct page *page, gfp_t gfp_flags)
7910 int ret = try_release_extent_mapping(page, gfp_flags);
7912 ClearPagePrivate(page);
7913 set_page_private(page, 0);
7919 static int btrfs_releasepage(struct page *page, gfp_t gfp_flags)
7921 if (PageWriteback(page) || PageDirty(page))
7923 return __btrfs_releasepage(page, gfp_flags);
7926 #ifdef CONFIG_MIGRATION
7927 static int btrfs_migratepage(struct address_space *mapping,
7928 struct page *newpage, struct page *page,
7929 enum migrate_mode mode)
7933 ret = migrate_page_move_mapping(mapping, newpage, page, 0);
7934 if (ret != MIGRATEPAGE_SUCCESS)
7937 if (page_has_private(page)) {
7938 ClearPagePrivate(page);
7940 set_page_private(newpage, page_private(page));
7941 set_page_private(page, 0);
7943 SetPagePrivate(newpage);
7946 if (PagePrivate2(page)) {
7947 ClearPagePrivate2(page);
7948 SetPagePrivate2(newpage);
7951 if (mode != MIGRATE_SYNC_NO_COPY)
7952 migrate_page_copy(newpage, page);
7954 migrate_page_states(newpage, page);
7955 return MIGRATEPAGE_SUCCESS;
7959 static void btrfs_invalidatepage(struct page *page, unsigned int offset,
7960 unsigned int length)
7962 struct inode *inode = page->mapping->host;
7963 struct extent_io_tree *tree;
7964 struct btrfs_ordered_extent *ordered;
7965 struct extent_state *cached_state = NULL;
7966 u64 page_start = page_offset(page);
7967 u64 page_end = page_start + PAGE_SIZE - 1;
7970 int inode_evicting = inode->i_state & I_FREEING;
7973 * we have the page locked, so new writeback can't start,
7974 * and the dirty bit won't be cleared while we are here.
7976 * Wait for IO on this page so that we can safely clear
7977 * the PagePrivate2 bit and do ordered accounting
7979 wait_on_page_writeback(page);
7981 tree = &BTRFS_I(inode)->io_tree;
7983 btrfs_releasepage(page, GFP_NOFS);
7987 if (!inode_evicting)
7988 lock_extent_bits(tree, page_start, page_end, &cached_state);
7991 ordered = btrfs_lookup_ordered_range(BTRFS_I(inode), start,
7992 page_end - start + 1);
7995 ordered->file_offset + ordered->num_bytes - 1);
7997 * IO on this page will never be started, so we need
7998 * to account for any ordered extents now
8000 if (!inode_evicting)
8001 clear_extent_bit(tree, start, end,
8002 EXTENT_DELALLOC | EXTENT_DELALLOC_NEW |
8003 EXTENT_LOCKED | EXTENT_DO_ACCOUNTING |
8004 EXTENT_DEFRAG, 1, 0, &cached_state);
8006 * whoever cleared the private bit is responsible
8007 * for the finish_ordered_io
8009 if (TestClearPagePrivate2(page)) {
8010 struct btrfs_ordered_inode_tree *tree;
8013 tree = &BTRFS_I(inode)->ordered_tree;
8015 spin_lock_irq(&tree->lock);
8016 set_bit(BTRFS_ORDERED_TRUNCATED, &ordered->flags);
8017 new_len = start - ordered->file_offset;
8018 if (new_len < ordered->truncated_len)
8019 ordered->truncated_len = new_len;
8020 spin_unlock_irq(&tree->lock);
8022 if (btrfs_dec_test_ordered_pending(inode, &ordered,
8024 end - start + 1, 1))
8025 btrfs_finish_ordered_io(ordered);
8027 btrfs_put_ordered_extent(ordered);
8028 if (!inode_evicting) {
8029 cached_state = NULL;
8030 lock_extent_bits(tree, start, end,
8035 if (start < page_end)
8040 * Qgroup reserved space handler
8041 * Page here will be either
8042 * 1) Already written to disk
8043 * In this case, its reserved space is released from data rsv map
8044 * and will be freed by delayed_ref handler finally.
8045 * So even we call qgroup_free_data(), it won't decrease reserved
8047 * 2) Not written to disk
8048 * This means the reserved space should be freed here. However,
8049 * if a truncate invalidates the page (by clearing PageDirty)
8050 * and the page is accounted for while allocating extent
8051 * in btrfs_check_data_free_space() we let delayed_ref to
8052 * free the entire extent.
8054 if (PageDirty(page))
8055 btrfs_qgroup_free_data(inode, NULL, page_start, PAGE_SIZE);
8056 if (!inode_evicting) {
8057 clear_extent_bit(tree, page_start, page_end, EXTENT_LOCKED |
8058 EXTENT_DELALLOC | EXTENT_DELALLOC_NEW |
8059 EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG, 1, 1,
8062 __btrfs_releasepage(page, GFP_NOFS);
8065 ClearPageChecked(page);
8066 if (PagePrivate(page)) {
8067 ClearPagePrivate(page);
8068 set_page_private(page, 0);
8074 * btrfs_page_mkwrite() is not allowed to change the file size as it gets
8075 * called from a page fault handler when a page is first dirtied. Hence we must
8076 * be careful to check for EOF conditions here. We set the page up correctly
8077 * for a written page which means we get ENOSPC checking when writing into
8078 * holes and correct delalloc and unwritten extent mapping on filesystems that
8079 * support these features.
8081 * We are not allowed to take the i_mutex here so we have to play games to
8082 * protect against truncate races as the page could now be beyond EOF. Because
8083 * truncate_setsize() writes the inode size before removing pages, once we have
8084 * the page lock we can determine safely if the page is beyond EOF. If it is not
8085 * beyond EOF, then the page is guaranteed safe against truncation until we
8088 vm_fault_t btrfs_page_mkwrite(struct vm_fault *vmf)
8090 struct page *page = vmf->page;
8091 struct inode *inode = file_inode(vmf->vma->vm_file);
8092 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
8093 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
8094 struct btrfs_ordered_extent *ordered;
8095 struct extent_state *cached_state = NULL;
8096 struct extent_changeset *data_reserved = NULL;
8098 unsigned long zero_start;
8108 reserved_space = PAGE_SIZE;
8110 sb_start_pagefault(inode->i_sb);
8111 page_start = page_offset(page);
8112 page_end = page_start + PAGE_SIZE - 1;
8116 * Reserving delalloc space after obtaining the page lock can lead to
8117 * deadlock. For example, if a dirty page is locked by this function
8118 * and the call to btrfs_delalloc_reserve_space() ends up triggering
8119 * dirty page write out, then the btrfs_writepage() function could
8120 * end up waiting indefinitely to get a lock on the page currently
8121 * being processed by btrfs_page_mkwrite() function.
8123 ret2 = btrfs_delalloc_reserve_space(inode, &data_reserved, page_start,
8126 ret2 = file_update_time(vmf->vma->vm_file);
8130 ret = vmf_error(ret2);
8136 ret = VM_FAULT_NOPAGE; /* make the VM retry the fault */
8139 size = i_size_read(inode);
8141 if ((page->mapping != inode->i_mapping) ||
8142 (page_start >= size)) {
8143 /* page got truncated out from underneath us */
8146 wait_on_page_writeback(page);
8148 lock_extent_bits(io_tree, page_start, page_end, &cached_state);
8149 set_page_extent_mapped(page);
8152 * we can't set the delalloc bits if there are pending ordered
8153 * extents. Drop our locks and wait for them to finish
8155 ordered = btrfs_lookup_ordered_range(BTRFS_I(inode), page_start,
8158 unlock_extent_cached(io_tree, page_start, page_end,
8161 btrfs_start_ordered_extent(inode, ordered, 1);
8162 btrfs_put_ordered_extent(ordered);
8166 if (page->index == ((size - 1) >> PAGE_SHIFT)) {
8167 reserved_space = round_up(size - page_start,
8168 fs_info->sectorsize);
8169 if (reserved_space < PAGE_SIZE) {
8170 end = page_start + reserved_space - 1;
8171 btrfs_delalloc_release_space(inode, data_reserved,
8172 page_start, PAGE_SIZE - reserved_space,
8178 * page_mkwrite gets called when the page is firstly dirtied after it's
8179 * faulted in, but write(2) could also dirty a page and set delalloc
8180 * bits, thus in this case for space account reason, we still need to
8181 * clear any delalloc bits within this page range since we have to
8182 * reserve data&meta space before lock_page() (see above comments).
8184 clear_extent_bit(&BTRFS_I(inode)->io_tree, page_start, end,
8185 EXTENT_DELALLOC | EXTENT_DO_ACCOUNTING |
8186 EXTENT_DEFRAG, 0, 0, &cached_state);
8188 ret2 = btrfs_set_extent_delalloc(inode, page_start, end, 0,
8191 unlock_extent_cached(io_tree, page_start, page_end,
8193 ret = VM_FAULT_SIGBUS;
8197 /* page is wholly or partially inside EOF */
8198 if (page_start + PAGE_SIZE > size)
8199 zero_start = offset_in_page(size);
8201 zero_start = PAGE_SIZE;
8203 if (zero_start != PAGE_SIZE) {
8205 memset(kaddr + zero_start, 0, PAGE_SIZE - zero_start);
8206 flush_dcache_page(page);
8209 ClearPageChecked(page);
8210 set_page_dirty(page);
8211 SetPageUptodate(page);
8213 BTRFS_I(inode)->last_trans = fs_info->generation;
8214 BTRFS_I(inode)->last_sub_trans = BTRFS_I(inode)->root->log_transid;
8215 BTRFS_I(inode)->last_log_commit = BTRFS_I(inode)->root->last_log_commit;
8217 unlock_extent_cached(io_tree, page_start, page_end, &cached_state);
8219 btrfs_delalloc_release_extents(BTRFS_I(inode), PAGE_SIZE);
8220 sb_end_pagefault(inode->i_sb);
8221 extent_changeset_free(data_reserved);
8222 return VM_FAULT_LOCKED;
8227 btrfs_delalloc_release_extents(BTRFS_I(inode), PAGE_SIZE);
8228 btrfs_delalloc_release_space(inode, data_reserved, page_start,
8229 reserved_space, (ret != 0));
8231 sb_end_pagefault(inode->i_sb);
8232 extent_changeset_free(data_reserved);
8236 static int btrfs_truncate(struct inode *inode, bool skip_writeback)
8238 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
8239 struct btrfs_root *root = BTRFS_I(inode)->root;
8240 struct btrfs_block_rsv *rsv;
8242 struct btrfs_trans_handle *trans;
8243 u64 mask = fs_info->sectorsize - 1;
8244 u64 min_size = btrfs_calc_metadata_size(fs_info, 1);
8246 if (!skip_writeback) {
8247 ret = btrfs_wait_ordered_range(inode, inode->i_size & (~mask),
8254 * Yes ladies and gentlemen, this is indeed ugly. We have a couple of
8255 * things going on here:
8257 * 1) We need to reserve space to update our inode.
8259 * 2) We need to have something to cache all the space that is going to
8260 * be free'd up by the truncate operation, but also have some slack
8261 * space reserved in case it uses space during the truncate (thank you
8262 * very much snapshotting).
8264 * And we need these to be separate. The fact is we can use a lot of
8265 * space doing the truncate, and we have no earthly idea how much space
8266 * we will use, so we need the truncate reservation to be separate so it
8267 * doesn't end up using space reserved for updating the inode. We also
8268 * need to be able to stop the transaction and start a new one, which
8269 * means we need to be able to update the inode several times, and we
8270 * have no idea of knowing how many times that will be, so we can't just
8271 * reserve 1 item for the entirety of the operation, so that has to be
8272 * done separately as well.
8274 * So that leaves us with
8276 * 1) rsv - for the truncate reservation, which we will steal from the
8277 * transaction reservation.
8278 * 2) fs_info->trans_block_rsv - this will have 1 items worth left for
8279 * updating the inode.
8281 rsv = btrfs_alloc_block_rsv(fs_info, BTRFS_BLOCK_RSV_TEMP);
8284 rsv->size = min_size;
8288 * 1 for the truncate slack space
8289 * 1 for updating the inode.
8291 trans = btrfs_start_transaction(root, 2);
8292 if (IS_ERR(trans)) {
8293 ret = PTR_ERR(trans);
8297 /* Migrate the slack space for the truncate to our reserve */
8298 ret = btrfs_block_rsv_migrate(&fs_info->trans_block_rsv, rsv,
8303 * So if we truncate and then write and fsync we normally would just
8304 * write the extents that changed, which is a problem if we need to
8305 * first truncate that entire inode. So set this flag so we write out
8306 * all of the extents in the inode to the sync log so we're completely
8309 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &BTRFS_I(inode)->runtime_flags);
8310 trans->block_rsv = rsv;
8313 ret = btrfs_truncate_inode_items(trans, root, inode,
8315 BTRFS_EXTENT_DATA_KEY);
8316 trans->block_rsv = &fs_info->trans_block_rsv;
8317 if (ret != -ENOSPC && ret != -EAGAIN)
8320 ret = btrfs_update_inode(trans, root, inode);
8324 btrfs_end_transaction(trans);
8325 btrfs_btree_balance_dirty(fs_info);
8327 trans = btrfs_start_transaction(root, 2);
8328 if (IS_ERR(trans)) {
8329 ret = PTR_ERR(trans);
8334 btrfs_block_rsv_release(fs_info, rsv, -1, NULL);
8335 ret = btrfs_block_rsv_migrate(&fs_info->trans_block_rsv,
8336 rsv, min_size, false);
8337 BUG_ON(ret); /* shouldn't happen */
8338 trans->block_rsv = rsv;
8342 * We can't call btrfs_truncate_block inside a trans handle as we could
8343 * deadlock with freeze, if we got NEED_TRUNCATE_BLOCK then we know
8344 * we've truncated everything except the last little bit, and can do
8345 * btrfs_truncate_block and then update the disk_i_size.
8347 if (ret == NEED_TRUNCATE_BLOCK) {
8348 btrfs_end_transaction(trans);
8349 btrfs_btree_balance_dirty(fs_info);
8351 ret = btrfs_truncate_block(inode, inode->i_size, 0, 0);
8354 trans = btrfs_start_transaction(root, 1);
8355 if (IS_ERR(trans)) {
8356 ret = PTR_ERR(trans);
8359 btrfs_inode_safe_disk_i_size_write(inode, 0);
8365 trans->block_rsv = &fs_info->trans_block_rsv;
8366 ret2 = btrfs_update_inode(trans, root, inode);
8370 ret2 = btrfs_end_transaction(trans);
8373 btrfs_btree_balance_dirty(fs_info);
8376 btrfs_free_block_rsv(fs_info, rsv);
8382 * create a new subvolume directory/inode (helper for the ioctl).
8384 int btrfs_create_subvol_root(struct btrfs_trans_handle *trans,
8385 struct btrfs_root *new_root,
8386 struct btrfs_root *parent_root,
8389 struct inode *inode;
8393 inode = btrfs_new_inode(trans, new_root, NULL, "..", 2,
8394 new_dirid, new_dirid,
8395 S_IFDIR | (~current_umask() & S_IRWXUGO),
8398 return PTR_ERR(inode);
8399 inode->i_op = &btrfs_dir_inode_operations;
8400 inode->i_fop = &btrfs_dir_file_operations;
8402 set_nlink(inode, 1);
8403 btrfs_i_size_write(BTRFS_I(inode), 0);
8404 unlock_new_inode(inode);
8406 err = btrfs_subvol_inherit_props(trans, new_root, parent_root);
8408 btrfs_err(new_root->fs_info,
8409 "error inheriting subvolume %llu properties: %d",
8410 new_root->root_key.objectid, err);
8412 err = btrfs_update_inode(trans, new_root, inode);
8418 struct inode *btrfs_alloc_inode(struct super_block *sb)
8420 struct btrfs_fs_info *fs_info = btrfs_sb(sb);
8421 struct btrfs_inode *ei;
8422 struct inode *inode;
8424 ei = kmem_cache_alloc(btrfs_inode_cachep, GFP_KERNEL);
8431 ei->last_sub_trans = 0;
8432 ei->logged_trans = 0;
8433 ei->delalloc_bytes = 0;
8434 ei->new_delalloc_bytes = 0;
8435 ei->defrag_bytes = 0;
8436 ei->disk_i_size = 0;
8439 ei->index_cnt = (u64)-1;
8441 ei->last_unlink_trans = 0;
8442 ei->last_log_commit = 0;
8444 spin_lock_init(&ei->lock);
8445 ei->outstanding_extents = 0;
8446 if (sb->s_magic != BTRFS_TEST_MAGIC)
8447 btrfs_init_metadata_block_rsv(fs_info, &ei->block_rsv,
8448 BTRFS_BLOCK_RSV_DELALLOC);
8449 ei->runtime_flags = 0;
8450 ei->prop_compress = BTRFS_COMPRESS_NONE;
8451 ei->defrag_compress = BTRFS_COMPRESS_NONE;
8453 ei->delayed_node = NULL;
8455 ei->i_otime.tv_sec = 0;
8456 ei->i_otime.tv_nsec = 0;
8458 inode = &ei->vfs_inode;
8459 extent_map_tree_init(&ei->extent_tree);
8460 extent_io_tree_init(fs_info, &ei->io_tree, IO_TREE_INODE_IO, inode);
8461 extent_io_tree_init(fs_info, &ei->io_failure_tree,
8462 IO_TREE_INODE_IO_FAILURE, inode);
8463 extent_io_tree_init(fs_info, &ei->file_extent_tree,
8464 IO_TREE_INODE_FILE_EXTENT, inode);
8465 ei->io_tree.track_uptodate = true;
8466 ei->io_failure_tree.track_uptodate = true;
8467 atomic_set(&ei->sync_writers, 0);
8468 mutex_init(&ei->log_mutex);
8469 btrfs_ordered_inode_tree_init(&ei->ordered_tree);
8470 INIT_LIST_HEAD(&ei->delalloc_inodes);
8471 INIT_LIST_HEAD(&ei->delayed_iput);
8472 RB_CLEAR_NODE(&ei->rb_node);
8473 init_rwsem(&ei->dio_sem);
8478 #ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
8479 void btrfs_test_destroy_inode(struct inode *inode)
8481 btrfs_drop_extent_cache(BTRFS_I(inode), 0, (u64)-1, 0);
8482 kmem_cache_free(btrfs_inode_cachep, BTRFS_I(inode));
8486 void btrfs_free_inode(struct inode *inode)
8488 kmem_cache_free(btrfs_inode_cachep, BTRFS_I(inode));
8491 void btrfs_destroy_inode(struct inode *inode)
8493 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
8494 struct btrfs_ordered_extent *ordered;
8495 struct btrfs_root *root = BTRFS_I(inode)->root;
8497 WARN_ON(!hlist_empty(&inode->i_dentry));
8498 WARN_ON(inode->i_data.nrpages);
8499 WARN_ON(BTRFS_I(inode)->block_rsv.reserved);
8500 WARN_ON(BTRFS_I(inode)->block_rsv.size);
8501 WARN_ON(BTRFS_I(inode)->outstanding_extents);
8502 WARN_ON(BTRFS_I(inode)->delalloc_bytes);
8503 WARN_ON(BTRFS_I(inode)->new_delalloc_bytes);
8504 WARN_ON(BTRFS_I(inode)->csum_bytes);
8505 WARN_ON(BTRFS_I(inode)->defrag_bytes);
8508 * This can happen where we create an inode, but somebody else also
8509 * created the same inode and we need to destroy the one we already
8516 ordered = btrfs_lookup_first_ordered_extent(inode, (u64)-1);
8521 "found ordered extent %llu %llu on inode cleanup",
8522 ordered->file_offset, ordered->num_bytes);
8523 btrfs_remove_ordered_extent(inode, ordered);
8524 btrfs_put_ordered_extent(ordered);
8525 btrfs_put_ordered_extent(ordered);
8528 btrfs_qgroup_check_reserved_leak(inode);
8529 inode_tree_del(inode);
8530 btrfs_drop_extent_cache(BTRFS_I(inode), 0, (u64)-1, 0);
8531 btrfs_inode_clear_file_extent_range(BTRFS_I(inode), 0, (u64)-1);
8532 btrfs_put_root(BTRFS_I(inode)->root);
8535 int btrfs_drop_inode(struct inode *inode)
8537 struct btrfs_root *root = BTRFS_I(inode)->root;
8542 /* the snap/subvol tree is on deleting */
8543 if (btrfs_root_refs(&root->root_item) == 0)
8546 return generic_drop_inode(inode);
8549 static void init_once(void *foo)
8551 struct btrfs_inode *ei = (struct btrfs_inode *) foo;
8553 inode_init_once(&ei->vfs_inode);
8556 void __cold btrfs_destroy_cachep(void)
8559 * Make sure all delayed rcu free inodes are flushed before we
8563 kmem_cache_destroy(btrfs_inode_cachep);
8564 kmem_cache_destroy(btrfs_trans_handle_cachep);
8565 kmem_cache_destroy(btrfs_path_cachep);
8566 kmem_cache_destroy(btrfs_free_space_cachep);
8567 kmem_cache_destroy(btrfs_free_space_bitmap_cachep);
8570 int __init btrfs_init_cachep(void)
8572 btrfs_inode_cachep = kmem_cache_create("btrfs_inode",
8573 sizeof(struct btrfs_inode), 0,
8574 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD | SLAB_ACCOUNT,
8576 if (!btrfs_inode_cachep)
8579 btrfs_trans_handle_cachep = kmem_cache_create("btrfs_trans_handle",
8580 sizeof(struct btrfs_trans_handle), 0,
8581 SLAB_TEMPORARY | SLAB_MEM_SPREAD, NULL);
8582 if (!btrfs_trans_handle_cachep)
8585 btrfs_path_cachep = kmem_cache_create("btrfs_path",
8586 sizeof(struct btrfs_path), 0,
8587 SLAB_MEM_SPREAD, NULL);
8588 if (!btrfs_path_cachep)
8591 btrfs_free_space_cachep = kmem_cache_create("btrfs_free_space",
8592 sizeof(struct btrfs_free_space), 0,
8593 SLAB_MEM_SPREAD, NULL);
8594 if (!btrfs_free_space_cachep)
8597 btrfs_free_space_bitmap_cachep = kmem_cache_create("btrfs_free_space_bitmap",
8598 PAGE_SIZE, PAGE_SIZE,
8599 SLAB_RED_ZONE, NULL);
8600 if (!btrfs_free_space_bitmap_cachep)
8605 btrfs_destroy_cachep();
8609 static int btrfs_getattr(const struct path *path, struct kstat *stat,
8610 u32 request_mask, unsigned int flags)
8613 struct inode *inode = d_inode(path->dentry);
8614 u32 blocksize = inode->i_sb->s_blocksize;
8615 u32 bi_flags = BTRFS_I(inode)->flags;
8617 stat->result_mask |= STATX_BTIME;
8618 stat->btime.tv_sec = BTRFS_I(inode)->i_otime.tv_sec;
8619 stat->btime.tv_nsec = BTRFS_I(inode)->i_otime.tv_nsec;
8620 if (bi_flags & BTRFS_INODE_APPEND)
8621 stat->attributes |= STATX_ATTR_APPEND;
8622 if (bi_flags & BTRFS_INODE_COMPRESS)
8623 stat->attributes |= STATX_ATTR_COMPRESSED;
8624 if (bi_flags & BTRFS_INODE_IMMUTABLE)
8625 stat->attributes |= STATX_ATTR_IMMUTABLE;
8626 if (bi_flags & BTRFS_INODE_NODUMP)
8627 stat->attributes |= STATX_ATTR_NODUMP;
8629 stat->attributes_mask |= (STATX_ATTR_APPEND |
8630 STATX_ATTR_COMPRESSED |
8631 STATX_ATTR_IMMUTABLE |
8634 generic_fillattr(inode, stat);
8635 stat->dev = BTRFS_I(inode)->root->anon_dev;
8637 spin_lock(&BTRFS_I(inode)->lock);
8638 delalloc_bytes = BTRFS_I(inode)->new_delalloc_bytes;
8639 spin_unlock(&BTRFS_I(inode)->lock);
8640 stat->blocks = (ALIGN(inode_get_bytes(inode), blocksize) +
8641 ALIGN(delalloc_bytes, blocksize)) >> 9;
8645 static int btrfs_rename_exchange(struct inode *old_dir,
8646 struct dentry *old_dentry,
8647 struct inode *new_dir,
8648 struct dentry *new_dentry)
8650 struct btrfs_fs_info *fs_info = btrfs_sb(old_dir->i_sb);
8651 struct btrfs_trans_handle *trans;
8652 struct btrfs_root *root = BTRFS_I(old_dir)->root;
8653 struct btrfs_root *dest = BTRFS_I(new_dir)->root;
8654 struct inode *new_inode = new_dentry->d_inode;
8655 struct inode *old_inode = old_dentry->d_inode;
8656 struct timespec64 ctime = current_time(old_inode);
8657 struct dentry *parent;
8658 u64 old_ino = btrfs_ino(BTRFS_I(old_inode));
8659 u64 new_ino = btrfs_ino(BTRFS_I(new_inode));
8663 bool root_log_pinned = false;
8664 bool dest_log_pinned = false;
8665 struct btrfs_log_ctx ctx_root;
8666 struct btrfs_log_ctx ctx_dest;
8667 bool sync_log_root = false;
8668 bool sync_log_dest = false;
8669 bool commit_transaction = false;
8671 /* we only allow rename subvolume link between subvolumes */
8672 if (old_ino != BTRFS_FIRST_FREE_OBJECTID && root != dest)
8675 btrfs_init_log_ctx(&ctx_root, old_inode);
8676 btrfs_init_log_ctx(&ctx_dest, new_inode);
8678 /* close the race window with snapshot create/destroy ioctl */
8679 if (old_ino == BTRFS_FIRST_FREE_OBJECTID ||
8680 new_ino == BTRFS_FIRST_FREE_OBJECTID)
8681 down_read(&fs_info->subvol_sem);
8684 * We want to reserve the absolute worst case amount of items. So if
8685 * both inodes are subvols and we need to unlink them then that would
8686 * require 4 item modifications, but if they are both normal inodes it
8687 * would require 5 item modifications, so we'll assume their normal
8688 * inodes. So 5 * 2 is 10, plus 2 for the new links, so 12 total items
8689 * should cover the worst case number of items we'll modify.
8691 trans = btrfs_start_transaction(root, 12);
8692 if (IS_ERR(trans)) {
8693 ret = PTR_ERR(trans);
8698 btrfs_record_root_in_trans(trans, dest);
8701 * We need to find a free sequence number both in the source and
8702 * in the destination directory for the exchange.
8704 ret = btrfs_set_inode_index(BTRFS_I(new_dir), &old_idx);
8707 ret = btrfs_set_inode_index(BTRFS_I(old_dir), &new_idx);
8711 BTRFS_I(old_inode)->dir_index = 0ULL;
8712 BTRFS_I(new_inode)->dir_index = 0ULL;
8714 /* Reference for the source. */
8715 if (old_ino == BTRFS_FIRST_FREE_OBJECTID) {
8716 /* force full log commit if subvolume involved. */
8717 btrfs_set_log_full_commit(trans);
8719 btrfs_pin_log_trans(root);
8720 root_log_pinned = true;
8721 ret = btrfs_insert_inode_ref(trans, dest,
8722 new_dentry->d_name.name,
8723 new_dentry->d_name.len,
8725 btrfs_ino(BTRFS_I(new_dir)),
8731 /* And now for the dest. */
8732 if (new_ino == BTRFS_FIRST_FREE_OBJECTID) {
8733 /* force full log commit if subvolume involved. */
8734 btrfs_set_log_full_commit(trans);
8736 btrfs_pin_log_trans(dest);
8737 dest_log_pinned = true;
8738 ret = btrfs_insert_inode_ref(trans, root,
8739 old_dentry->d_name.name,
8740 old_dentry->d_name.len,
8742 btrfs_ino(BTRFS_I(old_dir)),
8748 /* Update inode version and ctime/mtime. */
8749 inode_inc_iversion(old_dir);
8750 inode_inc_iversion(new_dir);
8751 inode_inc_iversion(old_inode);
8752 inode_inc_iversion(new_inode);
8753 old_dir->i_ctime = old_dir->i_mtime = ctime;
8754 new_dir->i_ctime = new_dir->i_mtime = ctime;
8755 old_inode->i_ctime = ctime;
8756 new_inode->i_ctime = ctime;
8758 if (old_dentry->d_parent != new_dentry->d_parent) {
8759 btrfs_record_unlink_dir(trans, BTRFS_I(old_dir),
8760 BTRFS_I(old_inode), 1);
8761 btrfs_record_unlink_dir(trans, BTRFS_I(new_dir),
8762 BTRFS_I(new_inode), 1);
8765 /* src is a subvolume */
8766 if (old_ino == BTRFS_FIRST_FREE_OBJECTID) {
8767 ret = btrfs_unlink_subvol(trans, old_dir, old_dentry);
8768 } else { /* src is an inode */
8769 ret = __btrfs_unlink_inode(trans, root, BTRFS_I(old_dir),
8770 BTRFS_I(old_dentry->d_inode),
8771 old_dentry->d_name.name,
8772 old_dentry->d_name.len);
8774 ret = btrfs_update_inode(trans, root, old_inode);
8777 btrfs_abort_transaction(trans, ret);
8781 /* dest is a subvolume */
8782 if (new_ino == BTRFS_FIRST_FREE_OBJECTID) {
8783 ret = btrfs_unlink_subvol(trans, new_dir, new_dentry);
8784 } else { /* dest is an inode */
8785 ret = __btrfs_unlink_inode(trans, dest, BTRFS_I(new_dir),
8786 BTRFS_I(new_dentry->d_inode),
8787 new_dentry->d_name.name,
8788 new_dentry->d_name.len);
8790 ret = btrfs_update_inode(trans, dest, new_inode);
8793 btrfs_abort_transaction(trans, ret);
8797 ret = btrfs_add_link(trans, BTRFS_I(new_dir), BTRFS_I(old_inode),
8798 new_dentry->d_name.name,
8799 new_dentry->d_name.len, 0, old_idx);
8801 btrfs_abort_transaction(trans, ret);
8805 ret = btrfs_add_link(trans, BTRFS_I(old_dir), BTRFS_I(new_inode),
8806 old_dentry->d_name.name,
8807 old_dentry->d_name.len, 0, new_idx);
8809 btrfs_abort_transaction(trans, ret);
8813 if (old_inode->i_nlink == 1)
8814 BTRFS_I(old_inode)->dir_index = old_idx;
8815 if (new_inode->i_nlink == 1)
8816 BTRFS_I(new_inode)->dir_index = new_idx;
8818 if (root_log_pinned) {
8819 parent = new_dentry->d_parent;
8820 ret = btrfs_log_new_name(trans, BTRFS_I(old_inode),
8821 BTRFS_I(old_dir), parent,
8823 if (ret == BTRFS_NEED_LOG_SYNC)
8824 sync_log_root = true;
8825 else if (ret == BTRFS_NEED_TRANS_COMMIT)
8826 commit_transaction = true;
8828 btrfs_end_log_trans(root);
8829 root_log_pinned = false;
8831 if (dest_log_pinned) {
8832 if (!commit_transaction) {
8833 parent = old_dentry->d_parent;
8834 ret = btrfs_log_new_name(trans, BTRFS_I(new_inode),
8835 BTRFS_I(new_dir), parent,
8837 if (ret == BTRFS_NEED_LOG_SYNC)
8838 sync_log_dest = true;
8839 else if (ret == BTRFS_NEED_TRANS_COMMIT)
8840 commit_transaction = true;
8843 btrfs_end_log_trans(dest);
8844 dest_log_pinned = false;
8848 * If we have pinned a log and an error happened, we unpin tasks
8849 * trying to sync the log and force them to fallback to a transaction
8850 * commit if the log currently contains any of the inodes involved in
8851 * this rename operation (to ensure we do not persist a log with an
8852 * inconsistent state for any of these inodes or leading to any
8853 * inconsistencies when replayed). If the transaction was aborted, the
8854 * abortion reason is propagated to userspace when attempting to commit
8855 * the transaction. If the log does not contain any of these inodes, we
8856 * allow the tasks to sync it.
8858 if (ret && (root_log_pinned || dest_log_pinned)) {
8859 if (btrfs_inode_in_log(BTRFS_I(old_dir), fs_info->generation) ||
8860 btrfs_inode_in_log(BTRFS_I(new_dir), fs_info->generation) ||
8861 btrfs_inode_in_log(BTRFS_I(old_inode), fs_info->generation) ||
8863 btrfs_inode_in_log(BTRFS_I(new_inode), fs_info->generation)))
8864 btrfs_set_log_full_commit(trans);
8866 if (root_log_pinned) {
8867 btrfs_end_log_trans(root);
8868 root_log_pinned = false;
8870 if (dest_log_pinned) {
8871 btrfs_end_log_trans(dest);
8872 dest_log_pinned = false;
8875 if (!ret && sync_log_root && !commit_transaction) {
8876 ret = btrfs_sync_log(trans, BTRFS_I(old_inode)->root,
8879 commit_transaction = true;
8881 if (!ret && sync_log_dest && !commit_transaction) {
8882 ret = btrfs_sync_log(trans, BTRFS_I(new_inode)->root,
8885 commit_transaction = true;
8887 if (commit_transaction) {
8889 * We may have set commit_transaction when logging the new name
8890 * in the destination root, in which case we left the source
8891 * root context in the list of log contextes. So make sure we
8892 * remove it to avoid invalid memory accesses, since the context
8893 * was allocated in our stack frame.
8895 if (sync_log_root) {
8896 mutex_lock(&root->log_mutex);
8897 list_del_init(&ctx_root.list);
8898 mutex_unlock(&root->log_mutex);
8900 ret = btrfs_commit_transaction(trans);
8904 ret2 = btrfs_end_transaction(trans);
8905 ret = ret ? ret : ret2;
8908 if (new_ino == BTRFS_FIRST_FREE_OBJECTID ||
8909 old_ino == BTRFS_FIRST_FREE_OBJECTID)
8910 up_read(&fs_info->subvol_sem);
8912 ASSERT(list_empty(&ctx_root.list));
8913 ASSERT(list_empty(&ctx_dest.list));
8918 static int btrfs_whiteout_for_rename(struct btrfs_trans_handle *trans,
8919 struct btrfs_root *root,
8921 struct dentry *dentry)
8924 struct inode *inode;
8928 ret = btrfs_find_free_ino(root, &objectid);
8932 inode = btrfs_new_inode(trans, root, dir,
8933 dentry->d_name.name,
8935 btrfs_ino(BTRFS_I(dir)),
8937 S_IFCHR | WHITEOUT_MODE,
8940 if (IS_ERR(inode)) {
8941 ret = PTR_ERR(inode);
8945 inode->i_op = &btrfs_special_inode_operations;
8946 init_special_inode(inode, inode->i_mode,
8949 ret = btrfs_init_inode_security(trans, inode, dir,
8954 ret = btrfs_add_nondir(trans, BTRFS_I(dir), dentry,
8955 BTRFS_I(inode), 0, index);
8959 ret = btrfs_update_inode(trans, root, inode);
8961 unlock_new_inode(inode);
8963 inode_dec_link_count(inode);
8969 static int btrfs_rename(struct inode *old_dir, struct dentry *old_dentry,
8970 struct inode *new_dir, struct dentry *new_dentry,
8973 struct btrfs_fs_info *fs_info = btrfs_sb(old_dir->i_sb);
8974 struct btrfs_trans_handle *trans;
8975 unsigned int trans_num_items;
8976 struct btrfs_root *root = BTRFS_I(old_dir)->root;
8977 struct btrfs_root *dest = BTRFS_I(new_dir)->root;
8978 struct inode *new_inode = d_inode(new_dentry);
8979 struct inode *old_inode = d_inode(old_dentry);
8982 u64 old_ino = btrfs_ino(BTRFS_I(old_inode));
8983 bool log_pinned = false;
8984 struct btrfs_log_ctx ctx;
8985 bool sync_log = false;
8986 bool commit_transaction = false;
8988 if (btrfs_ino(BTRFS_I(new_dir)) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)
8991 /* we only allow rename subvolume link between subvolumes */
8992 if (old_ino != BTRFS_FIRST_FREE_OBJECTID && root != dest)
8995 if (old_ino == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID ||
8996 (new_inode && btrfs_ino(BTRFS_I(new_inode)) == BTRFS_FIRST_FREE_OBJECTID))
8999 if (S_ISDIR(old_inode->i_mode) && new_inode &&
9000 new_inode->i_size > BTRFS_EMPTY_DIR_SIZE)
9004 /* check for collisions, even if the name isn't there */
9005 ret = btrfs_check_dir_item_collision(dest, new_dir->i_ino,
9006 new_dentry->d_name.name,
9007 new_dentry->d_name.len);
9010 if (ret == -EEXIST) {
9012 * eexist without a new_inode */
9013 if (WARN_ON(!new_inode)) {
9017 /* maybe -EOVERFLOW */
9024 * we're using rename to replace one file with another. Start IO on it
9025 * now so we don't add too much work to the end of the transaction
9027 if (new_inode && S_ISREG(old_inode->i_mode) && new_inode->i_size)
9028 filemap_flush(old_inode->i_mapping);
9030 /* close the racy window with snapshot create/destroy ioctl */
9031 if (old_ino == BTRFS_FIRST_FREE_OBJECTID)
9032 down_read(&fs_info->subvol_sem);
9034 * We want to reserve the absolute worst case amount of items. So if
9035 * both inodes are subvols and we need to unlink them then that would
9036 * require 4 item modifications, but if they are both normal inodes it
9037 * would require 5 item modifications, so we'll assume they are normal
9038 * inodes. So 5 * 2 is 10, plus 1 for the new link, so 11 total items
9039 * should cover the worst case number of items we'll modify.
9040 * If our rename has the whiteout flag, we need more 5 units for the
9041 * new inode (1 inode item, 1 inode ref, 2 dir items and 1 xattr item
9042 * when selinux is enabled).
9044 trans_num_items = 11;
9045 if (flags & RENAME_WHITEOUT)
9046 trans_num_items += 5;
9047 trans = btrfs_start_transaction(root, trans_num_items);
9048 if (IS_ERR(trans)) {
9049 ret = PTR_ERR(trans);
9054 btrfs_record_root_in_trans(trans, dest);
9056 ret = btrfs_set_inode_index(BTRFS_I(new_dir), &index);
9060 BTRFS_I(old_inode)->dir_index = 0ULL;
9061 if (unlikely(old_ino == BTRFS_FIRST_FREE_OBJECTID)) {
9062 /* force full log commit if subvolume involved. */
9063 btrfs_set_log_full_commit(trans);
9065 btrfs_pin_log_trans(root);
9067 ret = btrfs_insert_inode_ref(trans, dest,
9068 new_dentry->d_name.name,
9069 new_dentry->d_name.len,
9071 btrfs_ino(BTRFS_I(new_dir)), index);
9076 inode_inc_iversion(old_dir);
9077 inode_inc_iversion(new_dir);
9078 inode_inc_iversion(old_inode);
9079 old_dir->i_ctime = old_dir->i_mtime =
9080 new_dir->i_ctime = new_dir->i_mtime =
9081 old_inode->i_ctime = current_time(old_dir);
9083 if (old_dentry->d_parent != new_dentry->d_parent)
9084 btrfs_record_unlink_dir(trans, BTRFS_I(old_dir),
9085 BTRFS_I(old_inode), 1);
9087 if (unlikely(old_ino == BTRFS_FIRST_FREE_OBJECTID)) {
9088 ret = btrfs_unlink_subvol(trans, old_dir, old_dentry);
9090 ret = __btrfs_unlink_inode(trans, root, BTRFS_I(old_dir),
9091 BTRFS_I(d_inode(old_dentry)),
9092 old_dentry->d_name.name,
9093 old_dentry->d_name.len);
9095 ret = btrfs_update_inode(trans, root, old_inode);
9098 btrfs_abort_transaction(trans, ret);
9103 inode_inc_iversion(new_inode);
9104 new_inode->i_ctime = current_time(new_inode);
9105 if (unlikely(btrfs_ino(BTRFS_I(new_inode)) ==
9106 BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)) {
9107 ret = btrfs_unlink_subvol(trans, new_dir, new_dentry);
9108 BUG_ON(new_inode->i_nlink == 0);
9110 ret = btrfs_unlink_inode(trans, dest, BTRFS_I(new_dir),
9111 BTRFS_I(d_inode(new_dentry)),
9112 new_dentry->d_name.name,
9113 new_dentry->d_name.len);
9115 if (!ret && new_inode->i_nlink == 0)
9116 ret = btrfs_orphan_add(trans,
9117 BTRFS_I(d_inode(new_dentry)));
9119 btrfs_abort_transaction(trans, ret);
9124 ret = btrfs_add_link(trans, BTRFS_I(new_dir), BTRFS_I(old_inode),
9125 new_dentry->d_name.name,
9126 new_dentry->d_name.len, 0, index);
9128 btrfs_abort_transaction(trans, ret);
9132 if (old_inode->i_nlink == 1)
9133 BTRFS_I(old_inode)->dir_index = index;
9136 struct dentry *parent = new_dentry->d_parent;
9138 btrfs_init_log_ctx(&ctx, old_inode);
9139 ret = btrfs_log_new_name(trans, BTRFS_I(old_inode),
9140 BTRFS_I(old_dir), parent,
9142 if (ret == BTRFS_NEED_LOG_SYNC)
9144 else if (ret == BTRFS_NEED_TRANS_COMMIT)
9145 commit_transaction = true;
9147 btrfs_end_log_trans(root);
9151 if (flags & RENAME_WHITEOUT) {
9152 ret = btrfs_whiteout_for_rename(trans, root, old_dir,
9156 btrfs_abort_transaction(trans, ret);
9162 * If we have pinned the log and an error happened, we unpin tasks
9163 * trying to sync the log and force them to fallback to a transaction
9164 * commit if the log currently contains any of the inodes involved in
9165 * this rename operation (to ensure we do not persist a log with an
9166 * inconsistent state for any of these inodes or leading to any
9167 * inconsistencies when replayed). If the transaction was aborted, the
9168 * abortion reason is propagated to userspace when attempting to commit
9169 * the transaction. If the log does not contain any of these inodes, we
9170 * allow the tasks to sync it.
9172 if (ret && log_pinned) {
9173 if (btrfs_inode_in_log(BTRFS_I(old_dir), fs_info->generation) ||
9174 btrfs_inode_in_log(BTRFS_I(new_dir), fs_info->generation) ||
9175 btrfs_inode_in_log(BTRFS_I(old_inode), fs_info->generation) ||
9177 btrfs_inode_in_log(BTRFS_I(new_inode), fs_info->generation)))
9178 btrfs_set_log_full_commit(trans);
9180 btrfs_end_log_trans(root);
9183 if (!ret && sync_log) {
9184 ret = btrfs_sync_log(trans, BTRFS_I(old_inode)->root, &ctx);
9186 commit_transaction = true;
9187 } else if (sync_log) {
9188 mutex_lock(&root->log_mutex);
9189 list_del(&ctx.list);
9190 mutex_unlock(&root->log_mutex);
9192 if (commit_transaction) {
9193 ret = btrfs_commit_transaction(trans);
9197 ret2 = btrfs_end_transaction(trans);
9198 ret = ret ? ret : ret2;
9201 if (old_ino == BTRFS_FIRST_FREE_OBJECTID)
9202 up_read(&fs_info->subvol_sem);
9207 static int btrfs_rename2(struct inode *old_dir, struct dentry *old_dentry,
9208 struct inode *new_dir, struct dentry *new_dentry,
9211 if (flags & ~(RENAME_NOREPLACE | RENAME_EXCHANGE | RENAME_WHITEOUT))
9214 if (flags & RENAME_EXCHANGE)
9215 return btrfs_rename_exchange(old_dir, old_dentry, new_dir,
9218 return btrfs_rename(old_dir, old_dentry, new_dir, new_dentry, flags);
9221 struct btrfs_delalloc_work {
9222 struct inode *inode;
9223 struct completion completion;
9224 struct list_head list;
9225 struct btrfs_work work;
9228 static void btrfs_run_delalloc_work(struct btrfs_work *work)
9230 struct btrfs_delalloc_work *delalloc_work;
9231 struct inode *inode;
9233 delalloc_work = container_of(work, struct btrfs_delalloc_work,
9235 inode = delalloc_work->inode;
9236 filemap_flush(inode->i_mapping);
9237 if (test_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
9238 &BTRFS_I(inode)->runtime_flags))
9239 filemap_flush(inode->i_mapping);
9242 complete(&delalloc_work->completion);
9245 static struct btrfs_delalloc_work *btrfs_alloc_delalloc_work(struct inode *inode)
9247 struct btrfs_delalloc_work *work;
9249 work = kmalloc(sizeof(*work), GFP_NOFS);
9253 init_completion(&work->completion);
9254 INIT_LIST_HEAD(&work->list);
9255 work->inode = inode;
9256 btrfs_init_work(&work->work, btrfs_run_delalloc_work, NULL, NULL);
9262 * some fairly slow code that needs optimization. This walks the list
9263 * of all the inodes with pending delalloc and forces them to disk.
9265 static int start_delalloc_inodes(struct btrfs_root *root, int nr, bool snapshot)
9267 struct btrfs_inode *binode;
9268 struct inode *inode;
9269 struct btrfs_delalloc_work *work, *next;
9270 struct list_head works;
9271 struct list_head splice;
9274 INIT_LIST_HEAD(&works);
9275 INIT_LIST_HEAD(&splice);
9277 mutex_lock(&root->delalloc_mutex);
9278 spin_lock(&root->delalloc_lock);
9279 list_splice_init(&root->delalloc_inodes, &splice);
9280 while (!list_empty(&splice)) {
9281 binode = list_entry(splice.next, struct btrfs_inode,
9284 list_move_tail(&binode->delalloc_inodes,
9285 &root->delalloc_inodes);
9286 inode = igrab(&binode->vfs_inode);
9288 cond_resched_lock(&root->delalloc_lock);
9291 spin_unlock(&root->delalloc_lock);
9294 set_bit(BTRFS_INODE_SNAPSHOT_FLUSH,
9295 &binode->runtime_flags);
9296 work = btrfs_alloc_delalloc_work(inode);
9302 list_add_tail(&work->list, &works);
9303 btrfs_queue_work(root->fs_info->flush_workers,
9306 if (nr != -1 && ret >= nr)
9309 spin_lock(&root->delalloc_lock);
9311 spin_unlock(&root->delalloc_lock);
9314 list_for_each_entry_safe(work, next, &works, list) {
9315 list_del_init(&work->list);
9316 wait_for_completion(&work->completion);
9320 if (!list_empty(&splice)) {
9321 spin_lock(&root->delalloc_lock);
9322 list_splice_tail(&splice, &root->delalloc_inodes);
9323 spin_unlock(&root->delalloc_lock);
9325 mutex_unlock(&root->delalloc_mutex);
9329 int btrfs_start_delalloc_snapshot(struct btrfs_root *root)
9331 struct btrfs_fs_info *fs_info = root->fs_info;
9334 if (test_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state))
9337 ret = start_delalloc_inodes(root, -1, true);
9343 int btrfs_start_delalloc_roots(struct btrfs_fs_info *fs_info, int nr)
9345 struct btrfs_root *root;
9346 struct list_head splice;
9349 if (test_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state))
9352 INIT_LIST_HEAD(&splice);
9354 mutex_lock(&fs_info->delalloc_root_mutex);
9355 spin_lock(&fs_info->delalloc_root_lock);
9356 list_splice_init(&fs_info->delalloc_roots, &splice);
9357 while (!list_empty(&splice) && nr) {
9358 root = list_first_entry(&splice, struct btrfs_root,
9360 root = btrfs_grab_root(root);
9362 list_move_tail(&root->delalloc_root,
9363 &fs_info->delalloc_roots);
9364 spin_unlock(&fs_info->delalloc_root_lock);
9366 ret = start_delalloc_inodes(root, nr, false);
9367 btrfs_put_root(root);
9375 spin_lock(&fs_info->delalloc_root_lock);
9377 spin_unlock(&fs_info->delalloc_root_lock);
9381 if (!list_empty(&splice)) {
9382 spin_lock(&fs_info->delalloc_root_lock);
9383 list_splice_tail(&splice, &fs_info->delalloc_roots);
9384 spin_unlock(&fs_info->delalloc_root_lock);
9386 mutex_unlock(&fs_info->delalloc_root_mutex);
9390 static int btrfs_symlink(struct inode *dir, struct dentry *dentry,
9391 const char *symname)
9393 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
9394 struct btrfs_trans_handle *trans;
9395 struct btrfs_root *root = BTRFS_I(dir)->root;
9396 struct btrfs_path *path;
9397 struct btrfs_key key;
9398 struct inode *inode = NULL;
9405 struct btrfs_file_extent_item *ei;
9406 struct extent_buffer *leaf;
9408 name_len = strlen(symname);
9409 if (name_len > BTRFS_MAX_INLINE_DATA_SIZE(fs_info))
9410 return -ENAMETOOLONG;
9413 * 2 items for inode item and ref
9414 * 2 items for dir items
9415 * 1 item for updating parent inode item
9416 * 1 item for the inline extent item
9417 * 1 item for xattr if selinux is on
9419 trans = btrfs_start_transaction(root, 7);
9421 return PTR_ERR(trans);
9423 err = btrfs_find_free_ino(root, &objectid);
9427 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
9428 dentry->d_name.len, btrfs_ino(BTRFS_I(dir)),
9429 objectid, S_IFLNK|S_IRWXUGO, &index);
9430 if (IS_ERR(inode)) {
9431 err = PTR_ERR(inode);
9437 * If the active LSM wants to access the inode during
9438 * d_instantiate it needs these. Smack checks to see
9439 * if the filesystem supports xattrs by looking at the
9442 inode->i_fop = &btrfs_file_operations;
9443 inode->i_op = &btrfs_file_inode_operations;
9444 inode->i_mapping->a_ops = &btrfs_aops;
9445 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
9447 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
9451 path = btrfs_alloc_path();
9456 key.objectid = btrfs_ino(BTRFS_I(inode));
9458 key.type = BTRFS_EXTENT_DATA_KEY;
9459 datasize = btrfs_file_extent_calc_inline_size(name_len);
9460 err = btrfs_insert_empty_item(trans, root, path, &key,
9463 btrfs_free_path(path);
9466 leaf = path->nodes[0];
9467 ei = btrfs_item_ptr(leaf, path->slots[0],
9468 struct btrfs_file_extent_item);
9469 btrfs_set_file_extent_generation(leaf, ei, trans->transid);
9470 btrfs_set_file_extent_type(leaf, ei,
9471 BTRFS_FILE_EXTENT_INLINE);
9472 btrfs_set_file_extent_encryption(leaf, ei, 0);
9473 btrfs_set_file_extent_compression(leaf, ei, 0);
9474 btrfs_set_file_extent_other_encoding(leaf, ei, 0);
9475 btrfs_set_file_extent_ram_bytes(leaf, ei, name_len);
9477 ptr = btrfs_file_extent_inline_start(ei);
9478 write_extent_buffer(leaf, symname, ptr, name_len);
9479 btrfs_mark_buffer_dirty(leaf);
9480 btrfs_free_path(path);
9482 inode->i_op = &btrfs_symlink_inode_operations;
9483 inode_nohighmem(inode);
9484 inode_set_bytes(inode, name_len);
9485 btrfs_i_size_write(BTRFS_I(inode), name_len);
9486 err = btrfs_update_inode(trans, root, inode);
9488 * Last step, add directory indexes for our symlink inode. This is the
9489 * last step to avoid extra cleanup of these indexes if an error happens
9493 err = btrfs_add_nondir(trans, BTRFS_I(dir), dentry,
9494 BTRFS_I(inode), 0, index);
9498 d_instantiate_new(dentry, inode);
9501 btrfs_end_transaction(trans);
9503 inode_dec_link_count(inode);
9504 discard_new_inode(inode);
9506 btrfs_btree_balance_dirty(fs_info);
9510 static int __btrfs_prealloc_file_range(struct inode *inode, int mode,
9511 u64 start, u64 num_bytes, u64 min_size,
9512 loff_t actual_len, u64 *alloc_hint,
9513 struct btrfs_trans_handle *trans)
9515 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
9516 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
9517 struct extent_map *em;
9518 struct btrfs_root *root = BTRFS_I(inode)->root;
9519 struct btrfs_key ins;
9520 u64 cur_offset = start;
9521 u64 clear_offset = start;
9524 u64 last_alloc = (u64)-1;
9526 bool own_trans = true;
9527 u64 end = start + num_bytes - 1;
9531 while (num_bytes > 0) {
9533 trans = btrfs_start_transaction(root, 3);
9534 if (IS_ERR(trans)) {
9535 ret = PTR_ERR(trans);
9540 cur_bytes = min_t(u64, num_bytes, SZ_256M);
9541 cur_bytes = max(cur_bytes, min_size);
9543 * If we are severely fragmented we could end up with really
9544 * small allocations, so if the allocator is returning small
9545 * chunks lets make its job easier by only searching for those
9548 cur_bytes = min(cur_bytes, last_alloc);
9549 ret = btrfs_reserve_extent(root, cur_bytes, cur_bytes,
9550 min_size, 0, *alloc_hint, &ins, 1, 0);
9553 btrfs_end_transaction(trans);
9558 * We've reserved this space, and thus converted it from
9559 * ->bytes_may_use to ->bytes_reserved. Any error that happens
9560 * from here on out we will only need to clear our reservation
9561 * for the remaining unreserved area, so advance our
9562 * clear_offset by our extent size.
9564 clear_offset += ins.offset;
9565 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
9567 last_alloc = ins.offset;
9568 ret = insert_reserved_file_extent(trans, inode,
9569 cur_offset, ins.objectid,
9570 ins.offset, ins.offset,
9571 ins.offset, 0, 0, 0,
9572 BTRFS_FILE_EXTENT_PREALLOC);
9574 btrfs_free_reserved_extent(fs_info, ins.objectid,
9576 btrfs_abort_transaction(trans, ret);
9578 btrfs_end_transaction(trans);
9582 btrfs_drop_extent_cache(BTRFS_I(inode), cur_offset,
9583 cur_offset + ins.offset -1, 0);
9585 em = alloc_extent_map();
9587 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
9588 &BTRFS_I(inode)->runtime_flags);
9592 em->start = cur_offset;
9593 em->orig_start = cur_offset;
9594 em->len = ins.offset;
9595 em->block_start = ins.objectid;
9596 em->block_len = ins.offset;
9597 em->orig_block_len = ins.offset;
9598 em->ram_bytes = ins.offset;
9599 set_bit(EXTENT_FLAG_PREALLOC, &em->flags);
9600 em->generation = trans->transid;
9603 write_lock(&em_tree->lock);
9604 ret = add_extent_mapping(em_tree, em, 1);
9605 write_unlock(&em_tree->lock);
9608 btrfs_drop_extent_cache(BTRFS_I(inode), cur_offset,
9609 cur_offset + ins.offset - 1,
9612 free_extent_map(em);
9614 num_bytes -= ins.offset;
9615 cur_offset += ins.offset;
9616 *alloc_hint = ins.objectid + ins.offset;
9618 inode_inc_iversion(inode);
9619 inode->i_ctime = current_time(inode);
9620 BTRFS_I(inode)->flags |= BTRFS_INODE_PREALLOC;
9621 if (!(mode & FALLOC_FL_KEEP_SIZE) &&
9622 (actual_len > inode->i_size) &&
9623 (cur_offset > inode->i_size)) {
9624 if (cur_offset > actual_len)
9625 i_size = actual_len;
9627 i_size = cur_offset;
9628 i_size_write(inode, i_size);
9629 btrfs_inode_safe_disk_i_size_write(inode, 0);
9632 ret = btrfs_update_inode(trans, root, inode);
9635 btrfs_abort_transaction(trans, ret);
9637 btrfs_end_transaction(trans);
9642 btrfs_end_transaction(trans);
9644 if (clear_offset < end)
9645 btrfs_free_reserved_data_space(inode, NULL, clear_offset,
9646 end - clear_offset + 1);
9650 int btrfs_prealloc_file_range(struct inode *inode, int mode,
9651 u64 start, u64 num_bytes, u64 min_size,
9652 loff_t actual_len, u64 *alloc_hint)
9654 return __btrfs_prealloc_file_range(inode, mode, start, num_bytes,
9655 min_size, actual_len, alloc_hint,
9659 int btrfs_prealloc_file_range_trans(struct inode *inode,
9660 struct btrfs_trans_handle *trans, int mode,
9661 u64 start, u64 num_bytes, u64 min_size,
9662 loff_t actual_len, u64 *alloc_hint)
9664 return __btrfs_prealloc_file_range(inode, mode, start, num_bytes,
9665 min_size, actual_len, alloc_hint, trans);
9668 static int btrfs_set_page_dirty(struct page *page)
9670 return __set_page_dirty_nobuffers(page);
9673 static int btrfs_permission(struct inode *inode, int mask)
9675 struct btrfs_root *root = BTRFS_I(inode)->root;
9676 umode_t mode = inode->i_mode;
9678 if (mask & MAY_WRITE &&
9679 (S_ISREG(mode) || S_ISDIR(mode) || S_ISLNK(mode))) {
9680 if (btrfs_root_readonly(root))
9682 if (BTRFS_I(inode)->flags & BTRFS_INODE_READONLY)
9685 return generic_permission(inode, mask);
9688 static int btrfs_tmpfile(struct inode *dir, struct dentry *dentry, umode_t mode)
9690 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
9691 struct btrfs_trans_handle *trans;
9692 struct btrfs_root *root = BTRFS_I(dir)->root;
9693 struct inode *inode = NULL;
9699 * 5 units required for adding orphan entry
9701 trans = btrfs_start_transaction(root, 5);
9703 return PTR_ERR(trans);
9705 ret = btrfs_find_free_ino(root, &objectid);
9709 inode = btrfs_new_inode(trans, root, dir, NULL, 0,
9710 btrfs_ino(BTRFS_I(dir)), objectid, mode, &index);
9711 if (IS_ERR(inode)) {
9712 ret = PTR_ERR(inode);
9717 inode->i_fop = &btrfs_file_operations;
9718 inode->i_op = &btrfs_file_inode_operations;
9720 inode->i_mapping->a_ops = &btrfs_aops;
9721 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
9723 ret = btrfs_init_inode_security(trans, inode, dir, NULL);
9727 ret = btrfs_update_inode(trans, root, inode);
9730 ret = btrfs_orphan_add(trans, BTRFS_I(inode));
9735 * We set number of links to 0 in btrfs_new_inode(), and here we set
9736 * it to 1 because d_tmpfile() will issue a warning if the count is 0,
9739 * d_tmpfile() -> inode_dec_link_count() -> drop_nlink()
9741 set_nlink(inode, 1);
9742 d_tmpfile(dentry, inode);
9743 unlock_new_inode(inode);
9744 mark_inode_dirty(inode);
9746 btrfs_end_transaction(trans);
9748 discard_new_inode(inode);
9749 btrfs_btree_balance_dirty(fs_info);
9753 void btrfs_set_range_writeback(struct extent_io_tree *tree, u64 start, u64 end)
9755 struct inode *inode = tree->private_data;
9756 unsigned long index = start >> PAGE_SHIFT;
9757 unsigned long end_index = end >> PAGE_SHIFT;
9760 while (index <= end_index) {
9761 page = find_get_page(inode->i_mapping, index);
9762 ASSERT(page); /* Pages should be in the extent_io_tree */
9763 set_page_writeback(page);
9771 * Add an entry indicating a block group or device which is pinned by a
9772 * swapfile. Returns 0 on success, 1 if there is already an entry for it, or a
9773 * negative errno on failure.
9775 static int btrfs_add_swapfile_pin(struct inode *inode, void *ptr,
9776 bool is_block_group)
9778 struct btrfs_fs_info *fs_info = BTRFS_I(inode)->root->fs_info;
9779 struct btrfs_swapfile_pin *sp, *entry;
9781 struct rb_node *parent = NULL;
9783 sp = kmalloc(sizeof(*sp), GFP_NOFS);
9788 sp->is_block_group = is_block_group;
9790 spin_lock(&fs_info->swapfile_pins_lock);
9791 p = &fs_info->swapfile_pins.rb_node;
9794 entry = rb_entry(parent, struct btrfs_swapfile_pin, node);
9795 if (sp->ptr < entry->ptr ||
9796 (sp->ptr == entry->ptr && sp->inode < entry->inode)) {
9798 } else if (sp->ptr > entry->ptr ||
9799 (sp->ptr == entry->ptr && sp->inode > entry->inode)) {
9800 p = &(*p)->rb_right;
9802 spin_unlock(&fs_info->swapfile_pins_lock);
9807 rb_link_node(&sp->node, parent, p);
9808 rb_insert_color(&sp->node, &fs_info->swapfile_pins);
9809 spin_unlock(&fs_info->swapfile_pins_lock);
9813 /* Free all of the entries pinned by this swapfile. */
9814 static void btrfs_free_swapfile_pins(struct inode *inode)
9816 struct btrfs_fs_info *fs_info = BTRFS_I(inode)->root->fs_info;
9817 struct btrfs_swapfile_pin *sp;
9818 struct rb_node *node, *next;
9820 spin_lock(&fs_info->swapfile_pins_lock);
9821 node = rb_first(&fs_info->swapfile_pins);
9823 next = rb_next(node);
9824 sp = rb_entry(node, struct btrfs_swapfile_pin, node);
9825 if (sp->inode == inode) {
9826 rb_erase(&sp->node, &fs_info->swapfile_pins);
9827 if (sp->is_block_group)
9828 btrfs_put_block_group(sp->ptr);
9833 spin_unlock(&fs_info->swapfile_pins_lock);
9836 struct btrfs_swap_info {
9842 unsigned long nr_pages;
9846 static int btrfs_add_swap_extent(struct swap_info_struct *sis,
9847 struct btrfs_swap_info *bsi)
9849 unsigned long nr_pages;
9850 u64 first_ppage, first_ppage_reported, next_ppage;
9853 first_ppage = ALIGN(bsi->block_start, PAGE_SIZE) >> PAGE_SHIFT;
9854 next_ppage = ALIGN_DOWN(bsi->block_start + bsi->block_len,
9855 PAGE_SIZE) >> PAGE_SHIFT;
9857 if (first_ppage >= next_ppage)
9859 nr_pages = next_ppage - first_ppage;
9861 first_ppage_reported = first_ppage;
9862 if (bsi->start == 0)
9863 first_ppage_reported++;
9864 if (bsi->lowest_ppage > first_ppage_reported)
9865 bsi->lowest_ppage = first_ppage_reported;
9866 if (bsi->highest_ppage < (next_ppage - 1))
9867 bsi->highest_ppage = next_ppage - 1;
9869 ret = add_swap_extent(sis, bsi->nr_pages, nr_pages, first_ppage);
9872 bsi->nr_extents += ret;
9873 bsi->nr_pages += nr_pages;
9877 static void btrfs_swap_deactivate(struct file *file)
9879 struct inode *inode = file_inode(file);
9881 btrfs_free_swapfile_pins(inode);
9882 atomic_dec(&BTRFS_I(inode)->root->nr_swapfiles);
9885 static int btrfs_swap_activate(struct swap_info_struct *sis, struct file *file,
9888 struct inode *inode = file_inode(file);
9889 struct btrfs_fs_info *fs_info = BTRFS_I(inode)->root->fs_info;
9890 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
9891 struct extent_state *cached_state = NULL;
9892 struct extent_map *em = NULL;
9893 struct btrfs_device *device = NULL;
9894 struct btrfs_swap_info bsi = {
9895 .lowest_ppage = (sector_t)-1ULL,
9902 * If the swap file was just created, make sure delalloc is done. If the
9903 * file changes again after this, the user is doing something stupid and
9904 * we don't really care.
9906 ret = btrfs_wait_ordered_range(inode, 0, (u64)-1);
9911 * The inode is locked, so these flags won't change after we check them.
9913 if (BTRFS_I(inode)->flags & BTRFS_INODE_COMPRESS) {
9914 btrfs_warn(fs_info, "swapfile must not be compressed");
9917 if (!(BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW)) {
9918 btrfs_warn(fs_info, "swapfile must not be copy-on-write");
9921 if (!(BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)) {
9922 btrfs_warn(fs_info, "swapfile must not be checksummed");
9927 * Balance or device remove/replace/resize can move stuff around from
9928 * under us. The EXCL_OP flag makes sure they aren't running/won't run
9929 * concurrently while we are mapping the swap extents, and
9930 * fs_info->swapfile_pins prevents them from running while the swap file
9931 * is active and moving the extents. Note that this also prevents a
9932 * concurrent device add which isn't actually necessary, but it's not
9933 * really worth the trouble to allow it.
9935 if (test_and_set_bit(BTRFS_FS_EXCL_OP, &fs_info->flags)) {
9937 "cannot activate swapfile while exclusive operation is running");
9941 * Snapshots can create extents which require COW even if NODATACOW is
9942 * set. We use this counter to prevent snapshots. We must increment it
9943 * before walking the extents because we don't want a concurrent
9944 * snapshot to run after we've already checked the extents.
9946 atomic_inc(&BTRFS_I(inode)->root->nr_swapfiles);
9948 isize = ALIGN_DOWN(inode->i_size, fs_info->sectorsize);
9950 lock_extent_bits(io_tree, 0, isize - 1, &cached_state);
9952 while (start < isize) {
9953 u64 logical_block_start, physical_block_start;
9954 struct btrfs_block_group *bg;
9955 u64 len = isize - start;
9957 em = btrfs_get_extent(BTRFS_I(inode), NULL, 0, start, len);
9963 if (em->block_start == EXTENT_MAP_HOLE) {
9964 btrfs_warn(fs_info, "swapfile must not have holes");
9968 if (em->block_start == EXTENT_MAP_INLINE) {
9970 * It's unlikely we'll ever actually find ourselves
9971 * here, as a file small enough to fit inline won't be
9972 * big enough to store more than the swap header, but in
9973 * case something changes in the future, let's catch it
9974 * here rather than later.
9976 btrfs_warn(fs_info, "swapfile must not be inline");
9980 if (test_bit(EXTENT_FLAG_COMPRESSED, &em->flags)) {
9981 btrfs_warn(fs_info, "swapfile must not be compressed");
9986 logical_block_start = em->block_start + (start - em->start);
9987 len = min(len, em->len - (start - em->start));
9988 free_extent_map(em);
9991 ret = can_nocow_extent(inode, start, &len, NULL, NULL, NULL);
9998 "swapfile must not be copy-on-write");
10003 em = btrfs_get_chunk_map(fs_info, logical_block_start, len);
10009 if (em->map_lookup->type & BTRFS_BLOCK_GROUP_PROFILE_MASK) {
10010 btrfs_warn(fs_info,
10011 "swapfile must have single data profile");
10016 if (device == NULL) {
10017 device = em->map_lookup->stripes[0].dev;
10018 ret = btrfs_add_swapfile_pin(inode, device, false);
10023 } else if (device != em->map_lookup->stripes[0].dev) {
10024 btrfs_warn(fs_info, "swapfile must be on one device");
10029 physical_block_start = (em->map_lookup->stripes[0].physical +
10030 (logical_block_start - em->start));
10031 len = min(len, em->len - (logical_block_start - em->start));
10032 free_extent_map(em);
10035 bg = btrfs_lookup_block_group(fs_info, logical_block_start);
10037 btrfs_warn(fs_info,
10038 "could not find block group containing swapfile");
10043 ret = btrfs_add_swapfile_pin(inode, bg, true);
10045 btrfs_put_block_group(bg);
10052 if (bsi.block_len &&
10053 bsi.block_start + bsi.block_len == physical_block_start) {
10054 bsi.block_len += len;
10056 if (bsi.block_len) {
10057 ret = btrfs_add_swap_extent(sis, &bsi);
10062 bsi.block_start = physical_block_start;
10063 bsi.block_len = len;
10070 ret = btrfs_add_swap_extent(sis, &bsi);
10073 if (!IS_ERR_OR_NULL(em))
10074 free_extent_map(em);
10076 unlock_extent_cached(io_tree, 0, isize - 1, &cached_state);
10079 btrfs_swap_deactivate(file);
10081 clear_bit(BTRFS_FS_EXCL_OP, &fs_info->flags);
10087 sis->bdev = device->bdev;
10088 *span = bsi.highest_ppage - bsi.lowest_ppage + 1;
10089 sis->max = bsi.nr_pages;
10090 sis->pages = bsi.nr_pages - 1;
10091 sis->highest_bit = bsi.nr_pages - 1;
10092 return bsi.nr_extents;
10095 static void btrfs_swap_deactivate(struct file *file)
10099 static int btrfs_swap_activate(struct swap_info_struct *sis, struct file *file,
10102 return -EOPNOTSUPP;
10106 static const struct inode_operations btrfs_dir_inode_operations = {
10107 .getattr = btrfs_getattr,
10108 .lookup = btrfs_lookup,
10109 .create = btrfs_create,
10110 .unlink = btrfs_unlink,
10111 .link = btrfs_link,
10112 .mkdir = btrfs_mkdir,
10113 .rmdir = btrfs_rmdir,
10114 .rename = btrfs_rename2,
10115 .symlink = btrfs_symlink,
10116 .setattr = btrfs_setattr,
10117 .mknod = btrfs_mknod,
10118 .listxattr = btrfs_listxattr,
10119 .permission = btrfs_permission,
10120 .get_acl = btrfs_get_acl,
10121 .set_acl = btrfs_set_acl,
10122 .update_time = btrfs_update_time,
10123 .tmpfile = btrfs_tmpfile,
10126 static const struct file_operations btrfs_dir_file_operations = {
10127 .llseek = generic_file_llseek,
10128 .read = generic_read_dir,
10129 .iterate_shared = btrfs_real_readdir,
10130 .open = btrfs_opendir,
10131 .unlocked_ioctl = btrfs_ioctl,
10132 #ifdef CONFIG_COMPAT
10133 .compat_ioctl = btrfs_compat_ioctl,
10135 .release = btrfs_release_file,
10136 .fsync = btrfs_sync_file,
10139 static const struct extent_io_ops btrfs_extent_io_ops = {
10140 /* mandatory callbacks */
10141 .submit_bio_hook = btrfs_submit_bio_hook,
10142 .readpage_end_io_hook = btrfs_readpage_end_io_hook,
10146 * btrfs doesn't support the bmap operation because swapfiles
10147 * use bmap to make a mapping of extents in the file. They assume
10148 * these extents won't change over the life of the file and they
10149 * use the bmap result to do IO directly to the drive.
10151 * the btrfs bmap call would return logical addresses that aren't
10152 * suitable for IO and they also will change frequently as COW
10153 * operations happen. So, swapfile + btrfs == corruption.
10155 * For now we're avoiding this by dropping bmap.
10157 static const struct address_space_operations btrfs_aops = {
10158 .readpage = btrfs_readpage,
10159 .writepage = btrfs_writepage,
10160 .writepages = btrfs_writepages,
10161 .readpages = btrfs_readpages,
10162 .direct_IO = noop_direct_IO,
10163 .invalidatepage = btrfs_invalidatepage,
10164 .releasepage = btrfs_releasepage,
10165 #ifdef CONFIG_MIGRATION
10166 .migratepage = btrfs_migratepage,
10168 .set_page_dirty = btrfs_set_page_dirty,
10169 .error_remove_page = generic_error_remove_page,
10170 .swap_activate = btrfs_swap_activate,
10171 .swap_deactivate = btrfs_swap_deactivate,
10174 static const struct inode_operations btrfs_file_inode_operations = {
10175 .getattr = btrfs_getattr,
10176 .setattr = btrfs_setattr,
10177 .listxattr = btrfs_listxattr,
10178 .permission = btrfs_permission,
10179 .fiemap = btrfs_fiemap,
10180 .get_acl = btrfs_get_acl,
10181 .set_acl = btrfs_set_acl,
10182 .update_time = btrfs_update_time,
10184 static const struct inode_operations btrfs_special_inode_operations = {
10185 .getattr = btrfs_getattr,
10186 .setattr = btrfs_setattr,
10187 .permission = btrfs_permission,
10188 .listxattr = btrfs_listxattr,
10189 .get_acl = btrfs_get_acl,
10190 .set_acl = btrfs_set_acl,
10191 .update_time = btrfs_update_time,
10193 static const struct inode_operations btrfs_symlink_inode_operations = {
10194 .get_link = page_get_link,
10195 .getattr = btrfs_getattr,
10196 .setattr = btrfs_setattr,
10197 .permission = btrfs_permission,
10198 .listxattr = btrfs_listxattr,
10199 .update_time = btrfs_update_time,
10202 const struct dentry_operations btrfs_dentry_operations = {
10203 .d_delete = btrfs_dentry_delete,