1 // SPDX-License-Identifier: GPL-2.0
3 * Copyright (C) 2007 Oracle. All rights reserved.
6 #include <linux/kernel.h>
8 #include <linux/buffer_head.h>
9 #include <linux/file.h>
11 #include <linux/pagemap.h>
12 #include <linux/highmem.h>
13 #include <linux/time.h>
14 #include <linux/init.h>
15 #include <linux/string.h>
16 #include <linux/backing-dev.h>
17 #include <linux/writeback.h>
18 #include <linux/compat.h>
19 #include <linux/xattr.h>
20 #include <linux/posix_acl.h>
21 #include <linux/falloc.h>
22 #include <linux/slab.h>
23 #include <linux/ratelimit.h>
24 #include <linux/btrfs.h>
25 #include <linux/blkdev.h>
26 #include <linux/posix_acl_xattr.h>
27 #include <linux/uio.h>
28 #include <linux/magic.h>
29 #include <linux/iversion.h>
30 #include <linux/swap.h>
31 #include <linux/migrate.h>
32 #include <linux/sched/mm.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 {
54 struct btrfs_key *location;
55 struct btrfs_root *root;
58 struct btrfs_dio_data {
60 u64 unsubmitted_oe_range_start;
61 u64 unsubmitted_oe_range_end;
65 static const struct inode_operations btrfs_dir_inode_operations;
66 static const struct inode_operations btrfs_symlink_inode_operations;
67 static const struct inode_operations btrfs_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_init(shash);
2746 crypto_shash_update(shash, kaddr + pgoff, len);
2747 crypto_shash_final(shash, csum);
2749 if (memcmp(csum, csum_expected, csum_size))
2752 kunmap_atomic(kaddr);
2755 btrfs_print_data_csum_error(BTRFS_I(inode), start, csum, csum_expected,
2756 io_bio->mirror_num);
2757 memset(kaddr + pgoff, 1, len);
2758 flush_dcache_page(page);
2759 kunmap_atomic(kaddr);
2764 * when reads are done, we need to check csums to verify the data is correct
2765 * if there's a match, we allow the bio to finish. If not, the code in
2766 * extent_io.c will try to find good copies for us.
2768 static int btrfs_readpage_end_io_hook(struct btrfs_io_bio *io_bio,
2769 u64 phy_offset, struct page *page,
2770 u64 start, u64 end, int mirror)
2772 size_t offset = start - page_offset(page);
2773 struct inode *inode = page->mapping->host;
2774 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
2775 struct btrfs_root *root = BTRFS_I(inode)->root;
2777 if (PageChecked(page)) {
2778 ClearPageChecked(page);
2782 if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)
2785 if (root->root_key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID &&
2786 test_range_bit(io_tree, start, end, EXTENT_NODATASUM, 1, NULL)) {
2787 clear_extent_bits(io_tree, start, end, EXTENT_NODATASUM);
2791 phy_offset >>= inode->i_sb->s_blocksize_bits;
2792 return check_data_csum(inode, io_bio, phy_offset, page, offset, start,
2793 (size_t)(end - start + 1));
2797 * btrfs_add_delayed_iput - perform a delayed iput on @inode
2799 * @inode: The inode we want to perform iput on
2801 * This function uses the generic vfs_inode::i_count to track whether we should
2802 * just decrement it (in case it's > 1) or if this is the last iput then link
2803 * the inode to the delayed iput machinery. Delayed iputs are processed at
2804 * transaction commit time/superblock commit/cleaner kthread.
2806 void btrfs_add_delayed_iput(struct inode *inode)
2808 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2809 struct btrfs_inode *binode = BTRFS_I(inode);
2811 if (atomic_add_unless(&inode->i_count, -1, 1))
2814 atomic_inc(&fs_info->nr_delayed_iputs);
2815 spin_lock(&fs_info->delayed_iput_lock);
2816 ASSERT(list_empty(&binode->delayed_iput));
2817 list_add_tail(&binode->delayed_iput, &fs_info->delayed_iputs);
2818 spin_unlock(&fs_info->delayed_iput_lock);
2819 if (!test_bit(BTRFS_FS_CLEANER_RUNNING, &fs_info->flags))
2820 wake_up_process(fs_info->cleaner_kthread);
2823 static void run_delayed_iput_locked(struct btrfs_fs_info *fs_info,
2824 struct btrfs_inode *inode)
2826 list_del_init(&inode->delayed_iput);
2827 spin_unlock(&fs_info->delayed_iput_lock);
2828 iput(&inode->vfs_inode);
2829 if (atomic_dec_and_test(&fs_info->nr_delayed_iputs))
2830 wake_up(&fs_info->delayed_iputs_wait);
2831 spin_lock(&fs_info->delayed_iput_lock);
2834 static void btrfs_run_delayed_iput(struct btrfs_fs_info *fs_info,
2835 struct btrfs_inode *inode)
2837 if (!list_empty(&inode->delayed_iput)) {
2838 spin_lock(&fs_info->delayed_iput_lock);
2839 if (!list_empty(&inode->delayed_iput))
2840 run_delayed_iput_locked(fs_info, inode);
2841 spin_unlock(&fs_info->delayed_iput_lock);
2845 void btrfs_run_delayed_iputs(struct btrfs_fs_info *fs_info)
2848 spin_lock(&fs_info->delayed_iput_lock);
2849 while (!list_empty(&fs_info->delayed_iputs)) {
2850 struct btrfs_inode *inode;
2852 inode = list_first_entry(&fs_info->delayed_iputs,
2853 struct btrfs_inode, delayed_iput);
2854 run_delayed_iput_locked(fs_info, inode);
2856 spin_unlock(&fs_info->delayed_iput_lock);
2860 * btrfs_wait_on_delayed_iputs - wait on the delayed iputs to be done running
2861 * @fs_info - the fs_info for this fs
2862 * @return - EINTR if we were killed, 0 if nothing's pending
2864 * This will wait on any delayed iputs that are currently running with KILLABLE
2865 * set. Once they are all done running we will return, unless we are killed in
2866 * which case we return EINTR. This helps in user operations like fallocate etc
2867 * that might get blocked on the iputs.
2869 int btrfs_wait_on_delayed_iputs(struct btrfs_fs_info *fs_info)
2871 int ret = wait_event_killable(fs_info->delayed_iputs_wait,
2872 atomic_read(&fs_info->nr_delayed_iputs) == 0);
2879 * This creates an orphan entry for the given inode in case something goes wrong
2880 * in the middle of an unlink.
2882 int btrfs_orphan_add(struct btrfs_trans_handle *trans,
2883 struct btrfs_inode *inode)
2887 ret = btrfs_insert_orphan_item(trans, inode->root, btrfs_ino(inode));
2888 if (ret && ret != -EEXIST) {
2889 btrfs_abort_transaction(trans, ret);
2897 * We have done the delete so we can go ahead and remove the orphan item for
2898 * this particular inode.
2900 static int btrfs_orphan_del(struct btrfs_trans_handle *trans,
2901 struct btrfs_inode *inode)
2903 return btrfs_del_orphan_item(trans, inode->root, btrfs_ino(inode));
2907 * this cleans up any orphans that may be left on the list from the last use
2910 int btrfs_orphan_cleanup(struct btrfs_root *root)
2912 struct btrfs_fs_info *fs_info = root->fs_info;
2913 struct btrfs_path *path;
2914 struct extent_buffer *leaf;
2915 struct btrfs_key key, found_key;
2916 struct btrfs_trans_handle *trans;
2917 struct inode *inode;
2918 u64 last_objectid = 0;
2919 int ret = 0, nr_unlink = 0;
2921 if (cmpxchg(&root->orphan_cleanup_state, 0, ORPHAN_CLEANUP_STARTED))
2924 path = btrfs_alloc_path();
2929 path->reada = READA_BACK;
2931 key.objectid = BTRFS_ORPHAN_OBJECTID;
2932 key.type = BTRFS_ORPHAN_ITEM_KEY;
2933 key.offset = (u64)-1;
2936 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2941 * if ret == 0 means we found what we were searching for, which
2942 * is weird, but possible, so only screw with path if we didn't
2943 * find the key and see if we have stuff that matches
2947 if (path->slots[0] == 0)
2952 /* pull out the item */
2953 leaf = path->nodes[0];
2954 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
2956 /* make sure the item matches what we want */
2957 if (found_key.objectid != BTRFS_ORPHAN_OBJECTID)
2959 if (found_key.type != BTRFS_ORPHAN_ITEM_KEY)
2962 /* release the path since we're done with it */
2963 btrfs_release_path(path);
2966 * this is where we are basically btrfs_lookup, without the
2967 * crossing root thing. we store the inode number in the
2968 * offset of the orphan item.
2971 if (found_key.offset == last_objectid) {
2973 "Error removing orphan entry, stopping orphan cleanup");
2978 last_objectid = found_key.offset;
2980 found_key.objectid = found_key.offset;
2981 found_key.type = BTRFS_INODE_ITEM_KEY;
2982 found_key.offset = 0;
2983 inode = btrfs_iget(fs_info->sb, &found_key, root);
2984 ret = PTR_ERR_OR_ZERO(inode);
2985 if (ret && ret != -ENOENT)
2988 if (ret == -ENOENT && root == fs_info->tree_root) {
2989 struct btrfs_root *dead_root;
2990 struct btrfs_fs_info *fs_info = root->fs_info;
2991 int is_dead_root = 0;
2994 * this is an orphan in the tree root. Currently these
2995 * could come from 2 sources:
2996 * a) a snapshot deletion in progress
2997 * b) a free space cache inode
2998 * We need to distinguish those two, as the snapshot
2999 * orphan must not get deleted.
3000 * find_dead_roots already ran before us, so if this
3001 * is a snapshot deletion, we should find the root
3002 * in the dead_roots list
3004 spin_lock(&fs_info->trans_lock);
3005 list_for_each_entry(dead_root, &fs_info->dead_roots,
3007 if (dead_root->root_key.objectid ==
3008 found_key.objectid) {
3013 spin_unlock(&fs_info->trans_lock);
3015 /* prevent this orphan from being found again */
3016 key.offset = found_key.objectid - 1;
3023 * If we have an inode with links, there are a couple of
3024 * possibilities. Old kernels (before v3.12) used to create an
3025 * orphan item for truncate indicating that there were possibly
3026 * extent items past i_size that needed to be deleted. In v3.12,
3027 * truncate was changed to update i_size in sync with the extent
3028 * items, but the (useless) orphan item was still created. Since
3029 * v4.18, we don't create the orphan item for truncate at all.
3031 * So, this item could mean that we need to do a truncate, but
3032 * only if this filesystem was last used on a pre-v3.12 kernel
3033 * and was not cleanly unmounted. The odds of that are quite
3034 * slim, and it's a pain to do the truncate now, so just delete
3037 * It's also possible that this orphan item was supposed to be
3038 * deleted but wasn't. The inode number may have been reused,
3039 * but either way, we can delete the orphan item.
3041 if (ret == -ENOENT || inode->i_nlink) {
3044 trans = btrfs_start_transaction(root, 1);
3045 if (IS_ERR(trans)) {
3046 ret = PTR_ERR(trans);
3049 btrfs_debug(fs_info, "auto deleting %Lu",
3050 found_key.objectid);
3051 ret = btrfs_del_orphan_item(trans, root,
3052 found_key.objectid);
3053 btrfs_end_transaction(trans);
3061 /* this will do delete_inode and everything for us */
3064 /* release the path since we're done with it */
3065 btrfs_release_path(path);
3067 root->orphan_cleanup_state = ORPHAN_CLEANUP_DONE;
3069 if (test_bit(BTRFS_ROOT_ORPHAN_ITEM_INSERTED, &root->state)) {
3070 trans = btrfs_join_transaction(root);
3072 btrfs_end_transaction(trans);
3076 btrfs_debug(fs_info, "unlinked %d orphans", nr_unlink);
3080 btrfs_err(fs_info, "could not do orphan cleanup %d", ret);
3081 btrfs_free_path(path);
3086 * very simple check to peek ahead in the leaf looking for xattrs. If we
3087 * don't find any xattrs, we know there can't be any acls.
3089 * slot is the slot the inode is in, objectid is the objectid of the inode
3091 static noinline int acls_after_inode_item(struct extent_buffer *leaf,
3092 int slot, u64 objectid,
3093 int *first_xattr_slot)
3095 u32 nritems = btrfs_header_nritems(leaf);
3096 struct btrfs_key found_key;
3097 static u64 xattr_access = 0;
3098 static u64 xattr_default = 0;
3101 if (!xattr_access) {
3102 xattr_access = btrfs_name_hash(XATTR_NAME_POSIX_ACL_ACCESS,
3103 strlen(XATTR_NAME_POSIX_ACL_ACCESS));
3104 xattr_default = btrfs_name_hash(XATTR_NAME_POSIX_ACL_DEFAULT,
3105 strlen(XATTR_NAME_POSIX_ACL_DEFAULT));
3109 *first_xattr_slot = -1;
3110 while (slot < nritems) {
3111 btrfs_item_key_to_cpu(leaf, &found_key, slot);
3113 /* we found a different objectid, there must not be acls */
3114 if (found_key.objectid != objectid)
3117 /* we found an xattr, assume we've got an acl */
3118 if (found_key.type == BTRFS_XATTR_ITEM_KEY) {
3119 if (*first_xattr_slot == -1)
3120 *first_xattr_slot = slot;
3121 if (found_key.offset == xattr_access ||
3122 found_key.offset == xattr_default)
3127 * we found a key greater than an xattr key, there can't
3128 * be any acls later on
3130 if (found_key.type > BTRFS_XATTR_ITEM_KEY)
3137 * it goes inode, inode backrefs, xattrs, extents,
3138 * so if there are a ton of hard links to an inode there can
3139 * be a lot of backrefs. Don't waste time searching too hard,
3140 * this is just an optimization
3145 /* we hit the end of the leaf before we found an xattr or
3146 * something larger than an xattr. We have to assume the inode
3149 if (*first_xattr_slot == -1)
3150 *first_xattr_slot = slot;
3155 * read an inode from the btree into the in-memory inode
3157 static int btrfs_read_locked_inode(struct inode *inode,
3158 struct btrfs_path *in_path)
3160 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
3161 struct btrfs_path *path = in_path;
3162 struct extent_buffer *leaf;
3163 struct btrfs_inode_item *inode_item;
3164 struct btrfs_root *root = BTRFS_I(inode)->root;
3165 struct btrfs_key location;
3170 bool filled = false;
3171 int first_xattr_slot;
3173 ret = btrfs_fill_inode(inode, &rdev);
3178 path = btrfs_alloc_path();
3183 memcpy(&location, &BTRFS_I(inode)->location, sizeof(location));
3185 ret = btrfs_lookup_inode(NULL, root, path, &location, 0);
3187 if (path != in_path)
3188 btrfs_free_path(path);
3192 leaf = path->nodes[0];
3197 inode_item = btrfs_item_ptr(leaf, path->slots[0],
3198 struct btrfs_inode_item);
3199 inode->i_mode = btrfs_inode_mode(leaf, inode_item);
3200 set_nlink(inode, btrfs_inode_nlink(leaf, inode_item));
3201 i_uid_write(inode, btrfs_inode_uid(leaf, inode_item));
3202 i_gid_write(inode, btrfs_inode_gid(leaf, inode_item));
3203 btrfs_i_size_write(BTRFS_I(inode), btrfs_inode_size(leaf, inode_item));
3204 btrfs_inode_set_file_extent_range(BTRFS_I(inode), 0,
3205 round_up(i_size_read(inode), fs_info->sectorsize));
3207 inode->i_atime.tv_sec = btrfs_timespec_sec(leaf, &inode_item->atime);
3208 inode->i_atime.tv_nsec = btrfs_timespec_nsec(leaf, &inode_item->atime);
3210 inode->i_mtime.tv_sec = btrfs_timespec_sec(leaf, &inode_item->mtime);
3211 inode->i_mtime.tv_nsec = btrfs_timespec_nsec(leaf, &inode_item->mtime);
3213 inode->i_ctime.tv_sec = btrfs_timespec_sec(leaf, &inode_item->ctime);
3214 inode->i_ctime.tv_nsec = btrfs_timespec_nsec(leaf, &inode_item->ctime);
3216 BTRFS_I(inode)->i_otime.tv_sec =
3217 btrfs_timespec_sec(leaf, &inode_item->otime);
3218 BTRFS_I(inode)->i_otime.tv_nsec =
3219 btrfs_timespec_nsec(leaf, &inode_item->otime);
3221 inode_set_bytes(inode, btrfs_inode_nbytes(leaf, inode_item));
3222 BTRFS_I(inode)->generation = btrfs_inode_generation(leaf, inode_item);
3223 BTRFS_I(inode)->last_trans = btrfs_inode_transid(leaf, inode_item);
3225 inode_set_iversion_queried(inode,
3226 btrfs_inode_sequence(leaf, inode_item));
3227 inode->i_generation = BTRFS_I(inode)->generation;
3229 rdev = btrfs_inode_rdev(leaf, inode_item);
3231 BTRFS_I(inode)->index_cnt = (u64)-1;
3232 BTRFS_I(inode)->flags = btrfs_inode_flags(leaf, inode_item);
3236 * If we were modified in the current generation and evicted from memory
3237 * and then re-read we need to do a full sync since we don't have any
3238 * idea about which extents were modified before we were evicted from
3241 * This is required for both inode re-read from disk and delayed inode
3242 * in delayed_nodes_tree.
3244 if (BTRFS_I(inode)->last_trans == fs_info->generation)
3245 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
3246 &BTRFS_I(inode)->runtime_flags);
3249 * We don't persist the id of the transaction where an unlink operation
3250 * against the inode was last made. So here we assume the inode might
3251 * have been evicted, and therefore the exact value of last_unlink_trans
3252 * lost, and set it to last_trans to avoid metadata inconsistencies
3253 * between the inode and its parent if the inode is fsync'ed and the log
3254 * replayed. For example, in the scenario:
3257 * ln mydir/foo mydir/bar
3260 * echo 2 > /proc/sys/vm/drop_caches # evicts inode
3261 * xfs_io -c fsync mydir/foo
3263 * mount fs, triggers fsync log replay
3265 * We must make sure that when we fsync our inode foo we also log its
3266 * parent inode, otherwise after log replay the parent still has the
3267 * dentry with the "bar" name but our inode foo has a link count of 1
3268 * and doesn't have an inode ref with the name "bar" anymore.
3270 * Setting last_unlink_trans to last_trans is a pessimistic approach,
3271 * but it guarantees correctness at the expense of occasional full
3272 * transaction commits on fsync if our inode is a directory, or if our
3273 * inode is not a directory, logging its parent unnecessarily.
3275 BTRFS_I(inode)->last_unlink_trans = BTRFS_I(inode)->last_trans;
3278 if (inode->i_nlink != 1 ||
3279 path->slots[0] >= btrfs_header_nritems(leaf))
3282 btrfs_item_key_to_cpu(leaf, &location, path->slots[0]);
3283 if (location.objectid != btrfs_ino(BTRFS_I(inode)))
3286 ptr = btrfs_item_ptr_offset(leaf, path->slots[0]);
3287 if (location.type == BTRFS_INODE_REF_KEY) {
3288 struct btrfs_inode_ref *ref;
3290 ref = (struct btrfs_inode_ref *)ptr;
3291 BTRFS_I(inode)->dir_index = btrfs_inode_ref_index(leaf, ref);
3292 } else if (location.type == BTRFS_INODE_EXTREF_KEY) {
3293 struct btrfs_inode_extref *extref;
3295 extref = (struct btrfs_inode_extref *)ptr;
3296 BTRFS_I(inode)->dir_index = btrfs_inode_extref_index(leaf,
3301 * try to precache a NULL acl entry for files that don't have
3302 * any xattrs or acls
3304 maybe_acls = acls_after_inode_item(leaf, path->slots[0],
3305 btrfs_ino(BTRFS_I(inode)), &first_xattr_slot);
3306 if (first_xattr_slot != -1) {
3307 path->slots[0] = first_xattr_slot;
3308 ret = btrfs_load_inode_props(inode, path);
3311 "error loading props for ino %llu (root %llu): %d",
3312 btrfs_ino(BTRFS_I(inode)),
3313 root->root_key.objectid, ret);
3315 if (path != in_path)
3316 btrfs_free_path(path);
3319 cache_no_acl(inode);
3321 switch (inode->i_mode & S_IFMT) {
3323 inode->i_mapping->a_ops = &btrfs_aops;
3324 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
3325 inode->i_fop = &btrfs_file_operations;
3326 inode->i_op = &btrfs_file_inode_operations;
3329 inode->i_fop = &btrfs_dir_file_operations;
3330 inode->i_op = &btrfs_dir_inode_operations;
3333 inode->i_op = &btrfs_symlink_inode_operations;
3334 inode_nohighmem(inode);
3335 inode->i_mapping->a_ops = &btrfs_aops;
3338 inode->i_op = &btrfs_special_inode_operations;
3339 init_special_inode(inode, inode->i_mode, rdev);
3343 btrfs_sync_inode_flags_to_i_flags(inode);
3348 * given a leaf and an inode, copy the inode fields into the leaf
3350 static void fill_inode_item(struct btrfs_trans_handle *trans,
3351 struct extent_buffer *leaf,
3352 struct btrfs_inode_item *item,
3353 struct inode *inode)
3355 struct btrfs_map_token token;
3357 btrfs_init_map_token(&token, leaf);
3359 btrfs_set_token_inode_uid(leaf, item, i_uid_read(inode), &token);
3360 btrfs_set_token_inode_gid(leaf, item, i_gid_read(inode), &token);
3361 btrfs_set_token_inode_size(leaf, item, BTRFS_I(inode)->disk_i_size,
3363 btrfs_set_token_inode_mode(leaf, item, inode->i_mode, &token);
3364 btrfs_set_token_inode_nlink(leaf, item, inode->i_nlink, &token);
3366 btrfs_set_token_timespec_sec(leaf, &item->atime,
3367 inode->i_atime.tv_sec, &token);
3368 btrfs_set_token_timespec_nsec(leaf, &item->atime,
3369 inode->i_atime.tv_nsec, &token);
3371 btrfs_set_token_timespec_sec(leaf, &item->mtime,
3372 inode->i_mtime.tv_sec, &token);
3373 btrfs_set_token_timespec_nsec(leaf, &item->mtime,
3374 inode->i_mtime.tv_nsec, &token);
3376 btrfs_set_token_timespec_sec(leaf, &item->ctime,
3377 inode->i_ctime.tv_sec, &token);
3378 btrfs_set_token_timespec_nsec(leaf, &item->ctime,
3379 inode->i_ctime.tv_nsec, &token);
3381 btrfs_set_token_timespec_sec(leaf, &item->otime,
3382 BTRFS_I(inode)->i_otime.tv_sec, &token);
3383 btrfs_set_token_timespec_nsec(leaf, &item->otime,
3384 BTRFS_I(inode)->i_otime.tv_nsec, &token);
3386 btrfs_set_token_inode_nbytes(leaf, item, inode_get_bytes(inode),
3388 btrfs_set_token_inode_generation(leaf, item, BTRFS_I(inode)->generation,
3390 btrfs_set_token_inode_sequence(leaf, item, inode_peek_iversion(inode),
3392 btrfs_set_token_inode_transid(leaf, item, trans->transid, &token);
3393 btrfs_set_token_inode_rdev(leaf, item, inode->i_rdev, &token);
3394 btrfs_set_token_inode_flags(leaf, item, BTRFS_I(inode)->flags, &token);
3395 btrfs_set_token_inode_block_group(leaf, item, 0, &token);
3399 * copy everything in the in-memory inode into the btree.
3401 static noinline int btrfs_update_inode_item(struct btrfs_trans_handle *trans,
3402 struct btrfs_root *root, struct inode *inode)
3404 struct btrfs_inode_item *inode_item;
3405 struct btrfs_path *path;
3406 struct extent_buffer *leaf;
3409 path = btrfs_alloc_path();
3413 path->leave_spinning = 1;
3414 ret = btrfs_lookup_inode(trans, root, path, &BTRFS_I(inode)->location,
3422 leaf = path->nodes[0];
3423 inode_item = btrfs_item_ptr(leaf, path->slots[0],
3424 struct btrfs_inode_item);
3426 fill_inode_item(trans, leaf, inode_item, inode);
3427 btrfs_mark_buffer_dirty(leaf);
3428 btrfs_set_inode_last_trans(trans, inode);
3431 btrfs_free_path(path);
3436 * copy everything in the in-memory inode into the btree.
3438 noinline int btrfs_update_inode(struct btrfs_trans_handle *trans,
3439 struct btrfs_root *root, struct inode *inode)
3441 struct btrfs_fs_info *fs_info = root->fs_info;
3445 * If the inode is a free space inode, we can deadlock during commit
3446 * if we put it into the delayed code.
3448 * The data relocation inode should also be directly updated
3451 if (!btrfs_is_free_space_inode(BTRFS_I(inode))
3452 && root->root_key.objectid != BTRFS_DATA_RELOC_TREE_OBJECTID
3453 && !test_bit(BTRFS_FS_LOG_RECOVERING, &fs_info->flags)) {
3454 btrfs_update_root_times(trans, root);
3456 ret = btrfs_delayed_update_inode(trans, root, inode);
3458 btrfs_set_inode_last_trans(trans, inode);
3462 return btrfs_update_inode_item(trans, root, inode);
3465 noinline int btrfs_update_inode_fallback(struct btrfs_trans_handle *trans,
3466 struct btrfs_root *root,
3467 struct inode *inode)
3471 ret = btrfs_update_inode(trans, root, inode);
3473 return btrfs_update_inode_item(trans, root, inode);
3478 * unlink helper that gets used here in inode.c and in the tree logging
3479 * recovery code. It remove a link in a directory with a given name, and
3480 * also drops the back refs in the inode to the directory
3482 static int __btrfs_unlink_inode(struct btrfs_trans_handle *trans,
3483 struct btrfs_root *root,
3484 struct btrfs_inode *dir,
3485 struct btrfs_inode *inode,
3486 const char *name, int name_len)
3488 struct btrfs_fs_info *fs_info = root->fs_info;
3489 struct btrfs_path *path;
3491 struct btrfs_dir_item *di;
3493 u64 ino = btrfs_ino(inode);
3494 u64 dir_ino = btrfs_ino(dir);
3496 path = btrfs_alloc_path();
3502 path->leave_spinning = 1;
3503 di = btrfs_lookup_dir_item(trans, root, path, dir_ino,
3504 name, name_len, -1);
3505 if (IS_ERR_OR_NULL(di)) {
3506 ret = di ? PTR_ERR(di) : -ENOENT;
3509 ret = btrfs_delete_one_dir_name(trans, root, path, di);
3512 btrfs_release_path(path);
3515 * If we don't have dir index, we have to get it by looking up
3516 * the inode ref, since we get the inode ref, remove it directly,
3517 * it is unnecessary to do delayed deletion.
3519 * But if we have dir index, needn't search inode ref to get it.
3520 * Since the inode ref is close to the inode item, it is better
3521 * that we delay to delete it, and just do this deletion when
3522 * we update the inode item.
3524 if (inode->dir_index) {
3525 ret = btrfs_delayed_delete_inode_ref(inode);
3527 index = inode->dir_index;
3532 ret = btrfs_del_inode_ref(trans, root, name, name_len, ino,
3536 "failed to delete reference to %.*s, inode %llu parent %llu",
3537 name_len, name, ino, dir_ino);
3538 btrfs_abort_transaction(trans, ret);
3542 ret = btrfs_delete_delayed_dir_index(trans, dir, index);
3544 btrfs_abort_transaction(trans, ret);
3548 ret = btrfs_del_inode_ref_in_log(trans, root, name, name_len, inode,
3550 if (ret != 0 && ret != -ENOENT) {
3551 btrfs_abort_transaction(trans, ret);
3555 ret = btrfs_del_dir_entries_in_log(trans, root, name, name_len, dir,
3560 btrfs_abort_transaction(trans, ret);
3563 * If we have a pending delayed iput we could end up with the final iput
3564 * being run in btrfs-cleaner context. If we have enough of these built
3565 * up we can end up burning a lot of time in btrfs-cleaner without any
3566 * way to throttle the unlinks. Since we're currently holding a ref on
3567 * the inode we can run the delayed iput here without any issues as the
3568 * final iput won't be done until after we drop the ref we're currently
3571 btrfs_run_delayed_iput(fs_info, inode);
3573 btrfs_free_path(path);
3577 btrfs_i_size_write(dir, dir->vfs_inode.i_size - name_len * 2);
3578 inode_inc_iversion(&inode->vfs_inode);
3579 inode_inc_iversion(&dir->vfs_inode);
3580 inode->vfs_inode.i_ctime = dir->vfs_inode.i_mtime =
3581 dir->vfs_inode.i_ctime = current_time(&inode->vfs_inode);
3582 ret = btrfs_update_inode(trans, root, &dir->vfs_inode);
3587 int btrfs_unlink_inode(struct btrfs_trans_handle *trans,
3588 struct btrfs_root *root,
3589 struct btrfs_inode *dir, struct btrfs_inode *inode,
3590 const char *name, int name_len)
3593 ret = __btrfs_unlink_inode(trans, root, dir, inode, name, name_len);
3595 drop_nlink(&inode->vfs_inode);
3596 ret = btrfs_update_inode(trans, root, &inode->vfs_inode);
3602 * helper to start transaction for unlink and rmdir.
3604 * unlink and rmdir are special in btrfs, they do not always free space, so
3605 * if we cannot make our reservations the normal way try and see if there is
3606 * plenty of slack room in the global reserve to migrate, otherwise we cannot
3607 * allow the unlink to occur.
3609 static struct btrfs_trans_handle *__unlink_start_trans(struct inode *dir)
3611 struct btrfs_root *root = BTRFS_I(dir)->root;
3614 * 1 for the possible orphan item
3615 * 1 for the dir item
3616 * 1 for the dir index
3617 * 1 for the inode ref
3620 return btrfs_start_transaction_fallback_global_rsv(root, 5);
3623 static int btrfs_unlink(struct inode *dir, struct dentry *dentry)
3625 struct btrfs_root *root = BTRFS_I(dir)->root;
3626 struct btrfs_trans_handle *trans;
3627 struct inode *inode = d_inode(dentry);
3630 trans = __unlink_start_trans(dir);
3632 return PTR_ERR(trans);
3634 btrfs_record_unlink_dir(trans, BTRFS_I(dir), BTRFS_I(d_inode(dentry)),
3637 ret = btrfs_unlink_inode(trans, root, BTRFS_I(dir),
3638 BTRFS_I(d_inode(dentry)), dentry->d_name.name,
3639 dentry->d_name.len);
3643 if (inode->i_nlink == 0) {
3644 ret = btrfs_orphan_add(trans, BTRFS_I(inode));
3650 btrfs_end_transaction(trans);
3651 btrfs_btree_balance_dirty(root->fs_info);
3655 static int btrfs_unlink_subvol(struct btrfs_trans_handle *trans,
3656 struct inode *dir, struct dentry *dentry)
3658 struct btrfs_root *root = BTRFS_I(dir)->root;
3659 struct btrfs_inode *inode = BTRFS_I(d_inode(dentry));
3660 struct btrfs_path *path;
3661 struct extent_buffer *leaf;
3662 struct btrfs_dir_item *di;
3663 struct btrfs_key key;
3664 const char *name = dentry->d_name.name;
3665 int name_len = dentry->d_name.len;
3669 u64 dir_ino = btrfs_ino(BTRFS_I(dir));
3671 if (btrfs_ino(inode) == BTRFS_FIRST_FREE_OBJECTID) {
3672 objectid = inode->root->root_key.objectid;
3673 } else if (btrfs_ino(inode) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID) {
3674 objectid = inode->location.objectid;
3680 path = btrfs_alloc_path();
3684 di = btrfs_lookup_dir_item(trans, root, path, dir_ino,
3685 name, name_len, -1);
3686 if (IS_ERR_OR_NULL(di)) {
3687 ret = di ? PTR_ERR(di) : -ENOENT;
3691 leaf = path->nodes[0];
3692 btrfs_dir_item_key_to_cpu(leaf, di, &key);
3693 WARN_ON(key.type != BTRFS_ROOT_ITEM_KEY || key.objectid != objectid);
3694 ret = btrfs_delete_one_dir_name(trans, root, path, di);
3696 btrfs_abort_transaction(trans, ret);
3699 btrfs_release_path(path);
3702 * This is a placeholder inode for a subvolume we didn't have a
3703 * reference to at the time of the snapshot creation. In the meantime
3704 * we could have renamed the real subvol link into our snapshot, so
3705 * depending on btrfs_del_root_ref to return -ENOENT here is incorret.
3706 * Instead simply lookup the dir_index_item for this entry so we can
3707 * remove it. Otherwise we know we have a ref to the root and we can
3708 * call btrfs_del_root_ref, and it _shouldn't_ fail.
3710 if (btrfs_ino(inode) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID) {
3711 di = btrfs_search_dir_index_item(root, path, dir_ino,
3713 if (IS_ERR_OR_NULL(di)) {
3718 btrfs_abort_transaction(trans, ret);
3722 leaf = path->nodes[0];
3723 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
3725 btrfs_release_path(path);
3727 ret = btrfs_del_root_ref(trans, objectid,
3728 root->root_key.objectid, dir_ino,
3729 &index, name, name_len);
3731 btrfs_abort_transaction(trans, ret);
3736 ret = btrfs_delete_delayed_dir_index(trans, BTRFS_I(dir), index);
3738 btrfs_abort_transaction(trans, ret);
3742 btrfs_i_size_write(BTRFS_I(dir), dir->i_size - name_len * 2);
3743 inode_inc_iversion(dir);
3744 dir->i_mtime = dir->i_ctime = current_time(dir);
3745 ret = btrfs_update_inode_fallback(trans, root, dir);
3747 btrfs_abort_transaction(trans, ret);
3749 btrfs_free_path(path);
3754 * Helper to check if the subvolume references other subvolumes or if it's
3757 static noinline int may_destroy_subvol(struct btrfs_root *root)
3759 struct btrfs_fs_info *fs_info = root->fs_info;
3760 struct btrfs_path *path;
3761 struct btrfs_dir_item *di;
3762 struct btrfs_key key;
3766 path = btrfs_alloc_path();
3770 /* Make sure this root isn't set as the default subvol */
3771 dir_id = btrfs_super_root_dir(fs_info->super_copy);
3772 di = btrfs_lookup_dir_item(NULL, fs_info->tree_root, path,
3773 dir_id, "default", 7, 0);
3774 if (di && !IS_ERR(di)) {
3775 btrfs_dir_item_key_to_cpu(path->nodes[0], di, &key);
3776 if (key.objectid == root->root_key.objectid) {
3779 "deleting default subvolume %llu is not allowed",
3783 btrfs_release_path(path);
3786 key.objectid = root->root_key.objectid;
3787 key.type = BTRFS_ROOT_REF_KEY;
3788 key.offset = (u64)-1;
3790 ret = btrfs_search_slot(NULL, fs_info->tree_root, &key, path, 0, 0);
3796 if (path->slots[0] > 0) {
3798 btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
3799 if (key.objectid == root->root_key.objectid &&
3800 key.type == BTRFS_ROOT_REF_KEY)
3804 btrfs_free_path(path);
3808 /* Delete all dentries for inodes belonging to the root */
3809 static void btrfs_prune_dentries(struct btrfs_root *root)
3811 struct btrfs_fs_info *fs_info = root->fs_info;
3812 struct rb_node *node;
3813 struct rb_node *prev;
3814 struct btrfs_inode *entry;
3815 struct inode *inode;
3818 if (!test_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state))
3819 WARN_ON(btrfs_root_refs(&root->root_item) != 0);
3821 spin_lock(&root->inode_lock);
3823 node = root->inode_tree.rb_node;
3827 entry = rb_entry(node, struct btrfs_inode, rb_node);
3829 if (objectid < btrfs_ino(entry))
3830 node = node->rb_left;
3831 else if (objectid > btrfs_ino(entry))
3832 node = node->rb_right;
3838 entry = rb_entry(prev, struct btrfs_inode, rb_node);
3839 if (objectid <= btrfs_ino(entry)) {
3843 prev = rb_next(prev);
3847 entry = rb_entry(node, struct btrfs_inode, rb_node);
3848 objectid = btrfs_ino(entry) + 1;
3849 inode = igrab(&entry->vfs_inode);
3851 spin_unlock(&root->inode_lock);
3852 if (atomic_read(&inode->i_count) > 1)
3853 d_prune_aliases(inode);
3855 * btrfs_drop_inode will have it removed from the inode
3856 * cache when its usage count hits zero.
3860 spin_lock(&root->inode_lock);
3864 if (cond_resched_lock(&root->inode_lock))
3867 node = rb_next(node);
3869 spin_unlock(&root->inode_lock);
3872 int btrfs_delete_subvolume(struct inode *dir, struct dentry *dentry)
3874 struct btrfs_fs_info *fs_info = btrfs_sb(dentry->d_sb);
3875 struct btrfs_root *root = BTRFS_I(dir)->root;
3876 struct inode *inode = d_inode(dentry);
3877 struct btrfs_root *dest = BTRFS_I(inode)->root;
3878 struct btrfs_trans_handle *trans;
3879 struct btrfs_block_rsv block_rsv;
3885 * Don't allow to delete a subvolume with send in progress. This is
3886 * inside the inode lock so the error handling that has to drop the bit
3887 * again is not run concurrently.
3889 spin_lock(&dest->root_item_lock);
3890 if (dest->send_in_progress) {
3891 spin_unlock(&dest->root_item_lock);
3893 "attempt to delete subvolume %llu during send",
3894 dest->root_key.objectid);
3897 root_flags = btrfs_root_flags(&dest->root_item);
3898 btrfs_set_root_flags(&dest->root_item,
3899 root_flags | BTRFS_ROOT_SUBVOL_DEAD);
3900 spin_unlock(&dest->root_item_lock);
3902 down_write(&fs_info->subvol_sem);
3904 err = may_destroy_subvol(dest);
3908 btrfs_init_block_rsv(&block_rsv, BTRFS_BLOCK_RSV_TEMP);
3910 * One for dir inode,
3911 * two for dir entries,
3912 * two for root ref/backref.
3914 err = btrfs_subvolume_reserve_metadata(root, &block_rsv, 5, true);
3918 trans = btrfs_start_transaction(root, 0);
3919 if (IS_ERR(trans)) {
3920 err = PTR_ERR(trans);
3923 trans->block_rsv = &block_rsv;
3924 trans->bytes_reserved = block_rsv.size;
3926 btrfs_record_snapshot_destroy(trans, BTRFS_I(dir));
3928 ret = btrfs_unlink_subvol(trans, dir, dentry);
3931 btrfs_abort_transaction(trans, ret);
3935 btrfs_record_root_in_trans(trans, dest);
3937 memset(&dest->root_item.drop_progress, 0,
3938 sizeof(dest->root_item.drop_progress));
3939 dest->root_item.drop_level = 0;
3940 btrfs_set_root_refs(&dest->root_item, 0);
3942 if (!test_and_set_bit(BTRFS_ROOT_ORPHAN_ITEM_INSERTED, &dest->state)) {
3943 ret = btrfs_insert_orphan_item(trans,
3945 dest->root_key.objectid);
3947 btrfs_abort_transaction(trans, ret);
3953 ret = btrfs_uuid_tree_remove(trans, dest->root_item.uuid,
3954 BTRFS_UUID_KEY_SUBVOL,
3955 dest->root_key.objectid);
3956 if (ret && ret != -ENOENT) {
3957 btrfs_abort_transaction(trans, ret);
3961 if (!btrfs_is_empty_uuid(dest->root_item.received_uuid)) {
3962 ret = btrfs_uuid_tree_remove(trans,
3963 dest->root_item.received_uuid,
3964 BTRFS_UUID_KEY_RECEIVED_SUBVOL,
3965 dest->root_key.objectid);
3966 if (ret && ret != -ENOENT) {
3967 btrfs_abort_transaction(trans, ret);
3974 trans->block_rsv = NULL;
3975 trans->bytes_reserved = 0;
3976 ret = btrfs_end_transaction(trans);
3979 inode->i_flags |= S_DEAD;
3981 btrfs_subvolume_release_metadata(fs_info, &block_rsv);
3983 up_write(&fs_info->subvol_sem);
3985 spin_lock(&dest->root_item_lock);
3986 root_flags = btrfs_root_flags(&dest->root_item);
3987 btrfs_set_root_flags(&dest->root_item,
3988 root_flags & ~BTRFS_ROOT_SUBVOL_DEAD);
3989 spin_unlock(&dest->root_item_lock);
3991 d_invalidate(dentry);
3992 btrfs_prune_dentries(dest);
3993 ASSERT(dest->send_in_progress == 0);
3996 if (dest->ino_cache_inode) {
3997 iput(dest->ino_cache_inode);
3998 dest->ino_cache_inode = NULL;
4005 static int btrfs_rmdir(struct inode *dir, struct dentry *dentry)
4007 struct inode *inode = d_inode(dentry);
4009 struct btrfs_root *root = BTRFS_I(dir)->root;
4010 struct btrfs_trans_handle *trans;
4011 u64 last_unlink_trans;
4013 if (inode->i_size > BTRFS_EMPTY_DIR_SIZE)
4015 if (btrfs_ino(BTRFS_I(inode)) == BTRFS_FIRST_FREE_OBJECTID)
4016 return btrfs_delete_subvolume(dir, dentry);
4018 trans = __unlink_start_trans(dir);
4020 return PTR_ERR(trans);
4022 if (unlikely(btrfs_ino(BTRFS_I(inode)) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)) {
4023 err = btrfs_unlink_subvol(trans, dir, dentry);
4027 err = btrfs_orphan_add(trans, BTRFS_I(inode));
4031 last_unlink_trans = BTRFS_I(inode)->last_unlink_trans;
4033 /* now the directory is empty */
4034 err = btrfs_unlink_inode(trans, root, BTRFS_I(dir),
4035 BTRFS_I(d_inode(dentry)), dentry->d_name.name,
4036 dentry->d_name.len);
4038 btrfs_i_size_write(BTRFS_I(inode), 0);
4040 * Propagate the last_unlink_trans value of the deleted dir to
4041 * its parent directory. This is to prevent an unrecoverable
4042 * log tree in the case we do something like this:
4044 * 2) create snapshot under dir foo
4045 * 3) delete the snapshot
4048 * 6) fsync foo or some file inside foo
4050 if (last_unlink_trans >= trans->transid)
4051 BTRFS_I(dir)->last_unlink_trans = last_unlink_trans;
4054 btrfs_end_transaction(trans);
4055 btrfs_btree_balance_dirty(root->fs_info);
4061 * Return this if we need to call truncate_block for the last bit of the
4064 #define NEED_TRUNCATE_BLOCK 1
4067 * this can truncate away extent items, csum items and directory items.
4068 * It starts at a high offset and removes keys until it can't find
4069 * any higher than new_size
4071 * csum items that cross the new i_size are truncated to the new size
4074 * min_type is the minimum key type to truncate down to. If set to 0, this
4075 * will kill all the items on this inode, including the INODE_ITEM_KEY.
4077 int btrfs_truncate_inode_items(struct btrfs_trans_handle *trans,
4078 struct btrfs_root *root,
4079 struct inode *inode,
4080 u64 new_size, u32 min_type)
4082 struct btrfs_fs_info *fs_info = root->fs_info;
4083 struct btrfs_path *path;
4084 struct extent_buffer *leaf;
4085 struct btrfs_file_extent_item *fi;
4086 struct btrfs_key key;
4087 struct btrfs_key found_key;
4088 u64 extent_start = 0;
4089 u64 extent_num_bytes = 0;
4090 u64 extent_offset = 0;
4092 u64 last_size = new_size;
4093 u32 found_type = (u8)-1;
4096 int pending_del_nr = 0;
4097 int pending_del_slot = 0;
4098 int extent_type = -1;
4100 u64 ino = btrfs_ino(BTRFS_I(inode));
4101 u64 bytes_deleted = 0;
4102 bool be_nice = false;
4103 bool should_throttle = false;
4104 const u64 lock_start = ALIGN_DOWN(new_size, fs_info->sectorsize);
4105 struct extent_state *cached_state = NULL;
4107 BUG_ON(new_size > 0 && min_type != BTRFS_EXTENT_DATA_KEY);
4110 * for non-free space inodes and ref cows, we want to back off from
4113 if (!btrfs_is_free_space_inode(BTRFS_I(inode)) &&
4114 test_bit(BTRFS_ROOT_REF_COWS, &root->state))
4117 path = btrfs_alloc_path();
4120 path->reada = READA_BACK;
4122 if (root->root_key.objectid != BTRFS_TREE_LOG_OBJECTID)
4123 lock_extent_bits(&BTRFS_I(inode)->io_tree, lock_start, (u64)-1,
4127 * We want to drop from the next block forward in case this new size is
4128 * not block aligned since we will be keeping the last block of the
4129 * extent just the way it is.
4131 if (test_bit(BTRFS_ROOT_REF_COWS, &root->state) ||
4132 root == fs_info->tree_root)
4133 btrfs_drop_extent_cache(BTRFS_I(inode), ALIGN(new_size,
4134 fs_info->sectorsize),
4138 * This function is also used to drop the items in the log tree before
4139 * we relog the inode, so if root != BTRFS_I(inode)->root, it means
4140 * it is used to drop the logged items. So we shouldn't kill the delayed
4143 if (min_type == 0 && root == BTRFS_I(inode)->root)
4144 btrfs_kill_delayed_inode_items(BTRFS_I(inode));
4147 key.offset = (u64)-1;
4152 * with a 16K leaf size and 128MB extents, you can actually queue
4153 * up a huge file in a single leaf. Most of the time that
4154 * bytes_deleted is > 0, it will be huge by the time we get here
4156 if (be_nice && bytes_deleted > SZ_32M &&
4157 btrfs_should_end_transaction(trans)) {
4162 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
4168 /* there are no items in the tree for us to truncate, we're
4171 if (path->slots[0] == 0)
4177 u64 clear_start = 0, clear_len = 0;
4180 leaf = path->nodes[0];
4181 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
4182 found_type = found_key.type;
4184 if (found_key.objectid != ino)
4187 if (found_type < min_type)
4190 item_end = found_key.offset;
4191 if (found_type == BTRFS_EXTENT_DATA_KEY) {
4192 fi = btrfs_item_ptr(leaf, path->slots[0],
4193 struct btrfs_file_extent_item);
4194 extent_type = btrfs_file_extent_type(leaf, fi);
4195 if (extent_type != BTRFS_FILE_EXTENT_INLINE) {
4197 btrfs_file_extent_num_bytes(leaf, fi);
4199 trace_btrfs_truncate_show_fi_regular(
4200 BTRFS_I(inode), leaf, fi,
4202 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
4203 item_end += btrfs_file_extent_ram_bytes(leaf,
4206 trace_btrfs_truncate_show_fi_inline(
4207 BTRFS_I(inode), leaf, fi, path->slots[0],
4212 if (found_type > min_type) {
4215 if (item_end < new_size)
4217 if (found_key.offset >= new_size)
4223 /* FIXME, shrink the extent if the ref count is only 1 */
4224 if (found_type != BTRFS_EXTENT_DATA_KEY)
4227 if (extent_type != BTRFS_FILE_EXTENT_INLINE) {
4230 clear_start = found_key.offset;
4231 extent_start = btrfs_file_extent_disk_bytenr(leaf, fi);
4233 u64 orig_num_bytes =
4234 btrfs_file_extent_num_bytes(leaf, fi);
4235 extent_num_bytes = ALIGN(new_size -
4237 fs_info->sectorsize);
4238 clear_start = ALIGN(new_size, fs_info->sectorsize);
4239 btrfs_set_file_extent_num_bytes(leaf, fi,
4241 num_dec = (orig_num_bytes -
4243 if (test_bit(BTRFS_ROOT_REF_COWS,
4246 inode_sub_bytes(inode, num_dec);
4247 btrfs_mark_buffer_dirty(leaf);
4250 btrfs_file_extent_disk_num_bytes(leaf,
4252 extent_offset = found_key.offset -
4253 btrfs_file_extent_offset(leaf, fi);
4255 /* FIXME blocksize != 4096 */
4256 num_dec = btrfs_file_extent_num_bytes(leaf, fi);
4257 if (extent_start != 0) {
4259 if (test_bit(BTRFS_ROOT_REF_COWS,
4261 inode_sub_bytes(inode, num_dec);
4264 clear_len = num_dec;
4265 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
4267 * we can't truncate inline items that have had
4271 btrfs_file_extent_encryption(leaf, fi) == 0 &&
4272 btrfs_file_extent_other_encoding(leaf, fi) == 0 &&
4273 btrfs_file_extent_compression(leaf, fi) == 0) {
4274 u32 size = (u32)(new_size - found_key.offset);
4276 btrfs_set_file_extent_ram_bytes(leaf, fi, size);
4277 size = btrfs_file_extent_calc_inline_size(size);
4278 btrfs_truncate_item(path, size, 1);
4279 } else if (!del_item) {
4281 * We have to bail so the last_size is set to
4282 * just before this extent.
4284 ret = NEED_TRUNCATE_BLOCK;
4288 * Inline extents are special, we just treat
4289 * them as a full sector worth in the file
4290 * extent tree just for simplicity sake.
4292 clear_len = fs_info->sectorsize;
4295 if (test_bit(BTRFS_ROOT_REF_COWS, &root->state))
4296 inode_sub_bytes(inode, item_end + 1 - new_size);
4300 * We use btrfs_truncate_inode_items() to clean up log trees for
4301 * multiple fsyncs, and in this case we don't want to clear the
4302 * file extent range because it's just the log.
4304 if (root == BTRFS_I(inode)->root) {
4305 ret = btrfs_inode_clear_file_extent_range(BTRFS_I(inode),
4306 clear_start, clear_len);
4308 btrfs_abort_transaction(trans, ret);
4314 last_size = found_key.offset;
4316 last_size = new_size;
4318 if (!pending_del_nr) {
4319 /* no pending yet, add ourselves */
4320 pending_del_slot = path->slots[0];
4322 } else if (pending_del_nr &&
4323 path->slots[0] + 1 == pending_del_slot) {
4324 /* hop on the pending chunk */
4326 pending_del_slot = path->slots[0];
4333 should_throttle = false;
4336 (test_bit(BTRFS_ROOT_REF_COWS, &root->state) ||
4337 root == fs_info->tree_root)) {
4338 struct btrfs_ref ref = { 0 };
4340 bytes_deleted += extent_num_bytes;
4342 btrfs_init_generic_ref(&ref, BTRFS_DROP_DELAYED_REF,
4343 extent_start, extent_num_bytes, 0);
4344 ref.real_root = root->root_key.objectid;
4345 btrfs_init_data_ref(&ref, btrfs_header_owner(leaf),
4346 ino, extent_offset);
4347 ret = btrfs_free_extent(trans, &ref);
4349 btrfs_abort_transaction(trans, ret);
4353 if (btrfs_should_throttle_delayed_refs(trans))
4354 should_throttle = true;
4358 if (found_type == BTRFS_INODE_ITEM_KEY)
4361 if (path->slots[0] == 0 ||
4362 path->slots[0] != pending_del_slot ||
4364 if (pending_del_nr) {
4365 ret = btrfs_del_items(trans, root, path,
4369 btrfs_abort_transaction(trans, ret);
4374 btrfs_release_path(path);
4377 * We can generate a lot of delayed refs, so we need to
4378 * throttle every once and a while and make sure we're
4379 * adding enough space to keep up with the work we are
4380 * generating. Since we hold a transaction here we
4381 * can't flush, and we don't want to FLUSH_LIMIT because
4382 * we could have generated too many delayed refs to
4383 * actually allocate, so just bail if we're short and
4384 * let the normal reservation dance happen higher up.
4386 if (should_throttle) {
4387 ret = btrfs_delayed_refs_rsv_refill(fs_info,
4388 BTRFS_RESERVE_NO_FLUSH);
4400 if (ret >= 0 && pending_del_nr) {
4403 err = btrfs_del_items(trans, root, path, pending_del_slot,
4406 btrfs_abort_transaction(trans, err);
4410 if (root->root_key.objectid != BTRFS_TREE_LOG_OBJECTID) {
4411 ASSERT(last_size >= new_size);
4412 if (!ret && last_size > new_size)
4413 last_size = new_size;
4414 btrfs_inode_safe_disk_i_size_write(inode, last_size);
4415 unlock_extent_cached(&BTRFS_I(inode)->io_tree, lock_start,
4416 (u64)-1, &cached_state);
4419 btrfs_free_path(path);
4424 * btrfs_truncate_block - read, zero a chunk and write a block
4425 * @inode - inode that we're zeroing
4426 * @from - the offset to start zeroing
4427 * @len - the length to zero, 0 to zero the entire range respective to the
4429 * @front - zero up to the offset instead of from the offset on
4431 * This will find the block for the "from" offset and cow the block and zero the
4432 * part we want to zero. This is used with truncate and hole punching.
4434 int btrfs_truncate_block(struct inode *inode, loff_t from, loff_t len,
4437 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
4438 struct address_space *mapping = inode->i_mapping;
4439 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
4440 struct btrfs_ordered_extent *ordered;
4441 struct extent_state *cached_state = NULL;
4442 struct extent_changeset *data_reserved = NULL;
4444 u32 blocksize = fs_info->sectorsize;
4445 pgoff_t index = from >> PAGE_SHIFT;
4446 unsigned offset = from & (blocksize - 1);
4448 gfp_t mask = btrfs_alloc_write_mask(mapping);
4453 if (IS_ALIGNED(offset, blocksize) &&
4454 (!len || IS_ALIGNED(len, blocksize)))
4457 block_start = round_down(from, blocksize);
4458 block_end = block_start + blocksize - 1;
4460 ret = btrfs_delalloc_reserve_space(inode, &data_reserved,
4461 block_start, blocksize);
4466 page = find_or_create_page(mapping, index, mask);
4468 btrfs_delalloc_release_space(inode, data_reserved,
4469 block_start, blocksize, true);
4470 btrfs_delalloc_release_extents(BTRFS_I(inode), blocksize);
4475 if (!PageUptodate(page)) {
4476 ret = btrfs_readpage(NULL, page);
4478 if (page->mapping != mapping) {
4483 if (!PageUptodate(page)) {
4488 wait_on_page_writeback(page);
4490 lock_extent_bits(io_tree, block_start, block_end, &cached_state);
4491 set_page_extent_mapped(page);
4493 ordered = btrfs_lookup_ordered_extent(inode, block_start);
4495 unlock_extent_cached(io_tree, block_start, block_end,
4499 btrfs_start_ordered_extent(inode, ordered, 1);
4500 btrfs_put_ordered_extent(ordered);
4504 clear_extent_bit(&BTRFS_I(inode)->io_tree, block_start, block_end,
4505 EXTENT_DELALLOC | EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG,
4506 0, 0, &cached_state);
4508 ret = btrfs_set_extent_delalloc(inode, block_start, block_end, 0,
4511 unlock_extent_cached(io_tree, block_start, block_end,
4516 if (offset != blocksize) {
4518 len = blocksize - offset;
4521 memset(kaddr + (block_start - page_offset(page)),
4524 memset(kaddr + (block_start - page_offset(page)) + offset,
4526 flush_dcache_page(page);
4529 ClearPageChecked(page);
4530 set_page_dirty(page);
4531 unlock_extent_cached(io_tree, block_start, block_end, &cached_state);
4535 btrfs_delalloc_release_space(inode, data_reserved, block_start,
4537 btrfs_delalloc_release_extents(BTRFS_I(inode), blocksize);
4541 extent_changeset_free(data_reserved);
4545 static int maybe_insert_hole(struct btrfs_root *root, struct inode *inode,
4546 u64 offset, u64 len)
4548 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
4549 struct btrfs_trans_handle *trans;
4553 * Still need to make sure the inode looks like it's been updated so
4554 * that any holes get logged if we fsync.
4556 if (btrfs_fs_incompat(fs_info, NO_HOLES)) {
4557 BTRFS_I(inode)->last_trans = fs_info->generation;
4558 BTRFS_I(inode)->last_sub_trans = root->log_transid;
4559 BTRFS_I(inode)->last_log_commit = root->last_log_commit;
4564 * 1 - for the one we're dropping
4565 * 1 - for the one we're adding
4566 * 1 - for updating the inode.
4568 trans = btrfs_start_transaction(root, 3);
4570 return PTR_ERR(trans);
4572 ret = btrfs_drop_extents(trans, root, inode, offset, offset + len, 1);
4574 btrfs_abort_transaction(trans, ret);
4575 btrfs_end_transaction(trans);
4579 ret = btrfs_insert_file_extent(trans, root, btrfs_ino(BTRFS_I(inode)),
4580 offset, 0, 0, len, 0, len, 0, 0, 0);
4582 btrfs_abort_transaction(trans, ret);
4584 btrfs_update_inode(trans, root, inode);
4585 btrfs_end_transaction(trans);
4590 * This function puts in dummy file extents for the area we're creating a hole
4591 * for. So if we are truncating this file to a larger size we need to insert
4592 * these file extents so that btrfs_get_extent will return a EXTENT_MAP_HOLE for
4593 * the range between oldsize and size
4595 int btrfs_cont_expand(struct inode *inode, loff_t oldsize, loff_t size)
4597 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
4598 struct btrfs_root *root = BTRFS_I(inode)->root;
4599 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
4600 struct extent_map *em = NULL;
4601 struct extent_state *cached_state = NULL;
4602 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
4603 u64 hole_start = ALIGN(oldsize, fs_info->sectorsize);
4604 u64 block_end = ALIGN(size, fs_info->sectorsize);
4611 * If our size started in the middle of a block we need to zero out the
4612 * rest of the block before we expand the i_size, otherwise we could
4613 * expose stale data.
4615 err = btrfs_truncate_block(inode, oldsize, 0, 0);
4619 if (size <= hole_start)
4622 btrfs_lock_and_flush_ordered_range(BTRFS_I(inode), hole_start,
4623 block_end - 1, &cached_state);
4624 cur_offset = hole_start;
4626 em = btrfs_get_extent(BTRFS_I(inode), NULL, 0, cur_offset,
4627 block_end - cur_offset);
4633 last_byte = min(extent_map_end(em), block_end);
4634 last_byte = ALIGN(last_byte, fs_info->sectorsize);
4635 hole_size = last_byte - cur_offset;
4637 if (!test_bit(EXTENT_FLAG_PREALLOC, &em->flags)) {
4638 struct extent_map *hole_em;
4640 err = maybe_insert_hole(root, inode, cur_offset,
4645 err = btrfs_inode_set_file_extent_range(BTRFS_I(inode),
4646 cur_offset, hole_size);
4650 btrfs_drop_extent_cache(BTRFS_I(inode), cur_offset,
4651 cur_offset + hole_size - 1, 0);
4652 hole_em = alloc_extent_map();
4654 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
4655 &BTRFS_I(inode)->runtime_flags);
4658 hole_em->start = cur_offset;
4659 hole_em->len = hole_size;
4660 hole_em->orig_start = cur_offset;
4662 hole_em->block_start = EXTENT_MAP_HOLE;
4663 hole_em->block_len = 0;
4664 hole_em->orig_block_len = 0;
4665 hole_em->ram_bytes = hole_size;
4666 hole_em->compress_type = BTRFS_COMPRESS_NONE;
4667 hole_em->generation = fs_info->generation;
4670 write_lock(&em_tree->lock);
4671 err = add_extent_mapping(em_tree, hole_em, 1);
4672 write_unlock(&em_tree->lock);
4675 btrfs_drop_extent_cache(BTRFS_I(inode),
4680 free_extent_map(hole_em);
4682 err = btrfs_inode_set_file_extent_range(BTRFS_I(inode),
4683 cur_offset, hole_size);
4688 free_extent_map(em);
4690 cur_offset = last_byte;
4691 if (cur_offset >= block_end)
4694 free_extent_map(em);
4695 unlock_extent_cached(io_tree, hole_start, block_end - 1, &cached_state);
4699 static int btrfs_setsize(struct inode *inode, struct iattr *attr)
4701 struct btrfs_root *root = BTRFS_I(inode)->root;
4702 struct btrfs_trans_handle *trans;
4703 loff_t oldsize = i_size_read(inode);
4704 loff_t newsize = attr->ia_size;
4705 int mask = attr->ia_valid;
4709 * The regular truncate() case without ATTR_CTIME and ATTR_MTIME is a
4710 * special case where we need to update the times despite not having
4711 * these flags set. For all other operations the VFS set these flags
4712 * explicitly if it wants a timestamp update.
4714 if (newsize != oldsize) {
4715 inode_inc_iversion(inode);
4716 if (!(mask & (ATTR_CTIME | ATTR_MTIME)))
4717 inode->i_ctime = inode->i_mtime =
4718 current_time(inode);
4721 if (newsize > oldsize) {
4723 * Don't do an expanding truncate while snapshotting is ongoing.
4724 * This is to ensure the snapshot captures a fully consistent
4725 * state of this file - if the snapshot captures this expanding
4726 * truncation, it must capture all writes that happened before
4729 btrfs_drew_write_lock(&root->snapshot_lock);
4730 ret = btrfs_cont_expand(inode, oldsize, newsize);
4732 btrfs_drew_write_unlock(&root->snapshot_lock);
4736 trans = btrfs_start_transaction(root, 1);
4737 if (IS_ERR(trans)) {
4738 btrfs_drew_write_unlock(&root->snapshot_lock);
4739 return PTR_ERR(trans);
4742 i_size_write(inode, newsize);
4743 btrfs_inode_safe_disk_i_size_write(inode, 0);
4744 pagecache_isize_extended(inode, oldsize, newsize);
4745 ret = btrfs_update_inode(trans, root, inode);
4746 btrfs_drew_write_unlock(&root->snapshot_lock);
4747 btrfs_end_transaction(trans);
4751 * We're truncating a file that used to have good data down to
4752 * zero. Make sure it gets into the ordered flush list so that
4753 * any new writes get down to disk quickly.
4756 set_bit(BTRFS_INODE_ORDERED_DATA_CLOSE,
4757 &BTRFS_I(inode)->runtime_flags);
4759 truncate_setsize(inode, newsize);
4761 /* Disable nonlocked read DIO to avoid the endless truncate */
4762 btrfs_inode_block_unlocked_dio(BTRFS_I(inode));
4763 inode_dio_wait(inode);
4764 btrfs_inode_resume_unlocked_dio(BTRFS_I(inode));
4766 ret = btrfs_truncate(inode, newsize == oldsize);
4767 if (ret && inode->i_nlink) {
4771 * Truncate failed, so fix up the in-memory size. We
4772 * adjusted disk_i_size down as we removed extents, so
4773 * wait for disk_i_size to be stable and then update the
4774 * in-memory size to match.
4776 err = btrfs_wait_ordered_range(inode, 0, (u64)-1);
4779 i_size_write(inode, BTRFS_I(inode)->disk_i_size);
4786 static int btrfs_setattr(struct dentry *dentry, struct iattr *attr)
4788 struct inode *inode = d_inode(dentry);
4789 struct btrfs_root *root = BTRFS_I(inode)->root;
4792 if (btrfs_root_readonly(root))
4795 err = setattr_prepare(dentry, attr);
4799 if (S_ISREG(inode->i_mode) && (attr->ia_valid & ATTR_SIZE)) {
4800 err = btrfs_setsize(inode, attr);
4805 if (attr->ia_valid) {
4806 setattr_copy(inode, attr);
4807 inode_inc_iversion(inode);
4808 err = btrfs_dirty_inode(inode);
4810 if (!err && attr->ia_valid & ATTR_MODE)
4811 err = posix_acl_chmod(inode, inode->i_mode);
4818 * While truncating the inode pages during eviction, we get the VFS calling
4819 * btrfs_invalidatepage() against each page of the inode. This is slow because
4820 * the calls to btrfs_invalidatepage() result in a huge amount of calls to
4821 * lock_extent_bits() and clear_extent_bit(), which keep merging and splitting
4822 * extent_state structures over and over, wasting lots of time.
4824 * Therefore if the inode is being evicted, let btrfs_invalidatepage() skip all
4825 * those expensive operations on a per page basis and do only the ordered io
4826 * finishing, while we release here the extent_map and extent_state structures,
4827 * without the excessive merging and splitting.
4829 static void evict_inode_truncate_pages(struct inode *inode)
4831 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
4832 struct extent_map_tree *map_tree = &BTRFS_I(inode)->extent_tree;
4833 struct rb_node *node;
4835 ASSERT(inode->i_state & I_FREEING);
4836 truncate_inode_pages_final(&inode->i_data);
4838 write_lock(&map_tree->lock);
4839 while (!RB_EMPTY_ROOT(&map_tree->map.rb_root)) {
4840 struct extent_map *em;
4842 node = rb_first_cached(&map_tree->map);
4843 em = rb_entry(node, struct extent_map, rb_node);
4844 clear_bit(EXTENT_FLAG_PINNED, &em->flags);
4845 clear_bit(EXTENT_FLAG_LOGGING, &em->flags);
4846 remove_extent_mapping(map_tree, em);
4847 free_extent_map(em);
4848 if (need_resched()) {
4849 write_unlock(&map_tree->lock);
4851 write_lock(&map_tree->lock);
4854 write_unlock(&map_tree->lock);
4857 * Keep looping until we have no more ranges in the io tree.
4858 * We can have ongoing bios started by readpages (called from readahead)
4859 * that have their endio callback (extent_io.c:end_bio_extent_readpage)
4860 * still in progress (unlocked the pages in the bio but did not yet
4861 * unlocked the ranges in the io tree). Therefore this means some
4862 * ranges can still be locked and eviction started because before
4863 * submitting those bios, which are executed by a separate task (work
4864 * queue kthread), inode references (inode->i_count) were not taken
4865 * (which would be dropped in the end io callback of each bio).
4866 * Therefore here we effectively end up waiting for those bios and
4867 * anyone else holding locked ranges without having bumped the inode's
4868 * reference count - if we don't do it, when they access the inode's
4869 * io_tree to unlock a range it may be too late, leading to an
4870 * use-after-free issue.
4872 spin_lock(&io_tree->lock);
4873 while (!RB_EMPTY_ROOT(&io_tree->state)) {
4874 struct extent_state *state;
4875 struct extent_state *cached_state = NULL;
4878 unsigned state_flags;
4880 node = rb_first(&io_tree->state);
4881 state = rb_entry(node, struct extent_state, rb_node);
4882 start = state->start;
4884 state_flags = state->state;
4885 spin_unlock(&io_tree->lock);
4887 lock_extent_bits(io_tree, start, end, &cached_state);
4890 * If still has DELALLOC flag, the extent didn't reach disk,
4891 * and its reserved space won't be freed by delayed_ref.
4892 * So we need to free its reserved space here.
4893 * (Refer to comment in btrfs_invalidatepage, case 2)
4895 * Note, end is the bytenr of last byte, so we need + 1 here.
4897 if (state_flags & EXTENT_DELALLOC)
4898 btrfs_qgroup_free_data(inode, NULL, start, end - start + 1);
4900 clear_extent_bit(io_tree, start, end,
4901 EXTENT_LOCKED | EXTENT_DELALLOC |
4902 EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG, 1, 1,
4906 spin_lock(&io_tree->lock);
4908 spin_unlock(&io_tree->lock);
4911 static struct btrfs_trans_handle *evict_refill_and_join(struct btrfs_root *root,
4912 struct btrfs_block_rsv *rsv)
4914 struct btrfs_fs_info *fs_info = root->fs_info;
4915 struct btrfs_block_rsv *global_rsv = &fs_info->global_block_rsv;
4916 struct btrfs_trans_handle *trans;
4917 u64 delayed_refs_extra = btrfs_calc_insert_metadata_size(fs_info, 1);
4921 * Eviction should be taking place at some place safe because of our
4922 * delayed iputs. However the normal flushing code will run delayed
4923 * iputs, so we cannot use FLUSH_ALL otherwise we'll deadlock.
4925 * We reserve the delayed_refs_extra here again because we can't use
4926 * btrfs_start_transaction(root, 0) for the same deadlocky reason as
4927 * above. We reserve our extra bit here because we generate a ton of
4928 * delayed refs activity by truncating.
4930 * If we cannot make our reservation we'll attempt to steal from the
4931 * global reserve, because we really want to be able to free up space.
4933 ret = btrfs_block_rsv_refill(root, rsv, rsv->size + delayed_refs_extra,
4934 BTRFS_RESERVE_FLUSH_EVICT);
4937 * Try to steal from the global reserve if there is space for
4940 if (btrfs_check_space_for_delayed_refs(fs_info) ||
4941 btrfs_block_rsv_migrate(global_rsv, rsv, rsv->size, 0)) {
4943 "could not allocate space for delete; will truncate on mount");
4944 return ERR_PTR(-ENOSPC);
4946 delayed_refs_extra = 0;
4949 trans = btrfs_join_transaction(root);
4953 if (delayed_refs_extra) {
4954 trans->block_rsv = &fs_info->trans_block_rsv;
4955 trans->bytes_reserved = delayed_refs_extra;
4956 btrfs_block_rsv_migrate(rsv, trans->block_rsv,
4957 delayed_refs_extra, 1);
4962 void btrfs_evict_inode(struct inode *inode)
4964 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
4965 struct btrfs_trans_handle *trans;
4966 struct btrfs_root *root = BTRFS_I(inode)->root;
4967 struct btrfs_block_rsv *rsv;
4970 trace_btrfs_inode_evict(inode);
4977 evict_inode_truncate_pages(inode);
4979 if (inode->i_nlink &&
4980 ((btrfs_root_refs(&root->root_item) != 0 &&
4981 root->root_key.objectid != BTRFS_ROOT_TREE_OBJECTID) ||
4982 btrfs_is_free_space_inode(BTRFS_I(inode))))
4985 if (is_bad_inode(inode))
4988 btrfs_free_io_failure_record(BTRFS_I(inode), 0, (u64)-1);
4990 if (test_bit(BTRFS_FS_LOG_RECOVERING, &fs_info->flags))
4993 if (inode->i_nlink > 0) {
4994 BUG_ON(btrfs_root_refs(&root->root_item) != 0 &&
4995 root->root_key.objectid != BTRFS_ROOT_TREE_OBJECTID);
4999 ret = btrfs_commit_inode_delayed_inode(BTRFS_I(inode));
5003 rsv = btrfs_alloc_block_rsv(fs_info, BTRFS_BLOCK_RSV_TEMP);
5006 rsv->size = btrfs_calc_metadata_size(fs_info, 1);
5009 btrfs_i_size_write(BTRFS_I(inode), 0);
5012 trans = evict_refill_and_join(root, rsv);
5016 trans->block_rsv = rsv;
5018 ret = btrfs_truncate_inode_items(trans, root, inode, 0, 0);
5019 trans->block_rsv = &fs_info->trans_block_rsv;
5020 btrfs_end_transaction(trans);
5021 btrfs_btree_balance_dirty(fs_info);
5022 if (ret && ret != -ENOSPC && ret != -EAGAIN)
5029 * Errors here aren't a big deal, it just means we leave orphan items in
5030 * the tree. They will be cleaned up on the next mount. If the inode
5031 * number gets reused, cleanup deletes the orphan item without doing
5032 * anything, and unlink reuses the existing orphan item.
5034 * If it turns out that we are dropping too many of these, we might want
5035 * to add a mechanism for retrying these after a commit.
5037 trans = evict_refill_and_join(root, rsv);
5038 if (!IS_ERR(trans)) {
5039 trans->block_rsv = rsv;
5040 btrfs_orphan_del(trans, BTRFS_I(inode));
5041 trans->block_rsv = &fs_info->trans_block_rsv;
5042 btrfs_end_transaction(trans);
5045 if (!(root == fs_info->tree_root ||
5046 root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID))
5047 btrfs_return_ino(root, btrfs_ino(BTRFS_I(inode)));
5050 btrfs_free_block_rsv(fs_info, rsv);
5053 * If we didn't successfully delete, the orphan item will still be in
5054 * the tree and we'll retry on the next mount. Again, we might also want
5055 * to retry these periodically in the future.
5057 btrfs_remove_delayed_node(BTRFS_I(inode));
5062 * Return the key found in the dir entry in the location pointer, fill @type
5063 * with BTRFS_FT_*, and return 0.
5065 * If no dir entries were found, returns -ENOENT.
5066 * If found a corrupted location in dir entry, returns -EUCLEAN.
5068 static int btrfs_inode_by_name(struct inode *dir, struct dentry *dentry,
5069 struct btrfs_key *location, u8 *type)
5071 const char *name = dentry->d_name.name;
5072 int namelen = dentry->d_name.len;
5073 struct btrfs_dir_item *di;
5074 struct btrfs_path *path;
5075 struct btrfs_root *root = BTRFS_I(dir)->root;
5078 path = btrfs_alloc_path();
5082 di = btrfs_lookup_dir_item(NULL, root, path, btrfs_ino(BTRFS_I(dir)),
5084 if (IS_ERR_OR_NULL(di)) {
5085 ret = di ? PTR_ERR(di) : -ENOENT;
5089 btrfs_dir_item_key_to_cpu(path->nodes[0], di, location);
5090 if (location->type != BTRFS_INODE_ITEM_KEY &&
5091 location->type != BTRFS_ROOT_ITEM_KEY) {
5093 btrfs_warn(root->fs_info,
5094 "%s gets something invalid in DIR_ITEM (name %s, directory ino %llu, location(%llu %u %llu))",
5095 __func__, name, btrfs_ino(BTRFS_I(dir)),
5096 location->objectid, location->type, location->offset);
5099 *type = btrfs_dir_type(path->nodes[0], di);
5101 btrfs_free_path(path);
5106 * when we hit a tree root in a directory, the btrfs part of the inode
5107 * needs to be changed to reflect the root directory of the tree root. This
5108 * is kind of like crossing a mount point.
5110 static int fixup_tree_root_location(struct btrfs_fs_info *fs_info,
5112 struct dentry *dentry,
5113 struct btrfs_key *location,
5114 struct btrfs_root **sub_root)
5116 struct btrfs_path *path;
5117 struct btrfs_root *new_root;
5118 struct btrfs_root_ref *ref;
5119 struct extent_buffer *leaf;
5120 struct btrfs_key key;
5124 path = btrfs_alloc_path();
5131 key.objectid = BTRFS_I(dir)->root->root_key.objectid;
5132 key.type = BTRFS_ROOT_REF_KEY;
5133 key.offset = location->objectid;
5135 ret = btrfs_search_slot(NULL, fs_info->tree_root, &key, path, 0, 0);
5142 leaf = path->nodes[0];
5143 ref = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_root_ref);
5144 if (btrfs_root_ref_dirid(leaf, ref) != btrfs_ino(BTRFS_I(dir)) ||
5145 btrfs_root_ref_name_len(leaf, ref) != dentry->d_name.len)
5148 ret = memcmp_extent_buffer(leaf, dentry->d_name.name,
5149 (unsigned long)(ref + 1),
5150 dentry->d_name.len);
5154 btrfs_release_path(path);
5156 new_root = btrfs_get_fs_root(fs_info, location, true);
5157 if (IS_ERR(new_root)) {
5158 err = PTR_ERR(new_root);
5162 *sub_root = new_root;
5163 location->objectid = btrfs_root_dirid(&new_root->root_item);
5164 location->type = BTRFS_INODE_ITEM_KEY;
5165 location->offset = 0;
5168 btrfs_free_path(path);
5172 static void inode_tree_add(struct inode *inode)
5174 struct btrfs_root *root = BTRFS_I(inode)->root;
5175 struct btrfs_inode *entry;
5177 struct rb_node *parent;
5178 struct rb_node *new = &BTRFS_I(inode)->rb_node;
5179 u64 ino = btrfs_ino(BTRFS_I(inode));
5181 if (inode_unhashed(inode))
5184 spin_lock(&root->inode_lock);
5185 p = &root->inode_tree.rb_node;
5188 entry = rb_entry(parent, struct btrfs_inode, rb_node);
5190 if (ino < btrfs_ino(entry))
5191 p = &parent->rb_left;
5192 else if (ino > btrfs_ino(entry))
5193 p = &parent->rb_right;
5195 WARN_ON(!(entry->vfs_inode.i_state &
5196 (I_WILL_FREE | I_FREEING)));
5197 rb_replace_node(parent, new, &root->inode_tree);
5198 RB_CLEAR_NODE(parent);
5199 spin_unlock(&root->inode_lock);
5203 rb_link_node(new, parent, p);
5204 rb_insert_color(new, &root->inode_tree);
5205 spin_unlock(&root->inode_lock);
5208 static void inode_tree_del(struct inode *inode)
5210 struct btrfs_root *root = BTRFS_I(inode)->root;
5213 spin_lock(&root->inode_lock);
5214 if (!RB_EMPTY_NODE(&BTRFS_I(inode)->rb_node)) {
5215 rb_erase(&BTRFS_I(inode)->rb_node, &root->inode_tree);
5216 RB_CLEAR_NODE(&BTRFS_I(inode)->rb_node);
5217 empty = RB_EMPTY_ROOT(&root->inode_tree);
5219 spin_unlock(&root->inode_lock);
5221 if (empty && btrfs_root_refs(&root->root_item) == 0) {
5222 spin_lock(&root->inode_lock);
5223 empty = RB_EMPTY_ROOT(&root->inode_tree);
5224 spin_unlock(&root->inode_lock);
5226 btrfs_add_dead_root(root);
5231 static int btrfs_init_locked_inode(struct inode *inode, void *p)
5233 struct btrfs_iget_args *args = p;
5234 inode->i_ino = args->location->objectid;
5235 memcpy(&BTRFS_I(inode)->location, args->location,
5236 sizeof(*args->location));
5237 BTRFS_I(inode)->root = btrfs_grab_root(args->root);
5238 BUG_ON(args->root && !BTRFS_I(inode)->root);
5242 static int btrfs_find_actor(struct inode *inode, void *opaque)
5244 struct btrfs_iget_args *args = opaque;
5245 return args->location->objectid == BTRFS_I(inode)->location.objectid &&
5246 args->root == BTRFS_I(inode)->root;
5249 static struct inode *btrfs_iget_locked(struct super_block *s,
5250 struct btrfs_key *location,
5251 struct btrfs_root *root)
5253 struct inode *inode;
5254 struct btrfs_iget_args args;
5255 unsigned long hashval = btrfs_inode_hash(location->objectid, root);
5257 args.location = location;
5260 inode = iget5_locked(s, hashval, btrfs_find_actor,
5261 btrfs_init_locked_inode,
5267 * Get an inode object given its location and corresponding root.
5268 * Path can be preallocated to prevent recursing back to iget through
5269 * allocator. NULL is also valid but may require an additional allocation
5272 struct inode *btrfs_iget_path(struct super_block *s, struct btrfs_key *location,
5273 struct btrfs_root *root, struct btrfs_path *path)
5275 struct inode *inode;
5277 inode = btrfs_iget_locked(s, location, root);
5279 return ERR_PTR(-ENOMEM);
5281 if (inode->i_state & I_NEW) {
5284 ret = btrfs_read_locked_inode(inode, path);
5286 inode_tree_add(inode);
5287 unlock_new_inode(inode);
5291 * ret > 0 can come from btrfs_search_slot called by
5292 * btrfs_read_locked_inode, this means the inode item
5297 inode = ERR_PTR(ret);
5304 struct inode *btrfs_iget(struct super_block *s, struct btrfs_key *location,
5305 struct btrfs_root *root)
5307 return btrfs_iget_path(s, location, root, NULL);
5310 static struct inode *new_simple_dir(struct super_block *s,
5311 struct btrfs_key *key,
5312 struct btrfs_root *root)
5314 struct inode *inode = new_inode(s);
5317 return ERR_PTR(-ENOMEM);
5319 BTRFS_I(inode)->root = btrfs_grab_root(root);
5320 memcpy(&BTRFS_I(inode)->location, key, sizeof(*key));
5321 set_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags);
5323 inode->i_ino = BTRFS_EMPTY_SUBVOL_DIR_OBJECTID;
5325 * We only need lookup, the rest is read-only and there's no inode
5326 * associated with the dentry
5328 inode->i_op = &simple_dir_inode_operations;
5329 inode->i_opflags &= ~IOP_XATTR;
5330 inode->i_fop = &simple_dir_operations;
5331 inode->i_mode = S_IFDIR | S_IRUGO | S_IWUSR | S_IXUGO;
5332 inode->i_mtime = current_time(inode);
5333 inode->i_atime = inode->i_mtime;
5334 inode->i_ctime = inode->i_mtime;
5335 BTRFS_I(inode)->i_otime = inode->i_mtime;
5340 static inline u8 btrfs_inode_type(struct inode *inode)
5343 * Compile-time asserts that generic FT_* types still match
5346 BUILD_BUG_ON(BTRFS_FT_UNKNOWN != FT_UNKNOWN);
5347 BUILD_BUG_ON(BTRFS_FT_REG_FILE != FT_REG_FILE);
5348 BUILD_BUG_ON(BTRFS_FT_DIR != FT_DIR);
5349 BUILD_BUG_ON(BTRFS_FT_CHRDEV != FT_CHRDEV);
5350 BUILD_BUG_ON(BTRFS_FT_BLKDEV != FT_BLKDEV);
5351 BUILD_BUG_ON(BTRFS_FT_FIFO != FT_FIFO);
5352 BUILD_BUG_ON(BTRFS_FT_SOCK != FT_SOCK);
5353 BUILD_BUG_ON(BTRFS_FT_SYMLINK != FT_SYMLINK);
5355 return fs_umode_to_ftype(inode->i_mode);
5358 struct inode *btrfs_lookup_dentry(struct inode *dir, struct dentry *dentry)
5360 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
5361 struct inode *inode;
5362 struct btrfs_root *root = BTRFS_I(dir)->root;
5363 struct btrfs_root *sub_root = root;
5364 struct btrfs_key location;
5368 if (dentry->d_name.len > BTRFS_NAME_LEN)
5369 return ERR_PTR(-ENAMETOOLONG);
5371 ret = btrfs_inode_by_name(dir, dentry, &location, &di_type);
5373 return ERR_PTR(ret);
5375 if (location.type == BTRFS_INODE_ITEM_KEY) {
5376 inode = btrfs_iget(dir->i_sb, &location, root);
5380 /* Do extra check against inode mode with di_type */
5381 if (btrfs_inode_type(inode) != di_type) {
5383 "inode mode mismatch with dir: inode mode=0%o btrfs type=%u dir type=%u",
5384 inode->i_mode, btrfs_inode_type(inode),
5387 return ERR_PTR(-EUCLEAN);
5392 ret = fixup_tree_root_location(fs_info, dir, dentry,
5393 &location, &sub_root);
5396 inode = ERR_PTR(ret);
5398 inode = new_simple_dir(dir->i_sb, &location, sub_root);
5400 inode = btrfs_iget(dir->i_sb, &location, sub_root);
5402 if (root != sub_root)
5403 btrfs_put_root(sub_root);
5405 if (!IS_ERR(inode) && root != sub_root) {
5406 down_read(&fs_info->cleanup_work_sem);
5407 if (!sb_rdonly(inode->i_sb))
5408 ret = btrfs_orphan_cleanup(sub_root);
5409 up_read(&fs_info->cleanup_work_sem);
5412 inode = ERR_PTR(ret);
5419 static int btrfs_dentry_delete(const struct dentry *dentry)
5421 struct btrfs_root *root;
5422 struct inode *inode = d_inode(dentry);
5424 if (!inode && !IS_ROOT(dentry))
5425 inode = d_inode(dentry->d_parent);
5428 root = BTRFS_I(inode)->root;
5429 if (btrfs_root_refs(&root->root_item) == 0)
5432 if (btrfs_ino(BTRFS_I(inode)) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)
5438 static struct dentry *btrfs_lookup(struct inode *dir, struct dentry *dentry,
5441 struct inode *inode = btrfs_lookup_dentry(dir, dentry);
5443 if (inode == ERR_PTR(-ENOENT))
5445 return d_splice_alias(inode, dentry);
5449 * All this infrastructure exists because dir_emit can fault, and we are holding
5450 * the tree lock when doing readdir. For now just allocate a buffer and copy
5451 * our information into that, and then dir_emit from the buffer. This is
5452 * similar to what NFS does, only we don't keep the buffer around in pagecache
5453 * because I'm afraid I'll mess that up. Long term we need to make filldir do
5454 * copy_to_user_inatomic so we don't have to worry about page faulting under the
5457 static int btrfs_opendir(struct inode *inode, struct file *file)
5459 struct btrfs_file_private *private;
5461 private = kzalloc(sizeof(struct btrfs_file_private), GFP_KERNEL);
5464 private->filldir_buf = kzalloc(PAGE_SIZE, GFP_KERNEL);
5465 if (!private->filldir_buf) {
5469 file->private_data = private;
5480 static int btrfs_filldir(void *addr, int entries, struct dir_context *ctx)
5483 struct dir_entry *entry = addr;
5484 char *name = (char *)(entry + 1);
5486 ctx->pos = get_unaligned(&entry->offset);
5487 if (!dir_emit(ctx, name, get_unaligned(&entry->name_len),
5488 get_unaligned(&entry->ino),
5489 get_unaligned(&entry->type)))
5491 addr += sizeof(struct dir_entry) +
5492 get_unaligned(&entry->name_len);
5498 static int btrfs_real_readdir(struct file *file, struct dir_context *ctx)
5500 struct inode *inode = file_inode(file);
5501 struct btrfs_root *root = BTRFS_I(inode)->root;
5502 struct btrfs_file_private *private = file->private_data;
5503 struct btrfs_dir_item *di;
5504 struct btrfs_key key;
5505 struct btrfs_key found_key;
5506 struct btrfs_path *path;
5508 struct list_head ins_list;
5509 struct list_head del_list;
5511 struct extent_buffer *leaf;
5518 struct btrfs_key location;
5520 if (!dir_emit_dots(file, ctx))
5523 path = btrfs_alloc_path();
5527 addr = private->filldir_buf;
5528 path->reada = READA_FORWARD;
5530 INIT_LIST_HEAD(&ins_list);
5531 INIT_LIST_HEAD(&del_list);
5532 put = btrfs_readdir_get_delayed_items(inode, &ins_list, &del_list);
5535 key.type = BTRFS_DIR_INDEX_KEY;
5536 key.offset = ctx->pos;
5537 key.objectid = btrfs_ino(BTRFS_I(inode));
5539 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
5544 struct dir_entry *entry;
5546 leaf = path->nodes[0];
5547 slot = path->slots[0];
5548 if (slot >= btrfs_header_nritems(leaf)) {
5549 ret = btrfs_next_leaf(root, path);
5557 btrfs_item_key_to_cpu(leaf, &found_key, slot);
5559 if (found_key.objectid != key.objectid)
5561 if (found_key.type != BTRFS_DIR_INDEX_KEY)
5563 if (found_key.offset < ctx->pos)
5565 if (btrfs_should_delete_dir_index(&del_list, found_key.offset))
5567 di = btrfs_item_ptr(leaf, slot, struct btrfs_dir_item);
5568 name_len = btrfs_dir_name_len(leaf, di);
5569 if ((total_len + sizeof(struct dir_entry) + name_len) >=
5571 btrfs_release_path(path);
5572 ret = btrfs_filldir(private->filldir_buf, entries, ctx);
5575 addr = private->filldir_buf;
5582 put_unaligned(name_len, &entry->name_len);
5583 name_ptr = (char *)(entry + 1);
5584 read_extent_buffer(leaf, name_ptr, (unsigned long)(di + 1),
5586 put_unaligned(fs_ftype_to_dtype(btrfs_dir_type(leaf, di)),
5588 btrfs_dir_item_key_to_cpu(leaf, di, &location);
5589 put_unaligned(location.objectid, &entry->ino);
5590 put_unaligned(found_key.offset, &entry->offset);
5592 addr += sizeof(struct dir_entry) + name_len;
5593 total_len += sizeof(struct dir_entry) + name_len;
5597 btrfs_release_path(path);
5599 ret = btrfs_filldir(private->filldir_buf, entries, ctx);
5603 ret = btrfs_readdir_delayed_dir_index(ctx, &ins_list);
5608 * Stop new entries from being returned after we return the last
5611 * New directory entries are assigned a strictly increasing
5612 * offset. This means that new entries created during readdir
5613 * are *guaranteed* to be seen in the future by that readdir.
5614 * This has broken buggy programs which operate on names as
5615 * they're returned by readdir. Until we re-use freed offsets
5616 * we have this hack to stop new entries from being returned
5617 * under the assumption that they'll never reach this huge
5620 * This is being careful not to overflow 32bit loff_t unless the
5621 * last entry requires it because doing so has broken 32bit apps
5624 if (ctx->pos >= INT_MAX)
5625 ctx->pos = LLONG_MAX;
5632 btrfs_readdir_put_delayed_items(inode, &ins_list, &del_list);
5633 btrfs_free_path(path);
5638 * This is somewhat expensive, updating the tree every time the
5639 * inode changes. But, it is most likely to find the inode in cache.
5640 * FIXME, needs more benchmarking...there are no reasons other than performance
5641 * to keep or drop this code.
5643 static int btrfs_dirty_inode(struct inode *inode)
5645 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
5646 struct btrfs_root *root = BTRFS_I(inode)->root;
5647 struct btrfs_trans_handle *trans;
5650 if (test_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags))
5653 trans = btrfs_join_transaction(root);
5655 return PTR_ERR(trans);
5657 ret = btrfs_update_inode(trans, root, inode);
5658 if (ret && ret == -ENOSPC) {
5659 /* whoops, lets try again with the full transaction */
5660 btrfs_end_transaction(trans);
5661 trans = btrfs_start_transaction(root, 1);
5663 return PTR_ERR(trans);
5665 ret = btrfs_update_inode(trans, root, inode);
5667 btrfs_end_transaction(trans);
5668 if (BTRFS_I(inode)->delayed_node)
5669 btrfs_balance_delayed_items(fs_info);
5675 * This is a copy of file_update_time. We need this so we can return error on
5676 * ENOSPC for updating the inode in the case of file write and mmap writes.
5678 static int btrfs_update_time(struct inode *inode, struct timespec64 *now,
5681 struct btrfs_root *root = BTRFS_I(inode)->root;
5682 bool dirty = flags & ~S_VERSION;
5684 if (btrfs_root_readonly(root))
5687 if (flags & S_VERSION)
5688 dirty |= inode_maybe_inc_iversion(inode, dirty);
5689 if (flags & S_CTIME)
5690 inode->i_ctime = *now;
5691 if (flags & S_MTIME)
5692 inode->i_mtime = *now;
5693 if (flags & S_ATIME)
5694 inode->i_atime = *now;
5695 return dirty ? btrfs_dirty_inode(inode) : 0;
5699 * find the highest existing sequence number in a directory
5700 * and then set the in-memory index_cnt variable to reflect
5701 * free sequence numbers
5703 static int btrfs_set_inode_index_count(struct btrfs_inode *inode)
5705 struct btrfs_root *root = inode->root;
5706 struct btrfs_key key, found_key;
5707 struct btrfs_path *path;
5708 struct extent_buffer *leaf;
5711 key.objectid = btrfs_ino(inode);
5712 key.type = BTRFS_DIR_INDEX_KEY;
5713 key.offset = (u64)-1;
5715 path = btrfs_alloc_path();
5719 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
5722 /* FIXME: we should be able to handle this */
5728 * MAGIC NUMBER EXPLANATION:
5729 * since we search a directory based on f_pos we have to start at 2
5730 * since '.' and '..' have f_pos of 0 and 1 respectively, so everybody
5731 * else has to start at 2
5733 if (path->slots[0] == 0) {
5734 inode->index_cnt = 2;
5740 leaf = path->nodes[0];
5741 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
5743 if (found_key.objectid != btrfs_ino(inode) ||
5744 found_key.type != BTRFS_DIR_INDEX_KEY) {
5745 inode->index_cnt = 2;
5749 inode->index_cnt = found_key.offset + 1;
5751 btrfs_free_path(path);
5756 * helper to find a free sequence number in a given directory. This current
5757 * code is very simple, later versions will do smarter things in the btree
5759 int btrfs_set_inode_index(struct btrfs_inode *dir, u64 *index)
5763 if (dir->index_cnt == (u64)-1) {
5764 ret = btrfs_inode_delayed_dir_index_count(dir);
5766 ret = btrfs_set_inode_index_count(dir);
5772 *index = dir->index_cnt;
5778 static int btrfs_insert_inode_locked(struct inode *inode)
5780 struct btrfs_iget_args args;
5781 args.location = &BTRFS_I(inode)->location;
5782 args.root = BTRFS_I(inode)->root;
5784 return insert_inode_locked4(inode,
5785 btrfs_inode_hash(inode->i_ino, BTRFS_I(inode)->root),
5786 btrfs_find_actor, &args);
5790 * Inherit flags from the parent inode.
5792 * Currently only the compression flags and the cow flags are inherited.
5794 static void btrfs_inherit_iflags(struct inode *inode, struct inode *dir)
5801 flags = BTRFS_I(dir)->flags;
5803 if (flags & BTRFS_INODE_NOCOMPRESS) {
5804 BTRFS_I(inode)->flags &= ~BTRFS_INODE_COMPRESS;
5805 BTRFS_I(inode)->flags |= BTRFS_INODE_NOCOMPRESS;
5806 } else if (flags & BTRFS_INODE_COMPRESS) {
5807 BTRFS_I(inode)->flags &= ~BTRFS_INODE_NOCOMPRESS;
5808 BTRFS_I(inode)->flags |= BTRFS_INODE_COMPRESS;
5811 if (flags & BTRFS_INODE_NODATACOW) {
5812 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATACOW;
5813 if (S_ISREG(inode->i_mode))
5814 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATASUM;
5817 btrfs_sync_inode_flags_to_i_flags(inode);
5820 static struct inode *btrfs_new_inode(struct btrfs_trans_handle *trans,
5821 struct btrfs_root *root,
5823 const char *name, int name_len,
5824 u64 ref_objectid, u64 objectid,
5825 umode_t mode, u64 *index)
5827 struct btrfs_fs_info *fs_info = root->fs_info;
5828 struct inode *inode;
5829 struct btrfs_inode_item *inode_item;
5830 struct btrfs_key *location;
5831 struct btrfs_path *path;
5832 struct btrfs_inode_ref *ref;
5833 struct btrfs_key key[2];
5835 int nitems = name ? 2 : 1;
5837 unsigned int nofs_flag;
5840 path = btrfs_alloc_path();
5842 return ERR_PTR(-ENOMEM);
5844 nofs_flag = memalloc_nofs_save();
5845 inode = new_inode(fs_info->sb);
5846 memalloc_nofs_restore(nofs_flag);
5848 btrfs_free_path(path);
5849 return ERR_PTR(-ENOMEM);
5853 * O_TMPFILE, set link count to 0, so that after this point,
5854 * we fill in an inode item with the correct link count.
5857 set_nlink(inode, 0);
5860 * we have to initialize this early, so we can reclaim the inode
5861 * number if we fail afterwards in this function.
5863 inode->i_ino = objectid;
5866 trace_btrfs_inode_request(dir);
5868 ret = btrfs_set_inode_index(BTRFS_I(dir), index);
5870 btrfs_free_path(path);
5872 return ERR_PTR(ret);
5878 * index_cnt is ignored for everything but a dir,
5879 * btrfs_set_inode_index_count has an explanation for the magic
5882 BTRFS_I(inode)->index_cnt = 2;
5883 BTRFS_I(inode)->dir_index = *index;
5884 BTRFS_I(inode)->root = btrfs_grab_root(root);
5885 BTRFS_I(inode)->generation = trans->transid;
5886 inode->i_generation = BTRFS_I(inode)->generation;
5889 * We could have gotten an inode number from somebody who was fsynced
5890 * and then removed in this same transaction, so let's just set full
5891 * sync since it will be a full sync anyway and this will blow away the
5892 * old info in the log.
5894 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &BTRFS_I(inode)->runtime_flags);
5896 key[0].objectid = objectid;
5897 key[0].type = BTRFS_INODE_ITEM_KEY;
5900 sizes[0] = sizeof(struct btrfs_inode_item);
5904 * Start new inodes with an inode_ref. This is slightly more
5905 * efficient for small numbers of hard links since they will
5906 * be packed into one item. Extended refs will kick in if we
5907 * add more hard links than can fit in the ref item.
5909 key[1].objectid = objectid;
5910 key[1].type = BTRFS_INODE_REF_KEY;
5911 key[1].offset = ref_objectid;
5913 sizes[1] = name_len + sizeof(*ref);
5916 location = &BTRFS_I(inode)->location;
5917 location->objectid = objectid;
5918 location->offset = 0;
5919 location->type = BTRFS_INODE_ITEM_KEY;
5921 ret = btrfs_insert_inode_locked(inode);
5927 path->leave_spinning = 1;
5928 ret = btrfs_insert_empty_items(trans, root, path, key, sizes, nitems);
5932 inode_init_owner(inode, dir, mode);
5933 inode_set_bytes(inode, 0);
5935 inode->i_mtime = current_time(inode);
5936 inode->i_atime = inode->i_mtime;
5937 inode->i_ctime = inode->i_mtime;
5938 BTRFS_I(inode)->i_otime = inode->i_mtime;
5940 inode_item = btrfs_item_ptr(path->nodes[0], path->slots[0],
5941 struct btrfs_inode_item);
5942 memzero_extent_buffer(path->nodes[0], (unsigned long)inode_item,
5943 sizeof(*inode_item));
5944 fill_inode_item(trans, path->nodes[0], inode_item, inode);
5947 ref = btrfs_item_ptr(path->nodes[0], path->slots[0] + 1,
5948 struct btrfs_inode_ref);
5949 btrfs_set_inode_ref_name_len(path->nodes[0], ref, name_len);
5950 btrfs_set_inode_ref_index(path->nodes[0], ref, *index);
5951 ptr = (unsigned long)(ref + 1);
5952 write_extent_buffer(path->nodes[0], name, ptr, name_len);
5955 btrfs_mark_buffer_dirty(path->nodes[0]);
5956 btrfs_free_path(path);
5958 btrfs_inherit_iflags(inode, dir);
5960 if (S_ISREG(mode)) {
5961 if (btrfs_test_opt(fs_info, NODATASUM))
5962 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATASUM;
5963 if (btrfs_test_opt(fs_info, NODATACOW))
5964 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATACOW |
5965 BTRFS_INODE_NODATASUM;
5968 inode_tree_add(inode);
5970 trace_btrfs_inode_new(inode);
5971 btrfs_set_inode_last_trans(trans, inode);
5973 btrfs_update_root_times(trans, root);
5975 ret = btrfs_inode_inherit_props(trans, inode, dir);
5978 "error inheriting props for ino %llu (root %llu): %d",
5979 btrfs_ino(BTRFS_I(inode)), root->root_key.objectid, ret);
5984 discard_new_inode(inode);
5987 BTRFS_I(dir)->index_cnt--;
5988 btrfs_free_path(path);
5989 return ERR_PTR(ret);
5993 * utility function to add 'inode' into 'parent_inode' with
5994 * a give name and a given sequence number.
5995 * if 'add_backref' is true, also insert a backref from the
5996 * inode to the parent directory.
5998 int btrfs_add_link(struct btrfs_trans_handle *trans,
5999 struct btrfs_inode *parent_inode, struct btrfs_inode *inode,
6000 const char *name, int name_len, int add_backref, u64 index)
6003 struct btrfs_key key;
6004 struct btrfs_root *root = parent_inode->root;
6005 u64 ino = btrfs_ino(inode);
6006 u64 parent_ino = btrfs_ino(parent_inode);
6008 if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
6009 memcpy(&key, &inode->root->root_key, sizeof(key));
6012 key.type = BTRFS_INODE_ITEM_KEY;
6016 if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
6017 ret = btrfs_add_root_ref(trans, key.objectid,
6018 root->root_key.objectid, parent_ino,
6019 index, name, name_len);
6020 } else if (add_backref) {
6021 ret = btrfs_insert_inode_ref(trans, root, name, name_len, ino,
6025 /* Nothing to clean up yet */
6029 ret = btrfs_insert_dir_item(trans, name, name_len, parent_inode, &key,
6030 btrfs_inode_type(&inode->vfs_inode), index);
6031 if (ret == -EEXIST || ret == -EOVERFLOW)
6034 btrfs_abort_transaction(trans, ret);
6038 btrfs_i_size_write(parent_inode, parent_inode->vfs_inode.i_size +
6040 inode_inc_iversion(&parent_inode->vfs_inode);
6042 * If we are replaying a log tree, we do not want to update the mtime
6043 * and ctime of the parent directory with the current time, since the
6044 * log replay procedure is responsible for setting them to their correct
6045 * values (the ones it had when the fsync was done).
6047 if (!test_bit(BTRFS_FS_LOG_RECOVERING, &root->fs_info->flags)) {
6048 struct timespec64 now = current_time(&parent_inode->vfs_inode);
6050 parent_inode->vfs_inode.i_mtime = now;
6051 parent_inode->vfs_inode.i_ctime = now;
6053 ret = btrfs_update_inode(trans, root, &parent_inode->vfs_inode);
6055 btrfs_abort_transaction(trans, ret);
6059 if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
6062 err = btrfs_del_root_ref(trans, key.objectid,
6063 root->root_key.objectid, parent_ino,
6064 &local_index, name, name_len);
6066 btrfs_abort_transaction(trans, err);
6067 } else if (add_backref) {
6071 err = btrfs_del_inode_ref(trans, root, name, name_len,
6072 ino, parent_ino, &local_index);
6074 btrfs_abort_transaction(trans, err);
6077 /* Return the original error code */
6081 static int btrfs_add_nondir(struct btrfs_trans_handle *trans,
6082 struct btrfs_inode *dir, struct dentry *dentry,
6083 struct btrfs_inode *inode, int backref, u64 index)
6085 int err = btrfs_add_link(trans, dir, inode,
6086 dentry->d_name.name, dentry->d_name.len,
6093 static int btrfs_mknod(struct inode *dir, struct dentry *dentry,
6094 umode_t mode, dev_t rdev)
6096 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
6097 struct btrfs_trans_handle *trans;
6098 struct btrfs_root *root = BTRFS_I(dir)->root;
6099 struct inode *inode = NULL;
6105 * 2 for inode item and ref
6107 * 1 for xattr if selinux is on
6109 trans = btrfs_start_transaction(root, 5);
6111 return PTR_ERR(trans);
6113 err = btrfs_find_free_ino(root, &objectid);
6117 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
6118 dentry->d_name.len, btrfs_ino(BTRFS_I(dir)), objectid,
6120 if (IS_ERR(inode)) {
6121 err = PTR_ERR(inode);
6127 * If the active LSM wants to access the inode during
6128 * d_instantiate it needs these. Smack checks to see
6129 * if the filesystem supports xattrs by looking at the
6132 inode->i_op = &btrfs_special_inode_operations;
6133 init_special_inode(inode, inode->i_mode, rdev);
6135 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
6139 err = btrfs_add_nondir(trans, BTRFS_I(dir), dentry, BTRFS_I(inode),
6144 btrfs_update_inode(trans, root, inode);
6145 d_instantiate_new(dentry, inode);
6148 btrfs_end_transaction(trans);
6149 btrfs_btree_balance_dirty(fs_info);
6151 inode_dec_link_count(inode);
6152 discard_new_inode(inode);
6157 static int btrfs_create(struct inode *dir, struct dentry *dentry,
6158 umode_t mode, bool excl)
6160 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
6161 struct btrfs_trans_handle *trans;
6162 struct btrfs_root *root = BTRFS_I(dir)->root;
6163 struct inode *inode = NULL;
6169 * 2 for inode item and ref
6171 * 1 for xattr if selinux is on
6173 trans = btrfs_start_transaction(root, 5);
6175 return PTR_ERR(trans);
6177 err = btrfs_find_free_ino(root, &objectid);
6181 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
6182 dentry->d_name.len, btrfs_ino(BTRFS_I(dir)), objectid,
6184 if (IS_ERR(inode)) {
6185 err = PTR_ERR(inode);
6190 * If the active LSM wants to access the inode during
6191 * d_instantiate it needs these. Smack checks to see
6192 * if the filesystem supports xattrs by looking at the
6195 inode->i_fop = &btrfs_file_operations;
6196 inode->i_op = &btrfs_file_inode_operations;
6197 inode->i_mapping->a_ops = &btrfs_aops;
6199 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
6203 err = btrfs_update_inode(trans, root, inode);
6207 err = btrfs_add_nondir(trans, BTRFS_I(dir), dentry, BTRFS_I(inode),
6212 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
6213 d_instantiate_new(dentry, inode);
6216 btrfs_end_transaction(trans);
6218 inode_dec_link_count(inode);
6219 discard_new_inode(inode);
6221 btrfs_btree_balance_dirty(fs_info);
6225 static int btrfs_link(struct dentry *old_dentry, struct inode *dir,
6226 struct dentry *dentry)
6228 struct btrfs_trans_handle *trans = NULL;
6229 struct btrfs_root *root = BTRFS_I(dir)->root;
6230 struct inode *inode = d_inode(old_dentry);
6231 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
6236 /* do not allow sys_link's with other subvols of the same device */
6237 if (root->root_key.objectid != BTRFS_I(inode)->root->root_key.objectid)
6240 if (inode->i_nlink >= BTRFS_LINK_MAX)
6243 err = btrfs_set_inode_index(BTRFS_I(dir), &index);
6248 * 2 items for inode and inode ref
6249 * 2 items for dir items
6250 * 1 item for parent inode
6251 * 1 item for orphan item deletion if O_TMPFILE
6253 trans = btrfs_start_transaction(root, inode->i_nlink ? 5 : 6);
6254 if (IS_ERR(trans)) {
6255 err = PTR_ERR(trans);
6260 /* There are several dir indexes for this inode, clear the cache. */
6261 BTRFS_I(inode)->dir_index = 0ULL;
6263 inode_inc_iversion(inode);
6264 inode->i_ctime = current_time(inode);
6266 set_bit(BTRFS_INODE_COPY_EVERYTHING, &BTRFS_I(inode)->runtime_flags);
6268 err = btrfs_add_nondir(trans, BTRFS_I(dir), dentry, BTRFS_I(inode),
6274 struct dentry *parent = dentry->d_parent;
6277 err = btrfs_update_inode(trans, root, inode);
6280 if (inode->i_nlink == 1) {
6282 * If new hard link count is 1, it's a file created
6283 * with open(2) O_TMPFILE flag.
6285 err = btrfs_orphan_del(trans, BTRFS_I(inode));
6289 d_instantiate(dentry, inode);
6290 ret = btrfs_log_new_name(trans, BTRFS_I(inode), NULL, parent,
6292 if (ret == BTRFS_NEED_TRANS_COMMIT) {
6293 err = btrfs_commit_transaction(trans);
6300 btrfs_end_transaction(trans);
6302 inode_dec_link_count(inode);
6305 btrfs_btree_balance_dirty(fs_info);
6309 static int btrfs_mkdir(struct inode *dir, struct dentry *dentry, umode_t mode)
6311 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
6312 struct inode *inode = NULL;
6313 struct btrfs_trans_handle *trans;
6314 struct btrfs_root *root = BTRFS_I(dir)->root;
6320 * 2 items for inode and ref
6321 * 2 items for dir items
6322 * 1 for xattr if selinux is on
6324 trans = btrfs_start_transaction(root, 5);
6326 return PTR_ERR(trans);
6328 err = btrfs_find_free_ino(root, &objectid);
6332 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
6333 dentry->d_name.len, btrfs_ino(BTRFS_I(dir)), objectid,
6334 S_IFDIR | mode, &index);
6335 if (IS_ERR(inode)) {
6336 err = PTR_ERR(inode);
6341 /* these must be set before we unlock the inode */
6342 inode->i_op = &btrfs_dir_inode_operations;
6343 inode->i_fop = &btrfs_dir_file_operations;
6345 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
6349 btrfs_i_size_write(BTRFS_I(inode), 0);
6350 err = btrfs_update_inode(trans, root, inode);
6354 err = btrfs_add_link(trans, BTRFS_I(dir), BTRFS_I(inode),
6355 dentry->d_name.name,
6356 dentry->d_name.len, 0, index);
6360 d_instantiate_new(dentry, inode);
6363 btrfs_end_transaction(trans);
6365 inode_dec_link_count(inode);
6366 discard_new_inode(inode);
6368 btrfs_btree_balance_dirty(fs_info);
6372 static noinline int uncompress_inline(struct btrfs_path *path,
6374 size_t pg_offset, u64 extent_offset,
6375 struct btrfs_file_extent_item *item)
6378 struct extent_buffer *leaf = path->nodes[0];
6381 unsigned long inline_size;
6385 WARN_ON(pg_offset != 0);
6386 compress_type = btrfs_file_extent_compression(leaf, item);
6387 max_size = btrfs_file_extent_ram_bytes(leaf, item);
6388 inline_size = btrfs_file_extent_inline_item_len(leaf,
6389 btrfs_item_nr(path->slots[0]));
6390 tmp = kmalloc(inline_size, GFP_NOFS);
6393 ptr = btrfs_file_extent_inline_start(item);
6395 read_extent_buffer(leaf, tmp, ptr, inline_size);
6397 max_size = min_t(unsigned long, PAGE_SIZE, max_size);
6398 ret = btrfs_decompress(compress_type, tmp, page,
6399 extent_offset, inline_size, max_size);
6402 * decompression code contains a memset to fill in any space between the end
6403 * of the uncompressed data and the end of max_size in case the decompressed
6404 * data ends up shorter than ram_bytes. That doesn't cover the hole between
6405 * the end of an inline extent and the beginning of the next block, so we
6406 * cover that region here.
6409 if (max_size + pg_offset < PAGE_SIZE) {
6410 char *map = kmap(page);
6411 memset(map + pg_offset + max_size, 0, PAGE_SIZE - max_size - pg_offset);
6419 * btrfs_get_extent - Lookup the first extent overlapping a range in a file.
6420 * @inode: file to search in
6421 * @page: page to read extent data into if the extent is inline
6422 * @pg_offset: offset into @page to copy to
6423 * @start: file offset
6424 * @len: length of range starting at @start
6426 * This returns the first &struct extent_map which overlaps with the given
6427 * range, reading it from the B-tree and caching it if necessary. Note that
6428 * there may be more extents which overlap the given range after the returned
6431 * If @page is not NULL and the extent is inline, this also reads the extent
6432 * data directly into the page and marks the extent up to date in the io_tree.
6434 * Return: ERR_PTR on error, non-NULL extent_map on success.
6436 struct extent_map *btrfs_get_extent(struct btrfs_inode *inode,
6437 struct page *page, size_t pg_offset,
6440 struct btrfs_fs_info *fs_info = inode->root->fs_info;
6443 u64 extent_start = 0;
6445 u64 objectid = btrfs_ino(inode);
6446 int extent_type = -1;
6447 struct btrfs_path *path = NULL;
6448 struct btrfs_root *root = inode->root;
6449 struct btrfs_file_extent_item *item;
6450 struct extent_buffer *leaf;
6451 struct btrfs_key found_key;
6452 struct extent_map *em = NULL;
6453 struct extent_map_tree *em_tree = &inode->extent_tree;
6454 struct extent_io_tree *io_tree = &inode->io_tree;
6456 read_lock(&em_tree->lock);
6457 em = lookup_extent_mapping(em_tree, start, len);
6458 read_unlock(&em_tree->lock);
6461 if (em->start > start || em->start + em->len <= start)
6462 free_extent_map(em);
6463 else if (em->block_start == EXTENT_MAP_INLINE && page)
6464 free_extent_map(em);
6468 em = alloc_extent_map();
6473 em->start = EXTENT_MAP_HOLE;
6474 em->orig_start = EXTENT_MAP_HOLE;
6476 em->block_len = (u64)-1;
6478 path = btrfs_alloc_path();
6484 /* Chances are we'll be called again, so go ahead and do readahead */
6485 path->reada = READA_FORWARD;
6488 * Unless we're going to uncompress the inline extent, no sleep would
6491 path->leave_spinning = 1;
6493 ret = btrfs_lookup_file_extent(NULL, root, path, objectid, start, 0);
6497 } else if (ret > 0) {
6498 if (path->slots[0] == 0)
6503 leaf = path->nodes[0];
6504 item = btrfs_item_ptr(leaf, path->slots[0],
6505 struct btrfs_file_extent_item);
6506 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
6507 if (found_key.objectid != objectid ||
6508 found_key.type != BTRFS_EXTENT_DATA_KEY) {
6510 * If we backup past the first extent we want to move forward
6511 * and see if there is an extent in front of us, otherwise we'll
6512 * say there is a hole for our whole search range which can
6519 extent_type = btrfs_file_extent_type(leaf, item);
6520 extent_start = found_key.offset;
6521 extent_end = btrfs_file_extent_end(path);
6522 if (extent_type == BTRFS_FILE_EXTENT_REG ||
6523 extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
6524 /* Only regular file could have regular/prealloc extent */
6525 if (!S_ISREG(inode->vfs_inode.i_mode)) {
6528 "regular/prealloc extent found for non-regular inode %llu",
6532 trace_btrfs_get_extent_show_fi_regular(inode, leaf, item,
6534 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
6535 trace_btrfs_get_extent_show_fi_inline(inode, leaf, item,
6540 if (start >= extent_end) {
6542 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
6543 ret = btrfs_next_leaf(root, path);
6547 } else if (ret > 0) {
6550 leaf = path->nodes[0];
6552 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
6553 if (found_key.objectid != objectid ||
6554 found_key.type != BTRFS_EXTENT_DATA_KEY)
6556 if (start + len <= found_key.offset)
6558 if (start > found_key.offset)
6561 /* New extent overlaps with existing one */
6563 em->orig_start = start;
6564 em->len = found_key.offset - start;
6565 em->block_start = EXTENT_MAP_HOLE;
6569 btrfs_extent_item_to_extent_map(inode, path, item, !page, em);
6571 if (extent_type == BTRFS_FILE_EXTENT_REG ||
6572 extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
6574 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
6578 size_t extent_offset;
6584 size = btrfs_file_extent_ram_bytes(leaf, item);
6585 extent_offset = page_offset(page) + pg_offset - extent_start;
6586 copy_size = min_t(u64, PAGE_SIZE - pg_offset,
6587 size - extent_offset);
6588 em->start = extent_start + extent_offset;
6589 em->len = ALIGN(copy_size, fs_info->sectorsize);
6590 em->orig_block_len = em->len;
6591 em->orig_start = em->start;
6592 ptr = btrfs_file_extent_inline_start(item) + extent_offset;
6594 btrfs_set_path_blocking(path);
6595 if (!PageUptodate(page)) {
6596 if (btrfs_file_extent_compression(leaf, item) !=
6597 BTRFS_COMPRESS_NONE) {
6598 ret = uncompress_inline(path, page, pg_offset,
6599 extent_offset, item);
6606 read_extent_buffer(leaf, map + pg_offset, ptr,
6608 if (pg_offset + copy_size < PAGE_SIZE) {
6609 memset(map + pg_offset + copy_size, 0,
6610 PAGE_SIZE - pg_offset -
6615 flush_dcache_page(page);
6617 set_extent_uptodate(io_tree, em->start,
6618 extent_map_end(em) - 1, NULL, GFP_NOFS);
6623 em->orig_start = start;
6625 em->block_start = EXTENT_MAP_HOLE;
6627 btrfs_release_path(path);
6628 if (em->start > start || extent_map_end(em) <= start) {
6630 "bad extent! em: [%llu %llu] passed [%llu %llu]",
6631 em->start, em->len, start, len);
6637 write_lock(&em_tree->lock);
6638 err = btrfs_add_extent_mapping(fs_info, em_tree, &em, start, len);
6639 write_unlock(&em_tree->lock);
6641 btrfs_free_path(path);
6643 trace_btrfs_get_extent(root, inode, em);
6646 free_extent_map(em);
6647 return ERR_PTR(err);
6649 BUG_ON(!em); /* Error is always set */
6653 struct extent_map *btrfs_get_extent_fiemap(struct btrfs_inode *inode,
6656 struct extent_map *em;
6657 struct extent_map *hole_em = NULL;
6658 u64 delalloc_start = start;
6664 em = btrfs_get_extent(inode, NULL, 0, start, len);
6668 * If our em maps to:
6670 * - a pre-alloc extent,
6671 * there might actually be delalloc bytes behind it.
6673 if (em->block_start != EXTENT_MAP_HOLE &&
6674 !test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
6679 /* check to see if we've wrapped (len == -1 or similar) */
6688 /* ok, we didn't find anything, lets look for delalloc */
6689 delalloc_len = count_range_bits(&inode->io_tree, &delalloc_start,
6690 end, len, EXTENT_DELALLOC, 1);
6691 delalloc_end = delalloc_start + delalloc_len;
6692 if (delalloc_end < delalloc_start)
6693 delalloc_end = (u64)-1;
6696 * We didn't find anything useful, return the original results from
6699 if (delalloc_start > end || delalloc_end <= start) {
6706 * Adjust the delalloc_start to make sure it doesn't go backwards from
6707 * the start they passed in
6709 delalloc_start = max(start, delalloc_start);
6710 delalloc_len = delalloc_end - delalloc_start;
6712 if (delalloc_len > 0) {
6715 const u64 hole_end = extent_map_end(hole_em);
6717 em = alloc_extent_map();
6725 * When btrfs_get_extent can't find anything it returns one
6728 * Make sure what it found really fits our range, and adjust to
6729 * make sure it is based on the start from the caller
6731 if (hole_end <= start || hole_em->start > end) {
6732 free_extent_map(hole_em);
6735 hole_start = max(hole_em->start, start);
6736 hole_len = hole_end - hole_start;
6739 if (hole_em && delalloc_start > hole_start) {
6741 * Our hole starts before our delalloc, so we have to
6742 * return just the parts of the hole that go until the
6745 em->len = min(hole_len, delalloc_start - hole_start);
6746 em->start = hole_start;
6747 em->orig_start = hole_start;
6749 * Don't adjust block start at all, it is fixed at
6752 em->block_start = hole_em->block_start;
6753 em->block_len = hole_len;
6754 if (test_bit(EXTENT_FLAG_PREALLOC, &hole_em->flags))
6755 set_bit(EXTENT_FLAG_PREALLOC, &em->flags);
6758 * Hole is out of passed range or it starts after
6761 em->start = delalloc_start;
6762 em->len = delalloc_len;
6763 em->orig_start = delalloc_start;
6764 em->block_start = EXTENT_MAP_DELALLOC;
6765 em->block_len = delalloc_len;
6772 free_extent_map(hole_em);
6774 free_extent_map(em);
6775 return ERR_PTR(err);
6780 static struct extent_map *btrfs_create_dio_extent(struct inode *inode,
6783 const u64 orig_start,
6784 const u64 block_start,
6785 const u64 block_len,
6786 const u64 orig_block_len,
6787 const u64 ram_bytes,
6790 struct extent_map *em = NULL;
6793 if (type != BTRFS_ORDERED_NOCOW) {
6794 em = create_io_em(inode, start, len, orig_start,
6795 block_start, block_len, orig_block_len,
6797 BTRFS_COMPRESS_NONE, /* compress_type */
6802 ret = btrfs_add_ordered_extent_dio(inode, start, block_start,
6803 len, block_len, type);
6806 free_extent_map(em);
6807 btrfs_drop_extent_cache(BTRFS_I(inode), start,
6808 start + len - 1, 0);
6817 static struct extent_map *btrfs_new_extent_direct(struct inode *inode,
6820 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
6821 struct btrfs_root *root = BTRFS_I(inode)->root;
6822 struct extent_map *em;
6823 struct btrfs_key ins;
6827 alloc_hint = get_extent_allocation_hint(inode, start, len);
6828 ret = btrfs_reserve_extent(root, len, len, fs_info->sectorsize,
6829 0, alloc_hint, &ins, 1, 1);
6831 return ERR_PTR(ret);
6833 em = btrfs_create_dio_extent(inode, start, ins.offset, start,
6834 ins.objectid, ins.offset, ins.offset,
6835 ins.offset, BTRFS_ORDERED_REGULAR);
6836 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
6838 btrfs_free_reserved_extent(fs_info, ins.objectid,
6845 * returns 1 when the nocow is safe, < 1 on error, 0 if the
6846 * block must be cow'd
6848 noinline int can_nocow_extent(struct inode *inode, u64 offset, u64 *len,
6849 u64 *orig_start, u64 *orig_block_len,
6852 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
6853 struct btrfs_path *path;
6855 struct extent_buffer *leaf;
6856 struct btrfs_root *root = BTRFS_I(inode)->root;
6857 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
6858 struct btrfs_file_extent_item *fi;
6859 struct btrfs_key key;
6866 bool nocow = (BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW);
6868 path = btrfs_alloc_path();
6872 ret = btrfs_lookup_file_extent(NULL, root, path,
6873 btrfs_ino(BTRFS_I(inode)), offset, 0);
6877 slot = path->slots[0];
6880 /* can't find the item, must cow */
6887 leaf = path->nodes[0];
6888 btrfs_item_key_to_cpu(leaf, &key, slot);
6889 if (key.objectid != btrfs_ino(BTRFS_I(inode)) ||
6890 key.type != BTRFS_EXTENT_DATA_KEY) {
6891 /* not our file or wrong item type, must cow */
6895 if (key.offset > offset) {
6896 /* Wrong offset, must cow */
6900 fi = btrfs_item_ptr(leaf, slot, struct btrfs_file_extent_item);
6901 found_type = btrfs_file_extent_type(leaf, fi);
6902 if (found_type != BTRFS_FILE_EXTENT_REG &&
6903 found_type != BTRFS_FILE_EXTENT_PREALLOC) {
6904 /* not a regular extent, must cow */
6908 if (!nocow && found_type == BTRFS_FILE_EXTENT_REG)
6911 extent_end = key.offset + btrfs_file_extent_num_bytes(leaf, fi);
6912 if (extent_end <= offset)
6915 disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
6916 if (disk_bytenr == 0)
6919 if (btrfs_file_extent_compression(leaf, fi) ||
6920 btrfs_file_extent_encryption(leaf, fi) ||
6921 btrfs_file_extent_other_encoding(leaf, fi))
6925 * Do the same check as in btrfs_cross_ref_exist but without the
6926 * unnecessary search.
6928 if (btrfs_file_extent_generation(leaf, fi) <=
6929 btrfs_root_last_snapshot(&root->root_item))
6932 backref_offset = btrfs_file_extent_offset(leaf, fi);
6935 *orig_start = key.offset - backref_offset;
6936 *orig_block_len = btrfs_file_extent_disk_num_bytes(leaf, fi);
6937 *ram_bytes = btrfs_file_extent_ram_bytes(leaf, fi);
6940 if (btrfs_extent_readonly(fs_info, disk_bytenr))
6943 num_bytes = min(offset + *len, extent_end) - offset;
6944 if (!nocow && found_type == BTRFS_FILE_EXTENT_PREALLOC) {
6947 range_end = round_up(offset + num_bytes,
6948 root->fs_info->sectorsize) - 1;
6949 ret = test_range_bit(io_tree, offset, range_end,
6950 EXTENT_DELALLOC, 0, NULL);
6957 btrfs_release_path(path);
6960 * look for other files referencing this extent, if we
6961 * find any we must cow
6964 ret = btrfs_cross_ref_exist(root, btrfs_ino(BTRFS_I(inode)),
6965 key.offset - backref_offset, disk_bytenr);
6972 * adjust disk_bytenr and num_bytes to cover just the bytes
6973 * in this extent we are about to write. If there
6974 * are any csums in that range we have to cow in order
6975 * to keep the csums correct
6977 disk_bytenr += backref_offset;
6978 disk_bytenr += offset - key.offset;
6979 if (csum_exist_in_range(fs_info, disk_bytenr, num_bytes))
6982 * all of the above have passed, it is safe to overwrite this extent
6988 btrfs_free_path(path);
6992 static int lock_extent_direct(struct inode *inode, u64 lockstart, u64 lockend,
6993 struct extent_state **cached_state, int writing)
6995 struct btrfs_ordered_extent *ordered;
6999 lock_extent_bits(&BTRFS_I(inode)->io_tree, lockstart, lockend,
7002 * We're concerned with the entire range that we're going to be
7003 * doing DIO to, so we need to make sure there's no ordered
7004 * extents in this range.
7006 ordered = btrfs_lookup_ordered_range(BTRFS_I(inode), lockstart,
7007 lockend - lockstart + 1);
7010 * We need to make sure there are no buffered pages in this
7011 * range either, we could have raced between the invalidate in
7012 * generic_file_direct_write and locking the extent. The
7013 * invalidate needs to happen so that reads after a write do not
7017 (!writing || !filemap_range_has_page(inode->i_mapping,
7018 lockstart, lockend)))
7021 unlock_extent_cached(&BTRFS_I(inode)->io_tree, lockstart, lockend,
7026 * If we are doing a DIO read and the ordered extent we
7027 * found is for a buffered write, we can not wait for it
7028 * to complete and retry, because if we do so we can
7029 * deadlock with concurrent buffered writes on page
7030 * locks. This happens only if our DIO read covers more
7031 * than one extent map, if at this point has already
7032 * created an ordered extent for a previous extent map
7033 * and locked its range in the inode's io tree, and a
7034 * concurrent write against that previous extent map's
7035 * range and this range started (we unlock the ranges
7036 * in the io tree only when the bios complete and
7037 * buffered writes always lock pages before attempting
7038 * to lock range in the io tree).
7041 test_bit(BTRFS_ORDERED_DIRECT, &ordered->flags))
7042 btrfs_start_ordered_extent(inode, ordered, 1);
7045 btrfs_put_ordered_extent(ordered);
7048 * We could trigger writeback for this range (and wait
7049 * for it to complete) and then invalidate the pages for
7050 * this range (through invalidate_inode_pages2_range()),
7051 * but that can lead us to a deadlock with a concurrent
7052 * call to readpages() (a buffered read or a defrag call
7053 * triggered a readahead) on a page lock due to an
7054 * ordered dio extent we created before but did not have
7055 * yet a corresponding bio submitted (whence it can not
7056 * complete), which makes readpages() wait for that
7057 * ordered extent to complete while holding a lock on
7072 /* The callers of this must take lock_extent() */
7073 static struct extent_map *create_io_em(struct inode *inode, u64 start, u64 len,
7074 u64 orig_start, u64 block_start,
7075 u64 block_len, u64 orig_block_len,
7076 u64 ram_bytes, int compress_type,
7079 struct extent_map_tree *em_tree;
7080 struct extent_map *em;
7083 ASSERT(type == BTRFS_ORDERED_PREALLOC ||
7084 type == BTRFS_ORDERED_COMPRESSED ||
7085 type == BTRFS_ORDERED_NOCOW ||
7086 type == BTRFS_ORDERED_REGULAR);
7088 em_tree = &BTRFS_I(inode)->extent_tree;
7089 em = alloc_extent_map();
7091 return ERR_PTR(-ENOMEM);
7094 em->orig_start = orig_start;
7096 em->block_len = block_len;
7097 em->block_start = block_start;
7098 em->orig_block_len = orig_block_len;
7099 em->ram_bytes = ram_bytes;
7100 em->generation = -1;
7101 set_bit(EXTENT_FLAG_PINNED, &em->flags);
7102 if (type == BTRFS_ORDERED_PREALLOC) {
7103 set_bit(EXTENT_FLAG_FILLING, &em->flags);
7104 } else if (type == BTRFS_ORDERED_COMPRESSED) {
7105 set_bit(EXTENT_FLAG_COMPRESSED, &em->flags);
7106 em->compress_type = compress_type;
7110 btrfs_drop_extent_cache(BTRFS_I(inode), em->start,
7111 em->start + em->len - 1, 0);
7112 write_lock(&em_tree->lock);
7113 ret = add_extent_mapping(em_tree, em, 1);
7114 write_unlock(&em_tree->lock);
7116 * The caller has taken lock_extent(), who could race with us
7119 } while (ret == -EEXIST);
7122 free_extent_map(em);
7123 return ERR_PTR(ret);
7126 /* em got 2 refs now, callers needs to do free_extent_map once. */
7131 static int btrfs_get_blocks_direct_read(struct extent_map *em,
7132 struct buffer_head *bh_result,
7133 struct inode *inode,
7136 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7138 if (em->block_start == EXTENT_MAP_HOLE ||
7139 test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
7142 len = min(len, em->len - (start - em->start));
7144 bh_result->b_blocknr = (em->block_start + (start - em->start)) >>
7146 bh_result->b_size = len;
7147 bh_result->b_bdev = fs_info->fs_devices->latest_bdev;
7148 set_buffer_mapped(bh_result);
7153 static int btrfs_get_blocks_direct_write(struct extent_map **map,
7154 struct buffer_head *bh_result,
7155 struct inode *inode,
7156 struct btrfs_dio_data *dio_data,
7159 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7160 struct extent_map *em = *map;
7164 * We don't allocate a new extent in the following cases
7166 * 1) The inode is marked as NODATACOW. In this case we'll just use the
7168 * 2) The extent is marked as PREALLOC. We're good to go here and can
7169 * just use the extent.
7172 if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags) ||
7173 ((BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW) &&
7174 em->block_start != EXTENT_MAP_HOLE)) {
7176 u64 block_start, orig_start, orig_block_len, ram_bytes;
7178 if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
7179 type = BTRFS_ORDERED_PREALLOC;
7181 type = BTRFS_ORDERED_NOCOW;
7182 len = min(len, em->len - (start - em->start));
7183 block_start = em->block_start + (start - em->start);
7185 if (can_nocow_extent(inode, start, &len, &orig_start,
7186 &orig_block_len, &ram_bytes) == 1 &&
7187 btrfs_inc_nocow_writers(fs_info, block_start)) {
7188 struct extent_map *em2;
7190 em2 = btrfs_create_dio_extent(inode, start, len,
7191 orig_start, block_start,
7192 len, orig_block_len,
7194 btrfs_dec_nocow_writers(fs_info, block_start);
7195 if (type == BTRFS_ORDERED_PREALLOC) {
7196 free_extent_map(em);
7200 if (em2 && IS_ERR(em2)) {
7205 * For inode marked NODATACOW or extent marked PREALLOC,
7206 * use the existing or preallocated extent, so does not
7207 * need to adjust btrfs_space_info's bytes_may_use.
7209 btrfs_free_reserved_data_space_noquota(inode, start,
7215 /* this will cow the extent */
7216 len = bh_result->b_size;
7217 free_extent_map(em);
7218 *map = em = btrfs_new_extent_direct(inode, start, len);
7224 len = min(len, em->len - (start - em->start));
7227 bh_result->b_blocknr = (em->block_start + (start - em->start)) >>
7229 bh_result->b_size = len;
7230 bh_result->b_bdev = fs_info->fs_devices->latest_bdev;
7231 set_buffer_mapped(bh_result);
7233 if (!test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
7234 set_buffer_new(bh_result);
7237 * Need to update the i_size under the extent lock so buffered
7238 * readers will get the updated i_size when we unlock.
7240 if (!dio_data->overwrite && start + len > i_size_read(inode))
7241 i_size_write(inode, start + len);
7243 WARN_ON(dio_data->reserve < len);
7244 dio_data->reserve -= len;
7245 dio_data->unsubmitted_oe_range_end = start + len;
7246 current->journal_info = dio_data;
7251 static int btrfs_get_blocks_direct(struct inode *inode, sector_t iblock,
7252 struct buffer_head *bh_result, int create)
7254 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7255 struct extent_map *em;
7256 struct extent_state *cached_state = NULL;
7257 struct btrfs_dio_data *dio_data = NULL;
7258 u64 start = iblock << inode->i_blkbits;
7259 u64 lockstart, lockend;
7260 u64 len = bh_result->b_size;
7264 len = min_t(u64, len, fs_info->sectorsize);
7267 lockend = start + len - 1;
7269 if (current->journal_info) {
7271 * Need to pull our outstanding extents and set journal_info to NULL so
7272 * that anything that needs to check if there's a transaction doesn't get
7275 dio_data = current->journal_info;
7276 current->journal_info = NULL;
7280 * If this errors out it's because we couldn't invalidate pagecache for
7281 * this range and we need to fallback to buffered.
7283 if (lock_extent_direct(inode, lockstart, lockend, &cached_state,
7289 em = btrfs_get_extent(BTRFS_I(inode), NULL, 0, start, len);
7296 * Ok for INLINE and COMPRESSED extents we need to fallback on buffered
7297 * io. INLINE is special, and we could probably kludge it in here, but
7298 * it's still buffered so for safety lets just fall back to the generic
7301 * For COMPRESSED we _have_ to read the entire extent in so we can
7302 * decompress it, so there will be buffering required no matter what we
7303 * do, so go ahead and fallback to buffered.
7305 * We return -ENOTBLK because that's what makes DIO go ahead and go back
7306 * to buffered IO. Don't blame me, this is the price we pay for using
7309 if (test_bit(EXTENT_FLAG_COMPRESSED, &em->flags) ||
7310 em->block_start == EXTENT_MAP_INLINE) {
7311 free_extent_map(em);
7317 ret = btrfs_get_blocks_direct_write(&em, bh_result, inode,
7318 dio_data, start, len);
7322 unlock_extent_cached(&BTRFS_I(inode)->io_tree, lockstart,
7323 lockend, &cached_state);
7325 ret = btrfs_get_blocks_direct_read(em, bh_result, inode,
7327 /* Can be negative only if we read from a hole */
7330 free_extent_map(em);
7334 * We need to unlock only the end area that we aren't using.
7335 * The rest is going to be unlocked by the endio routine.
7337 lockstart = start + bh_result->b_size;
7338 if (lockstart < lockend) {
7339 unlock_extent_cached(&BTRFS_I(inode)->io_tree,
7340 lockstart, lockend, &cached_state);
7342 free_extent_state(cached_state);
7346 free_extent_map(em);
7351 unlock_extent_cached(&BTRFS_I(inode)->io_tree, lockstart, lockend,
7355 current->journal_info = dio_data;
7359 static inline blk_status_t submit_dio_repair_bio(struct inode *inode,
7363 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7366 BUG_ON(bio_op(bio) == REQ_OP_WRITE);
7368 ret = btrfs_bio_wq_end_io(fs_info, bio, BTRFS_WQ_ENDIO_DIO_REPAIR);
7372 ret = btrfs_map_bio(fs_info, bio, mirror_num);
7377 static int btrfs_check_dio_repairable(struct inode *inode,
7378 struct bio *failed_bio,
7379 struct io_failure_record *failrec,
7382 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7385 num_copies = btrfs_num_copies(fs_info, failrec->logical, failrec->len);
7386 if (num_copies == 1) {
7388 * we only have a single copy of the data, so don't bother with
7389 * all the retry and error correction code that follows. no
7390 * matter what the error is, it is very likely to persist.
7392 btrfs_debug(fs_info,
7393 "Check DIO Repairable: cannot repair, num_copies=%d, next_mirror %d, failed_mirror %d",
7394 num_copies, failrec->this_mirror, failed_mirror);
7398 failrec->failed_mirror = failed_mirror;
7399 failrec->this_mirror++;
7400 if (failrec->this_mirror == failed_mirror)
7401 failrec->this_mirror++;
7403 if (failrec->this_mirror > num_copies) {
7404 btrfs_debug(fs_info,
7405 "Check DIO Repairable: (fail) num_copies=%d, next_mirror %d, failed_mirror %d",
7406 num_copies, failrec->this_mirror, failed_mirror);
7413 static blk_status_t dio_read_error(struct inode *inode, struct bio *failed_bio,
7414 struct page *page, unsigned int pgoff,
7415 u64 start, u64 end, int failed_mirror,
7416 bio_end_io_t *repair_endio, void *repair_arg)
7418 struct io_failure_record *failrec;
7419 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
7420 struct extent_io_tree *failure_tree = &BTRFS_I(inode)->io_failure_tree;
7423 unsigned int read_mode = 0;
7426 blk_status_t status;
7427 struct bio_vec bvec;
7429 BUG_ON(bio_op(failed_bio) == REQ_OP_WRITE);
7431 ret = btrfs_get_io_failure_record(inode, start, end, &failrec);
7433 return errno_to_blk_status(ret);
7435 ret = btrfs_check_dio_repairable(inode, failed_bio, failrec,
7438 free_io_failure(failure_tree, io_tree, failrec);
7439 return BLK_STS_IOERR;
7442 segs = bio_segments(failed_bio);
7443 bio_get_first_bvec(failed_bio, &bvec);
7445 (bvec.bv_len > btrfs_inode_sectorsize(inode)))
7446 read_mode |= REQ_FAILFAST_DEV;
7448 isector = start - btrfs_io_bio(failed_bio)->logical;
7449 isector >>= inode->i_sb->s_blocksize_bits;
7450 bio = btrfs_create_repair_bio(inode, failed_bio, failrec, page,
7451 pgoff, isector, repair_endio, repair_arg);
7452 bio->bi_opf = REQ_OP_READ | read_mode;
7454 btrfs_debug(BTRFS_I(inode)->root->fs_info,
7455 "repair DIO read error: submitting new dio read[%#x] to this_mirror=%d, in_validation=%d",
7456 read_mode, failrec->this_mirror, failrec->in_validation);
7458 status = submit_dio_repair_bio(inode, bio, failrec->this_mirror);
7460 free_io_failure(failure_tree, io_tree, failrec);
7467 struct btrfs_retry_complete {
7468 struct completion done;
7469 struct inode *inode;
7474 static void btrfs_retry_endio_nocsum(struct bio *bio)
7476 struct btrfs_retry_complete *done = bio->bi_private;
7477 struct inode *inode = done->inode;
7478 struct bio_vec *bvec;
7479 struct extent_io_tree *io_tree, *failure_tree;
7480 struct bvec_iter_all iter_all;
7485 ASSERT(bio->bi_vcnt == 1);
7486 io_tree = &BTRFS_I(inode)->io_tree;
7487 failure_tree = &BTRFS_I(inode)->io_failure_tree;
7488 ASSERT(bio_first_bvec_all(bio)->bv_len == btrfs_inode_sectorsize(inode));
7491 ASSERT(!bio_flagged(bio, BIO_CLONED));
7492 bio_for_each_segment_all(bvec, bio, iter_all)
7493 clean_io_failure(BTRFS_I(inode)->root->fs_info, failure_tree,
7494 io_tree, done->start, bvec->bv_page,
7495 btrfs_ino(BTRFS_I(inode)), 0);
7497 complete(&done->done);
7501 static blk_status_t __btrfs_correct_data_nocsum(struct inode *inode,
7502 struct btrfs_io_bio *io_bio)
7504 struct btrfs_fs_info *fs_info;
7505 struct bio_vec bvec;
7506 struct bvec_iter iter;
7507 struct btrfs_retry_complete done;
7513 blk_status_t err = BLK_STS_OK;
7515 fs_info = BTRFS_I(inode)->root->fs_info;
7516 sectorsize = fs_info->sectorsize;
7518 start = io_bio->logical;
7520 io_bio->bio.bi_iter = io_bio->iter;
7522 bio_for_each_segment(bvec, &io_bio->bio, iter) {
7523 nr_sectors = BTRFS_BYTES_TO_BLKS(fs_info, bvec.bv_len);
7524 pgoff = bvec.bv_offset;
7526 next_block_or_try_again:
7529 init_completion(&done.done);
7531 ret = dio_read_error(inode, &io_bio->bio, bvec.bv_page,
7532 pgoff, start, start + sectorsize - 1,
7534 btrfs_retry_endio_nocsum, &done);
7540 wait_for_completion_io(&done.done);
7542 if (!done.uptodate) {
7543 /* We might have another mirror, so try again */
7544 goto next_block_or_try_again;
7548 start += sectorsize;
7552 pgoff += sectorsize;
7553 ASSERT(pgoff < PAGE_SIZE);
7554 goto next_block_or_try_again;
7561 static void btrfs_retry_endio(struct bio *bio)
7563 struct btrfs_retry_complete *done = bio->bi_private;
7564 struct btrfs_io_bio *io_bio = btrfs_io_bio(bio);
7565 struct extent_io_tree *io_tree, *failure_tree;
7566 struct inode *inode = done->inode;
7567 struct bio_vec *bvec;
7571 struct bvec_iter_all iter_all;
7578 ASSERT(bio->bi_vcnt == 1);
7579 ASSERT(bio_first_bvec_all(bio)->bv_len == btrfs_inode_sectorsize(done->inode));
7581 io_tree = &BTRFS_I(inode)->io_tree;
7582 failure_tree = &BTRFS_I(inode)->io_failure_tree;
7584 ASSERT(!bio_flagged(bio, BIO_CLONED));
7585 bio_for_each_segment_all(bvec, bio, iter_all) {
7586 ret = check_data_csum(inode, io_bio, i, bvec->bv_page,
7587 bvec->bv_offset, done->start,
7590 clean_io_failure(BTRFS_I(inode)->root->fs_info,
7591 failure_tree, io_tree, done->start,
7593 btrfs_ino(BTRFS_I(inode)),
7600 done->uptodate = uptodate;
7602 complete(&done->done);
7606 static blk_status_t __btrfs_subio_endio_read(struct inode *inode,
7607 struct btrfs_io_bio *io_bio, blk_status_t err)
7609 struct btrfs_fs_info *fs_info;
7610 struct bio_vec bvec;
7611 struct bvec_iter iter;
7612 struct btrfs_retry_complete done;
7619 bool uptodate = (err == 0);
7621 blk_status_t status;
7623 fs_info = BTRFS_I(inode)->root->fs_info;
7624 sectorsize = fs_info->sectorsize;
7627 start = io_bio->logical;
7629 io_bio->bio.bi_iter = io_bio->iter;
7631 bio_for_each_segment(bvec, &io_bio->bio, iter) {
7632 nr_sectors = BTRFS_BYTES_TO_BLKS(fs_info, bvec.bv_len);
7634 pgoff = bvec.bv_offset;
7637 csum_pos = BTRFS_BYTES_TO_BLKS(fs_info, offset);
7638 ret = check_data_csum(inode, io_bio, csum_pos,
7639 bvec.bv_page, pgoff, start,
7647 init_completion(&done.done);
7649 status = dio_read_error(inode, &io_bio->bio, bvec.bv_page,
7650 pgoff, start, start + sectorsize - 1,
7651 io_bio->mirror_num, btrfs_retry_endio,
7658 wait_for_completion_io(&done.done);
7660 if (!done.uptodate) {
7661 /* We might have another mirror, so try again */
7665 offset += sectorsize;
7666 start += sectorsize;
7672 pgoff += sectorsize;
7673 ASSERT(pgoff < PAGE_SIZE);
7681 static blk_status_t btrfs_subio_endio_read(struct inode *inode,
7682 struct btrfs_io_bio *io_bio, blk_status_t err)
7684 bool skip_csum = BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM;
7688 return __btrfs_correct_data_nocsum(inode, io_bio);
7692 return __btrfs_subio_endio_read(inode, io_bio, err);
7696 static void btrfs_endio_direct_read(struct bio *bio)
7698 struct btrfs_dio_private *dip = bio->bi_private;
7699 struct inode *inode = dip->inode;
7700 struct bio *dio_bio;
7701 struct btrfs_io_bio *io_bio = btrfs_io_bio(bio);
7702 blk_status_t err = bio->bi_status;
7704 if (dip->flags & BTRFS_DIO_ORIG_BIO_SUBMITTED)
7705 err = btrfs_subio_endio_read(inode, io_bio, err);
7707 unlock_extent(&BTRFS_I(inode)->io_tree, dip->logical_offset,
7708 dip->logical_offset + dip->bytes - 1);
7709 dio_bio = dip->dio_bio;
7713 dio_bio->bi_status = err;
7714 dio_end_io(dio_bio);
7715 btrfs_io_bio_free_csum(io_bio);
7719 static void __endio_write_update_ordered(struct inode *inode,
7720 const u64 offset, const u64 bytes,
7721 const bool uptodate)
7723 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7724 struct btrfs_ordered_extent *ordered = NULL;
7725 struct btrfs_workqueue *wq;
7726 u64 ordered_offset = offset;
7727 u64 ordered_bytes = bytes;
7730 if (btrfs_is_free_space_inode(BTRFS_I(inode)))
7731 wq = fs_info->endio_freespace_worker;
7733 wq = fs_info->endio_write_workers;
7735 while (ordered_offset < offset + bytes) {
7736 last_offset = ordered_offset;
7737 if (btrfs_dec_test_first_ordered_pending(inode, &ordered,
7741 btrfs_init_work(&ordered->work, finish_ordered_fn, NULL,
7743 btrfs_queue_work(wq, &ordered->work);
7746 * If btrfs_dec_test_ordered_pending does not find any ordered
7747 * extent in the range, we can exit.
7749 if (ordered_offset == last_offset)
7752 * Our bio might span multiple ordered extents. In this case
7753 * we keep going until we have accounted the whole dio.
7755 if (ordered_offset < offset + bytes) {
7756 ordered_bytes = offset + bytes - ordered_offset;
7762 static void btrfs_endio_direct_write(struct bio *bio)
7764 struct btrfs_dio_private *dip = bio->bi_private;
7765 struct bio *dio_bio = dip->dio_bio;
7767 __endio_write_update_ordered(dip->inode, dip->logical_offset,
7768 dip->bytes, !bio->bi_status);
7772 dio_bio->bi_status = bio->bi_status;
7773 dio_end_io(dio_bio);
7777 static blk_status_t btrfs_submit_bio_start_direct_io(void *private_data,
7778 struct bio *bio, u64 offset)
7780 struct inode *inode = private_data;
7782 ret = btrfs_csum_one_bio(inode, bio, offset, 1);
7783 BUG_ON(ret); /* -ENOMEM */
7787 static void btrfs_end_dio_bio(struct bio *bio)
7789 struct btrfs_dio_private *dip = bio->bi_private;
7790 blk_status_t err = bio->bi_status;
7793 btrfs_warn(BTRFS_I(dip->inode)->root->fs_info,
7794 "direct IO failed ino %llu rw %d,%u sector %#Lx len %u err no %d",
7795 btrfs_ino(BTRFS_I(dip->inode)), bio_op(bio),
7797 (unsigned long long)bio->bi_iter.bi_sector,
7798 bio->bi_iter.bi_size, err);
7800 if (dip->subio_endio)
7801 err = dip->subio_endio(dip->inode, btrfs_io_bio(bio), err);
7805 * We want to perceive the errors flag being set before
7806 * decrementing the reference count. We don't need a barrier
7807 * since atomic operations with a return value are fully
7808 * ordered as per atomic_t.txt
7813 /* if there are more bios still pending for this dio, just exit */
7814 if (!atomic_dec_and_test(&dip->pending_bios))
7818 bio_io_error(dip->orig_bio);
7820 dip->dio_bio->bi_status = BLK_STS_OK;
7821 bio_endio(dip->orig_bio);
7827 static inline blk_status_t btrfs_lookup_and_bind_dio_csum(struct inode *inode,
7828 struct btrfs_dio_private *dip,
7832 struct btrfs_io_bio *io_bio = btrfs_io_bio(bio);
7833 struct btrfs_io_bio *orig_io_bio = btrfs_io_bio(dip->orig_bio);
7838 * We load all the csum data we need when we submit
7839 * the first bio to reduce the csum tree search and
7842 if (dip->logical_offset == file_offset) {
7843 ret = btrfs_lookup_bio_sums(inode, dip->orig_bio, file_offset,
7849 if (bio == dip->orig_bio)
7852 file_offset -= dip->logical_offset;
7853 file_offset >>= inode->i_sb->s_blocksize_bits;
7854 csum_size = btrfs_super_csum_size(btrfs_sb(inode->i_sb)->super_copy);
7855 io_bio->csum = orig_io_bio->csum + csum_size * file_offset;
7860 static inline blk_status_t btrfs_submit_dio_bio(struct bio *bio,
7861 struct inode *inode, u64 file_offset, int async_submit)
7863 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7864 struct btrfs_dio_private *dip = bio->bi_private;
7865 bool write = bio_op(bio) == REQ_OP_WRITE;
7868 /* Check btrfs_submit_bio_hook() for rules about async submit. */
7870 async_submit = !atomic_read(&BTRFS_I(inode)->sync_writers);
7873 ret = btrfs_bio_wq_end_io(fs_info, bio, BTRFS_WQ_ENDIO_DATA);
7878 if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)
7881 if (write && async_submit) {
7882 ret = btrfs_wq_submit_bio(fs_info, bio, 0, 0,
7884 btrfs_submit_bio_start_direct_io);
7888 * If we aren't doing async submit, calculate the csum of the
7891 ret = btrfs_csum_one_bio(inode, bio, file_offset, 1);
7895 ret = btrfs_lookup_and_bind_dio_csum(inode, dip, bio,
7901 ret = btrfs_map_bio(fs_info, bio, 0);
7907 * If this succeeds, the btrfs_dio_private is responsible for cleaning up locked
7908 * or ordered extents whether or not we submit any bios.
7910 static struct btrfs_dio_private *btrfs_create_dio_private(struct bio *dio_bio,
7911 struct inode *inode,
7914 const bool write = (bio_op(dio_bio) == REQ_OP_WRITE);
7915 struct btrfs_dio_private *dip;
7918 dip = kzalloc(sizeof(*dip), GFP_NOFS);
7922 bio = btrfs_bio_clone(dio_bio);
7923 bio->bi_private = dip;
7924 btrfs_io_bio(bio)->logical = file_offset;
7927 dip->logical_offset = file_offset;
7928 dip->bytes = dio_bio->bi_iter.bi_size;
7929 dip->disk_bytenr = (u64)dio_bio->bi_iter.bi_sector << 9;
7930 dip->orig_bio = bio;
7931 dip->dio_bio = dio_bio;
7932 atomic_set(&dip->pending_bios, 1);
7935 struct btrfs_dio_data *dio_data = current->journal_info;
7938 * Setting range start and end to the same value means that
7939 * no cleanup will happen in btrfs_direct_IO
7941 dio_data->unsubmitted_oe_range_end = dip->logical_offset +
7943 dio_data->unsubmitted_oe_range_start =
7944 dio_data->unsubmitted_oe_range_end;
7946 bio->bi_end_io = btrfs_endio_direct_write;
7948 bio->bi_end_io = btrfs_endio_direct_read;
7949 dip->subio_endio = btrfs_subio_endio_read;
7954 static void btrfs_submit_direct(struct bio *dio_bio, struct inode *inode,
7957 const bool write = (bio_op(dio_bio) == REQ_OP_WRITE);
7958 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7959 struct btrfs_dio_private *dip;
7961 struct bio *orig_bio;
7963 int async_submit = 0;
7965 int clone_offset = 0;
7968 blk_status_t status;
7969 struct btrfs_io_geometry geom;
7971 dip = btrfs_create_dio_private(dio_bio, inode, file_offset);
7974 unlock_extent(&BTRFS_I(inode)->io_tree, file_offset,
7975 file_offset + dio_bio->bi_iter.bi_size - 1);
7977 dio_bio->bi_status = BLK_STS_RESOURCE;
7978 dio_end_io(dio_bio);
7982 orig_bio = dip->orig_bio;
7983 start_sector = orig_bio->bi_iter.bi_sector;
7984 submit_len = orig_bio->bi_iter.bi_size;
7985 ret = btrfs_get_io_geometry(fs_info, btrfs_op(orig_bio),
7986 start_sector << 9, submit_len, &geom);
7990 if (geom.len >= submit_len) {
7992 dip->flags |= BTRFS_DIO_ORIG_BIO_SUBMITTED;
7996 /* async crcs make it difficult to collect full stripe writes. */
7997 if (btrfs_data_alloc_profile(fs_info) & BTRFS_BLOCK_GROUP_RAID56_MASK)
8003 ASSERT(geom.len <= INT_MAX);
8005 clone_len = min_t(int, submit_len, geom.len);
8008 * This will never fail as it's passing GPF_NOFS and
8009 * the allocation is backed by btrfs_bioset.
8011 bio = btrfs_bio_clone_partial(orig_bio, clone_offset,
8013 bio->bi_private = dip;
8014 bio->bi_end_io = btrfs_end_dio_bio;
8015 btrfs_io_bio(bio)->logical = file_offset;
8017 ASSERT(submit_len >= clone_len);
8018 submit_len -= clone_len;
8019 if (submit_len == 0)
8023 * Increase the count before we submit the bio so we know
8024 * the end IO handler won't happen before we increase the
8025 * count. Otherwise, the dip might get freed before we're
8026 * done setting it up.
8028 atomic_inc(&dip->pending_bios);
8030 status = btrfs_submit_dio_bio(bio, inode, file_offset,
8034 atomic_dec(&dip->pending_bios);
8038 clone_offset += clone_len;
8039 start_sector += clone_len >> 9;
8040 file_offset += clone_len;
8042 ret = btrfs_get_io_geometry(fs_info, btrfs_op(orig_bio),
8043 start_sector << 9, submit_len, &geom);
8046 } while (submit_len > 0);
8049 status = btrfs_submit_dio_bio(bio, inode, file_offset, async_submit);
8053 if (bio != orig_bio)
8058 * Before atomic variable goto zero, we must make sure dip->errors is
8059 * perceived to be set. This ordering is ensured by the fact that an
8060 * atomic operations with a return value are fully ordered as per
8063 if (atomic_dec_and_test(&dip->pending_bios))
8064 bio_io_error(dip->orig_bio);
8067 static ssize_t check_direct_IO(struct btrfs_fs_info *fs_info,
8068 const struct iov_iter *iter, loff_t offset)
8072 unsigned int blocksize_mask = fs_info->sectorsize - 1;
8073 ssize_t retval = -EINVAL;
8075 if (offset & blocksize_mask)
8078 if (iov_iter_alignment(iter) & blocksize_mask)
8081 /* If this is a write we don't need to check anymore */
8082 if (iov_iter_rw(iter) != READ || !iter_is_iovec(iter))
8085 * Check to make sure we don't have duplicate iov_base's in this
8086 * iovec, if so return EINVAL, otherwise we'll get csum errors
8087 * when reading back.
8089 for (seg = 0; seg < iter->nr_segs; seg++) {
8090 for (i = seg + 1; i < iter->nr_segs; i++) {
8091 if (iter->iov[seg].iov_base == iter->iov[i].iov_base)
8100 static ssize_t btrfs_direct_IO(struct kiocb *iocb, struct iov_iter *iter)
8102 struct file *file = iocb->ki_filp;
8103 struct inode *inode = file->f_mapping->host;
8104 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
8105 struct btrfs_dio_data dio_data = { 0 };
8106 struct extent_changeset *data_reserved = NULL;
8107 loff_t offset = iocb->ki_pos;
8111 bool relock = false;
8114 if (check_direct_IO(fs_info, iter, offset))
8117 inode_dio_begin(inode);
8120 * The generic stuff only does filemap_write_and_wait_range, which
8121 * isn't enough if we've written compressed pages to this area, so
8122 * we need to flush the dirty pages again to make absolutely sure
8123 * that any outstanding dirty pages are on disk.
8125 count = iov_iter_count(iter);
8126 if (test_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
8127 &BTRFS_I(inode)->runtime_flags))
8128 filemap_fdatawrite_range(inode->i_mapping, offset,
8129 offset + count - 1);
8131 if (iov_iter_rw(iter) == WRITE) {
8133 * If the write DIO is beyond the EOF, we need update
8134 * the isize, but it is protected by i_mutex. So we can
8135 * not unlock the i_mutex at this case.
8137 if (offset + count <= inode->i_size) {
8138 dio_data.overwrite = 1;
8139 inode_unlock(inode);
8141 } else if (iocb->ki_flags & IOCB_NOWAIT) {
8145 ret = btrfs_delalloc_reserve_space(inode, &data_reserved,
8151 * We need to know how many extents we reserved so that we can
8152 * do the accounting properly if we go over the number we
8153 * originally calculated. Abuse current->journal_info for this.
8155 dio_data.reserve = round_up(count,
8156 fs_info->sectorsize);
8157 dio_data.unsubmitted_oe_range_start = (u64)offset;
8158 dio_data.unsubmitted_oe_range_end = (u64)offset;
8159 current->journal_info = &dio_data;
8160 down_read(&BTRFS_I(inode)->dio_sem);
8161 } else if (test_bit(BTRFS_INODE_READDIO_NEED_LOCK,
8162 &BTRFS_I(inode)->runtime_flags)) {
8163 inode_dio_end(inode);
8164 flags = DIO_LOCKING | DIO_SKIP_HOLES;
8168 ret = __blockdev_direct_IO(iocb, inode,
8169 fs_info->fs_devices->latest_bdev,
8170 iter, btrfs_get_blocks_direct, NULL,
8171 btrfs_submit_direct, flags);
8172 if (iov_iter_rw(iter) == WRITE) {
8173 up_read(&BTRFS_I(inode)->dio_sem);
8174 current->journal_info = NULL;
8175 if (ret < 0 && ret != -EIOCBQUEUED) {
8176 if (dio_data.reserve)
8177 btrfs_delalloc_release_space(inode, data_reserved,
8178 offset, dio_data.reserve, true);
8180 * On error we might have left some ordered extents
8181 * without submitting corresponding bios for them, so
8182 * cleanup them up to avoid other tasks getting them
8183 * and waiting for them to complete forever.
8185 if (dio_data.unsubmitted_oe_range_start <
8186 dio_data.unsubmitted_oe_range_end)
8187 __endio_write_update_ordered(inode,
8188 dio_data.unsubmitted_oe_range_start,
8189 dio_data.unsubmitted_oe_range_end -
8190 dio_data.unsubmitted_oe_range_start,
8192 } else if (ret >= 0 && (size_t)ret < count)
8193 btrfs_delalloc_release_space(inode, data_reserved,
8194 offset, count - (size_t)ret, true);
8195 btrfs_delalloc_release_extents(BTRFS_I(inode), count);
8199 inode_dio_end(inode);
8203 extent_changeset_free(data_reserved);
8207 #define BTRFS_FIEMAP_FLAGS (FIEMAP_FLAG_SYNC)
8209 static int btrfs_fiemap(struct inode *inode, struct fiemap_extent_info *fieinfo,
8210 __u64 start, __u64 len)
8214 ret = fiemap_check_flags(fieinfo, BTRFS_FIEMAP_FLAGS);
8218 return extent_fiemap(inode, fieinfo, start, len);
8221 int btrfs_readpage(struct file *file, struct page *page)
8223 return extent_read_full_page(page, btrfs_get_extent, 0);
8226 static int btrfs_writepage(struct page *page, struct writeback_control *wbc)
8228 struct inode *inode = page->mapping->host;
8231 if (current->flags & PF_MEMALLOC) {
8232 redirty_page_for_writepage(wbc, page);
8238 * If we are under memory pressure we will call this directly from the
8239 * VM, we need to make sure we have the inode referenced for the ordered
8240 * extent. If not just return like we didn't do anything.
8242 if (!igrab(inode)) {
8243 redirty_page_for_writepage(wbc, page);
8244 return AOP_WRITEPAGE_ACTIVATE;
8246 ret = extent_write_full_page(page, wbc);
8247 btrfs_add_delayed_iput(inode);
8251 static int btrfs_writepages(struct address_space *mapping,
8252 struct writeback_control *wbc)
8254 return extent_writepages(mapping, wbc);
8258 btrfs_readpages(struct file *file, struct address_space *mapping,
8259 struct list_head *pages, unsigned nr_pages)
8261 return extent_readpages(mapping, pages, nr_pages);
8264 static int __btrfs_releasepage(struct page *page, gfp_t gfp_flags)
8266 int ret = try_release_extent_mapping(page, gfp_flags);
8268 ClearPagePrivate(page);
8269 set_page_private(page, 0);
8275 static int btrfs_releasepage(struct page *page, gfp_t gfp_flags)
8277 if (PageWriteback(page) || PageDirty(page))
8279 return __btrfs_releasepage(page, gfp_flags);
8282 #ifdef CONFIG_MIGRATION
8283 static int btrfs_migratepage(struct address_space *mapping,
8284 struct page *newpage, struct page *page,
8285 enum migrate_mode mode)
8289 ret = migrate_page_move_mapping(mapping, newpage, page, 0);
8290 if (ret != MIGRATEPAGE_SUCCESS)
8293 if (page_has_private(page)) {
8294 ClearPagePrivate(page);
8296 set_page_private(newpage, page_private(page));
8297 set_page_private(page, 0);
8299 SetPagePrivate(newpage);
8302 if (PagePrivate2(page)) {
8303 ClearPagePrivate2(page);
8304 SetPagePrivate2(newpage);
8307 if (mode != MIGRATE_SYNC_NO_COPY)
8308 migrate_page_copy(newpage, page);
8310 migrate_page_states(newpage, page);
8311 return MIGRATEPAGE_SUCCESS;
8315 static void btrfs_invalidatepage(struct page *page, unsigned int offset,
8316 unsigned int length)
8318 struct inode *inode = page->mapping->host;
8319 struct extent_io_tree *tree;
8320 struct btrfs_ordered_extent *ordered;
8321 struct extent_state *cached_state = NULL;
8322 u64 page_start = page_offset(page);
8323 u64 page_end = page_start + PAGE_SIZE - 1;
8326 int inode_evicting = inode->i_state & I_FREEING;
8329 * we have the page locked, so new writeback can't start,
8330 * and the dirty bit won't be cleared while we are here.
8332 * Wait for IO on this page so that we can safely clear
8333 * the PagePrivate2 bit and do ordered accounting
8335 wait_on_page_writeback(page);
8337 tree = &BTRFS_I(inode)->io_tree;
8339 btrfs_releasepage(page, GFP_NOFS);
8343 if (!inode_evicting)
8344 lock_extent_bits(tree, page_start, page_end, &cached_state);
8347 ordered = btrfs_lookup_ordered_range(BTRFS_I(inode), start,
8348 page_end - start + 1);
8351 ordered->file_offset + ordered->num_bytes - 1);
8353 * IO on this page will never be started, so we need
8354 * to account for any ordered extents now
8356 if (!inode_evicting)
8357 clear_extent_bit(tree, start, end,
8358 EXTENT_DELALLOC | EXTENT_DELALLOC_NEW |
8359 EXTENT_LOCKED | EXTENT_DO_ACCOUNTING |
8360 EXTENT_DEFRAG, 1, 0, &cached_state);
8362 * whoever cleared the private bit is responsible
8363 * for the finish_ordered_io
8365 if (TestClearPagePrivate2(page)) {
8366 struct btrfs_ordered_inode_tree *tree;
8369 tree = &BTRFS_I(inode)->ordered_tree;
8371 spin_lock_irq(&tree->lock);
8372 set_bit(BTRFS_ORDERED_TRUNCATED, &ordered->flags);
8373 new_len = start - ordered->file_offset;
8374 if (new_len < ordered->truncated_len)
8375 ordered->truncated_len = new_len;
8376 spin_unlock_irq(&tree->lock);
8378 if (btrfs_dec_test_ordered_pending(inode, &ordered,
8380 end - start + 1, 1))
8381 btrfs_finish_ordered_io(ordered);
8383 btrfs_put_ordered_extent(ordered);
8384 if (!inode_evicting) {
8385 cached_state = NULL;
8386 lock_extent_bits(tree, start, end,
8391 if (start < page_end)
8396 * Qgroup reserved space handler
8397 * Page here will be either
8398 * 1) Already written to disk
8399 * In this case, its reserved space is released from data rsv map
8400 * and will be freed by delayed_ref handler finally.
8401 * So even we call qgroup_free_data(), it won't decrease reserved
8403 * 2) Not written to disk
8404 * This means the reserved space should be freed here. However,
8405 * if a truncate invalidates the page (by clearing PageDirty)
8406 * and the page is accounted for while allocating extent
8407 * in btrfs_check_data_free_space() we let delayed_ref to
8408 * free the entire extent.
8410 if (PageDirty(page))
8411 btrfs_qgroup_free_data(inode, NULL, page_start, PAGE_SIZE);
8412 if (!inode_evicting) {
8413 clear_extent_bit(tree, page_start, page_end, EXTENT_LOCKED |
8414 EXTENT_DELALLOC | EXTENT_DELALLOC_NEW |
8415 EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG, 1, 1,
8418 __btrfs_releasepage(page, GFP_NOFS);
8421 ClearPageChecked(page);
8422 if (PagePrivate(page)) {
8423 ClearPagePrivate(page);
8424 set_page_private(page, 0);
8430 * btrfs_page_mkwrite() is not allowed to change the file size as it gets
8431 * called from a page fault handler when a page is first dirtied. Hence we must
8432 * be careful to check for EOF conditions here. We set the page up correctly
8433 * for a written page which means we get ENOSPC checking when writing into
8434 * holes and correct delalloc and unwritten extent mapping on filesystems that
8435 * support these features.
8437 * We are not allowed to take the i_mutex here so we have to play games to
8438 * protect against truncate races as the page could now be beyond EOF. Because
8439 * truncate_setsize() writes the inode size before removing pages, once we have
8440 * the page lock we can determine safely if the page is beyond EOF. If it is not
8441 * beyond EOF, then the page is guaranteed safe against truncation until we
8444 vm_fault_t btrfs_page_mkwrite(struct vm_fault *vmf)
8446 struct page *page = vmf->page;
8447 struct inode *inode = file_inode(vmf->vma->vm_file);
8448 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
8449 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
8450 struct btrfs_ordered_extent *ordered;
8451 struct extent_state *cached_state = NULL;
8452 struct extent_changeset *data_reserved = NULL;
8454 unsigned long zero_start;
8464 reserved_space = PAGE_SIZE;
8466 sb_start_pagefault(inode->i_sb);
8467 page_start = page_offset(page);
8468 page_end = page_start + PAGE_SIZE - 1;
8472 * Reserving delalloc space after obtaining the page lock can lead to
8473 * deadlock. For example, if a dirty page is locked by this function
8474 * and the call to btrfs_delalloc_reserve_space() ends up triggering
8475 * dirty page write out, then the btrfs_writepage() function could
8476 * end up waiting indefinitely to get a lock on the page currently
8477 * being processed by btrfs_page_mkwrite() function.
8479 ret2 = btrfs_delalloc_reserve_space(inode, &data_reserved, page_start,
8482 ret2 = file_update_time(vmf->vma->vm_file);
8486 ret = vmf_error(ret2);
8492 ret = VM_FAULT_NOPAGE; /* make the VM retry the fault */
8495 size = i_size_read(inode);
8497 if ((page->mapping != inode->i_mapping) ||
8498 (page_start >= size)) {
8499 /* page got truncated out from underneath us */
8502 wait_on_page_writeback(page);
8504 lock_extent_bits(io_tree, page_start, page_end, &cached_state);
8505 set_page_extent_mapped(page);
8508 * we can't set the delalloc bits if there are pending ordered
8509 * extents. Drop our locks and wait for them to finish
8511 ordered = btrfs_lookup_ordered_range(BTRFS_I(inode), page_start,
8514 unlock_extent_cached(io_tree, page_start, page_end,
8517 btrfs_start_ordered_extent(inode, ordered, 1);
8518 btrfs_put_ordered_extent(ordered);
8522 if (page->index == ((size - 1) >> PAGE_SHIFT)) {
8523 reserved_space = round_up(size - page_start,
8524 fs_info->sectorsize);
8525 if (reserved_space < PAGE_SIZE) {
8526 end = page_start + reserved_space - 1;
8527 btrfs_delalloc_release_space(inode, data_reserved,
8528 page_start, PAGE_SIZE - reserved_space,
8534 * page_mkwrite gets called when the page is firstly dirtied after it's
8535 * faulted in, but write(2) could also dirty a page and set delalloc
8536 * bits, thus in this case for space account reason, we still need to
8537 * clear any delalloc bits within this page range since we have to
8538 * reserve data&meta space before lock_page() (see above comments).
8540 clear_extent_bit(&BTRFS_I(inode)->io_tree, page_start, end,
8541 EXTENT_DELALLOC | EXTENT_DO_ACCOUNTING |
8542 EXTENT_DEFRAG, 0, 0, &cached_state);
8544 ret2 = btrfs_set_extent_delalloc(inode, page_start, end, 0,
8547 unlock_extent_cached(io_tree, page_start, page_end,
8549 ret = VM_FAULT_SIGBUS;
8553 /* page is wholly or partially inside EOF */
8554 if (page_start + PAGE_SIZE > size)
8555 zero_start = offset_in_page(size);
8557 zero_start = PAGE_SIZE;
8559 if (zero_start != PAGE_SIZE) {
8561 memset(kaddr + zero_start, 0, PAGE_SIZE - zero_start);
8562 flush_dcache_page(page);
8565 ClearPageChecked(page);
8566 set_page_dirty(page);
8567 SetPageUptodate(page);
8569 BTRFS_I(inode)->last_trans = fs_info->generation;
8570 BTRFS_I(inode)->last_sub_trans = BTRFS_I(inode)->root->log_transid;
8571 BTRFS_I(inode)->last_log_commit = BTRFS_I(inode)->root->last_log_commit;
8573 unlock_extent_cached(io_tree, page_start, page_end, &cached_state);
8575 btrfs_delalloc_release_extents(BTRFS_I(inode), PAGE_SIZE);
8576 sb_end_pagefault(inode->i_sb);
8577 extent_changeset_free(data_reserved);
8578 return VM_FAULT_LOCKED;
8583 btrfs_delalloc_release_extents(BTRFS_I(inode), PAGE_SIZE);
8584 btrfs_delalloc_release_space(inode, data_reserved, page_start,
8585 reserved_space, (ret != 0));
8587 sb_end_pagefault(inode->i_sb);
8588 extent_changeset_free(data_reserved);
8592 static int btrfs_truncate(struct inode *inode, bool skip_writeback)
8594 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
8595 struct btrfs_root *root = BTRFS_I(inode)->root;
8596 struct btrfs_block_rsv *rsv;
8598 struct btrfs_trans_handle *trans;
8599 u64 mask = fs_info->sectorsize - 1;
8600 u64 min_size = btrfs_calc_metadata_size(fs_info, 1);
8602 if (!skip_writeback) {
8603 ret = btrfs_wait_ordered_range(inode, inode->i_size & (~mask),
8610 * Yes ladies and gentlemen, this is indeed ugly. We have a couple of
8611 * things going on here:
8613 * 1) We need to reserve space to update our inode.
8615 * 2) We need to have something to cache all the space that is going to
8616 * be free'd up by the truncate operation, but also have some slack
8617 * space reserved in case it uses space during the truncate (thank you
8618 * very much snapshotting).
8620 * And we need these to be separate. The fact is we can use a lot of
8621 * space doing the truncate, and we have no earthly idea how much space
8622 * we will use, so we need the truncate reservation to be separate so it
8623 * doesn't end up using space reserved for updating the inode. We also
8624 * need to be able to stop the transaction and start a new one, which
8625 * means we need to be able to update the inode several times, and we
8626 * have no idea of knowing how many times that will be, so we can't just
8627 * reserve 1 item for the entirety of the operation, so that has to be
8628 * done separately as well.
8630 * So that leaves us with
8632 * 1) rsv - for the truncate reservation, which we will steal from the
8633 * transaction reservation.
8634 * 2) fs_info->trans_block_rsv - this will have 1 items worth left for
8635 * updating the inode.
8637 rsv = btrfs_alloc_block_rsv(fs_info, BTRFS_BLOCK_RSV_TEMP);
8640 rsv->size = min_size;
8644 * 1 for the truncate slack space
8645 * 1 for updating the inode.
8647 trans = btrfs_start_transaction(root, 2);
8648 if (IS_ERR(trans)) {
8649 ret = PTR_ERR(trans);
8653 /* Migrate the slack space for the truncate to our reserve */
8654 ret = btrfs_block_rsv_migrate(&fs_info->trans_block_rsv, rsv,
8659 * So if we truncate and then write and fsync we normally would just
8660 * write the extents that changed, which is a problem if we need to
8661 * first truncate that entire inode. So set this flag so we write out
8662 * all of the extents in the inode to the sync log so we're completely
8665 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &BTRFS_I(inode)->runtime_flags);
8666 trans->block_rsv = rsv;
8669 ret = btrfs_truncate_inode_items(trans, root, inode,
8671 BTRFS_EXTENT_DATA_KEY);
8672 trans->block_rsv = &fs_info->trans_block_rsv;
8673 if (ret != -ENOSPC && ret != -EAGAIN)
8676 ret = btrfs_update_inode(trans, root, inode);
8680 btrfs_end_transaction(trans);
8681 btrfs_btree_balance_dirty(fs_info);
8683 trans = btrfs_start_transaction(root, 2);
8684 if (IS_ERR(trans)) {
8685 ret = PTR_ERR(trans);
8690 btrfs_block_rsv_release(fs_info, rsv, -1, NULL);
8691 ret = btrfs_block_rsv_migrate(&fs_info->trans_block_rsv,
8692 rsv, min_size, false);
8693 BUG_ON(ret); /* shouldn't happen */
8694 trans->block_rsv = rsv;
8698 * We can't call btrfs_truncate_block inside a trans handle as we could
8699 * deadlock with freeze, if we got NEED_TRUNCATE_BLOCK then we know
8700 * we've truncated everything except the last little bit, and can do
8701 * btrfs_truncate_block and then update the disk_i_size.
8703 if (ret == NEED_TRUNCATE_BLOCK) {
8704 btrfs_end_transaction(trans);
8705 btrfs_btree_balance_dirty(fs_info);
8707 ret = btrfs_truncate_block(inode, inode->i_size, 0, 0);
8710 trans = btrfs_start_transaction(root, 1);
8711 if (IS_ERR(trans)) {
8712 ret = PTR_ERR(trans);
8715 btrfs_inode_safe_disk_i_size_write(inode, 0);
8721 trans->block_rsv = &fs_info->trans_block_rsv;
8722 ret2 = btrfs_update_inode(trans, root, inode);
8726 ret2 = btrfs_end_transaction(trans);
8729 btrfs_btree_balance_dirty(fs_info);
8732 btrfs_free_block_rsv(fs_info, rsv);
8738 * create a new subvolume directory/inode (helper for the ioctl).
8740 int btrfs_create_subvol_root(struct btrfs_trans_handle *trans,
8741 struct btrfs_root *new_root,
8742 struct btrfs_root *parent_root,
8745 struct inode *inode;
8749 inode = btrfs_new_inode(trans, new_root, NULL, "..", 2,
8750 new_dirid, new_dirid,
8751 S_IFDIR | (~current_umask() & S_IRWXUGO),
8754 return PTR_ERR(inode);
8755 inode->i_op = &btrfs_dir_inode_operations;
8756 inode->i_fop = &btrfs_dir_file_operations;
8758 set_nlink(inode, 1);
8759 btrfs_i_size_write(BTRFS_I(inode), 0);
8760 unlock_new_inode(inode);
8762 err = btrfs_subvol_inherit_props(trans, new_root, parent_root);
8764 btrfs_err(new_root->fs_info,
8765 "error inheriting subvolume %llu properties: %d",
8766 new_root->root_key.objectid, err);
8768 err = btrfs_update_inode(trans, new_root, inode);
8774 struct inode *btrfs_alloc_inode(struct super_block *sb)
8776 struct btrfs_fs_info *fs_info = btrfs_sb(sb);
8777 struct btrfs_inode *ei;
8778 struct inode *inode;
8780 ei = kmem_cache_alloc(btrfs_inode_cachep, GFP_KERNEL);
8787 ei->last_sub_trans = 0;
8788 ei->logged_trans = 0;
8789 ei->delalloc_bytes = 0;
8790 ei->new_delalloc_bytes = 0;
8791 ei->defrag_bytes = 0;
8792 ei->disk_i_size = 0;
8795 ei->index_cnt = (u64)-1;
8797 ei->last_unlink_trans = 0;
8798 ei->last_log_commit = 0;
8800 spin_lock_init(&ei->lock);
8801 ei->outstanding_extents = 0;
8802 if (sb->s_magic != BTRFS_TEST_MAGIC)
8803 btrfs_init_metadata_block_rsv(fs_info, &ei->block_rsv,
8804 BTRFS_BLOCK_RSV_DELALLOC);
8805 ei->runtime_flags = 0;
8806 ei->prop_compress = BTRFS_COMPRESS_NONE;
8807 ei->defrag_compress = BTRFS_COMPRESS_NONE;
8809 ei->delayed_node = NULL;
8811 ei->i_otime.tv_sec = 0;
8812 ei->i_otime.tv_nsec = 0;
8814 inode = &ei->vfs_inode;
8815 extent_map_tree_init(&ei->extent_tree);
8816 extent_io_tree_init(fs_info, &ei->io_tree, IO_TREE_INODE_IO, inode);
8817 extent_io_tree_init(fs_info, &ei->io_failure_tree,
8818 IO_TREE_INODE_IO_FAILURE, inode);
8819 extent_io_tree_init(fs_info, &ei->file_extent_tree,
8820 IO_TREE_INODE_FILE_EXTENT, inode);
8821 ei->io_tree.track_uptodate = true;
8822 ei->io_failure_tree.track_uptodate = true;
8823 atomic_set(&ei->sync_writers, 0);
8824 mutex_init(&ei->log_mutex);
8825 btrfs_ordered_inode_tree_init(&ei->ordered_tree);
8826 INIT_LIST_HEAD(&ei->delalloc_inodes);
8827 INIT_LIST_HEAD(&ei->delayed_iput);
8828 RB_CLEAR_NODE(&ei->rb_node);
8829 init_rwsem(&ei->dio_sem);
8834 #ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
8835 void btrfs_test_destroy_inode(struct inode *inode)
8837 btrfs_drop_extent_cache(BTRFS_I(inode), 0, (u64)-1, 0);
8838 kmem_cache_free(btrfs_inode_cachep, BTRFS_I(inode));
8842 void btrfs_free_inode(struct inode *inode)
8844 kmem_cache_free(btrfs_inode_cachep, BTRFS_I(inode));
8847 void btrfs_destroy_inode(struct inode *inode)
8849 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
8850 struct btrfs_ordered_extent *ordered;
8851 struct btrfs_root *root = BTRFS_I(inode)->root;
8853 WARN_ON(!hlist_empty(&inode->i_dentry));
8854 WARN_ON(inode->i_data.nrpages);
8855 WARN_ON(BTRFS_I(inode)->block_rsv.reserved);
8856 WARN_ON(BTRFS_I(inode)->block_rsv.size);
8857 WARN_ON(BTRFS_I(inode)->outstanding_extents);
8858 WARN_ON(BTRFS_I(inode)->delalloc_bytes);
8859 WARN_ON(BTRFS_I(inode)->new_delalloc_bytes);
8860 WARN_ON(BTRFS_I(inode)->csum_bytes);
8861 WARN_ON(BTRFS_I(inode)->defrag_bytes);
8864 * This can happen where we create an inode, but somebody else also
8865 * created the same inode and we need to destroy the one we already
8872 ordered = btrfs_lookup_first_ordered_extent(inode, (u64)-1);
8877 "found ordered extent %llu %llu on inode cleanup",
8878 ordered->file_offset, ordered->num_bytes);
8879 btrfs_remove_ordered_extent(inode, ordered);
8880 btrfs_put_ordered_extent(ordered);
8881 btrfs_put_ordered_extent(ordered);
8884 btrfs_qgroup_check_reserved_leak(inode);
8885 inode_tree_del(inode);
8886 btrfs_drop_extent_cache(BTRFS_I(inode), 0, (u64)-1, 0);
8887 btrfs_inode_clear_file_extent_range(BTRFS_I(inode), 0, (u64)-1);
8888 btrfs_put_root(BTRFS_I(inode)->root);
8891 int btrfs_drop_inode(struct inode *inode)
8893 struct btrfs_root *root = BTRFS_I(inode)->root;
8898 /* the snap/subvol tree is on deleting */
8899 if (btrfs_root_refs(&root->root_item) == 0)
8902 return generic_drop_inode(inode);
8905 static void init_once(void *foo)
8907 struct btrfs_inode *ei = (struct btrfs_inode *) foo;
8909 inode_init_once(&ei->vfs_inode);
8912 void __cold btrfs_destroy_cachep(void)
8915 * Make sure all delayed rcu free inodes are flushed before we
8919 kmem_cache_destroy(btrfs_inode_cachep);
8920 kmem_cache_destroy(btrfs_trans_handle_cachep);
8921 kmem_cache_destroy(btrfs_path_cachep);
8922 kmem_cache_destroy(btrfs_free_space_cachep);
8923 kmem_cache_destroy(btrfs_free_space_bitmap_cachep);
8926 int __init btrfs_init_cachep(void)
8928 btrfs_inode_cachep = kmem_cache_create("btrfs_inode",
8929 sizeof(struct btrfs_inode), 0,
8930 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD | SLAB_ACCOUNT,
8932 if (!btrfs_inode_cachep)
8935 btrfs_trans_handle_cachep = kmem_cache_create("btrfs_trans_handle",
8936 sizeof(struct btrfs_trans_handle), 0,
8937 SLAB_TEMPORARY | SLAB_MEM_SPREAD, NULL);
8938 if (!btrfs_trans_handle_cachep)
8941 btrfs_path_cachep = kmem_cache_create("btrfs_path",
8942 sizeof(struct btrfs_path), 0,
8943 SLAB_MEM_SPREAD, NULL);
8944 if (!btrfs_path_cachep)
8947 btrfs_free_space_cachep = kmem_cache_create("btrfs_free_space",
8948 sizeof(struct btrfs_free_space), 0,
8949 SLAB_MEM_SPREAD, NULL);
8950 if (!btrfs_free_space_cachep)
8953 btrfs_free_space_bitmap_cachep = kmem_cache_create("btrfs_free_space_bitmap",
8954 PAGE_SIZE, PAGE_SIZE,
8955 SLAB_RED_ZONE, NULL);
8956 if (!btrfs_free_space_bitmap_cachep)
8961 btrfs_destroy_cachep();
8965 static int btrfs_getattr(const struct path *path, struct kstat *stat,
8966 u32 request_mask, unsigned int flags)
8969 struct inode *inode = d_inode(path->dentry);
8970 u32 blocksize = inode->i_sb->s_blocksize;
8971 u32 bi_flags = BTRFS_I(inode)->flags;
8973 stat->result_mask |= STATX_BTIME;
8974 stat->btime.tv_sec = BTRFS_I(inode)->i_otime.tv_sec;
8975 stat->btime.tv_nsec = BTRFS_I(inode)->i_otime.tv_nsec;
8976 if (bi_flags & BTRFS_INODE_APPEND)
8977 stat->attributes |= STATX_ATTR_APPEND;
8978 if (bi_flags & BTRFS_INODE_COMPRESS)
8979 stat->attributes |= STATX_ATTR_COMPRESSED;
8980 if (bi_flags & BTRFS_INODE_IMMUTABLE)
8981 stat->attributes |= STATX_ATTR_IMMUTABLE;
8982 if (bi_flags & BTRFS_INODE_NODUMP)
8983 stat->attributes |= STATX_ATTR_NODUMP;
8985 stat->attributes_mask |= (STATX_ATTR_APPEND |
8986 STATX_ATTR_COMPRESSED |
8987 STATX_ATTR_IMMUTABLE |
8990 generic_fillattr(inode, stat);
8991 stat->dev = BTRFS_I(inode)->root->anon_dev;
8993 spin_lock(&BTRFS_I(inode)->lock);
8994 delalloc_bytes = BTRFS_I(inode)->new_delalloc_bytes;
8995 spin_unlock(&BTRFS_I(inode)->lock);
8996 stat->blocks = (ALIGN(inode_get_bytes(inode), blocksize) +
8997 ALIGN(delalloc_bytes, blocksize)) >> 9;
9001 static int btrfs_rename_exchange(struct inode *old_dir,
9002 struct dentry *old_dentry,
9003 struct inode *new_dir,
9004 struct dentry *new_dentry)
9006 struct btrfs_fs_info *fs_info = btrfs_sb(old_dir->i_sb);
9007 struct btrfs_trans_handle *trans;
9008 struct btrfs_root *root = BTRFS_I(old_dir)->root;
9009 struct btrfs_root *dest = BTRFS_I(new_dir)->root;
9010 struct inode *new_inode = new_dentry->d_inode;
9011 struct inode *old_inode = old_dentry->d_inode;
9012 struct timespec64 ctime = current_time(old_inode);
9013 struct dentry *parent;
9014 u64 old_ino = btrfs_ino(BTRFS_I(old_inode));
9015 u64 new_ino = btrfs_ino(BTRFS_I(new_inode));
9019 bool root_log_pinned = false;
9020 bool dest_log_pinned = false;
9021 struct btrfs_log_ctx ctx_root;
9022 struct btrfs_log_ctx ctx_dest;
9023 bool sync_log_root = false;
9024 bool sync_log_dest = false;
9025 bool commit_transaction = false;
9027 /* we only allow rename subvolume link between subvolumes */
9028 if (old_ino != BTRFS_FIRST_FREE_OBJECTID && root != dest)
9031 btrfs_init_log_ctx(&ctx_root, old_inode);
9032 btrfs_init_log_ctx(&ctx_dest, new_inode);
9034 /* close the race window with snapshot create/destroy ioctl */
9035 if (old_ino == BTRFS_FIRST_FREE_OBJECTID ||
9036 new_ino == BTRFS_FIRST_FREE_OBJECTID)
9037 down_read(&fs_info->subvol_sem);
9040 * We want to reserve the absolute worst case amount of items. So if
9041 * both inodes are subvols and we need to unlink them then that would
9042 * require 4 item modifications, but if they are both normal inodes it
9043 * would require 5 item modifications, so we'll assume their normal
9044 * inodes. So 5 * 2 is 10, plus 2 for the new links, so 12 total items
9045 * should cover the worst case number of items we'll modify.
9047 trans = btrfs_start_transaction(root, 12);
9048 if (IS_ERR(trans)) {
9049 ret = PTR_ERR(trans);
9054 btrfs_record_root_in_trans(trans, dest);
9057 * We need to find a free sequence number both in the source and
9058 * in the destination directory for the exchange.
9060 ret = btrfs_set_inode_index(BTRFS_I(new_dir), &old_idx);
9063 ret = btrfs_set_inode_index(BTRFS_I(old_dir), &new_idx);
9067 BTRFS_I(old_inode)->dir_index = 0ULL;
9068 BTRFS_I(new_inode)->dir_index = 0ULL;
9070 /* Reference for the source. */
9071 if (old_ino == BTRFS_FIRST_FREE_OBJECTID) {
9072 /* force full log commit if subvolume involved. */
9073 btrfs_set_log_full_commit(trans);
9075 btrfs_pin_log_trans(root);
9076 root_log_pinned = true;
9077 ret = btrfs_insert_inode_ref(trans, dest,
9078 new_dentry->d_name.name,
9079 new_dentry->d_name.len,
9081 btrfs_ino(BTRFS_I(new_dir)),
9087 /* And now for the dest. */
9088 if (new_ino == BTRFS_FIRST_FREE_OBJECTID) {
9089 /* force full log commit if subvolume involved. */
9090 btrfs_set_log_full_commit(trans);
9092 btrfs_pin_log_trans(dest);
9093 dest_log_pinned = true;
9094 ret = btrfs_insert_inode_ref(trans, root,
9095 old_dentry->d_name.name,
9096 old_dentry->d_name.len,
9098 btrfs_ino(BTRFS_I(old_dir)),
9104 /* Update inode version and ctime/mtime. */
9105 inode_inc_iversion(old_dir);
9106 inode_inc_iversion(new_dir);
9107 inode_inc_iversion(old_inode);
9108 inode_inc_iversion(new_inode);
9109 old_dir->i_ctime = old_dir->i_mtime = ctime;
9110 new_dir->i_ctime = new_dir->i_mtime = ctime;
9111 old_inode->i_ctime = ctime;
9112 new_inode->i_ctime = ctime;
9114 if (old_dentry->d_parent != new_dentry->d_parent) {
9115 btrfs_record_unlink_dir(trans, BTRFS_I(old_dir),
9116 BTRFS_I(old_inode), 1);
9117 btrfs_record_unlink_dir(trans, BTRFS_I(new_dir),
9118 BTRFS_I(new_inode), 1);
9121 /* src is a subvolume */
9122 if (old_ino == BTRFS_FIRST_FREE_OBJECTID) {
9123 ret = btrfs_unlink_subvol(trans, old_dir, old_dentry);
9124 } else { /* src is an inode */
9125 ret = __btrfs_unlink_inode(trans, root, BTRFS_I(old_dir),
9126 BTRFS_I(old_dentry->d_inode),
9127 old_dentry->d_name.name,
9128 old_dentry->d_name.len);
9130 ret = btrfs_update_inode(trans, root, old_inode);
9133 btrfs_abort_transaction(trans, ret);
9137 /* dest is a subvolume */
9138 if (new_ino == BTRFS_FIRST_FREE_OBJECTID) {
9139 ret = btrfs_unlink_subvol(trans, new_dir, new_dentry);
9140 } else { /* dest is an inode */
9141 ret = __btrfs_unlink_inode(trans, dest, BTRFS_I(new_dir),
9142 BTRFS_I(new_dentry->d_inode),
9143 new_dentry->d_name.name,
9144 new_dentry->d_name.len);
9146 ret = btrfs_update_inode(trans, dest, new_inode);
9149 btrfs_abort_transaction(trans, ret);
9153 ret = btrfs_add_link(trans, BTRFS_I(new_dir), BTRFS_I(old_inode),
9154 new_dentry->d_name.name,
9155 new_dentry->d_name.len, 0, old_idx);
9157 btrfs_abort_transaction(trans, ret);
9161 ret = btrfs_add_link(trans, BTRFS_I(old_dir), BTRFS_I(new_inode),
9162 old_dentry->d_name.name,
9163 old_dentry->d_name.len, 0, new_idx);
9165 btrfs_abort_transaction(trans, ret);
9169 if (old_inode->i_nlink == 1)
9170 BTRFS_I(old_inode)->dir_index = old_idx;
9171 if (new_inode->i_nlink == 1)
9172 BTRFS_I(new_inode)->dir_index = new_idx;
9174 if (root_log_pinned) {
9175 parent = new_dentry->d_parent;
9176 ret = btrfs_log_new_name(trans, BTRFS_I(old_inode),
9177 BTRFS_I(old_dir), parent,
9179 if (ret == BTRFS_NEED_LOG_SYNC)
9180 sync_log_root = true;
9181 else if (ret == BTRFS_NEED_TRANS_COMMIT)
9182 commit_transaction = true;
9184 btrfs_end_log_trans(root);
9185 root_log_pinned = false;
9187 if (dest_log_pinned) {
9188 if (!commit_transaction) {
9189 parent = old_dentry->d_parent;
9190 ret = btrfs_log_new_name(trans, BTRFS_I(new_inode),
9191 BTRFS_I(new_dir), parent,
9193 if (ret == BTRFS_NEED_LOG_SYNC)
9194 sync_log_dest = true;
9195 else if (ret == BTRFS_NEED_TRANS_COMMIT)
9196 commit_transaction = true;
9199 btrfs_end_log_trans(dest);
9200 dest_log_pinned = false;
9204 * If we have pinned a log and an error happened, we unpin tasks
9205 * trying to sync the log and force them to fallback to a transaction
9206 * commit if the log currently contains any of the inodes involved in
9207 * this rename operation (to ensure we do not persist a log with an
9208 * inconsistent state for any of these inodes or leading to any
9209 * inconsistencies when replayed). If the transaction was aborted, the
9210 * abortion reason is propagated to userspace when attempting to commit
9211 * the transaction. If the log does not contain any of these inodes, we
9212 * allow the tasks to sync it.
9214 if (ret && (root_log_pinned || dest_log_pinned)) {
9215 if (btrfs_inode_in_log(BTRFS_I(old_dir), fs_info->generation) ||
9216 btrfs_inode_in_log(BTRFS_I(new_dir), fs_info->generation) ||
9217 btrfs_inode_in_log(BTRFS_I(old_inode), fs_info->generation) ||
9219 btrfs_inode_in_log(BTRFS_I(new_inode), fs_info->generation)))
9220 btrfs_set_log_full_commit(trans);
9222 if (root_log_pinned) {
9223 btrfs_end_log_trans(root);
9224 root_log_pinned = false;
9226 if (dest_log_pinned) {
9227 btrfs_end_log_trans(dest);
9228 dest_log_pinned = false;
9231 if (!ret && sync_log_root && !commit_transaction) {
9232 ret = btrfs_sync_log(trans, BTRFS_I(old_inode)->root,
9235 commit_transaction = true;
9237 if (!ret && sync_log_dest && !commit_transaction) {
9238 ret = btrfs_sync_log(trans, BTRFS_I(new_inode)->root,
9241 commit_transaction = true;
9243 if (commit_transaction) {
9245 * We may have set commit_transaction when logging the new name
9246 * in the destination root, in which case we left the source
9247 * root context in the list of log contextes. So make sure we
9248 * remove it to avoid invalid memory accesses, since the context
9249 * was allocated in our stack frame.
9251 if (sync_log_root) {
9252 mutex_lock(&root->log_mutex);
9253 list_del_init(&ctx_root.list);
9254 mutex_unlock(&root->log_mutex);
9256 ret = btrfs_commit_transaction(trans);
9260 ret2 = btrfs_end_transaction(trans);
9261 ret = ret ? ret : ret2;
9264 if (new_ino == BTRFS_FIRST_FREE_OBJECTID ||
9265 old_ino == BTRFS_FIRST_FREE_OBJECTID)
9266 up_read(&fs_info->subvol_sem);
9268 ASSERT(list_empty(&ctx_root.list));
9269 ASSERT(list_empty(&ctx_dest.list));
9274 static int btrfs_whiteout_for_rename(struct btrfs_trans_handle *trans,
9275 struct btrfs_root *root,
9277 struct dentry *dentry)
9280 struct inode *inode;
9284 ret = btrfs_find_free_ino(root, &objectid);
9288 inode = btrfs_new_inode(trans, root, dir,
9289 dentry->d_name.name,
9291 btrfs_ino(BTRFS_I(dir)),
9293 S_IFCHR | WHITEOUT_MODE,
9296 if (IS_ERR(inode)) {
9297 ret = PTR_ERR(inode);
9301 inode->i_op = &btrfs_special_inode_operations;
9302 init_special_inode(inode, inode->i_mode,
9305 ret = btrfs_init_inode_security(trans, inode, dir,
9310 ret = btrfs_add_nondir(trans, BTRFS_I(dir), dentry,
9311 BTRFS_I(inode), 0, index);
9315 ret = btrfs_update_inode(trans, root, inode);
9317 unlock_new_inode(inode);
9319 inode_dec_link_count(inode);
9325 static int btrfs_rename(struct inode *old_dir, struct dentry *old_dentry,
9326 struct inode *new_dir, struct dentry *new_dentry,
9329 struct btrfs_fs_info *fs_info = btrfs_sb(old_dir->i_sb);
9330 struct btrfs_trans_handle *trans;
9331 unsigned int trans_num_items;
9332 struct btrfs_root *root = BTRFS_I(old_dir)->root;
9333 struct btrfs_root *dest = BTRFS_I(new_dir)->root;
9334 struct inode *new_inode = d_inode(new_dentry);
9335 struct inode *old_inode = d_inode(old_dentry);
9338 u64 old_ino = btrfs_ino(BTRFS_I(old_inode));
9339 bool log_pinned = false;
9340 struct btrfs_log_ctx ctx;
9341 bool sync_log = false;
9342 bool commit_transaction = false;
9344 if (btrfs_ino(BTRFS_I(new_dir)) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)
9347 /* we only allow rename subvolume link between subvolumes */
9348 if (old_ino != BTRFS_FIRST_FREE_OBJECTID && root != dest)
9351 if (old_ino == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID ||
9352 (new_inode && btrfs_ino(BTRFS_I(new_inode)) == BTRFS_FIRST_FREE_OBJECTID))
9355 if (S_ISDIR(old_inode->i_mode) && new_inode &&
9356 new_inode->i_size > BTRFS_EMPTY_DIR_SIZE)
9360 /* check for collisions, even if the name isn't there */
9361 ret = btrfs_check_dir_item_collision(dest, new_dir->i_ino,
9362 new_dentry->d_name.name,
9363 new_dentry->d_name.len);
9366 if (ret == -EEXIST) {
9368 * eexist without a new_inode */
9369 if (WARN_ON(!new_inode)) {
9373 /* maybe -EOVERFLOW */
9380 * we're using rename to replace one file with another. Start IO on it
9381 * now so we don't add too much work to the end of the transaction
9383 if (new_inode && S_ISREG(old_inode->i_mode) && new_inode->i_size)
9384 filemap_flush(old_inode->i_mapping);
9386 /* close the racy window with snapshot create/destroy ioctl */
9387 if (old_ino == BTRFS_FIRST_FREE_OBJECTID)
9388 down_read(&fs_info->subvol_sem);
9390 * We want to reserve the absolute worst case amount of items. So if
9391 * both inodes are subvols and we need to unlink them then that would
9392 * require 4 item modifications, but if they are both normal inodes it
9393 * would require 5 item modifications, so we'll assume they are normal
9394 * inodes. So 5 * 2 is 10, plus 1 for the new link, so 11 total items
9395 * should cover the worst case number of items we'll modify.
9396 * If our rename has the whiteout flag, we need more 5 units for the
9397 * new inode (1 inode item, 1 inode ref, 2 dir items and 1 xattr item
9398 * when selinux is enabled).
9400 trans_num_items = 11;
9401 if (flags & RENAME_WHITEOUT)
9402 trans_num_items += 5;
9403 trans = btrfs_start_transaction(root, trans_num_items);
9404 if (IS_ERR(trans)) {
9405 ret = PTR_ERR(trans);
9410 btrfs_record_root_in_trans(trans, dest);
9412 ret = btrfs_set_inode_index(BTRFS_I(new_dir), &index);
9416 BTRFS_I(old_inode)->dir_index = 0ULL;
9417 if (unlikely(old_ino == BTRFS_FIRST_FREE_OBJECTID)) {
9418 /* force full log commit if subvolume involved. */
9419 btrfs_set_log_full_commit(trans);
9421 btrfs_pin_log_trans(root);
9423 ret = btrfs_insert_inode_ref(trans, dest,
9424 new_dentry->d_name.name,
9425 new_dentry->d_name.len,
9427 btrfs_ino(BTRFS_I(new_dir)), index);
9432 inode_inc_iversion(old_dir);
9433 inode_inc_iversion(new_dir);
9434 inode_inc_iversion(old_inode);
9435 old_dir->i_ctime = old_dir->i_mtime =
9436 new_dir->i_ctime = new_dir->i_mtime =
9437 old_inode->i_ctime = current_time(old_dir);
9439 if (old_dentry->d_parent != new_dentry->d_parent)
9440 btrfs_record_unlink_dir(trans, BTRFS_I(old_dir),
9441 BTRFS_I(old_inode), 1);
9443 if (unlikely(old_ino == BTRFS_FIRST_FREE_OBJECTID)) {
9444 ret = btrfs_unlink_subvol(trans, old_dir, old_dentry);
9446 ret = __btrfs_unlink_inode(trans, root, BTRFS_I(old_dir),
9447 BTRFS_I(d_inode(old_dentry)),
9448 old_dentry->d_name.name,
9449 old_dentry->d_name.len);
9451 ret = btrfs_update_inode(trans, root, old_inode);
9454 btrfs_abort_transaction(trans, ret);
9459 inode_inc_iversion(new_inode);
9460 new_inode->i_ctime = current_time(new_inode);
9461 if (unlikely(btrfs_ino(BTRFS_I(new_inode)) ==
9462 BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)) {
9463 ret = btrfs_unlink_subvol(trans, new_dir, new_dentry);
9464 BUG_ON(new_inode->i_nlink == 0);
9466 ret = btrfs_unlink_inode(trans, dest, BTRFS_I(new_dir),
9467 BTRFS_I(d_inode(new_dentry)),
9468 new_dentry->d_name.name,
9469 new_dentry->d_name.len);
9471 if (!ret && new_inode->i_nlink == 0)
9472 ret = btrfs_orphan_add(trans,
9473 BTRFS_I(d_inode(new_dentry)));
9475 btrfs_abort_transaction(trans, ret);
9480 ret = btrfs_add_link(trans, BTRFS_I(new_dir), BTRFS_I(old_inode),
9481 new_dentry->d_name.name,
9482 new_dentry->d_name.len, 0, index);
9484 btrfs_abort_transaction(trans, ret);
9488 if (old_inode->i_nlink == 1)
9489 BTRFS_I(old_inode)->dir_index = index;
9492 struct dentry *parent = new_dentry->d_parent;
9494 btrfs_init_log_ctx(&ctx, old_inode);
9495 ret = btrfs_log_new_name(trans, BTRFS_I(old_inode),
9496 BTRFS_I(old_dir), parent,
9498 if (ret == BTRFS_NEED_LOG_SYNC)
9500 else if (ret == BTRFS_NEED_TRANS_COMMIT)
9501 commit_transaction = true;
9503 btrfs_end_log_trans(root);
9507 if (flags & RENAME_WHITEOUT) {
9508 ret = btrfs_whiteout_for_rename(trans, root, old_dir,
9512 btrfs_abort_transaction(trans, ret);
9518 * If we have pinned the log and an error happened, we unpin tasks
9519 * trying to sync the log and force them to fallback to a transaction
9520 * commit if the log currently contains any of the inodes involved in
9521 * this rename operation (to ensure we do not persist a log with an
9522 * inconsistent state for any of these inodes or leading to any
9523 * inconsistencies when replayed). If the transaction was aborted, the
9524 * abortion reason is propagated to userspace when attempting to commit
9525 * the transaction. If the log does not contain any of these inodes, we
9526 * allow the tasks to sync it.
9528 if (ret && log_pinned) {
9529 if (btrfs_inode_in_log(BTRFS_I(old_dir), fs_info->generation) ||
9530 btrfs_inode_in_log(BTRFS_I(new_dir), fs_info->generation) ||
9531 btrfs_inode_in_log(BTRFS_I(old_inode), fs_info->generation) ||
9533 btrfs_inode_in_log(BTRFS_I(new_inode), fs_info->generation)))
9534 btrfs_set_log_full_commit(trans);
9536 btrfs_end_log_trans(root);
9539 if (!ret && sync_log) {
9540 ret = btrfs_sync_log(trans, BTRFS_I(old_inode)->root, &ctx);
9542 commit_transaction = true;
9543 } else if (sync_log) {
9544 mutex_lock(&root->log_mutex);
9545 list_del(&ctx.list);
9546 mutex_unlock(&root->log_mutex);
9548 if (commit_transaction) {
9549 ret = btrfs_commit_transaction(trans);
9553 ret2 = btrfs_end_transaction(trans);
9554 ret = ret ? ret : ret2;
9557 if (old_ino == BTRFS_FIRST_FREE_OBJECTID)
9558 up_read(&fs_info->subvol_sem);
9563 static int btrfs_rename2(struct inode *old_dir, struct dentry *old_dentry,
9564 struct inode *new_dir, struct dentry *new_dentry,
9567 if (flags & ~(RENAME_NOREPLACE | RENAME_EXCHANGE | RENAME_WHITEOUT))
9570 if (flags & RENAME_EXCHANGE)
9571 return btrfs_rename_exchange(old_dir, old_dentry, new_dir,
9574 return btrfs_rename(old_dir, old_dentry, new_dir, new_dentry, flags);
9577 struct btrfs_delalloc_work {
9578 struct inode *inode;
9579 struct completion completion;
9580 struct list_head list;
9581 struct btrfs_work work;
9584 static void btrfs_run_delalloc_work(struct btrfs_work *work)
9586 struct btrfs_delalloc_work *delalloc_work;
9587 struct inode *inode;
9589 delalloc_work = container_of(work, struct btrfs_delalloc_work,
9591 inode = delalloc_work->inode;
9592 filemap_flush(inode->i_mapping);
9593 if (test_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
9594 &BTRFS_I(inode)->runtime_flags))
9595 filemap_flush(inode->i_mapping);
9598 complete(&delalloc_work->completion);
9601 static struct btrfs_delalloc_work *btrfs_alloc_delalloc_work(struct inode *inode)
9603 struct btrfs_delalloc_work *work;
9605 work = kmalloc(sizeof(*work), GFP_NOFS);
9609 init_completion(&work->completion);
9610 INIT_LIST_HEAD(&work->list);
9611 work->inode = inode;
9612 btrfs_init_work(&work->work, btrfs_run_delalloc_work, NULL, NULL);
9618 * some fairly slow code that needs optimization. This walks the list
9619 * of all the inodes with pending delalloc and forces them to disk.
9621 static int start_delalloc_inodes(struct btrfs_root *root, int nr, bool snapshot)
9623 struct btrfs_inode *binode;
9624 struct inode *inode;
9625 struct btrfs_delalloc_work *work, *next;
9626 struct list_head works;
9627 struct list_head splice;
9630 INIT_LIST_HEAD(&works);
9631 INIT_LIST_HEAD(&splice);
9633 mutex_lock(&root->delalloc_mutex);
9634 spin_lock(&root->delalloc_lock);
9635 list_splice_init(&root->delalloc_inodes, &splice);
9636 while (!list_empty(&splice)) {
9637 binode = list_entry(splice.next, struct btrfs_inode,
9640 list_move_tail(&binode->delalloc_inodes,
9641 &root->delalloc_inodes);
9642 inode = igrab(&binode->vfs_inode);
9644 cond_resched_lock(&root->delalloc_lock);
9647 spin_unlock(&root->delalloc_lock);
9650 set_bit(BTRFS_INODE_SNAPSHOT_FLUSH,
9651 &binode->runtime_flags);
9652 work = btrfs_alloc_delalloc_work(inode);
9658 list_add_tail(&work->list, &works);
9659 btrfs_queue_work(root->fs_info->flush_workers,
9662 if (nr != -1 && ret >= nr)
9665 spin_lock(&root->delalloc_lock);
9667 spin_unlock(&root->delalloc_lock);
9670 list_for_each_entry_safe(work, next, &works, list) {
9671 list_del_init(&work->list);
9672 wait_for_completion(&work->completion);
9676 if (!list_empty(&splice)) {
9677 spin_lock(&root->delalloc_lock);
9678 list_splice_tail(&splice, &root->delalloc_inodes);
9679 spin_unlock(&root->delalloc_lock);
9681 mutex_unlock(&root->delalloc_mutex);
9685 int btrfs_start_delalloc_snapshot(struct btrfs_root *root)
9687 struct btrfs_fs_info *fs_info = root->fs_info;
9690 if (test_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state))
9693 ret = start_delalloc_inodes(root, -1, true);
9699 int btrfs_start_delalloc_roots(struct btrfs_fs_info *fs_info, int nr)
9701 struct btrfs_root *root;
9702 struct list_head splice;
9705 if (test_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state))
9708 INIT_LIST_HEAD(&splice);
9710 mutex_lock(&fs_info->delalloc_root_mutex);
9711 spin_lock(&fs_info->delalloc_root_lock);
9712 list_splice_init(&fs_info->delalloc_roots, &splice);
9713 while (!list_empty(&splice) && nr) {
9714 root = list_first_entry(&splice, struct btrfs_root,
9716 root = btrfs_grab_root(root);
9718 list_move_tail(&root->delalloc_root,
9719 &fs_info->delalloc_roots);
9720 spin_unlock(&fs_info->delalloc_root_lock);
9722 ret = start_delalloc_inodes(root, nr, false);
9723 btrfs_put_root(root);
9731 spin_lock(&fs_info->delalloc_root_lock);
9733 spin_unlock(&fs_info->delalloc_root_lock);
9737 if (!list_empty(&splice)) {
9738 spin_lock(&fs_info->delalloc_root_lock);
9739 list_splice_tail(&splice, &fs_info->delalloc_roots);
9740 spin_unlock(&fs_info->delalloc_root_lock);
9742 mutex_unlock(&fs_info->delalloc_root_mutex);
9746 static int btrfs_symlink(struct inode *dir, struct dentry *dentry,
9747 const char *symname)
9749 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
9750 struct btrfs_trans_handle *trans;
9751 struct btrfs_root *root = BTRFS_I(dir)->root;
9752 struct btrfs_path *path;
9753 struct btrfs_key key;
9754 struct inode *inode = NULL;
9761 struct btrfs_file_extent_item *ei;
9762 struct extent_buffer *leaf;
9764 name_len = strlen(symname);
9765 if (name_len > BTRFS_MAX_INLINE_DATA_SIZE(fs_info))
9766 return -ENAMETOOLONG;
9769 * 2 items for inode item and ref
9770 * 2 items for dir items
9771 * 1 item for updating parent inode item
9772 * 1 item for the inline extent item
9773 * 1 item for xattr if selinux is on
9775 trans = btrfs_start_transaction(root, 7);
9777 return PTR_ERR(trans);
9779 err = btrfs_find_free_ino(root, &objectid);
9783 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
9784 dentry->d_name.len, btrfs_ino(BTRFS_I(dir)),
9785 objectid, S_IFLNK|S_IRWXUGO, &index);
9786 if (IS_ERR(inode)) {
9787 err = PTR_ERR(inode);
9793 * If the active LSM wants to access the inode during
9794 * d_instantiate it needs these. Smack checks to see
9795 * if the filesystem supports xattrs by looking at the
9798 inode->i_fop = &btrfs_file_operations;
9799 inode->i_op = &btrfs_file_inode_operations;
9800 inode->i_mapping->a_ops = &btrfs_aops;
9801 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
9803 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
9807 path = btrfs_alloc_path();
9812 key.objectid = btrfs_ino(BTRFS_I(inode));
9814 key.type = BTRFS_EXTENT_DATA_KEY;
9815 datasize = btrfs_file_extent_calc_inline_size(name_len);
9816 err = btrfs_insert_empty_item(trans, root, path, &key,
9819 btrfs_free_path(path);
9822 leaf = path->nodes[0];
9823 ei = btrfs_item_ptr(leaf, path->slots[0],
9824 struct btrfs_file_extent_item);
9825 btrfs_set_file_extent_generation(leaf, ei, trans->transid);
9826 btrfs_set_file_extent_type(leaf, ei,
9827 BTRFS_FILE_EXTENT_INLINE);
9828 btrfs_set_file_extent_encryption(leaf, ei, 0);
9829 btrfs_set_file_extent_compression(leaf, ei, 0);
9830 btrfs_set_file_extent_other_encoding(leaf, ei, 0);
9831 btrfs_set_file_extent_ram_bytes(leaf, ei, name_len);
9833 ptr = btrfs_file_extent_inline_start(ei);
9834 write_extent_buffer(leaf, symname, ptr, name_len);
9835 btrfs_mark_buffer_dirty(leaf);
9836 btrfs_free_path(path);
9838 inode->i_op = &btrfs_symlink_inode_operations;
9839 inode_nohighmem(inode);
9840 inode_set_bytes(inode, name_len);
9841 btrfs_i_size_write(BTRFS_I(inode), name_len);
9842 err = btrfs_update_inode(trans, root, inode);
9844 * Last step, add directory indexes for our symlink inode. This is the
9845 * last step to avoid extra cleanup of these indexes if an error happens
9849 err = btrfs_add_nondir(trans, BTRFS_I(dir), dentry,
9850 BTRFS_I(inode), 0, index);
9854 d_instantiate_new(dentry, inode);
9857 btrfs_end_transaction(trans);
9859 inode_dec_link_count(inode);
9860 discard_new_inode(inode);
9862 btrfs_btree_balance_dirty(fs_info);
9866 static int __btrfs_prealloc_file_range(struct inode *inode, int mode,
9867 u64 start, u64 num_bytes, u64 min_size,
9868 loff_t actual_len, u64 *alloc_hint,
9869 struct btrfs_trans_handle *trans)
9871 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
9872 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
9873 struct extent_map *em;
9874 struct btrfs_root *root = BTRFS_I(inode)->root;
9875 struct btrfs_key ins;
9876 u64 cur_offset = start;
9877 u64 clear_offset = start;
9880 u64 last_alloc = (u64)-1;
9882 bool own_trans = true;
9883 u64 end = start + num_bytes - 1;
9887 while (num_bytes > 0) {
9889 trans = btrfs_start_transaction(root, 3);
9890 if (IS_ERR(trans)) {
9891 ret = PTR_ERR(trans);
9896 cur_bytes = min_t(u64, num_bytes, SZ_256M);
9897 cur_bytes = max(cur_bytes, min_size);
9899 * If we are severely fragmented we could end up with really
9900 * small allocations, so if the allocator is returning small
9901 * chunks lets make its job easier by only searching for those
9904 cur_bytes = min(cur_bytes, last_alloc);
9905 ret = btrfs_reserve_extent(root, cur_bytes, cur_bytes,
9906 min_size, 0, *alloc_hint, &ins, 1, 0);
9909 btrfs_end_transaction(trans);
9914 * We've reserved this space, and thus converted it from
9915 * ->bytes_may_use to ->bytes_reserved. Any error that happens
9916 * from here on out we will only need to clear our reservation
9917 * for the remaining unreserved area, so advance our
9918 * clear_offset by our extent size.
9920 clear_offset += ins.offset;
9921 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
9923 last_alloc = ins.offset;
9924 ret = insert_reserved_file_extent(trans, inode,
9925 cur_offset, ins.objectid,
9926 ins.offset, ins.offset,
9927 ins.offset, 0, 0, 0,
9928 BTRFS_FILE_EXTENT_PREALLOC);
9930 btrfs_free_reserved_extent(fs_info, ins.objectid,
9932 btrfs_abort_transaction(trans, ret);
9934 btrfs_end_transaction(trans);
9938 btrfs_drop_extent_cache(BTRFS_I(inode), cur_offset,
9939 cur_offset + ins.offset -1, 0);
9941 em = alloc_extent_map();
9943 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
9944 &BTRFS_I(inode)->runtime_flags);
9948 em->start = cur_offset;
9949 em->orig_start = cur_offset;
9950 em->len = ins.offset;
9951 em->block_start = ins.objectid;
9952 em->block_len = ins.offset;
9953 em->orig_block_len = ins.offset;
9954 em->ram_bytes = ins.offset;
9955 set_bit(EXTENT_FLAG_PREALLOC, &em->flags);
9956 em->generation = trans->transid;
9959 write_lock(&em_tree->lock);
9960 ret = add_extent_mapping(em_tree, em, 1);
9961 write_unlock(&em_tree->lock);
9964 btrfs_drop_extent_cache(BTRFS_I(inode), cur_offset,
9965 cur_offset + ins.offset - 1,
9968 free_extent_map(em);
9970 num_bytes -= ins.offset;
9971 cur_offset += ins.offset;
9972 *alloc_hint = ins.objectid + ins.offset;
9974 inode_inc_iversion(inode);
9975 inode->i_ctime = current_time(inode);
9976 BTRFS_I(inode)->flags |= BTRFS_INODE_PREALLOC;
9977 if (!(mode & FALLOC_FL_KEEP_SIZE) &&
9978 (actual_len > inode->i_size) &&
9979 (cur_offset > inode->i_size)) {
9980 if (cur_offset > actual_len)
9981 i_size = actual_len;
9983 i_size = cur_offset;
9984 i_size_write(inode, i_size);
9985 btrfs_inode_safe_disk_i_size_write(inode, 0);
9988 ret = btrfs_update_inode(trans, root, inode);
9991 btrfs_abort_transaction(trans, ret);
9993 btrfs_end_transaction(trans);
9998 btrfs_end_transaction(trans);
10000 if (clear_offset < end)
10001 btrfs_free_reserved_data_space(inode, NULL, clear_offset,
10002 end - clear_offset + 1);
10006 int btrfs_prealloc_file_range(struct inode *inode, int mode,
10007 u64 start, u64 num_bytes, u64 min_size,
10008 loff_t actual_len, u64 *alloc_hint)
10010 return __btrfs_prealloc_file_range(inode, mode, start, num_bytes,
10011 min_size, actual_len, alloc_hint,
10015 int btrfs_prealloc_file_range_trans(struct inode *inode,
10016 struct btrfs_trans_handle *trans, int mode,
10017 u64 start, u64 num_bytes, u64 min_size,
10018 loff_t actual_len, u64 *alloc_hint)
10020 return __btrfs_prealloc_file_range(inode, mode, start, num_bytes,
10021 min_size, actual_len, alloc_hint, trans);
10024 static int btrfs_set_page_dirty(struct page *page)
10026 return __set_page_dirty_nobuffers(page);
10029 static int btrfs_permission(struct inode *inode, int mask)
10031 struct btrfs_root *root = BTRFS_I(inode)->root;
10032 umode_t mode = inode->i_mode;
10034 if (mask & MAY_WRITE &&
10035 (S_ISREG(mode) || S_ISDIR(mode) || S_ISLNK(mode))) {
10036 if (btrfs_root_readonly(root))
10038 if (BTRFS_I(inode)->flags & BTRFS_INODE_READONLY)
10041 return generic_permission(inode, mask);
10044 static int btrfs_tmpfile(struct inode *dir, struct dentry *dentry, umode_t mode)
10046 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
10047 struct btrfs_trans_handle *trans;
10048 struct btrfs_root *root = BTRFS_I(dir)->root;
10049 struct inode *inode = NULL;
10055 * 5 units required for adding orphan entry
10057 trans = btrfs_start_transaction(root, 5);
10059 return PTR_ERR(trans);
10061 ret = btrfs_find_free_ino(root, &objectid);
10065 inode = btrfs_new_inode(trans, root, dir, NULL, 0,
10066 btrfs_ino(BTRFS_I(dir)), objectid, mode, &index);
10067 if (IS_ERR(inode)) {
10068 ret = PTR_ERR(inode);
10073 inode->i_fop = &btrfs_file_operations;
10074 inode->i_op = &btrfs_file_inode_operations;
10076 inode->i_mapping->a_ops = &btrfs_aops;
10077 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
10079 ret = btrfs_init_inode_security(trans, inode, dir, NULL);
10083 ret = btrfs_update_inode(trans, root, inode);
10086 ret = btrfs_orphan_add(trans, BTRFS_I(inode));
10091 * We set number of links to 0 in btrfs_new_inode(), and here we set
10092 * it to 1 because d_tmpfile() will issue a warning if the count is 0,
10095 * d_tmpfile() -> inode_dec_link_count() -> drop_nlink()
10097 set_nlink(inode, 1);
10098 d_tmpfile(dentry, inode);
10099 unlock_new_inode(inode);
10100 mark_inode_dirty(inode);
10102 btrfs_end_transaction(trans);
10104 discard_new_inode(inode);
10105 btrfs_btree_balance_dirty(fs_info);
10109 void btrfs_set_range_writeback(struct extent_io_tree *tree, u64 start, u64 end)
10111 struct inode *inode = tree->private_data;
10112 unsigned long index = start >> PAGE_SHIFT;
10113 unsigned long end_index = end >> PAGE_SHIFT;
10116 while (index <= end_index) {
10117 page = find_get_page(inode->i_mapping, index);
10118 ASSERT(page); /* Pages should be in the extent_io_tree */
10119 set_page_writeback(page);
10127 * Add an entry indicating a block group or device which is pinned by a
10128 * swapfile. Returns 0 on success, 1 if there is already an entry for it, or a
10129 * negative errno on failure.
10131 static int btrfs_add_swapfile_pin(struct inode *inode, void *ptr,
10132 bool is_block_group)
10134 struct btrfs_fs_info *fs_info = BTRFS_I(inode)->root->fs_info;
10135 struct btrfs_swapfile_pin *sp, *entry;
10136 struct rb_node **p;
10137 struct rb_node *parent = NULL;
10139 sp = kmalloc(sizeof(*sp), GFP_NOFS);
10144 sp->is_block_group = is_block_group;
10146 spin_lock(&fs_info->swapfile_pins_lock);
10147 p = &fs_info->swapfile_pins.rb_node;
10150 entry = rb_entry(parent, struct btrfs_swapfile_pin, node);
10151 if (sp->ptr < entry->ptr ||
10152 (sp->ptr == entry->ptr && sp->inode < entry->inode)) {
10153 p = &(*p)->rb_left;
10154 } else if (sp->ptr > entry->ptr ||
10155 (sp->ptr == entry->ptr && sp->inode > entry->inode)) {
10156 p = &(*p)->rb_right;
10158 spin_unlock(&fs_info->swapfile_pins_lock);
10163 rb_link_node(&sp->node, parent, p);
10164 rb_insert_color(&sp->node, &fs_info->swapfile_pins);
10165 spin_unlock(&fs_info->swapfile_pins_lock);
10169 /* Free all of the entries pinned by this swapfile. */
10170 static void btrfs_free_swapfile_pins(struct inode *inode)
10172 struct btrfs_fs_info *fs_info = BTRFS_I(inode)->root->fs_info;
10173 struct btrfs_swapfile_pin *sp;
10174 struct rb_node *node, *next;
10176 spin_lock(&fs_info->swapfile_pins_lock);
10177 node = rb_first(&fs_info->swapfile_pins);
10179 next = rb_next(node);
10180 sp = rb_entry(node, struct btrfs_swapfile_pin, node);
10181 if (sp->inode == inode) {
10182 rb_erase(&sp->node, &fs_info->swapfile_pins);
10183 if (sp->is_block_group)
10184 btrfs_put_block_group(sp->ptr);
10189 spin_unlock(&fs_info->swapfile_pins_lock);
10192 struct btrfs_swap_info {
10198 unsigned long nr_pages;
10202 static int btrfs_add_swap_extent(struct swap_info_struct *sis,
10203 struct btrfs_swap_info *bsi)
10205 unsigned long nr_pages;
10206 u64 first_ppage, first_ppage_reported, next_ppage;
10209 first_ppage = ALIGN(bsi->block_start, PAGE_SIZE) >> PAGE_SHIFT;
10210 next_ppage = ALIGN_DOWN(bsi->block_start + bsi->block_len,
10211 PAGE_SIZE) >> PAGE_SHIFT;
10213 if (first_ppage >= next_ppage)
10215 nr_pages = next_ppage - first_ppage;
10217 first_ppage_reported = first_ppage;
10218 if (bsi->start == 0)
10219 first_ppage_reported++;
10220 if (bsi->lowest_ppage > first_ppage_reported)
10221 bsi->lowest_ppage = first_ppage_reported;
10222 if (bsi->highest_ppage < (next_ppage - 1))
10223 bsi->highest_ppage = next_ppage - 1;
10225 ret = add_swap_extent(sis, bsi->nr_pages, nr_pages, first_ppage);
10228 bsi->nr_extents += ret;
10229 bsi->nr_pages += nr_pages;
10233 static void btrfs_swap_deactivate(struct file *file)
10235 struct inode *inode = file_inode(file);
10237 btrfs_free_swapfile_pins(inode);
10238 atomic_dec(&BTRFS_I(inode)->root->nr_swapfiles);
10241 static int btrfs_swap_activate(struct swap_info_struct *sis, struct file *file,
10244 struct inode *inode = file_inode(file);
10245 struct btrfs_fs_info *fs_info = BTRFS_I(inode)->root->fs_info;
10246 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
10247 struct extent_state *cached_state = NULL;
10248 struct extent_map *em = NULL;
10249 struct btrfs_device *device = NULL;
10250 struct btrfs_swap_info bsi = {
10251 .lowest_ppage = (sector_t)-1ULL,
10258 * If the swap file was just created, make sure delalloc is done. If the
10259 * file changes again after this, the user is doing something stupid and
10260 * we don't really care.
10262 ret = btrfs_wait_ordered_range(inode, 0, (u64)-1);
10267 * The inode is locked, so these flags won't change after we check them.
10269 if (BTRFS_I(inode)->flags & BTRFS_INODE_COMPRESS) {
10270 btrfs_warn(fs_info, "swapfile must not be compressed");
10273 if (!(BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW)) {
10274 btrfs_warn(fs_info, "swapfile must not be copy-on-write");
10277 if (!(BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)) {
10278 btrfs_warn(fs_info, "swapfile must not be checksummed");
10283 * Balance or device remove/replace/resize can move stuff around from
10284 * under us. The EXCL_OP flag makes sure they aren't running/won't run
10285 * concurrently while we are mapping the swap extents, and
10286 * fs_info->swapfile_pins prevents them from running while the swap file
10287 * is active and moving the extents. Note that this also prevents a
10288 * concurrent device add which isn't actually necessary, but it's not
10289 * really worth the trouble to allow it.
10291 if (test_and_set_bit(BTRFS_FS_EXCL_OP, &fs_info->flags)) {
10292 btrfs_warn(fs_info,
10293 "cannot activate swapfile while exclusive operation is running");
10297 * Snapshots can create extents which require COW even if NODATACOW is
10298 * set. We use this counter to prevent snapshots. We must increment it
10299 * before walking the extents because we don't want a concurrent
10300 * snapshot to run after we've already checked the extents.
10302 atomic_inc(&BTRFS_I(inode)->root->nr_swapfiles);
10304 isize = ALIGN_DOWN(inode->i_size, fs_info->sectorsize);
10306 lock_extent_bits(io_tree, 0, isize - 1, &cached_state);
10308 while (start < isize) {
10309 u64 logical_block_start, physical_block_start;
10310 struct btrfs_block_group *bg;
10311 u64 len = isize - start;
10313 em = btrfs_get_extent(BTRFS_I(inode), NULL, 0, start, len);
10319 if (em->block_start == EXTENT_MAP_HOLE) {
10320 btrfs_warn(fs_info, "swapfile must not have holes");
10324 if (em->block_start == EXTENT_MAP_INLINE) {
10326 * It's unlikely we'll ever actually find ourselves
10327 * here, as a file small enough to fit inline won't be
10328 * big enough to store more than the swap header, but in
10329 * case something changes in the future, let's catch it
10330 * here rather than later.
10332 btrfs_warn(fs_info, "swapfile must not be inline");
10336 if (test_bit(EXTENT_FLAG_COMPRESSED, &em->flags)) {
10337 btrfs_warn(fs_info, "swapfile must not be compressed");
10342 logical_block_start = em->block_start + (start - em->start);
10343 len = min(len, em->len - (start - em->start));
10344 free_extent_map(em);
10347 ret = can_nocow_extent(inode, start, &len, NULL, NULL, NULL);
10353 btrfs_warn(fs_info,
10354 "swapfile must not be copy-on-write");
10359 em = btrfs_get_chunk_map(fs_info, logical_block_start, len);
10365 if (em->map_lookup->type & BTRFS_BLOCK_GROUP_PROFILE_MASK) {
10366 btrfs_warn(fs_info,
10367 "swapfile must have single data profile");
10372 if (device == NULL) {
10373 device = em->map_lookup->stripes[0].dev;
10374 ret = btrfs_add_swapfile_pin(inode, device, false);
10379 } else if (device != em->map_lookup->stripes[0].dev) {
10380 btrfs_warn(fs_info, "swapfile must be on one device");
10385 physical_block_start = (em->map_lookup->stripes[0].physical +
10386 (logical_block_start - em->start));
10387 len = min(len, em->len - (logical_block_start - em->start));
10388 free_extent_map(em);
10391 bg = btrfs_lookup_block_group(fs_info, logical_block_start);
10393 btrfs_warn(fs_info,
10394 "could not find block group containing swapfile");
10399 ret = btrfs_add_swapfile_pin(inode, bg, true);
10401 btrfs_put_block_group(bg);
10408 if (bsi.block_len &&
10409 bsi.block_start + bsi.block_len == physical_block_start) {
10410 bsi.block_len += len;
10412 if (bsi.block_len) {
10413 ret = btrfs_add_swap_extent(sis, &bsi);
10418 bsi.block_start = physical_block_start;
10419 bsi.block_len = len;
10426 ret = btrfs_add_swap_extent(sis, &bsi);
10429 if (!IS_ERR_OR_NULL(em))
10430 free_extent_map(em);
10432 unlock_extent_cached(io_tree, 0, isize - 1, &cached_state);
10435 btrfs_swap_deactivate(file);
10437 clear_bit(BTRFS_FS_EXCL_OP, &fs_info->flags);
10443 sis->bdev = device->bdev;
10444 *span = bsi.highest_ppage - bsi.lowest_ppage + 1;
10445 sis->max = bsi.nr_pages;
10446 sis->pages = bsi.nr_pages - 1;
10447 sis->highest_bit = bsi.nr_pages - 1;
10448 return bsi.nr_extents;
10451 static void btrfs_swap_deactivate(struct file *file)
10455 static int btrfs_swap_activate(struct swap_info_struct *sis, struct file *file,
10458 return -EOPNOTSUPP;
10462 static const struct inode_operations btrfs_dir_inode_operations = {
10463 .getattr = btrfs_getattr,
10464 .lookup = btrfs_lookup,
10465 .create = btrfs_create,
10466 .unlink = btrfs_unlink,
10467 .link = btrfs_link,
10468 .mkdir = btrfs_mkdir,
10469 .rmdir = btrfs_rmdir,
10470 .rename = btrfs_rename2,
10471 .symlink = btrfs_symlink,
10472 .setattr = btrfs_setattr,
10473 .mknod = btrfs_mknod,
10474 .listxattr = btrfs_listxattr,
10475 .permission = btrfs_permission,
10476 .get_acl = btrfs_get_acl,
10477 .set_acl = btrfs_set_acl,
10478 .update_time = btrfs_update_time,
10479 .tmpfile = btrfs_tmpfile,
10482 static const struct file_operations btrfs_dir_file_operations = {
10483 .llseek = generic_file_llseek,
10484 .read = generic_read_dir,
10485 .iterate_shared = btrfs_real_readdir,
10486 .open = btrfs_opendir,
10487 .unlocked_ioctl = btrfs_ioctl,
10488 #ifdef CONFIG_COMPAT
10489 .compat_ioctl = btrfs_compat_ioctl,
10491 .release = btrfs_release_file,
10492 .fsync = btrfs_sync_file,
10495 static const struct extent_io_ops btrfs_extent_io_ops = {
10496 /* mandatory callbacks */
10497 .submit_bio_hook = btrfs_submit_bio_hook,
10498 .readpage_end_io_hook = btrfs_readpage_end_io_hook,
10502 * btrfs doesn't support the bmap operation because swapfiles
10503 * use bmap to make a mapping of extents in the file. They assume
10504 * these extents won't change over the life of the file and they
10505 * use the bmap result to do IO directly to the drive.
10507 * the btrfs bmap call would return logical addresses that aren't
10508 * suitable for IO and they also will change frequently as COW
10509 * operations happen. So, swapfile + btrfs == corruption.
10511 * For now we're avoiding this by dropping bmap.
10513 static const struct address_space_operations btrfs_aops = {
10514 .readpage = btrfs_readpage,
10515 .writepage = btrfs_writepage,
10516 .writepages = btrfs_writepages,
10517 .readpages = btrfs_readpages,
10518 .direct_IO = btrfs_direct_IO,
10519 .invalidatepage = btrfs_invalidatepage,
10520 .releasepage = btrfs_releasepage,
10521 #ifdef CONFIG_MIGRATION
10522 .migratepage = btrfs_migratepage,
10524 .set_page_dirty = btrfs_set_page_dirty,
10525 .error_remove_page = generic_error_remove_page,
10526 .swap_activate = btrfs_swap_activate,
10527 .swap_deactivate = btrfs_swap_deactivate,
10530 static const struct inode_operations btrfs_file_inode_operations = {
10531 .getattr = btrfs_getattr,
10532 .setattr = btrfs_setattr,
10533 .listxattr = btrfs_listxattr,
10534 .permission = btrfs_permission,
10535 .fiemap = btrfs_fiemap,
10536 .get_acl = btrfs_get_acl,
10537 .set_acl = btrfs_set_acl,
10538 .update_time = btrfs_update_time,
10540 static const struct inode_operations btrfs_special_inode_operations = {
10541 .getattr = btrfs_getattr,
10542 .setattr = btrfs_setattr,
10543 .permission = btrfs_permission,
10544 .listxattr = btrfs_listxattr,
10545 .get_acl = btrfs_get_acl,
10546 .set_acl = btrfs_set_acl,
10547 .update_time = btrfs_update_time,
10549 static const struct inode_operations btrfs_symlink_inode_operations = {
10550 .get_link = page_get_link,
10551 .getattr = btrfs_getattr,
10552 .setattr = btrfs_setattr,
10553 .permission = btrfs_permission,
10554 .listxattr = btrfs_listxattr,
10555 .update_time = btrfs_update_time,
10558 const struct dentry_operations btrfs_dentry_operations = {
10559 .d_delete = btrfs_dentry_delete,