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 {
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_digest(shash, kaddr + pgoff, len, csum);
2747 if (memcmp(csum, csum_expected, csum_size))
2750 kunmap_atomic(kaddr);
2753 btrfs_print_data_csum_error(BTRFS_I(inode), start, csum, csum_expected,
2754 io_bio->mirror_num);
2755 memset(kaddr + pgoff, 1, len);
2756 flush_dcache_page(page);
2757 kunmap_atomic(kaddr);
2762 * when reads are done, we need to check csums to verify the data is correct
2763 * if there's a match, we allow the bio to finish. If not, the code in
2764 * extent_io.c will try to find good copies for us.
2766 static int btrfs_readpage_end_io_hook(struct btrfs_io_bio *io_bio,
2767 u64 phy_offset, struct page *page,
2768 u64 start, u64 end, int mirror)
2770 size_t offset = start - page_offset(page);
2771 struct inode *inode = page->mapping->host;
2772 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
2773 struct btrfs_root *root = BTRFS_I(inode)->root;
2775 if (PageChecked(page)) {
2776 ClearPageChecked(page);
2780 if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)
2783 if (root->root_key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID &&
2784 test_range_bit(io_tree, start, end, EXTENT_NODATASUM, 1, NULL)) {
2785 clear_extent_bits(io_tree, start, end, EXTENT_NODATASUM);
2789 phy_offset >>= inode->i_sb->s_blocksize_bits;
2790 return check_data_csum(inode, io_bio, phy_offset, page, offset, start,
2791 (size_t)(end - start + 1));
2795 * btrfs_add_delayed_iput - perform a delayed iput on @inode
2797 * @inode: The inode we want to perform iput on
2799 * This function uses the generic vfs_inode::i_count to track whether we should
2800 * just decrement it (in case it's > 1) or if this is the last iput then link
2801 * the inode to the delayed iput machinery. Delayed iputs are processed at
2802 * transaction commit time/superblock commit/cleaner kthread.
2804 void btrfs_add_delayed_iput(struct inode *inode)
2806 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2807 struct btrfs_inode *binode = BTRFS_I(inode);
2809 if (atomic_add_unless(&inode->i_count, -1, 1))
2812 atomic_inc(&fs_info->nr_delayed_iputs);
2813 spin_lock(&fs_info->delayed_iput_lock);
2814 ASSERT(list_empty(&binode->delayed_iput));
2815 list_add_tail(&binode->delayed_iput, &fs_info->delayed_iputs);
2816 spin_unlock(&fs_info->delayed_iput_lock);
2817 if (!test_bit(BTRFS_FS_CLEANER_RUNNING, &fs_info->flags))
2818 wake_up_process(fs_info->cleaner_kthread);
2821 static void run_delayed_iput_locked(struct btrfs_fs_info *fs_info,
2822 struct btrfs_inode *inode)
2824 list_del_init(&inode->delayed_iput);
2825 spin_unlock(&fs_info->delayed_iput_lock);
2826 iput(&inode->vfs_inode);
2827 if (atomic_dec_and_test(&fs_info->nr_delayed_iputs))
2828 wake_up(&fs_info->delayed_iputs_wait);
2829 spin_lock(&fs_info->delayed_iput_lock);
2832 static void btrfs_run_delayed_iput(struct btrfs_fs_info *fs_info,
2833 struct btrfs_inode *inode)
2835 if (!list_empty(&inode->delayed_iput)) {
2836 spin_lock(&fs_info->delayed_iput_lock);
2837 if (!list_empty(&inode->delayed_iput))
2838 run_delayed_iput_locked(fs_info, inode);
2839 spin_unlock(&fs_info->delayed_iput_lock);
2843 void btrfs_run_delayed_iputs(struct btrfs_fs_info *fs_info)
2846 spin_lock(&fs_info->delayed_iput_lock);
2847 while (!list_empty(&fs_info->delayed_iputs)) {
2848 struct btrfs_inode *inode;
2850 inode = list_first_entry(&fs_info->delayed_iputs,
2851 struct btrfs_inode, delayed_iput);
2852 run_delayed_iput_locked(fs_info, inode);
2854 spin_unlock(&fs_info->delayed_iput_lock);
2858 * btrfs_wait_on_delayed_iputs - wait on the delayed iputs to be done running
2859 * @fs_info - the fs_info for this fs
2860 * @return - EINTR if we were killed, 0 if nothing's pending
2862 * This will wait on any delayed iputs that are currently running with KILLABLE
2863 * set. Once they are all done running we will return, unless we are killed in
2864 * which case we return EINTR. This helps in user operations like fallocate etc
2865 * that might get blocked on the iputs.
2867 int btrfs_wait_on_delayed_iputs(struct btrfs_fs_info *fs_info)
2869 int ret = wait_event_killable(fs_info->delayed_iputs_wait,
2870 atomic_read(&fs_info->nr_delayed_iputs) == 0);
2877 * This creates an orphan entry for the given inode in case something goes wrong
2878 * in the middle of an unlink.
2880 int btrfs_orphan_add(struct btrfs_trans_handle *trans,
2881 struct btrfs_inode *inode)
2885 ret = btrfs_insert_orphan_item(trans, inode->root, btrfs_ino(inode));
2886 if (ret && ret != -EEXIST) {
2887 btrfs_abort_transaction(trans, ret);
2895 * We have done the delete so we can go ahead and remove the orphan item for
2896 * this particular inode.
2898 static int btrfs_orphan_del(struct btrfs_trans_handle *trans,
2899 struct btrfs_inode *inode)
2901 return btrfs_del_orphan_item(trans, inode->root, btrfs_ino(inode));
2905 * this cleans up any orphans that may be left on the list from the last use
2908 int btrfs_orphan_cleanup(struct btrfs_root *root)
2910 struct btrfs_fs_info *fs_info = root->fs_info;
2911 struct btrfs_path *path;
2912 struct extent_buffer *leaf;
2913 struct btrfs_key key, found_key;
2914 struct btrfs_trans_handle *trans;
2915 struct inode *inode;
2916 u64 last_objectid = 0;
2917 int ret = 0, nr_unlink = 0;
2919 if (cmpxchg(&root->orphan_cleanup_state, 0, ORPHAN_CLEANUP_STARTED))
2922 path = btrfs_alloc_path();
2927 path->reada = READA_BACK;
2929 key.objectid = BTRFS_ORPHAN_OBJECTID;
2930 key.type = BTRFS_ORPHAN_ITEM_KEY;
2931 key.offset = (u64)-1;
2934 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2939 * if ret == 0 means we found what we were searching for, which
2940 * is weird, but possible, so only screw with path if we didn't
2941 * find the key and see if we have stuff that matches
2945 if (path->slots[0] == 0)
2950 /* pull out the item */
2951 leaf = path->nodes[0];
2952 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
2954 /* make sure the item matches what we want */
2955 if (found_key.objectid != BTRFS_ORPHAN_OBJECTID)
2957 if (found_key.type != BTRFS_ORPHAN_ITEM_KEY)
2960 /* release the path since we're done with it */
2961 btrfs_release_path(path);
2964 * this is where we are basically btrfs_lookup, without the
2965 * crossing root thing. we store the inode number in the
2966 * offset of the orphan item.
2969 if (found_key.offset == last_objectid) {
2971 "Error removing orphan entry, stopping orphan cleanup");
2976 last_objectid = found_key.offset;
2978 found_key.objectid = found_key.offset;
2979 found_key.type = BTRFS_INODE_ITEM_KEY;
2980 found_key.offset = 0;
2981 inode = btrfs_iget(fs_info->sb, last_objectid, root);
2982 ret = PTR_ERR_OR_ZERO(inode);
2983 if (ret && ret != -ENOENT)
2986 if (ret == -ENOENT && root == fs_info->tree_root) {
2987 struct btrfs_root *dead_root;
2988 struct btrfs_fs_info *fs_info = root->fs_info;
2989 int is_dead_root = 0;
2992 * this is an orphan in the tree root. Currently these
2993 * could come from 2 sources:
2994 * a) a snapshot deletion in progress
2995 * b) a free space cache inode
2996 * We need to distinguish those two, as the snapshot
2997 * orphan must not get deleted.
2998 * find_dead_roots already ran before us, so if this
2999 * is a snapshot deletion, we should find the root
3000 * in the fs_roots radix tree.
3003 spin_lock(&fs_info->fs_roots_radix_lock);
3004 dead_root = radix_tree_lookup(&fs_info->fs_roots_radix,
3005 (unsigned long)found_key.objectid);
3006 if (dead_root && btrfs_root_refs(&dead_root->root_item) == 0)
3008 spin_unlock(&fs_info->fs_roots_radix_lock);
3011 /* prevent this orphan from being found again */
3012 key.offset = found_key.objectid - 1;
3019 * If we have an inode with links, there are a couple of
3020 * possibilities. Old kernels (before v3.12) used to create an
3021 * orphan item for truncate indicating that there were possibly
3022 * extent items past i_size that needed to be deleted. In v3.12,
3023 * truncate was changed to update i_size in sync with the extent
3024 * items, but the (useless) orphan item was still created. Since
3025 * v4.18, we don't create the orphan item for truncate at all.
3027 * So, this item could mean that we need to do a truncate, but
3028 * only if this filesystem was last used on a pre-v3.12 kernel
3029 * and was not cleanly unmounted. The odds of that are quite
3030 * slim, and it's a pain to do the truncate now, so just delete
3033 * It's also possible that this orphan item was supposed to be
3034 * deleted but wasn't. The inode number may have been reused,
3035 * but either way, we can delete the orphan item.
3037 if (ret == -ENOENT || inode->i_nlink) {
3040 trans = btrfs_start_transaction(root, 1);
3041 if (IS_ERR(trans)) {
3042 ret = PTR_ERR(trans);
3045 btrfs_debug(fs_info, "auto deleting %Lu",
3046 found_key.objectid);
3047 ret = btrfs_del_orphan_item(trans, root,
3048 found_key.objectid);
3049 btrfs_end_transaction(trans);
3057 /* this will do delete_inode and everything for us */
3060 /* release the path since we're done with it */
3061 btrfs_release_path(path);
3063 root->orphan_cleanup_state = ORPHAN_CLEANUP_DONE;
3065 if (test_bit(BTRFS_ROOT_ORPHAN_ITEM_INSERTED, &root->state)) {
3066 trans = btrfs_join_transaction(root);
3068 btrfs_end_transaction(trans);
3072 btrfs_debug(fs_info, "unlinked %d orphans", nr_unlink);
3076 btrfs_err(fs_info, "could not do orphan cleanup %d", ret);
3077 btrfs_free_path(path);
3082 * very simple check to peek ahead in the leaf looking for xattrs. If we
3083 * don't find any xattrs, we know there can't be any acls.
3085 * slot is the slot the inode is in, objectid is the objectid of the inode
3087 static noinline int acls_after_inode_item(struct extent_buffer *leaf,
3088 int slot, u64 objectid,
3089 int *first_xattr_slot)
3091 u32 nritems = btrfs_header_nritems(leaf);
3092 struct btrfs_key found_key;
3093 static u64 xattr_access = 0;
3094 static u64 xattr_default = 0;
3097 if (!xattr_access) {
3098 xattr_access = btrfs_name_hash(XATTR_NAME_POSIX_ACL_ACCESS,
3099 strlen(XATTR_NAME_POSIX_ACL_ACCESS));
3100 xattr_default = btrfs_name_hash(XATTR_NAME_POSIX_ACL_DEFAULT,
3101 strlen(XATTR_NAME_POSIX_ACL_DEFAULT));
3105 *first_xattr_slot = -1;
3106 while (slot < nritems) {
3107 btrfs_item_key_to_cpu(leaf, &found_key, slot);
3109 /* we found a different objectid, there must not be acls */
3110 if (found_key.objectid != objectid)
3113 /* we found an xattr, assume we've got an acl */
3114 if (found_key.type == BTRFS_XATTR_ITEM_KEY) {
3115 if (*first_xattr_slot == -1)
3116 *first_xattr_slot = slot;
3117 if (found_key.offset == xattr_access ||
3118 found_key.offset == xattr_default)
3123 * we found a key greater than an xattr key, there can't
3124 * be any acls later on
3126 if (found_key.type > BTRFS_XATTR_ITEM_KEY)
3133 * it goes inode, inode backrefs, xattrs, extents,
3134 * so if there are a ton of hard links to an inode there can
3135 * be a lot of backrefs. Don't waste time searching too hard,
3136 * this is just an optimization
3141 /* we hit the end of the leaf before we found an xattr or
3142 * something larger than an xattr. We have to assume the inode
3145 if (*first_xattr_slot == -1)
3146 *first_xattr_slot = slot;
3151 * read an inode from the btree into the in-memory inode
3153 static int btrfs_read_locked_inode(struct inode *inode,
3154 struct btrfs_path *in_path)
3156 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
3157 struct btrfs_path *path = in_path;
3158 struct extent_buffer *leaf;
3159 struct btrfs_inode_item *inode_item;
3160 struct btrfs_root *root = BTRFS_I(inode)->root;
3161 struct btrfs_key location;
3166 bool filled = false;
3167 int first_xattr_slot;
3169 ret = btrfs_fill_inode(inode, &rdev);
3174 path = btrfs_alloc_path();
3179 memcpy(&location, &BTRFS_I(inode)->location, sizeof(location));
3181 ret = btrfs_lookup_inode(NULL, root, path, &location, 0);
3183 if (path != in_path)
3184 btrfs_free_path(path);
3188 leaf = path->nodes[0];
3193 inode_item = btrfs_item_ptr(leaf, path->slots[0],
3194 struct btrfs_inode_item);
3195 inode->i_mode = btrfs_inode_mode(leaf, inode_item);
3196 set_nlink(inode, btrfs_inode_nlink(leaf, inode_item));
3197 i_uid_write(inode, btrfs_inode_uid(leaf, inode_item));
3198 i_gid_write(inode, btrfs_inode_gid(leaf, inode_item));
3199 btrfs_i_size_write(BTRFS_I(inode), btrfs_inode_size(leaf, inode_item));
3200 btrfs_inode_set_file_extent_range(BTRFS_I(inode), 0,
3201 round_up(i_size_read(inode), fs_info->sectorsize));
3203 inode->i_atime.tv_sec = btrfs_timespec_sec(leaf, &inode_item->atime);
3204 inode->i_atime.tv_nsec = btrfs_timespec_nsec(leaf, &inode_item->atime);
3206 inode->i_mtime.tv_sec = btrfs_timespec_sec(leaf, &inode_item->mtime);
3207 inode->i_mtime.tv_nsec = btrfs_timespec_nsec(leaf, &inode_item->mtime);
3209 inode->i_ctime.tv_sec = btrfs_timespec_sec(leaf, &inode_item->ctime);
3210 inode->i_ctime.tv_nsec = btrfs_timespec_nsec(leaf, &inode_item->ctime);
3212 BTRFS_I(inode)->i_otime.tv_sec =
3213 btrfs_timespec_sec(leaf, &inode_item->otime);
3214 BTRFS_I(inode)->i_otime.tv_nsec =
3215 btrfs_timespec_nsec(leaf, &inode_item->otime);
3217 inode_set_bytes(inode, btrfs_inode_nbytes(leaf, inode_item));
3218 BTRFS_I(inode)->generation = btrfs_inode_generation(leaf, inode_item);
3219 BTRFS_I(inode)->last_trans = btrfs_inode_transid(leaf, inode_item);
3221 inode_set_iversion_queried(inode,
3222 btrfs_inode_sequence(leaf, inode_item));
3223 inode->i_generation = BTRFS_I(inode)->generation;
3225 rdev = btrfs_inode_rdev(leaf, inode_item);
3227 BTRFS_I(inode)->index_cnt = (u64)-1;
3228 BTRFS_I(inode)->flags = btrfs_inode_flags(leaf, inode_item);
3232 * If we were modified in the current generation and evicted from memory
3233 * and then re-read we need to do a full sync since we don't have any
3234 * idea about which extents were modified before we were evicted from
3237 * This is required for both inode re-read from disk and delayed inode
3238 * in delayed_nodes_tree.
3240 if (BTRFS_I(inode)->last_trans == fs_info->generation)
3241 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
3242 &BTRFS_I(inode)->runtime_flags);
3245 * We don't persist the id of the transaction where an unlink operation
3246 * against the inode was last made. So here we assume the inode might
3247 * have been evicted, and therefore the exact value of last_unlink_trans
3248 * lost, and set it to last_trans to avoid metadata inconsistencies
3249 * between the inode and its parent if the inode is fsync'ed and the log
3250 * replayed. For example, in the scenario:
3253 * ln mydir/foo mydir/bar
3256 * echo 2 > /proc/sys/vm/drop_caches # evicts inode
3257 * xfs_io -c fsync mydir/foo
3259 * mount fs, triggers fsync log replay
3261 * We must make sure that when we fsync our inode foo we also log its
3262 * parent inode, otherwise after log replay the parent still has the
3263 * dentry with the "bar" name but our inode foo has a link count of 1
3264 * and doesn't have an inode ref with the name "bar" anymore.
3266 * Setting last_unlink_trans to last_trans is a pessimistic approach,
3267 * but it guarantees correctness at the expense of occasional full
3268 * transaction commits on fsync if our inode is a directory, or if our
3269 * inode is not a directory, logging its parent unnecessarily.
3271 BTRFS_I(inode)->last_unlink_trans = BTRFS_I(inode)->last_trans;
3274 if (inode->i_nlink != 1 ||
3275 path->slots[0] >= btrfs_header_nritems(leaf))
3278 btrfs_item_key_to_cpu(leaf, &location, path->slots[0]);
3279 if (location.objectid != btrfs_ino(BTRFS_I(inode)))
3282 ptr = btrfs_item_ptr_offset(leaf, path->slots[0]);
3283 if (location.type == BTRFS_INODE_REF_KEY) {
3284 struct btrfs_inode_ref *ref;
3286 ref = (struct btrfs_inode_ref *)ptr;
3287 BTRFS_I(inode)->dir_index = btrfs_inode_ref_index(leaf, ref);
3288 } else if (location.type == BTRFS_INODE_EXTREF_KEY) {
3289 struct btrfs_inode_extref *extref;
3291 extref = (struct btrfs_inode_extref *)ptr;
3292 BTRFS_I(inode)->dir_index = btrfs_inode_extref_index(leaf,
3297 * try to precache a NULL acl entry for files that don't have
3298 * any xattrs or acls
3300 maybe_acls = acls_after_inode_item(leaf, path->slots[0],
3301 btrfs_ino(BTRFS_I(inode)), &first_xattr_slot);
3302 if (first_xattr_slot != -1) {
3303 path->slots[0] = first_xattr_slot;
3304 ret = btrfs_load_inode_props(inode, path);
3307 "error loading props for ino %llu (root %llu): %d",
3308 btrfs_ino(BTRFS_I(inode)),
3309 root->root_key.objectid, ret);
3311 if (path != in_path)
3312 btrfs_free_path(path);
3315 cache_no_acl(inode);
3317 switch (inode->i_mode & S_IFMT) {
3319 inode->i_mapping->a_ops = &btrfs_aops;
3320 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
3321 inode->i_fop = &btrfs_file_operations;
3322 inode->i_op = &btrfs_file_inode_operations;
3325 inode->i_fop = &btrfs_dir_file_operations;
3326 inode->i_op = &btrfs_dir_inode_operations;
3329 inode->i_op = &btrfs_symlink_inode_operations;
3330 inode_nohighmem(inode);
3331 inode->i_mapping->a_ops = &btrfs_aops;
3334 inode->i_op = &btrfs_special_inode_operations;
3335 init_special_inode(inode, inode->i_mode, rdev);
3339 btrfs_sync_inode_flags_to_i_flags(inode);
3344 * given a leaf and an inode, copy the inode fields into the leaf
3346 static void fill_inode_item(struct btrfs_trans_handle *trans,
3347 struct extent_buffer *leaf,
3348 struct btrfs_inode_item *item,
3349 struct inode *inode)
3351 struct btrfs_map_token token;
3353 btrfs_init_map_token(&token, leaf);
3355 btrfs_set_token_inode_uid(&token, item, i_uid_read(inode));
3356 btrfs_set_token_inode_gid(&token, item, i_gid_read(inode));
3357 btrfs_set_token_inode_size(&token, item, BTRFS_I(inode)->disk_i_size);
3358 btrfs_set_token_inode_mode(&token, item, inode->i_mode);
3359 btrfs_set_token_inode_nlink(&token, item, inode->i_nlink);
3361 btrfs_set_token_timespec_sec(&token, &item->atime,
3362 inode->i_atime.tv_sec);
3363 btrfs_set_token_timespec_nsec(&token, &item->atime,
3364 inode->i_atime.tv_nsec);
3366 btrfs_set_token_timespec_sec(&token, &item->mtime,
3367 inode->i_mtime.tv_sec);
3368 btrfs_set_token_timespec_nsec(&token, &item->mtime,
3369 inode->i_mtime.tv_nsec);
3371 btrfs_set_token_timespec_sec(&token, &item->ctime,
3372 inode->i_ctime.tv_sec);
3373 btrfs_set_token_timespec_nsec(&token, &item->ctime,
3374 inode->i_ctime.tv_nsec);
3376 btrfs_set_token_timespec_sec(&token, &item->otime,
3377 BTRFS_I(inode)->i_otime.tv_sec);
3378 btrfs_set_token_timespec_nsec(&token, &item->otime,
3379 BTRFS_I(inode)->i_otime.tv_nsec);
3381 btrfs_set_token_inode_nbytes(&token, item, inode_get_bytes(inode));
3382 btrfs_set_token_inode_generation(&token, item,
3383 BTRFS_I(inode)->generation);
3384 btrfs_set_token_inode_sequence(&token, item, inode_peek_iversion(inode));
3385 btrfs_set_token_inode_transid(&token, item, trans->transid);
3386 btrfs_set_token_inode_rdev(&token, item, inode->i_rdev);
3387 btrfs_set_token_inode_flags(&token, item, BTRFS_I(inode)->flags);
3388 btrfs_set_token_inode_block_group(&token, item, 0);
3392 * copy everything in the in-memory inode into the btree.
3394 static noinline int btrfs_update_inode_item(struct btrfs_trans_handle *trans,
3395 struct btrfs_root *root, struct inode *inode)
3397 struct btrfs_inode_item *inode_item;
3398 struct btrfs_path *path;
3399 struct extent_buffer *leaf;
3402 path = btrfs_alloc_path();
3406 path->leave_spinning = 1;
3407 ret = btrfs_lookup_inode(trans, root, path, &BTRFS_I(inode)->location,
3415 leaf = path->nodes[0];
3416 inode_item = btrfs_item_ptr(leaf, path->slots[0],
3417 struct btrfs_inode_item);
3419 fill_inode_item(trans, leaf, inode_item, inode);
3420 btrfs_mark_buffer_dirty(leaf);
3421 btrfs_set_inode_last_trans(trans, inode);
3424 btrfs_free_path(path);
3429 * copy everything in the in-memory inode into the btree.
3431 noinline int btrfs_update_inode(struct btrfs_trans_handle *trans,
3432 struct btrfs_root *root, struct inode *inode)
3434 struct btrfs_fs_info *fs_info = root->fs_info;
3438 * If the inode is a free space inode, we can deadlock during commit
3439 * if we put it into the delayed code.
3441 * The data relocation inode should also be directly updated
3444 if (!btrfs_is_free_space_inode(BTRFS_I(inode))
3445 && root->root_key.objectid != BTRFS_DATA_RELOC_TREE_OBJECTID
3446 && !test_bit(BTRFS_FS_LOG_RECOVERING, &fs_info->flags)) {
3447 btrfs_update_root_times(trans, root);
3449 ret = btrfs_delayed_update_inode(trans, root, inode);
3451 btrfs_set_inode_last_trans(trans, inode);
3455 return btrfs_update_inode_item(trans, root, inode);
3458 noinline int btrfs_update_inode_fallback(struct btrfs_trans_handle *trans,
3459 struct btrfs_root *root,
3460 struct inode *inode)
3464 ret = btrfs_update_inode(trans, root, inode);
3466 return btrfs_update_inode_item(trans, root, inode);
3471 * unlink helper that gets used here in inode.c and in the tree logging
3472 * recovery code. It remove a link in a directory with a given name, and
3473 * also drops the back refs in the inode to the directory
3475 static int __btrfs_unlink_inode(struct btrfs_trans_handle *trans,
3476 struct btrfs_root *root,
3477 struct btrfs_inode *dir,
3478 struct btrfs_inode *inode,
3479 const char *name, int name_len)
3481 struct btrfs_fs_info *fs_info = root->fs_info;
3482 struct btrfs_path *path;
3484 struct btrfs_dir_item *di;
3486 u64 ino = btrfs_ino(inode);
3487 u64 dir_ino = btrfs_ino(dir);
3489 path = btrfs_alloc_path();
3495 path->leave_spinning = 1;
3496 di = btrfs_lookup_dir_item(trans, root, path, dir_ino,
3497 name, name_len, -1);
3498 if (IS_ERR_OR_NULL(di)) {
3499 ret = di ? PTR_ERR(di) : -ENOENT;
3502 ret = btrfs_delete_one_dir_name(trans, root, path, di);
3505 btrfs_release_path(path);
3508 * If we don't have dir index, we have to get it by looking up
3509 * the inode ref, since we get the inode ref, remove it directly,
3510 * it is unnecessary to do delayed deletion.
3512 * But if we have dir index, needn't search inode ref to get it.
3513 * Since the inode ref is close to the inode item, it is better
3514 * that we delay to delete it, and just do this deletion when
3515 * we update the inode item.
3517 if (inode->dir_index) {
3518 ret = btrfs_delayed_delete_inode_ref(inode);
3520 index = inode->dir_index;
3525 ret = btrfs_del_inode_ref(trans, root, name, name_len, ino,
3529 "failed to delete reference to %.*s, inode %llu parent %llu",
3530 name_len, name, ino, dir_ino);
3531 btrfs_abort_transaction(trans, ret);
3535 ret = btrfs_delete_delayed_dir_index(trans, dir, index);
3537 btrfs_abort_transaction(trans, ret);
3541 ret = btrfs_del_inode_ref_in_log(trans, root, name, name_len, inode,
3543 if (ret != 0 && ret != -ENOENT) {
3544 btrfs_abort_transaction(trans, ret);
3548 ret = btrfs_del_dir_entries_in_log(trans, root, name, name_len, dir,
3553 btrfs_abort_transaction(trans, ret);
3556 * If we have a pending delayed iput we could end up with the final iput
3557 * being run in btrfs-cleaner context. If we have enough of these built
3558 * up we can end up burning a lot of time in btrfs-cleaner without any
3559 * way to throttle the unlinks. Since we're currently holding a ref on
3560 * the inode we can run the delayed iput here without any issues as the
3561 * final iput won't be done until after we drop the ref we're currently
3564 btrfs_run_delayed_iput(fs_info, inode);
3566 btrfs_free_path(path);
3570 btrfs_i_size_write(dir, dir->vfs_inode.i_size - name_len * 2);
3571 inode_inc_iversion(&inode->vfs_inode);
3572 inode_inc_iversion(&dir->vfs_inode);
3573 inode->vfs_inode.i_ctime = dir->vfs_inode.i_mtime =
3574 dir->vfs_inode.i_ctime = current_time(&inode->vfs_inode);
3575 ret = btrfs_update_inode(trans, root, &dir->vfs_inode);
3580 int btrfs_unlink_inode(struct btrfs_trans_handle *trans,
3581 struct btrfs_root *root,
3582 struct btrfs_inode *dir, struct btrfs_inode *inode,
3583 const char *name, int name_len)
3586 ret = __btrfs_unlink_inode(trans, root, dir, inode, name, name_len);
3588 drop_nlink(&inode->vfs_inode);
3589 ret = btrfs_update_inode(trans, root, &inode->vfs_inode);
3595 * helper to start transaction for unlink and rmdir.
3597 * unlink and rmdir are special in btrfs, they do not always free space, so
3598 * if we cannot make our reservations the normal way try and see if there is
3599 * plenty of slack room in the global reserve to migrate, otherwise we cannot
3600 * allow the unlink to occur.
3602 static struct btrfs_trans_handle *__unlink_start_trans(struct inode *dir)
3604 struct btrfs_root *root = BTRFS_I(dir)->root;
3607 * 1 for the possible orphan item
3608 * 1 for the dir item
3609 * 1 for the dir index
3610 * 1 for the inode ref
3613 return btrfs_start_transaction_fallback_global_rsv(root, 5);
3616 static int btrfs_unlink(struct inode *dir, struct dentry *dentry)
3618 struct btrfs_root *root = BTRFS_I(dir)->root;
3619 struct btrfs_trans_handle *trans;
3620 struct inode *inode = d_inode(dentry);
3623 trans = __unlink_start_trans(dir);
3625 return PTR_ERR(trans);
3627 btrfs_record_unlink_dir(trans, BTRFS_I(dir), BTRFS_I(d_inode(dentry)),
3630 ret = btrfs_unlink_inode(trans, root, BTRFS_I(dir),
3631 BTRFS_I(d_inode(dentry)), dentry->d_name.name,
3632 dentry->d_name.len);
3636 if (inode->i_nlink == 0) {
3637 ret = btrfs_orphan_add(trans, BTRFS_I(inode));
3643 btrfs_end_transaction(trans);
3644 btrfs_btree_balance_dirty(root->fs_info);
3648 static int btrfs_unlink_subvol(struct btrfs_trans_handle *trans,
3649 struct inode *dir, struct dentry *dentry)
3651 struct btrfs_root *root = BTRFS_I(dir)->root;
3652 struct btrfs_inode *inode = BTRFS_I(d_inode(dentry));
3653 struct btrfs_path *path;
3654 struct extent_buffer *leaf;
3655 struct btrfs_dir_item *di;
3656 struct btrfs_key key;
3657 const char *name = dentry->d_name.name;
3658 int name_len = dentry->d_name.len;
3662 u64 dir_ino = btrfs_ino(BTRFS_I(dir));
3664 if (btrfs_ino(inode) == BTRFS_FIRST_FREE_OBJECTID) {
3665 objectid = inode->root->root_key.objectid;
3666 } else if (btrfs_ino(inode) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID) {
3667 objectid = inode->location.objectid;
3673 path = btrfs_alloc_path();
3677 di = btrfs_lookup_dir_item(trans, root, path, dir_ino,
3678 name, name_len, -1);
3679 if (IS_ERR_OR_NULL(di)) {
3680 ret = di ? PTR_ERR(di) : -ENOENT;
3684 leaf = path->nodes[0];
3685 btrfs_dir_item_key_to_cpu(leaf, di, &key);
3686 WARN_ON(key.type != BTRFS_ROOT_ITEM_KEY || key.objectid != objectid);
3687 ret = btrfs_delete_one_dir_name(trans, root, path, di);
3689 btrfs_abort_transaction(trans, ret);
3692 btrfs_release_path(path);
3695 * This is a placeholder inode for a subvolume we didn't have a
3696 * reference to at the time of the snapshot creation. In the meantime
3697 * we could have renamed the real subvol link into our snapshot, so
3698 * depending on btrfs_del_root_ref to return -ENOENT here is incorret.
3699 * Instead simply lookup the dir_index_item for this entry so we can
3700 * remove it. Otherwise we know we have a ref to the root and we can
3701 * call btrfs_del_root_ref, and it _shouldn't_ fail.
3703 if (btrfs_ino(inode) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID) {
3704 di = btrfs_search_dir_index_item(root, path, dir_ino,
3706 if (IS_ERR_OR_NULL(di)) {
3711 btrfs_abort_transaction(trans, ret);
3715 leaf = path->nodes[0];
3716 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
3718 btrfs_release_path(path);
3720 ret = btrfs_del_root_ref(trans, objectid,
3721 root->root_key.objectid, dir_ino,
3722 &index, name, name_len);
3724 btrfs_abort_transaction(trans, ret);
3729 ret = btrfs_delete_delayed_dir_index(trans, BTRFS_I(dir), index);
3731 btrfs_abort_transaction(trans, ret);
3735 btrfs_i_size_write(BTRFS_I(dir), dir->i_size - name_len * 2);
3736 inode_inc_iversion(dir);
3737 dir->i_mtime = dir->i_ctime = current_time(dir);
3738 ret = btrfs_update_inode_fallback(trans, root, dir);
3740 btrfs_abort_transaction(trans, ret);
3742 btrfs_free_path(path);
3747 * Helper to check if the subvolume references other subvolumes or if it's
3750 static noinline int may_destroy_subvol(struct btrfs_root *root)
3752 struct btrfs_fs_info *fs_info = root->fs_info;
3753 struct btrfs_path *path;
3754 struct btrfs_dir_item *di;
3755 struct btrfs_key key;
3759 path = btrfs_alloc_path();
3763 /* Make sure this root isn't set as the default subvol */
3764 dir_id = btrfs_super_root_dir(fs_info->super_copy);
3765 di = btrfs_lookup_dir_item(NULL, fs_info->tree_root, path,
3766 dir_id, "default", 7, 0);
3767 if (di && !IS_ERR(di)) {
3768 btrfs_dir_item_key_to_cpu(path->nodes[0], di, &key);
3769 if (key.objectid == root->root_key.objectid) {
3772 "deleting default subvolume %llu is not allowed",
3776 btrfs_release_path(path);
3779 key.objectid = root->root_key.objectid;
3780 key.type = BTRFS_ROOT_REF_KEY;
3781 key.offset = (u64)-1;
3783 ret = btrfs_search_slot(NULL, fs_info->tree_root, &key, path, 0, 0);
3789 if (path->slots[0] > 0) {
3791 btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
3792 if (key.objectid == root->root_key.objectid &&
3793 key.type == BTRFS_ROOT_REF_KEY)
3797 btrfs_free_path(path);
3801 /* Delete all dentries for inodes belonging to the root */
3802 static void btrfs_prune_dentries(struct btrfs_root *root)
3804 struct btrfs_fs_info *fs_info = root->fs_info;
3805 struct rb_node *node;
3806 struct rb_node *prev;
3807 struct btrfs_inode *entry;
3808 struct inode *inode;
3811 if (!test_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state))
3812 WARN_ON(btrfs_root_refs(&root->root_item) != 0);
3814 spin_lock(&root->inode_lock);
3816 node = root->inode_tree.rb_node;
3820 entry = rb_entry(node, struct btrfs_inode, rb_node);
3822 if (objectid < btrfs_ino(entry))
3823 node = node->rb_left;
3824 else if (objectid > btrfs_ino(entry))
3825 node = node->rb_right;
3831 entry = rb_entry(prev, struct btrfs_inode, rb_node);
3832 if (objectid <= btrfs_ino(entry)) {
3836 prev = rb_next(prev);
3840 entry = rb_entry(node, struct btrfs_inode, rb_node);
3841 objectid = btrfs_ino(entry) + 1;
3842 inode = igrab(&entry->vfs_inode);
3844 spin_unlock(&root->inode_lock);
3845 if (atomic_read(&inode->i_count) > 1)
3846 d_prune_aliases(inode);
3848 * btrfs_drop_inode will have it removed from the inode
3849 * cache when its usage count hits zero.
3853 spin_lock(&root->inode_lock);
3857 if (cond_resched_lock(&root->inode_lock))
3860 node = rb_next(node);
3862 spin_unlock(&root->inode_lock);
3865 int btrfs_delete_subvolume(struct inode *dir, struct dentry *dentry)
3867 struct btrfs_fs_info *fs_info = btrfs_sb(dentry->d_sb);
3868 struct btrfs_root *root = BTRFS_I(dir)->root;
3869 struct inode *inode = d_inode(dentry);
3870 struct btrfs_root *dest = BTRFS_I(inode)->root;
3871 struct btrfs_trans_handle *trans;
3872 struct btrfs_block_rsv block_rsv;
3878 * Don't allow to delete a subvolume with send in progress. This is
3879 * inside the inode lock so the error handling that has to drop the bit
3880 * again is not run concurrently.
3882 spin_lock(&dest->root_item_lock);
3883 if (dest->send_in_progress) {
3884 spin_unlock(&dest->root_item_lock);
3886 "attempt to delete subvolume %llu during send",
3887 dest->root_key.objectid);
3890 root_flags = btrfs_root_flags(&dest->root_item);
3891 btrfs_set_root_flags(&dest->root_item,
3892 root_flags | BTRFS_ROOT_SUBVOL_DEAD);
3893 spin_unlock(&dest->root_item_lock);
3895 down_write(&fs_info->subvol_sem);
3897 err = may_destroy_subvol(dest);
3901 btrfs_init_block_rsv(&block_rsv, BTRFS_BLOCK_RSV_TEMP);
3903 * One for dir inode,
3904 * two for dir entries,
3905 * two for root ref/backref.
3907 err = btrfs_subvolume_reserve_metadata(root, &block_rsv, 5, true);
3911 trans = btrfs_start_transaction(root, 0);
3912 if (IS_ERR(trans)) {
3913 err = PTR_ERR(trans);
3916 trans->block_rsv = &block_rsv;
3917 trans->bytes_reserved = block_rsv.size;
3919 btrfs_record_snapshot_destroy(trans, BTRFS_I(dir));
3921 ret = btrfs_unlink_subvol(trans, dir, dentry);
3924 btrfs_abort_transaction(trans, ret);
3928 btrfs_record_root_in_trans(trans, dest);
3930 memset(&dest->root_item.drop_progress, 0,
3931 sizeof(dest->root_item.drop_progress));
3932 dest->root_item.drop_level = 0;
3933 btrfs_set_root_refs(&dest->root_item, 0);
3935 if (!test_and_set_bit(BTRFS_ROOT_ORPHAN_ITEM_INSERTED, &dest->state)) {
3936 ret = btrfs_insert_orphan_item(trans,
3938 dest->root_key.objectid);
3940 btrfs_abort_transaction(trans, ret);
3946 ret = btrfs_uuid_tree_remove(trans, dest->root_item.uuid,
3947 BTRFS_UUID_KEY_SUBVOL,
3948 dest->root_key.objectid);
3949 if (ret && ret != -ENOENT) {
3950 btrfs_abort_transaction(trans, ret);
3954 if (!btrfs_is_empty_uuid(dest->root_item.received_uuid)) {
3955 ret = btrfs_uuid_tree_remove(trans,
3956 dest->root_item.received_uuid,
3957 BTRFS_UUID_KEY_RECEIVED_SUBVOL,
3958 dest->root_key.objectid);
3959 if (ret && ret != -ENOENT) {
3960 btrfs_abort_transaction(trans, ret);
3967 trans->block_rsv = NULL;
3968 trans->bytes_reserved = 0;
3969 ret = btrfs_end_transaction(trans);
3972 inode->i_flags |= S_DEAD;
3974 btrfs_subvolume_release_metadata(fs_info, &block_rsv);
3976 up_write(&fs_info->subvol_sem);
3978 spin_lock(&dest->root_item_lock);
3979 root_flags = btrfs_root_flags(&dest->root_item);
3980 btrfs_set_root_flags(&dest->root_item,
3981 root_flags & ~BTRFS_ROOT_SUBVOL_DEAD);
3982 spin_unlock(&dest->root_item_lock);
3984 d_invalidate(dentry);
3985 btrfs_prune_dentries(dest);
3986 ASSERT(dest->send_in_progress == 0);
3989 if (dest->ino_cache_inode) {
3990 iput(dest->ino_cache_inode);
3991 dest->ino_cache_inode = NULL;
3998 static int btrfs_rmdir(struct inode *dir, struct dentry *dentry)
4000 struct inode *inode = d_inode(dentry);
4002 struct btrfs_root *root = BTRFS_I(dir)->root;
4003 struct btrfs_trans_handle *trans;
4004 u64 last_unlink_trans;
4006 if (inode->i_size > BTRFS_EMPTY_DIR_SIZE)
4008 if (btrfs_ino(BTRFS_I(inode)) == BTRFS_FIRST_FREE_OBJECTID)
4009 return btrfs_delete_subvolume(dir, dentry);
4011 trans = __unlink_start_trans(dir);
4013 return PTR_ERR(trans);
4015 if (unlikely(btrfs_ino(BTRFS_I(inode)) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)) {
4016 err = btrfs_unlink_subvol(trans, dir, dentry);
4020 err = btrfs_orphan_add(trans, BTRFS_I(inode));
4024 last_unlink_trans = BTRFS_I(inode)->last_unlink_trans;
4026 /* now the directory is empty */
4027 err = btrfs_unlink_inode(trans, root, BTRFS_I(dir),
4028 BTRFS_I(d_inode(dentry)), dentry->d_name.name,
4029 dentry->d_name.len);
4031 btrfs_i_size_write(BTRFS_I(inode), 0);
4033 * Propagate the last_unlink_trans value of the deleted dir to
4034 * its parent directory. This is to prevent an unrecoverable
4035 * log tree in the case we do something like this:
4037 * 2) create snapshot under dir foo
4038 * 3) delete the snapshot
4041 * 6) fsync foo or some file inside foo
4043 if (last_unlink_trans >= trans->transid)
4044 BTRFS_I(dir)->last_unlink_trans = last_unlink_trans;
4047 btrfs_end_transaction(trans);
4048 btrfs_btree_balance_dirty(root->fs_info);
4054 * Return this if we need to call truncate_block for the last bit of the
4057 #define NEED_TRUNCATE_BLOCK 1
4060 * this can truncate away extent items, csum items and directory items.
4061 * It starts at a high offset and removes keys until it can't find
4062 * any higher than new_size
4064 * csum items that cross the new i_size are truncated to the new size
4067 * min_type is the minimum key type to truncate down to. If set to 0, this
4068 * will kill all the items on this inode, including the INODE_ITEM_KEY.
4070 int btrfs_truncate_inode_items(struct btrfs_trans_handle *trans,
4071 struct btrfs_root *root,
4072 struct inode *inode,
4073 u64 new_size, u32 min_type)
4075 struct btrfs_fs_info *fs_info = root->fs_info;
4076 struct btrfs_path *path;
4077 struct extent_buffer *leaf;
4078 struct btrfs_file_extent_item *fi;
4079 struct btrfs_key key;
4080 struct btrfs_key found_key;
4081 u64 extent_start = 0;
4082 u64 extent_num_bytes = 0;
4083 u64 extent_offset = 0;
4085 u64 last_size = new_size;
4086 u32 found_type = (u8)-1;
4089 int pending_del_nr = 0;
4090 int pending_del_slot = 0;
4091 int extent_type = -1;
4093 u64 ino = btrfs_ino(BTRFS_I(inode));
4094 u64 bytes_deleted = 0;
4095 bool be_nice = false;
4096 bool should_throttle = false;
4097 const u64 lock_start = ALIGN_DOWN(new_size, fs_info->sectorsize);
4098 struct extent_state *cached_state = NULL;
4100 BUG_ON(new_size > 0 && min_type != BTRFS_EXTENT_DATA_KEY);
4103 * For non-free space inodes and non-shareable roots, we want to back
4104 * off from time to time. This means all inodes in subvolume roots,
4105 * reloc roots, and data reloc roots.
4107 if (!btrfs_is_free_space_inode(BTRFS_I(inode)) &&
4108 test_bit(BTRFS_ROOT_SHAREABLE, &root->state))
4111 path = btrfs_alloc_path();
4114 path->reada = READA_BACK;
4116 if (root->root_key.objectid != BTRFS_TREE_LOG_OBJECTID) {
4117 lock_extent_bits(&BTRFS_I(inode)->io_tree, lock_start, (u64)-1,
4121 * We want to drop from the next block forward in case this
4122 * new size is not block aligned since we will be keeping the
4123 * last block of the extent just the way it is.
4125 btrfs_drop_extent_cache(BTRFS_I(inode), ALIGN(new_size,
4126 fs_info->sectorsize),
4131 * This function is also used to drop the items in the log tree before
4132 * we relog the inode, so if root != BTRFS_I(inode)->root, it means
4133 * it is used to drop the logged items. So we shouldn't kill the delayed
4136 if (min_type == 0 && root == BTRFS_I(inode)->root)
4137 btrfs_kill_delayed_inode_items(BTRFS_I(inode));
4140 key.offset = (u64)-1;
4145 * with a 16K leaf size and 128MB extents, you can actually queue
4146 * up a huge file in a single leaf. Most of the time that
4147 * bytes_deleted is > 0, it will be huge by the time we get here
4149 if (be_nice && bytes_deleted > SZ_32M &&
4150 btrfs_should_end_transaction(trans)) {
4155 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
4161 /* there are no items in the tree for us to truncate, we're
4164 if (path->slots[0] == 0)
4170 u64 clear_start = 0, clear_len = 0;
4173 leaf = path->nodes[0];
4174 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
4175 found_type = found_key.type;
4177 if (found_key.objectid != ino)
4180 if (found_type < min_type)
4183 item_end = found_key.offset;
4184 if (found_type == BTRFS_EXTENT_DATA_KEY) {
4185 fi = btrfs_item_ptr(leaf, path->slots[0],
4186 struct btrfs_file_extent_item);
4187 extent_type = btrfs_file_extent_type(leaf, fi);
4188 if (extent_type != BTRFS_FILE_EXTENT_INLINE) {
4190 btrfs_file_extent_num_bytes(leaf, fi);
4192 trace_btrfs_truncate_show_fi_regular(
4193 BTRFS_I(inode), leaf, fi,
4195 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
4196 item_end += btrfs_file_extent_ram_bytes(leaf,
4199 trace_btrfs_truncate_show_fi_inline(
4200 BTRFS_I(inode), leaf, fi, path->slots[0],
4205 if (found_type > min_type) {
4208 if (item_end < new_size)
4210 if (found_key.offset >= new_size)
4216 /* FIXME, shrink the extent if the ref count is only 1 */
4217 if (found_type != BTRFS_EXTENT_DATA_KEY)
4220 if (extent_type != BTRFS_FILE_EXTENT_INLINE) {
4223 clear_start = found_key.offset;
4224 extent_start = btrfs_file_extent_disk_bytenr(leaf, fi);
4226 u64 orig_num_bytes =
4227 btrfs_file_extent_num_bytes(leaf, fi);
4228 extent_num_bytes = ALIGN(new_size -
4230 fs_info->sectorsize);
4231 clear_start = ALIGN(new_size, fs_info->sectorsize);
4232 btrfs_set_file_extent_num_bytes(leaf, fi,
4234 num_dec = (orig_num_bytes -
4236 if (test_bit(BTRFS_ROOT_SHAREABLE,
4239 inode_sub_bytes(inode, num_dec);
4240 btrfs_mark_buffer_dirty(leaf);
4243 btrfs_file_extent_disk_num_bytes(leaf,
4245 extent_offset = found_key.offset -
4246 btrfs_file_extent_offset(leaf, fi);
4248 /* FIXME blocksize != 4096 */
4249 num_dec = btrfs_file_extent_num_bytes(leaf, fi);
4250 if (extent_start != 0) {
4252 if (test_bit(BTRFS_ROOT_SHAREABLE,
4254 inode_sub_bytes(inode, num_dec);
4257 clear_len = num_dec;
4258 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
4260 * we can't truncate inline items that have had
4264 btrfs_file_extent_encryption(leaf, fi) == 0 &&
4265 btrfs_file_extent_other_encoding(leaf, fi) == 0 &&
4266 btrfs_file_extent_compression(leaf, fi) == 0) {
4267 u32 size = (u32)(new_size - found_key.offset);
4269 btrfs_set_file_extent_ram_bytes(leaf, fi, size);
4270 size = btrfs_file_extent_calc_inline_size(size);
4271 btrfs_truncate_item(path, size, 1);
4272 } else if (!del_item) {
4274 * We have to bail so the last_size is set to
4275 * just before this extent.
4277 ret = NEED_TRUNCATE_BLOCK;
4281 * Inline extents are special, we just treat
4282 * them as a full sector worth in the file
4283 * extent tree just for simplicity sake.
4285 clear_len = fs_info->sectorsize;
4288 if (test_bit(BTRFS_ROOT_SHAREABLE, &root->state))
4289 inode_sub_bytes(inode, item_end + 1 - new_size);
4293 * We use btrfs_truncate_inode_items() to clean up log trees for
4294 * multiple fsyncs, and in this case we don't want to clear the
4295 * file extent range because it's just the log.
4297 if (root == BTRFS_I(inode)->root) {
4298 ret = btrfs_inode_clear_file_extent_range(BTRFS_I(inode),
4299 clear_start, clear_len);
4301 btrfs_abort_transaction(trans, ret);
4307 last_size = found_key.offset;
4309 last_size = new_size;
4311 if (!pending_del_nr) {
4312 /* no pending yet, add ourselves */
4313 pending_del_slot = path->slots[0];
4315 } else if (pending_del_nr &&
4316 path->slots[0] + 1 == pending_del_slot) {
4317 /* hop on the pending chunk */
4319 pending_del_slot = path->slots[0];
4326 should_throttle = false;
4329 root->root_key.objectid != BTRFS_TREE_LOG_OBJECTID) {
4330 struct btrfs_ref ref = { 0 };
4332 bytes_deleted += extent_num_bytes;
4334 btrfs_init_generic_ref(&ref, BTRFS_DROP_DELAYED_REF,
4335 extent_start, extent_num_bytes, 0);
4336 ref.real_root = root->root_key.objectid;
4337 btrfs_init_data_ref(&ref, btrfs_header_owner(leaf),
4338 ino, extent_offset);
4339 ret = btrfs_free_extent(trans, &ref);
4341 btrfs_abort_transaction(trans, ret);
4345 if (btrfs_should_throttle_delayed_refs(trans))
4346 should_throttle = true;
4350 if (found_type == BTRFS_INODE_ITEM_KEY)
4353 if (path->slots[0] == 0 ||
4354 path->slots[0] != pending_del_slot ||
4356 if (pending_del_nr) {
4357 ret = btrfs_del_items(trans, root, path,
4361 btrfs_abort_transaction(trans, ret);
4366 btrfs_release_path(path);
4369 * We can generate a lot of delayed refs, so we need to
4370 * throttle every once and a while and make sure we're
4371 * adding enough space to keep up with the work we are
4372 * generating. Since we hold a transaction here we
4373 * can't flush, and we don't want to FLUSH_LIMIT because
4374 * we could have generated too many delayed refs to
4375 * actually allocate, so just bail if we're short and
4376 * let the normal reservation dance happen higher up.
4378 if (should_throttle) {
4379 ret = btrfs_delayed_refs_rsv_refill(fs_info,
4380 BTRFS_RESERVE_NO_FLUSH);
4392 if (ret >= 0 && pending_del_nr) {
4395 err = btrfs_del_items(trans, root, path, pending_del_slot,
4398 btrfs_abort_transaction(trans, err);
4402 if (root->root_key.objectid != BTRFS_TREE_LOG_OBJECTID) {
4403 ASSERT(last_size >= new_size);
4404 if (!ret && last_size > new_size)
4405 last_size = new_size;
4406 btrfs_inode_safe_disk_i_size_write(inode, last_size);
4407 unlock_extent_cached(&BTRFS_I(inode)->io_tree, lock_start,
4408 (u64)-1, &cached_state);
4411 btrfs_free_path(path);
4416 * btrfs_truncate_block - read, zero a chunk and write a block
4417 * @inode - inode that we're zeroing
4418 * @from - the offset to start zeroing
4419 * @len - the length to zero, 0 to zero the entire range respective to the
4421 * @front - zero up to the offset instead of from the offset on
4423 * This will find the block for the "from" offset and cow the block and zero the
4424 * part we want to zero. This is used with truncate and hole punching.
4426 int btrfs_truncate_block(struct inode *inode, loff_t from, loff_t len,
4429 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
4430 struct address_space *mapping = inode->i_mapping;
4431 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
4432 struct btrfs_ordered_extent *ordered;
4433 struct extent_state *cached_state = NULL;
4434 struct extent_changeset *data_reserved = NULL;
4436 u32 blocksize = fs_info->sectorsize;
4437 pgoff_t index = from >> PAGE_SHIFT;
4438 unsigned offset = from & (blocksize - 1);
4440 gfp_t mask = btrfs_alloc_write_mask(mapping);
4445 if (IS_ALIGNED(offset, blocksize) &&
4446 (!len || IS_ALIGNED(len, blocksize)))
4449 block_start = round_down(from, blocksize);
4450 block_end = block_start + blocksize - 1;
4452 ret = btrfs_delalloc_reserve_space(inode, &data_reserved,
4453 block_start, blocksize);
4458 page = find_or_create_page(mapping, index, mask);
4460 btrfs_delalloc_release_space(inode, data_reserved,
4461 block_start, blocksize, true);
4462 btrfs_delalloc_release_extents(BTRFS_I(inode), blocksize);
4467 if (!PageUptodate(page)) {
4468 ret = btrfs_readpage(NULL, page);
4470 if (page->mapping != mapping) {
4475 if (!PageUptodate(page)) {
4480 wait_on_page_writeback(page);
4482 lock_extent_bits(io_tree, block_start, block_end, &cached_state);
4483 set_page_extent_mapped(page);
4485 ordered = btrfs_lookup_ordered_extent(inode, block_start);
4487 unlock_extent_cached(io_tree, block_start, block_end,
4491 btrfs_start_ordered_extent(inode, ordered, 1);
4492 btrfs_put_ordered_extent(ordered);
4496 clear_extent_bit(&BTRFS_I(inode)->io_tree, block_start, block_end,
4497 EXTENT_DELALLOC | EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG,
4498 0, 0, &cached_state);
4500 ret = btrfs_set_extent_delalloc(inode, block_start, block_end, 0,
4503 unlock_extent_cached(io_tree, block_start, block_end,
4508 if (offset != blocksize) {
4510 len = blocksize - offset;
4513 memset(kaddr + (block_start - page_offset(page)),
4516 memset(kaddr + (block_start - page_offset(page)) + offset,
4518 flush_dcache_page(page);
4521 ClearPageChecked(page);
4522 set_page_dirty(page);
4523 unlock_extent_cached(io_tree, block_start, block_end, &cached_state);
4527 btrfs_delalloc_release_space(inode, data_reserved, block_start,
4529 btrfs_delalloc_release_extents(BTRFS_I(inode), blocksize);
4533 extent_changeset_free(data_reserved);
4537 static int maybe_insert_hole(struct btrfs_root *root, struct inode *inode,
4538 u64 offset, u64 len)
4540 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
4541 struct btrfs_trans_handle *trans;
4545 * Still need to make sure the inode looks like it's been updated so
4546 * that any holes get logged if we fsync.
4548 if (btrfs_fs_incompat(fs_info, NO_HOLES)) {
4549 BTRFS_I(inode)->last_trans = fs_info->generation;
4550 BTRFS_I(inode)->last_sub_trans = root->log_transid;
4551 BTRFS_I(inode)->last_log_commit = root->last_log_commit;
4556 * 1 - for the one we're dropping
4557 * 1 - for the one we're adding
4558 * 1 - for updating the inode.
4560 trans = btrfs_start_transaction(root, 3);
4562 return PTR_ERR(trans);
4564 ret = btrfs_drop_extents(trans, root, inode, offset, offset + len, 1);
4566 btrfs_abort_transaction(trans, ret);
4567 btrfs_end_transaction(trans);
4571 ret = btrfs_insert_file_extent(trans, root, btrfs_ino(BTRFS_I(inode)),
4572 offset, 0, 0, len, 0, len, 0, 0, 0);
4574 btrfs_abort_transaction(trans, ret);
4576 btrfs_update_inode(trans, root, inode);
4577 btrfs_end_transaction(trans);
4582 * This function puts in dummy file extents for the area we're creating a hole
4583 * for. So if we are truncating this file to a larger size we need to insert
4584 * these file extents so that btrfs_get_extent will return a EXTENT_MAP_HOLE for
4585 * the range between oldsize and size
4587 int btrfs_cont_expand(struct inode *inode, loff_t oldsize, loff_t size)
4589 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
4590 struct btrfs_root *root = BTRFS_I(inode)->root;
4591 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
4592 struct extent_map *em = NULL;
4593 struct extent_state *cached_state = NULL;
4594 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
4595 u64 hole_start = ALIGN(oldsize, fs_info->sectorsize);
4596 u64 block_end = ALIGN(size, fs_info->sectorsize);
4603 * If our size started in the middle of a block we need to zero out the
4604 * rest of the block before we expand the i_size, otherwise we could
4605 * expose stale data.
4607 err = btrfs_truncate_block(inode, oldsize, 0, 0);
4611 if (size <= hole_start)
4614 btrfs_lock_and_flush_ordered_range(BTRFS_I(inode), hole_start,
4615 block_end - 1, &cached_state);
4616 cur_offset = hole_start;
4618 em = btrfs_get_extent(BTRFS_I(inode), NULL, 0, cur_offset,
4619 block_end - cur_offset);
4625 last_byte = min(extent_map_end(em), block_end);
4626 last_byte = ALIGN(last_byte, fs_info->sectorsize);
4627 hole_size = last_byte - cur_offset;
4629 if (!test_bit(EXTENT_FLAG_PREALLOC, &em->flags)) {
4630 struct extent_map *hole_em;
4632 err = maybe_insert_hole(root, inode, cur_offset,
4637 err = btrfs_inode_set_file_extent_range(BTRFS_I(inode),
4638 cur_offset, hole_size);
4642 btrfs_drop_extent_cache(BTRFS_I(inode), cur_offset,
4643 cur_offset + hole_size - 1, 0);
4644 hole_em = alloc_extent_map();
4646 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
4647 &BTRFS_I(inode)->runtime_flags);
4650 hole_em->start = cur_offset;
4651 hole_em->len = hole_size;
4652 hole_em->orig_start = cur_offset;
4654 hole_em->block_start = EXTENT_MAP_HOLE;
4655 hole_em->block_len = 0;
4656 hole_em->orig_block_len = 0;
4657 hole_em->ram_bytes = hole_size;
4658 hole_em->compress_type = BTRFS_COMPRESS_NONE;
4659 hole_em->generation = fs_info->generation;
4662 write_lock(&em_tree->lock);
4663 err = add_extent_mapping(em_tree, hole_em, 1);
4664 write_unlock(&em_tree->lock);
4667 btrfs_drop_extent_cache(BTRFS_I(inode),
4672 free_extent_map(hole_em);
4674 err = btrfs_inode_set_file_extent_range(BTRFS_I(inode),
4675 cur_offset, hole_size);
4680 free_extent_map(em);
4682 cur_offset = last_byte;
4683 if (cur_offset >= block_end)
4686 free_extent_map(em);
4687 unlock_extent_cached(io_tree, hole_start, block_end - 1, &cached_state);
4691 static int btrfs_setsize(struct inode *inode, struct iattr *attr)
4693 struct btrfs_root *root = BTRFS_I(inode)->root;
4694 struct btrfs_trans_handle *trans;
4695 loff_t oldsize = i_size_read(inode);
4696 loff_t newsize = attr->ia_size;
4697 int mask = attr->ia_valid;
4701 * The regular truncate() case without ATTR_CTIME and ATTR_MTIME is a
4702 * special case where we need to update the times despite not having
4703 * these flags set. For all other operations the VFS set these flags
4704 * explicitly if it wants a timestamp update.
4706 if (newsize != oldsize) {
4707 inode_inc_iversion(inode);
4708 if (!(mask & (ATTR_CTIME | ATTR_MTIME)))
4709 inode->i_ctime = inode->i_mtime =
4710 current_time(inode);
4713 if (newsize > oldsize) {
4715 * Don't do an expanding truncate while snapshotting is ongoing.
4716 * This is to ensure the snapshot captures a fully consistent
4717 * state of this file - if the snapshot captures this expanding
4718 * truncation, it must capture all writes that happened before
4721 btrfs_drew_write_lock(&root->snapshot_lock);
4722 ret = btrfs_cont_expand(inode, oldsize, newsize);
4724 btrfs_drew_write_unlock(&root->snapshot_lock);
4728 trans = btrfs_start_transaction(root, 1);
4729 if (IS_ERR(trans)) {
4730 btrfs_drew_write_unlock(&root->snapshot_lock);
4731 return PTR_ERR(trans);
4734 i_size_write(inode, newsize);
4735 btrfs_inode_safe_disk_i_size_write(inode, 0);
4736 pagecache_isize_extended(inode, oldsize, newsize);
4737 ret = btrfs_update_inode(trans, root, inode);
4738 btrfs_drew_write_unlock(&root->snapshot_lock);
4739 btrfs_end_transaction(trans);
4743 * We're truncating a file that used to have good data down to
4744 * zero. Make sure it gets into the ordered flush list so that
4745 * any new writes get down to disk quickly.
4748 set_bit(BTRFS_INODE_ORDERED_DATA_CLOSE,
4749 &BTRFS_I(inode)->runtime_flags);
4751 truncate_setsize(inode, newsize);
4753 /* Disable nonlocked read DIO to avoid the endless truncate */
4754 btrfs_inode_block_unlocked_dio(BTRFS_I(inode));
4755 inode_dio_wait(inode);
4756 btrfs_inode_resume_unlocked_dio(BTRFS_I(inode));
4758 ret = btrfs_truncate(inode, newsize == oldsize);
4759 if (ret && inode->i_nlink) {
4763 * Truncate failed, so fix up the in-memory size. We
4764 * adjusted disk_i_size down as we removed extents, so
4765 * wait for disk_i_size to be stable and then update the
4766 * in-memory size to match.
4768 err = btrfs_wait_ordered_range(inode, 0, (u64)-1);
4771 i_size_write(inode, BTRFS_I(inode)->disk_i_size);
4778 static int btrfs_setattr(struct dentry *dentry, struct iattr *attr)
4780 struct inode *inode = d_inode(dentry);
4781 struct btrfs_root *root = BTRFS_I(inode)->root;
4784 if (btrfs_root_readonly(root))
4787 err = setattr_prepare(dentry, attr);
4791 if (S_ISREG(inode->i_mode) && (attr->ia_valid & ATTR_SIZE)) {
4792 err = btrfs_setsize(inode, attr);
4797 if (attr->ia_valid) {
4798 setattr_copy(inode, attr);
4799 inode_inc_iversion(inode);
4800 err = btrfs_dirty_inode(inode);
4802 if (!err && attr->ia_valid & ATTR_MODE)
4803 err = posix_acl_chmod(inode, inode->i_mode);
4810 * While truncating the inode pages during eviction, we get the VFS calling
4811 * btrfs_invalidatepage() against each page of the inode. This is slow because
4812 * the calls to btrfs_invalidatepage() result in a huge amount of calls to
4813 * lock_extent_bits() and clear_extent_bit(), which keep merging and splitting
4814 * extent_state structures over and over, wasting lots of time.
4816 * Therefore if the inode is being evicted, let btrfs_invalidatepage() skip all
4817 * those expensive operations on a per page basis and do only the ordered io
4818 * finishing, while we release here the extent_map and extent_state structures,
4819 * without the excessive merging and splitting.
4821 static void evict_inode_truncate_pages(struct inode *inode)
4823 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
4824 struct extent_map_tree *map_tree = &BTRFS_I(inode)->extent_tree;
4825 struct rb_node *node;
4827 ASSERT(inode->i_state & I_FREEING);
4828 truncate_inode_pages_final(&inode->i_data);
4830 write_lock(&map_tree->lock);
4831 while (!RB_EMPTY_ROOT(&map_tree->map.rb_root)) {
4832 struct extent_map *em;
4834 node = rb_first_cached(&map_tree->map);
4835 em = rb_entry(node, struct extent_map, rb_node);
4836 clear_bit(EXTENT_FLAG_PINNED, &em->flags);
4837 clear_bit(EXTENT_FLAG_LOGGING, &em->flags);
4838 remove_extent_mapping(map_tree, em);
4839 free_extent_map(em);
4840 if (need_resched()) {
4841 write_unlock(&map_tree->lock);
4843 write_lock(&map_tree->lock);
4846 write_unlock(&map_tree->lock);
4849 * Keep looping until we have no more ranges in the io tree.
4850 * We can have ongoing bios started by readpages (called from readahead)
4851 * that have their endio callback (extent_io.c:end_bio_extent_readpage)
4852 * still in progress (unlocked the pages in the bio but did not yet
4853 * unlocked the ranges in the io tree). Therefore this means some
4854 * ranges can still be locked and eviction started because before
4855 * submitting those bios, which are executed by a separate task (work
4856 * queue kthread), inode references (inode->i_count) were not taken
4857 * (which would be dropped in the end io callback of each bio).
4858 * Therefore here we effectively end up waiting for those bios and
4859 * anyone else holding locked ranges without having bumped the inode's
4860 * reference count - if we don't do it, when they access the inode's
4861 * io_tree to unlock a range it may be too late, leading to an
4862 * use-after-free issue.
4864 spin_lock(&io_tree->lock);
4865 while (!RB_EMPTY_ROOT(&io_tree->state)) {
4866 struct extent_state *state;
4867 struct extent_state *cached_state = NULL;
4870 unsigned state_flags;
4872 node = rb_first(&io_tree->state);
4873 state = rb_entry(node, struct extent_state, rb_node);
4874 start = state->start;
4876 state_flags = state->state;
4877 spin_unlock(&io_tree->lock);
4879 lock_extent_bits(io_tree, start, end, &cached_state);
4882 * If still has DELALLOC flag, the extent didn't reach disk,
4883 * and its reserved space won't be freed by delayed_ref.
4884 * So we need to free its reserved space here.
4885 * (Refer to comment in btrfs_invalidatepage, case 2)
4887 * Note, end is the bytenr of last byte, so we need + 1 here.
4889 if (state_flags & EXTENT_DELALLOC)
4890 btrfs_qgroup_free_data(inode, NULL, start, end - start + 1);
4892 clear_extent_bit(io_tree, start, end,
4893 EXTENT_LOCKED | EXTENT_DELALLOC |
4894 EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG, 1, 1,
4898 spin_lock(&io_tree->lock);
4900 spin_unlock(&io_tree->lock);
4903 static struct btrfs_trans_handle *evict_refill_and_join(struct btrfs_root *root,
4904 struct btrfs_block_rsv *rsv)
4906 struct btrfs_fs_info *fs_info = root->fs_info;
4907 struct btrfs_block_rsv *global_rsv = &fs_info->global_block_rsv;
4908 struct btrfs_trans_handle *trans;
4909 u64 delayed_refs_extra = btrfs_calc_insert_metadata_size(fs_info, 1);
4913 * Eviction should be taking place at some place safe because of our
4914 * delayed iputs. However the normal flushing code will run delayed
4915 * iputs, so we cannot use FLUSH_ALL otherwise we'll deadlock.
4917 * We reserve the delayed_refs_extra here again because we can't use
4918 * btrfs_start_transaction(root, 0) for the same deadlocky reason as
4919 * above. We reserve our extra bit here because we generate a ton of
4920 * delayed refs activity by truncating.
4922 * If we cannot make our reservation we'll attempt to steal from the
4923 * global reserve, because we really want to be able to free up space.
4925 ret = btrfs_block_rsv_refill(root, rsv, rsv->size + delayed_refs_extra,
4926 BTRFS_RESERVE_FLUSH_EVICT);
4929 * Try to steal from the global reserve if there is space for
4932 if (btrfs_check_space_for_delayed_refs(fs_info) ||
4933 btrfs_block_rsv_migrate(global_rsv, rsv, rsv->size, 0)) {
4935 "could not allocate space for delete; will truncate on mount");
4936 return ERR_PTR(-ENOSPC);
4938 delayed_refs_extra = 0;
4941 trans = btrfs_join_transaction(root);
4945 if (delayed_refs_extra) {
4946 trans->block_rsv = &fs_info->trans_block_rsv;
4947 trans->bytes_reserved = delayed_refs_extra;
4948 btrfs_block_rsv_migrate(rsv, trans->block_rsv,
4949 delayed_refs_extra, 1);
4954 void btrfs_evict_inode(struct inode *inode)
4956 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
4957 struct btrfs_trans_handle *trans;
4958 struct btrfs_root *root = BTRFS_I(inode)->root;
4959 struct btrfs_block_rsv *rsv;
4962 trace_btrfs_inode_evict(inode);
4969 evict_inode_truncate_pages(inode);
4971 if (inode->i_nlink &&
4972 ((btrfs_root_refs(&root->root_item) != 0 &&
4973 root->root_key.objectid != BTRFS_ROOT_TREE_OBJECTID) ||
4974 btrfs_is_free_space_inode(BTRFS_I(inode))))
4977 if (is_bad_inode(inode))
4980 btrfs_free_io_failure_record(BTRFS_I(inode), 0, (u64)-1);
4982 if (test_bit(BTRFS_FS_LOG_RECOVERING, &fs_info->flags))
4985 if (inode->i_nlink > 0) {
4986 BUG_ON(btrfs_root_refs(&root->root_item) != 0 &&
4987 root->root_key.objectid != BTRFS_ROOT_TREE_OBJECTID);
4991 ret = btrfs_commit_inode_delayed_inode(BTRFS_I(inode));
4995 rsv = btrfs_alloc_block_rsv(fs_info, BTRFS_BLOCK_RSV_TEMP);
4998 rsv->size = btrfs_calc_metadata_size(fs_info, 1);
5001 btrfs_i_size_write(BTRFS_I(inode), 0);
5004 trans = evict_refill_and_join(root, rsv);
5008 trans->block_rsv = rsv;
5010 ret = btrfs_truncate_inode_items(trans, root, inode, 0, 0);
5011 trans->block_rsv = &fs_info->trans_block_rsv;
5012 btrfs_end_transaction(trans);
5013 btrfs_btree_balance_dirty(fs_info);
5014 if (ret && ret != -ENOSPC && ret != -EAGAIN)
5021 * Errors here aren't a big deal, it just means we leave orphan items in
5022 * the tree. They will be cleaned up on the next mount. If the inode
5023 * number gets reused, cleanup deletes the orphan item without doing
5024 * anything, and unlink reuses the existing orphan item.
5026 * If it turns out that we are dropping too many of these, we might want
5027 * to add a mechanism for retrying these after a commit.
5029 trans = evict_refill_and_join(root, rsv);
5030 if (!IS_ERR(trans)) {
5031 trans->block_rsv = rsv;
5032 btrfs_orphan_del(trans, BTRFS_I(inode));
5033 trans->block_rsv = &fs_info->trans_block_rsv;
5034 btrfs_end_transaction(trans);
5037 if (!(root == fs_info->tree_root ||
5038 root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID))
5039 btrfs_return_ino(root, btrfs_ino(BTRFS_I(inode)));
5042 btrfs_free_block_rsv(fs_info, rsv);
5045 * If we didn't successfully delete, the orphan item will still be in
5046 * the tree and we'll retry on the next mount. Again, we might also want
5047 * to retry these periodically in the future.
5049 btrfs_remove_delayed_node(BTRFS_I(inode));
5054 * Return the key found in the dir entry in the location pointer, fill @type
5055 * with BTRFS_FT_*, and return 0.
5057 * If no dir entries were found, returns -ENOENT.
5058 * If found a corrupted location in dir entry, returns -EUCLEAN.
5060 static int btrfs_inode_by_name(struct inode *dir, struct dentry *dentry,
5061 struct btrfs_key *location, u8 *type)
5063 const char *name = dentry->d_name.name;
5064 int namelen = dentry->d_name.len;
5065 struct btrfs_dir_item *di;
5066 struct btrfs_path *path;
5067 struct btrfs_root *root = BTRFS_I(dir)->root;
5070 path = btrfs_alloc_path();
5074 di = btrfs_lookup_dir_item(NULL, root, path, btrfs_ino(BTRFS_I(dir)),
5076 if (IS_ERR_OR_NULL(di)) {
5077 ret = di ? PTR_ERR(di) : -ENOENT;
5081 btrfs_dir_item_key_to_cpu(path->nodes[0], di, location);
5082 if (location->type != BTRFS_INODE_ITEM_KEY &&
5083 location->type != BTRFS_ROOT_ITEM_KEY) {
5085 btrfs_warn(root->fs_info,
5086 "%s gets something invalid in DIR_ITEM (name %s, directory ino %llu, location(%llu %u %llu))",
5087 __func__, name, btrfs_ino(BTRFS_I(dir)),
5088 location->objectid, location->type, location->offset);
5091 *type = btrfs_dir_type(path->nodes[0], di);
5093 btrfs_free_path(path);
5098 * when we hit a tree root in a directory, the btrfs part of the inode
5099 * needs to be changed to reflect the root directory of the tree root. This
5100 * is kind of like crossing a mount point.
5102 static int fixup_tree_root_location(struct btrfs_fs_info *fs_info,
5104 struct dentry *dentry,
5105 struct btrfs_key *location,
5106 struct btrfs_root **sub_root)
5108 struct btrfs_path *path;
5109 struct btrfs_root *new_root;
5110 struct btrfs_root_ref *ref;
5111 struct extent_buffer *leaf;
5112 struct btrfs_key key;
5116 path = btrfs_alloc_path();
5123 key.objectid = BTRFS_I(dir)->root->root_key.objectid;
5124 key.type = BTRFS_ROOT_REF_KEY;
5125 key.offset = location->objectid;
5127 ret = btrfs_search_slot(NULL, fs_info->tree_root, &key, path, 0, 0);
5134 leaf = path->nodes[0];
5135 ref = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_root_ref);
5136 if (btrfs_root_ref_dirid(leaf, ref) != btrfs_ino(BTRFS_I(dir)) ||
5137 btrfs_root_ref_name_len(leaf, ref) != dentry->d_name.len)
5140 ret = memcmp_extent_buffer(leaf, dentry->d_name.name,
5141 (unsigned long)(ref + 1),
5142 dentry->d_name.len);
5146 btrfs_release_path(path);
5148 new_root = btrfs_get_fs_root(fs_info, location->objectid, true);
5149 if (IS_ERR(new_root)) {
5150 err = PTR_ERR(new_root);
5154 *sub_root = new_root;
5155 location->objectid = btrfs_root_dirid(&new_root->root_item);
5156 location->type = BTRFS_INODE_ITEM_KEY;
5157 location->offset = 0;
5160 btrfs_free_path(path);
5164 static void inode_tree_add(struct inode *inode)
5166 struct btrfs_root *root = BTRFS_I(inode)->root;
5167 struct btrfs_inode *entry;
5169 struct rb_node *parent;
5170 struct rb_node *new = &BTRFS_I(inode)->rb_node;
5171 u64 ino = btrfs_ino(BTRFS_I(inode));
5173 if (inode_unhashed(inode))
5176 spin_lock(&root->inode_lock);
5177 p = &root->inode_tree.rb_node;
5180 entry = rb_entry(parent, struct btrfs_inode, rb_node);
5182 if (ino < btrfs_ino(entry))
5183 p = &parent->rb_left;
5184 else if (ino > btrfs_ino(entry))
5185 p = &parent->rb_right;
5187 WARN_ON(!(entry->vfs_inode.i_state &
5188 (I_WILL_FREE | I_FREEING)));
5189 rb_replace_node(parent, new, &root->inode_tree);
5190 RB_CLEAR_NODE(parent);
5191 spin_unlock(&root->inode_lock);
5195 rb_link_node(new, parent, p);
5196 rb_insert_color(new, &root->inode_tree);
5197 spin_unlock(&root->inode_lock);
5200 static void inode_tree_del(struct inode *inode)
5202 struct btrfs_root *root = BTRFS_I(inode)->root;
5205 spin_lock(&root->inode_lock);
5206 if (!RB_EMPTY_NODE(&BTRFS_I(inode)->rb_node)) {
5207 rb_erase(&BTRFS_I(inode)->rb_node, &root->inode_tree);
5208 RB_CLEAR_NODE(&BTRFS_I(inode)->rb_node);
5209 empty = RB_EMPTY_ROOT(&root->inode_tree);
5211 spin_unlock(&root->inode_lock);
5213 if (empty && btrfs_root_refs(&root->root_item) == 0) {
5214 spin_lock(&root->inode_lock);
5215 empty = RB_EMPTY_ROOT(&root->inode_tree);
5216 spin_unlock(&root->inode_lock);
5218 btrfs_add_dead_root(root);
5223 static int btrfs_init_locked_inode(struct inode *inode, void *p)
5225 struct btrfs_iget_args *args = p;
5227 inode->i_ino = args->ino;
5228 BTRFS_I(inode)->location.objectid = args->ino;
5229 BTRFS_I(inode)->location.type = BTRFS_INODE_ITEM_KEY;
5230 BTRFS_I(inode)->location.offset = 0;
5231 BTRFS_I(inode)->root = btrfs_grab_root(args->root);
5232 BUG_ON(args->root && !BTRFS_I(inode)->root);
5236 static int btrfs_find_actor(struct inode *inode, void *opaque)
5238 struct btrfs_iget_args *args = opaque;
5240 return args->ino == BTRFS_I(inode)->location.objectid &&
5241 args->root == BTRFS_I(inode)->root;
5244 static struct inode *btrfs_iget_locked(struct super_block *s, u64 ino,
5245 struct btrfs_root *root)
5247 struct inode *inode;
5248 struct btrfs_iget_args args;
5249 unsigned long hashval = btrfs_inode_hash(ino, root);
5254 inode = iget5_locked(s, hashval, btrfs_find_actor,
5255 btrfs_init_locked_inode,
5261 * Get an inode object given its inode number and corresponding root.
5262 * Path can be preallocated to prevent recursing back to iget through
5263 * allocator. NULL is also valid but may require an additional allocation
5266 struct inode *btrfs_iget_path(struct super_block *s, u64 ino,
5267 struct btrfs_root *root, struct btrfs_path *path)
5269 struct inode *inode;
5271 inode = btrfs_iget_locked(s, ino, root);
5273 return ERR_PTR(-ENOMEM);
5275 if (inode->i_state & I_NEW) {
5278 ret = btrfs_read_locked_inode(inode, path);
5280 inode_tree_add(inode);
5281 unlock_new_inode(inode);
5285 * ret > 0 can come from btrfs_search_slot called by
5286 * btrfs_read_locked_inode, this means the inode item
5291 inode = ERR_PTR(ret);
5298 struct inode *btrfs_iget(struct super_block *s, u64 ino, struct btrfs_root *root)
5300 return btrfs_iget_path(s, ino, root, NULL);
5303 static struct inode *new_simple_dir(struct super_block *s,
5304 struct btrfs_key *key,
5305 struct btrfs_root *root)
5307 struct inode *inode = new_inode(s);
5310 return ERR_PTR(-ENOMEM);
5312 BTRFS_I(inode)->root = btrfs_grab_root(root);
5313 memcpy(&BTRFS_I(inode)->location, key, sizeof(*key));
5314 set_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags);
5316 inode->i_ino = BTRFS_EMPTY_SUBVOL_DIR_OBJECTID;
5318 * We only need lookup, the rest is read-only and there's no inode
5319 * associated with the dentry
5321 inode->i_op = &simple_dir_inode_operations;
5322 inode->i_opflags &= ~IOP_XATTR;
5323 inode->i_fop = &simple_dir_operations;
5324 inode->i_mode = S_IFDIR | S_IRUGO | S_IWUSR | S_IXUGO;
5325 inode->i_mtime = current_time(inode);
5326 inode->i_atime = inode->i_mtime;
5327 inode->i_ctime = inode->i_mtime;
5328 BTRFS_I(inode)->i_otime = inode->i_mtime;
5333 static inline u8 btrfs_inode_type(struct inode *inode)
5336 * Compile-time asserts that generic FT_* types still match
5339 BUILD_BUG_ON(BTRFS_FT_UNKNOWN != FT_UNKNOWN);
5340 BUILD_BUG_ON(BTRFS_FT_REG_FILE != FT_REG_FILE);
5341 BUILD_BUG_ON(BTRFS_FT_DIR != FT_DIR);
5342 BUILD_BUG_ON(BTRFS_FT_CHRDEV != FT_CHRDEV);
5343 BUILD_BUG_ON(BTRFS_FT_BLKDEV != FT_BLKDEV);
5344 BUILD_BUG_ON(BTRFS_FT_FIFO != FT_FIFO);
5345 BUILD_BUG_ON(BTRFS_FT_SOCK != FT_SOCK);
5346 BUILD_BUG_ON(BTRFS_FT_SYMLINK != FT_SYMLINK);
5348 return fs_umode_to_ftype(inode->i_mode);
5351 struct inode *btrfs_lookup_dentry(struct inode *dir, struct dentry *dentry)
5353 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
5354 struct inode *inode;
5355 struct btrfs_root *root = BTRFS_I(dir)->root;
5356 struct btrfs_root *sub_root = root;
5357 struct btrfs_key location;
5361 if (dentry->d_name.len > BTRFS_NAME_LEN)
5362 return ERR_PTR(-ENAMETOOLONG);
5364 ret = btrfs_inode_by_name(dir, dentry, &location, &di_type);
5366 return ERR_PTR(ret);
5368 if (location.type == BTRFS_INODE_ITEM_KEY) {
5369 inode = btrfs_iget(dir->i_sb, location.objectid, root);
5373 /* Do extra check against inode mode with di_type */
5374 if (btrfs_inode_type(inode) != di_type) {
5376 "inode mode mismatch with dir: inode mode=0%o btrfs type=%u dir type=%u",
5377 inode->i_mode, btrfs_inode_type(inode),
5380 return ERR_PTR(-EUCLEAN);
5385 ret = fixup_tree_root_location(fs_info, dir, dentry,
5386 &location, &sub_root);
5389 inode = ERR_PTR(ret);
5391 inode = new_simple_dir(dir->i_sb, &location, sub_root);
5393 inode = btrfs_iget(dir->i_sb, location.objectid, sub_root);
5395 if (root != sub_root)
5396 btrfs_put_root(sub_root);
5398 if (!IS_ERR(inode) && root != sub_root) {
5399 down_read(&fs_info->cleanup_work_sem);
5400 if (!sb_rdonly(inode->i_sb))
5401 ret = btrfs_orphan_cleanup(sub_root);
5402 up_read(&fs_info->cleanup_work_sem);
5405 inode = ERR_PTR(ret);
5412 static int btrfs_dentry_delete(const struct dentry *dentry)
5414 struct btrfs_root *root;
5415 struct inode *inode = d_inode(dentry);
5417 if (!inode && !IS_ROOT(dentry))
5418 inode = d_inode(dentry->d_parent);
5421 root = BTRFS_I(inode)->root;
5422 if (btrfs_root_refs(&root->root_item) == 0)
5425 if (btrfs_ino(BTRFS_I(inode)) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)
5431 static struct dentry *btrfs_lookup(struct inode *dir, struct dentry *dentry,
5434 struct inode *inode = btrfs_lookup_dentry(dir, dentry);
5436 if (inode == ERR_PTR(-ENOENT))
5438 return d_splice_alias(inode, dentry);
5442 * All this infrastructure exists because dir_emit can fault, and we are holding
5443 * the tree lock when doing readdir. For now just allocate a buffer and copy
5444 * our information into that, and then dir_emit from the buffer. This is
5445 * similar to what NFS does, only we don't keep the buffer around in pagecache
5446 * because I'm afraid I'll mess that up. Long term we need to make filldir do
5447 * copy_to_user_inatomic so we don't have to worry about page faulting under the
5450 static int btrfs_opendir(struct inode *inode, struct file *file)
5452 struct btrfs_file_private *private;
5454 private = kzalloc(sizeof(struct btrfs_file_private), GFP_KERNEL);
5457 private->filldir_buf = kzalloc(PAGE_SIZE, GFP_KERNEL);
5458 if (!private->filldir_buf) {
5462 file->private_data = private;
5473 static int btrfs_filldir(void *addr, int entries, struct dir_context *ctx)
5476 struct dir_entry *entry = addr;
5477 char *name = (char *)(entry + 1);
5479 ctx->pos = get_unaligned(&entry->offset);
5480 if (!dir_emit(ctx, name, get_unaligned(&entry->name_len),
5481 get_unaligned(&entry->ino),
5482 get_unaligned(&entry->type)))
5484 addr += sizeof(struct dir_entry) +
5485 get_unaligned(&entry->name_len);
5491 static int btrfs_real_readdir(struct file *file, struct dir_context *ctx)
5493 struct inode *inode = file_inode(file);
5494 struct btrfs_root *root = BTRFS_I(inode)->root;
5495 struct btrfs_file_private *private = file->private_data;
5496 struct btrfs_dir_item *di;
5497 struct btrfs_key key;
5498 struct btrfs_key found_key;
5499 struct btrfs_path *path;
5501 struct list_head ins_list;
5502 struct list_head del_list;
5504 struct extent_buffer *leaf;
5511 struct btrfs_key location;
5513 if (!dir_emit_dots(file, ctx))
5516 path = btrfs_alloc_path();
5520 addr = private->filldir_buf;
5521 path->reada = READA_FORWARD;
5523 INIT_LIST_HEAD(&ins_list);
5524 INIT_LIST_HEAD(&del_list);
5525 put = btrfs_readdir_get_delayed_items(inode, &ins_list, &del_list);
5528 key.type = BTRFS_DIR_INDEX_KEY;
5529 key.offset = ctx->pos;
5530 key.objectid = btrfs_ino(BTRFS_I(inode));
5532 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
5537 struct dir_entry *entry;
5539 leaf = path->nodes[0];
5540 slot = path->slots[0];
5541 if (slot >= btrfs_header_nritems(leaf)) {
5542 ret = btrfs_next_leaf(root, path);
5550 btrfs_item_key_to_cpu(leaf, &found_key, slot);
5552 if (found_key.objectid != key.objectid)
5554 if (found_key.type != BTRFS_DIR_INDEX_KEY)
5556 if (found_key.offset < ctx->pos)
5558 if (btrfs_should_delete_dir_index(&del_list, found_key.offset))
5560 di = btrfs_item_ptr(leaf, slot, struct btrfs_dir_item);
5561 name_len = btrfs_dir_name_len(leaf, di);
5562 if ((total_len + sizeof(struct dir_entry) + name_len) >=
5564 btrfs_release_path(path);
5565 ret = btrfs_filldir(private->filldir_buf, entries, ctx);
5568 addr = private->filldir_buf;
5575 put_unaligned(name_len, &entry->name_len);
5576 name_ptr = (char *)(entry + 1);
5577 read_extent_buffer(leaf, name_ptr, (unsigned long)(di + 1),
5579 put_unaligned(fs_ftype_to_dtype(btrfs_dir_type(leaf, di)),
5581 btrfs_dir_item_key_to_cpu(leaf, di, &location);
5582 put_unaligned(location.objectid, &entry->ino);
5583 put_unaligned(found_key.offset, &entry->offset);
5585 addr += sizeof(struct dir_entry) + name_len;
5586 total_len += sizeof(struct dir_entry) + name_len;
5590 btrfs_release_path(path);
5592 ret = btrfs_filldir(private->filldir_buf, entries, ctx);
5596 ret = btrfs_readdir_delayed_dir_index(ctx, &ins_list);
5601 * Stop new entries from being returned after we return the last
5604 * New directory entries are assigned a strictly increasing
5605 * offset. This means that new entries created during readdir
5606 * are *guaranteed* to be seen in the future by that readdir.
5607 * This has broken buggy programs which operate on names as
5608 * they're returned by readdir. Until we re-use freed offsets
5609 * we have this hack to stop new entries from being returned
5610 * under the assumption that they'll never reach this huge
5613 * This is being careful not to overflow 32bit loff_t unless the
5614 * last entry requires it because doing so has broken 32bit apps
5617 if (ctx->pos >= INT_MAX)
5618 ctx->pos = LLONG_MAX;
5625 btrfs_readdir_put_delayed_items(inode, &ins_list, &del_list);
5626 btrfs_free_path(path);
5631 * This is somewhat expensive, updating the tree every time the
5632 * inode changes. But, it is most likely to find the inode in cache.
5633 * FIXME, needs more benchmarking...there are no reasons other than performance
5634 * to keep or drop this code.
5636 static int btrfs_dirty_inode(struct inode *inode)
5638 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
5639 struct btrfs_root *root = BTRFS_I(inode)->root;
5640 struct btrfs_trans_handle *trans;
5643 if (test_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags))
5646 trans = btrfs_join_transaction(root);
5648 return PTR_ERR(trans);
5650 ret = btrfs_update_inode(trans, root, inode);
5651 if (ret && ret == -ENOSPC) {
5652 /* whoops, lets try again with the full transaction */
5653 btrfs_end_transaction(trans);
5654 trans = btrfs_start_transaction(root, 1);
5656 return PTR_ERR(trans);
5658 ret = btrfs_update_inode(trans, root, inode);
5660 btrfs_end_transaction(trans);
5661 if (BTRFS_I(inode)->delayed_node)
5662 btrfs_balance_delayed_items(fs_info);
5668 * This is a copy of file_update_time. We need this so we can return error on
5669 * ENOSPC for updating the inode in the case of file write and mmap writes.
5671 static int btrfs_update_time(struct inode *inode, struct timespec64 *now,
5674 struct btrfs_root *root = BTRFS_I(inode)->root;
5675 bool dirty = flags & ~S_VERSION;
5677 if (btrfs_root_readonly(root))
5680 if (flags & S_VERSION)
5681 dirty |= inode_maybe_inc_iversion(inode, dirty);
5682 if (flags & S_CTIME)
5683 inode->i_ctime = *now;
5684 if (flags & S_MTIME)
5685 inode->i_mtime = *now;
5686 if (flags & S_ATIME)
5687 inode->i_atime = *now;
5688 return dirty ? btrfs_dirty_inode(inode) : 0;
5692 * find the highest existing sequence number in a directory
5693 * and then set the in-memory index_cnt variable to reflect
5694 * free sequence numbers
5696 static int btrfs_set_inode_index_count(struct btrfs_inode *inode)
5698 struct btrfs_root *root = inode->root;
5699 struct btrfs_key key, found_key;
5700 struct btrfs_path *path;
5701 struct extent_buffer *leaf;
5704 key.objectid = btrfs_ino(inode);
5705 key.type = BTRFS_DIR_INDEX_KEY;
5706 key.offset = (u64)-1;
5708 path = btrfs_alloc_path();
5712 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
5715 /* FIXME: we should be able to handle this */
5721 * MAGIC NUMBER EXPLANATION:
5722 * since we search a directory based on f_pos we have to start at 2
5723 * since '.' and '..' have f_pos of 0 and 1 respectively, so everybody
5724 * else has to start at 2
5726 if (path->slots[0] == 0) {
5727 inode->index_cnt = 2;
5733 leaf = path->nodes[0];
5734 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
5736 if (found_key.objectid != btrfs_ino(inode) ||
5737 found_key.type != BTRFS_DIR_INDEX_KEY) {
5738 inode->index_cnt = 2;
5742 inode->index_cnt = found_key.offset + 1;
5744 btrfs_free_path(path);
5749 * helper to find a free sequence number in a given directory. This current
5750 * code is very simple, later versions will do smarter things in the btree
5752 int btrfs_set_inode_index(struct btrfs_inode *dir, u64 *index)
5756 if (dir->index_cnt == (u64)-1) {
5757 ret = btrfs_inode_delayed_dir_index_count(dir);
5759 ret = btrfs_set_inode_index_count(dir);
5765 *index = dir->index_cnt;
5771 static int btrfs_insert_inode_locked(struct inode *inode)
5773 struct btrfs_iget_args args;
5775 args.ino = BTRFS_I(inode)->location.objectid;
5776 args.root = BTRFS_I(inode)->root;
5778 return insert_inode_locked4(inode,
5779 btrfs_inode_hash(inode->i_ino, BTRFS_I(inode)->root),
5780 btrfs_find_actor, &args);
5784 * Inherit flags from the parent inode.
5786 * Currently only the compression flags and the cow flags are inherited.
5788 static void btrfs_inherit_iflags(struct inode *inode, struct inode *dir)
5795 flags = BTRFS_I(dir)->flags;
5797 if (flags & BTRFS_INODE_NOCOMPRESS) {
5798 BTRFS_I(inode)->flags &= ~BTRFS_INODE_COMPRESS;
5799 BTRFS_I(inode)->flags |= BTRFS_INODE_NOCOMPRESS;
5800 } else if (flags & BTRFS_INODE_COMPRESS) {
5801 BTRFS_I(inode)->flags &= ~BTRFS_INODE_NOCOMPRESS;
5802 BTRFS_I(inode)->flags |= BTRFS_INODE_COMPRESS;
5805 if (flags & BTRFS_INODE_NODATACOW) {
5806 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATACOW;
5807 if (S_ISREG(inode->i_mode))
5808 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATASUM;
5811 btrfs_sync_inode_flags_to_i_flags(inode);
5814 static struct inode *btrfs_new_inode(struct btrfs_trans_handle *trans,
5815 struct btrfs_root *root,
5817 const char *name, int name_len,
5818 u64 ref_objectid, u64 objectid,
5819 umode_t mode, u64 *index)
5821 struct btrfs_fs_info *fs_info = root->fs_info;
5822 struct inode *inode;
5823 struct btrfs_inode_item *inode_item;
5824 struct btrfs_key *location;
5825 struct btrfs_path *path;
5826 struct btrfs_inode_ref *ref;
5827 struct btrfs_key key[2];
5829 int nitems = name ? 2 : 1;
5831 unsigned int nofs_flag;
5834 path = btrfs_alloc_path();
5836 return ERR_PTR(-ENOMEM);
5838 nofs_flag = memalloc_nofs_save();
5839 inode = new_inode(fs_info->sb);
5840 memalloc_nofs_restore(nofs_flag);
5842 btrfs_free_path(path);
5843 return ERR_PTR(-ENOMEM);
5847 * O_TMPFILE, set link count to 0, so that after this point,
5848 * we fill in an inode item with the correct link count.
5851 set_nlink(inode, 0);
5854 * we have to initialize this early, so we can reclaim the inode
5855 * number if we fail afterwards in this function.
5857 inode->i_ino = objectid;
5860 trace_btrfs_inode_request(dir);
5862 ret = btrfs_set_inode_index(BTRFS_I(dir), index);
5864 btrfs_free_path(path);
5866 return ERR_PTR(ret);
5872 * index_cnt is ignored for everything but a dir,
5873 * btrfs_set_inode_index_count has an explanation for the magic
5876 BTRFS_I(inode)->index_cnt = 2;
5877 BTRFS_I(inode)->dir_index = *index;
5878 BTRFS_I(inode)->root = btrfs_grab_root(root);
5879 BTRFS_I(inode)->generation = trans->transid;
5880 inode->i_generation = BTRFS_I(inode)->generation;
5883 * We could have gotten an inode number from somebody who was fsynced
5884 * and then removed in this same transaction, so let's just set full
5885 * sync since it will be a full sync anyway and this will blow away the
5886 * old info in the log.
5888 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &BTRFS_I(inode)->runtime_flags);
5890 key[0].objectid = objectid;
5891 key[0].type = BTRFS_INODE_ITEM_KEY;
5894 sizes[0] = sizeof(struct btrfs_inode_item);
5898 * Start new inodes with an inode_ref. This is slightly more
5899 * efficient for small numbers of hard links since they will
5900 * be packed into one item. Extended refs will kick in if we
5901 * add more hard links than can fit in the ref item.
5903 key[1].objectid = objectid;
5904 key[1].type = BTRFS_INODE_REF_KEY;
5905 key[1].offset = ref_objectid;
5907 sizes[1] = name_len + sizeof(*ref);
5910 location = &BTRFS_I(inode)->location;
5911 location->objectid = objectid;
5912 location->offset = 0;
5913 location->type = BTRFS_INODE_ITEM_KEY;
5915 ret = btrfs_insert_inode_locked(inode);
5921 path->leave_spinning = 1;
5922 ret = btrfs_insert_empty_items(trans, root, path, key, sizes, nitems);
5926 inode_init_owner(inode, dir, mode);
5927 inode_set_bytes(inode, 0);
5929 inode->i_mtime = current_time(inode);
5930 inode->i_atime = inode->i_mtime;
5931 inode->i_ctime = inode->i_mtime;
5932 BTRFS_I(inode)->i_otime = inode->i_mtime;
5934 inode_item = btrfs_item_ptr(path->nodes[0], path->slots[0],
5935 struct btrfs_inode_item);
5936 memzero_extent_buffer(path->nodes[0], (unsigned long)inode_item,
5937 sizeof(*inode_item));
5938 fill_inode_item(trans, path->nodes[0], inode_item, inode);
5941 ref = btrfs_item_ptr(path->nodes[0], path->slots[0] + 1,
5942 struct btrfs_inode_ref);
5943 btrfs_set_inode_ref_name_len(path->nodes[0], ref, name_len);
5944 btrfs_set_inode_ref_index(path->nodes[0], ref, *index);
5945 ptr = (unsigned long)(ref + 1);
5946 write_extent_buffer(path->nodes[0], name, ptr, name_len);
5949 btrfs_mark_buffer_dirty(path->nodes[0]);
5950 btrfs_free_path(path);
5952 btrfs_inherit_iflags(inode, dir);
5954 if (S_ISREG(mode)) {
5955 if (btrfs_test_opt(fs_info, NODATASUM))
5956 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATASUM;
5957 if (btrfs_test_opt(fs_info, NODATACOW))
5958 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATACOW |
5959 BTRFS_INODE_NODATASUM;
5962 inode_tree_add(inode);
5964 trace_btrfs_inode_new(inode);
5965 btrfs_set_inode_last_trans(trans, inode);
5967 btrfs_update_root_times(trans, root);
5969 ret = btrfs_inode_inherit_props(trans, inode, dir);
5972 "error inheriting props for ino %llu (root %llu): %d",
5973 btrfs_ino(BTRFS_I(inode)), root->root_key.objectid, ret);
5978 discard_new_inode(inode);
5981 BTRFS_I(dir)->index_cnt--;
5982 btrfs_free_path(path);
5983 return ERR_PTR(ret);
5987 * utility function to add 'inode' into 'parent_inode' with
5988 * a give name and a given sequence number.
5989 * if 'add_backref' is true, also insert a backref from the
5990 * inode to the parent directory.
5992 int btrfs_add_link(struct btrfs_trans_handle *trans,
5993 struct btrfs_inode *parent_inode, struct btrfs_inode *inode,
5994 const char *name, int name_len, int add_backref, u64 index)
5997 struct btrfs_key key;
5998 struct btrfs_root *root = parent_inode->root;
5999 u64 ino = btrfs_ino(inode);
6000 u64 parent_ino = btrfs_ino(parent_inode);
6002 if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
6003 memcpy(&key, &inode->root->root_key, sizeof(key));
6006 key.type = BTRFS_INODE_ITEM_KEY;
6010 if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
6011 ret = btrfs_add_root_ref(trans, key.objectid,
6012 root->root_key.objectid, parent_ino,
6013 index, name, name_len);
6014 } else if (add_backref) {
6015 ret = btrfs_insert_inode_ref(trans, root, name, name_len, ino,
6019 /* Nothing to clean up yet */
6023 ret = btrfs_insert_dir_item(trans, name, name_len, parent_inode, &key,
6024 btrfs_inode_type(&inode->vfs_inode), index);
6025 if (ret == -EEXIST || ret == -EOVERFLOW)
6028 btrfs_abort_transaction(trans, ret);
6032 btrfs_i_size_write(parent_inode, parent_inode->vfs_inode.i_size +
6034 inode_inc_iversion(&parent_inode->vfs_inode);
6036 * If we are replaying a log tree, we do not want to update the mtime
6037 * and ctime of the parent directory with the current time, since the
6038 * log replay procedure is responsible for setting them to their correct
6039 * values (the ones it had when the fsync was done).
6041 if (!test_bit(BTRFS_FS_LOG_RECOVERING, &root->fs_info->flags)) {
6042 struct timespec64 now = current_time(&parent_inode->vfs_inode);
6044 parent_inode->vfs_inode.i_mtime = now;
6045 parent_inode->vfs_inode.i_ctime = now;
6047 ret = btrfs_update_inode(trans, root, &parent_inode->vfs_inode);
6049 btrfs_abort_transaction(trans, ret);
6053 if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
6056 err = btrfs_del_root_ref(trans, key.objectid,
6057 root->root_key.objectid, parent_ino,
6058 &local_index, name, name_len);
6060 btrfs_abort_transaction(trans, err);
6061 } else if (add_backref) {
6065 err = btrfs_del_inode_ref(trans, root, name, name_len,
6066 ino, parent_ino, &local_index);
6068 btrfs_abort_transaction(trans, err);
6071 /* Return the original error code */
6075 static int btrfs_add_nondir(struct btrfs_trans_handle *trans,
6076 struct btrfs_inode *dir, struct dentry *dentry,
6077 struct btrfs_inode *inode, int backref, u64 index)
6079 int err = btrfs_add_link(trans, dir, inode,
6080 dentry->d_name.name, dentry->d_name.len,
6087 static int btrfs_mknod(struct inode *dir, struct dentry *dentry,
6088 umode_t mode, dev_t rdev)
6090 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
6091 struct btrfs_trans_handle *trans;
6092 struct btrfs_root *root = BTRFS_I(dir)->root;
6093 struct inode *inode = NULL;
6099 * 2 for inode item and ref
6101 * 1 for xattr if selinux is on
6103 trans = btrfs_start_transaction(root, 5);
6105 return PTR_ERR(trans);
6107 err = btrfs_find_free_ino(root, &objectid);
6111 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
6112 dentry->d_name.len, btrfs_ino(BTRFS_I(dir)), objectid,
6114 if (IS_ERR(inode)) {
6115 err = PTR_ERR(inode);
6121 * If the active LSM wants to access the inode during
6122 * d_instantiate it needs these. Smack checks to see
6123 * if the filesystem supports xattrs by looking at the
6126 inode->i_op = &btrfs_special_inode_operations;
6127 init_special_inode(inode, inode->i_mode, rdev);
6129 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
6133 err = btrfs_add_nondir(trans, BTRFS_I(dir), dentry, BTRFS_I(inode),
6138 btrfs_update_inode(trans, root, inode);
6139 d_instantiate_new(dentry, inode);
6142 btrfs_end_transaction(trans);
6143 btrfs_btree_balance_dirty(fs_info);
6145 inode_dec_link_count(inode);
6146 discard_new_inode(inode);
6151 static int btrfs_create(struct inode *dir, struct dentry *dentry,
6152 umode_t mode, bool excl)
6154 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
6155 struct btrfs_trans_handle *trans;
6156 struct btrfs_root *root = BTRFS_I(dir)->root;
6157 struct inode *inode = NULL;
6163 * 2 for inode item and ref
6165 * 1 for xattr if selinux is on
6167 trans = btrfs_start_transaction(root, 5);
6169 return PTR_ERR(trans);
6171 err = btrfs_find_free_ino(root, &objectid);
6175 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
6176 dentry->d_name.len, btrfs_ino(BTRFS_I(dir)), objectid,
6178 if (IS_ERR(inode)) {
6179 err = PTR_ERR(inode);
6184 * If the active LSM wants to access the inode during
6185 * d_instantiate it needs these. Smack checks to see
6186 * if the filesystem supports xattrs by looking at the
6189 inode->i_fop = &btrfs_file_operations;
6190 inode->i_op = &btrfs_file_inode_operations;
6191 inode->i_mapping->a_ops = &btrfs_aops;
6193 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
6197 err = btrfs_update_inode(trans, root, inode);
6201 err = btrfs_add_nondir(trans, BTRFS_I(dir), dentry, BTRFS_I(inode),
6206 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
6207 d_instantiate_new(dentry, inode);
6210 btrfs_end_transaction(trans);
6212 inode_dec_link_count(inode);
6213 discard_new_inode(inode);
6215 btrfs_btree_balance_dirty(fs_info);
6219 static int btrfs_link(struct dentry *old_dentry, struct inode *dir,
6220 struct dentry *dentry)
6222 struct btrfs_trans_handle *trans = NULL;
6223 struct btrfs_root *root = BTRFS_I(dir)->root;
6224 struct inode *inode = d_inode(old_dentry);
6225 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
6230 /* do not allow sys_link's with other subvols of the same device */
6231 if (root->root_key.objectid != BTRFS_I(inode)->root->root_key.objectid)
6234 if (inode->i_nlink >= BTRFS_LINK_MAX)
6237 err = btrfs_set_inode_index(BTRFS_I(dir), &index);
6242 * 2 items for inode and inode ref
6243 * 2 items for dir items
6244 * 1 item for parent inode
6245 * 1 item for orphan item deletion if O_TMPFILE
6247 trans = btrfs_start_transaction(root, inode->i_nlink ? 5 : 6);
6248 if (IS_ERR(trans)) {
6249 err = PTR_ERR(trans);
6254 /* There are several dir indexes for this inode, clear the cache. */
6255 BTRFS_I(inode)->dir_index = 0ULL;
6257 inode_inc_iversion(inode);
6258 inode->i_ctime = current_time(inode);
6260 set_bit(BTRFS_INODE_COPY_EVERYTHING, &BTRFS_I(inode)->runtime_flags);
6262 err = btrfs_add_nondir(trans, BTRFS_I(dir), dentry, BTRFS_I(inode),
6268 struct dentry *parent = dentry->d_parent;
6271 err = btrfs_update_inode(trans, root, inode);
6274 if (inode->i_nlink == 1) {
6276 * If new hard link count is 1, it's a file created
6277 * with open(2) O_TMPFILE flag.
6279 err = btrfs_orphan_del(trans, BTRFS_I(inode));
6283 d_instantiate(dentry, inode);
6284 ret = btrfs_log_new_name(trans, BTRFS_I(inode), NULL, parent,
6286 if (ret == BTRFS_NEED_TRANS_COMMIT) {
6287 err = btrfs_commit_transaction(trans);
6294 btrfs_end_transaction(trans);
6296 inode_dec_link_count(inode);
6299 btrfs_btree_balance_dirty(fs_info);
6303 static int btrfs_mkdir(struct inode *dir, struct dentry *dentry, umode_t mode)
6305 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
6306 struct inode *inode = NULL;
6307 struct btrfs_trans_handle *trans;
6308 struct btrfs_root *root = BTRFS_I(dir)->root;
6314 * 2 items for inode and ref
6315 * 2 items for dir items
6316 * 1 for xattr if selinux is on
6318 trans = btrfs_start_transaction(root, 5);
6320 return PTR_ERR(trans);
6322 err = btrfs_find_free_ino(root, &objectid);
6326 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
6327 dentry->d_name.len, btrfs_ino(BTRFS_I(dir)), objectid,
6328 S_IFDIR | mode, &index);
6329 if (IS_ERR(inode)) {
6330 err = PTR_ERR(inode);
6335 /* these must be set before we unlock the inode */
6336 inode->i_op = &btrfs_dir_inode_operations;
6337 inode->i_fop = &btrfs_dir_file_operations;
6339 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
6343 btrfs_i_size_write(BTRFS_I(inode), 0);
6344 err = btrfs_update_inode(trans, root, inode);
6348 err = btrfs_add_link(trans, BTRFS_I(dir), BTRFS_I(inode),
6349 dentry->d_name.name,
6350 dentry->d_name.len, 0, index);
6354 d_instantiate_new(dentry, inode);
6357 btrfs_end_transaction(trans);
6359 inode_dec_link_count(inode);
6360 discard_new_inode(inode);
6362 btrfs_btree_balance_dirty(fs_info);
6366 static noinline int uncompress_inline(struct btrfs_path *path,
6368 size_t pg_offset, u64 extent_offset,
6369 struct btrfs_file_extent_item *item)
6372 struct extent_buffer *leaf = path->nodes[0];
6375 unsigned long inline_size;
6379 WARN_ON(pg_offset != 0);
6380 compress_type = btrfs_file_extent_compression(leaf, item);
6381 max_size = btrfs_file_extent_ram_bytes(leaf, item);
6382 inline_size = btrfs_file_extent_inline_item_len(leaf,
6383 btrfs_item_nr(path->slots[0]));
6384 tmp = kmalloc(inline_size, GFP_NOFS);
6387 ptr = btrfs_file_extent_inline_start(item);
6389 read_extent_buffer(leaf, tmp, ptr, inline_size);
6391 max_size = min_t(unsigned long, PAGE_SIZE, max_size);
6392 ret = btrfs_decompress(compress_type, tmp, page,
6393 extent_offset, inline_size, max_size);
6396 * decompression code contains a memset to fill in any space between the end
6397 * of the uncompressed data and the end of max_size in case the decompressed
6398 * data ends up shorter than ram_bytes. That doesn't cover the hole between
6399 * the end of an inline extent and the beginning of the next block, so we
6400 * cover that region here.
6403 if (max_size + pg_offset < PAGE_SIZE) {
6404 char *map = kmap(page);
6405 memset(map + pg_offset + max_size, 0, PAGE_SIZE - max_size - pg_offset);
6413 * btrfs_get_extent - Lookup the first extent overlapping a range in a file.
6414 * @inode: file to search in
6415 * @page: page to read extent data into if the extent is inline
6416 * @pg_offset: offset into @page to copy to
6417 * @start: file offset
6418 * @len: length of range starting at @start
6420 * This returns the first &struct extent_map which overlaps with the given
6421 * range, reading it from the B-tree and caching it if necessary. Note that
6422 * there may be more extents which overlap the given range after the returned
6425 * If @page is not NULL and the extent is inline, this also reads the extent
6426 * data directly into the page and marks the extent up to date in the io_tree.
6428 * Return: ERR_PTR on error, non-NULL extent_map on success.
6430 struct extent_map *btrfs_get_extent(struct btrfs_inode *inode,
6431 struct page *page, size_t pg_offset,
6434 struct btrfs_fs_info *fs_info = inode->root->fs_info;
6437 u64 extent_start = 0;
6439 u64 objectid = btrfs_ino(inode);
6440 int extent_type = -1;
6441 struct btrfs_path *path = NULL;
6442 struct btrfs_root *root = inode->root;
6443 struct btrfs_file_extent_item *item;
6444 struct extent_buffer *leaf;
6445 struct btrfs_key found_key;
6446 struct extent_map *em = NULL;
6447 struct extent_map_tree *em_tree = &inode->extent_tree;
6448 struct extent_io_tree *io_tree = &inode->io_tree;
6450 read_lock(&em_tree->lock);
6451 em = lookup_extent_mapping(em_tree, start, len);
6452 read_unlock(&em_tree->lock);
6455 if (em->start > start || em->start + em->len <= start)
6456 free_extent_map(em);
6457 else if (em->block_start == EXTENT_MAP_INLINE && page)
6458 free_extent_map(em);
6462 em = alloc_extent_map();
6467 em->start = EXTENT_MAP_HOLE;
6468 em->orig_start = EXTENT_MAP_HOLE;
6470 em->block_len = (u64)-1;
6472 path = btrfs_alloc_path();
6478 /* Chances are we'll be called again, so go ahead and do readahead */
6479 path->reada = READA_FORWARD;
6482 * Unless we're going to uncompress the inline extent, no sleep would
6485 path->leave_spinning = 1;
6487 ret = btrfs_lookup_file_extent(NULL, root, path, objectid, start, 0);
6491 } else if (ret > 0) {
6492 if (path->slots[0] == 0)
6497 leaf = path->nodes[0];
6498 item = btrfs_item_ptr(leaf, path->slots[0],
6499 struct btrfs_file_extent_item);
6500 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
6501 if (found_key.objectid != objectid ||
6502 found_key.type != BTRFS_EXTENT_DATA_KEY) {
6504 * If we backup past the first extent we want to move forward
6505 * and see if there is an extent in front of us, otherwise we'll
6506 * say there is a hole for our whole search range which can
6513 extent_type = btrfs_file_extent_type(leaf, item);
6514 extent_start = found_key.offset;
6515 extent_end = btrfs_file_extent_end(path);
6516 if (extent_type == BTRFS_FILE_EXTENT_REG ||
6517 extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
6518 /* Only regular file could have regular/prealloc extent */
6519 if (!S_ISREG(inode->vfs_inode.i_mode)) {
6522 "regular/prealloc extent found for non-regular inode %llu",
6526 trace_btrfs_get_extent_show_fi_regular(inode, leaf, item,
6528 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
6529 trace_btrfs_get_extent_show_fi_inline(inode, leaf, item,
6534 if (start >= extent_end) {
6536 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
6537 ret = btrfs_next_leaf(root, path);
6541 } else if (ret > 0) {
6544 leaf = path->nodes[0];
6546 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
6547 if (found_key.objectid != objectid ||
6548 found_key.type != BTRFS_EXTENT_DATA_KEY)
6550 if (start + len <= found_key.offset)
6552 if (start > found_key.offset)
6555 /* New extent overlaps with existing one */
6557 em->orig_start = start;
6558 em->len = found_key.offset - start;
6559 em->block_start = EXTENT_MAP_HOLE;
6563 btrfs_extent_item_to_extent_map(inode, path, item, !page, em);
6565 if (extent_type == BTRFS_FILE_EXTENT_REG ||
6566 extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
6568 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
6572 size_t extent_offset;
6578 size = btrfs_file_extent_ram_bytes(leaf, item);
6579 extent_offset = page_offset(page) + pg_offset - extent_start;
6580 copy_size = min_t(u64, PAGE_SIZE - pg_offset,
6581 size - extent_offset);
6582 em->start = extent_start + extent_offset;
6583 em->len = ALIGN(copy_size, fs_info->sectorsize);
6584 em->orig_block_len = em->len;
6585 em->orig_start = em->start;
6586 ptr = btrfs_file_extent_inline_start(item) + extent_offset;
6588 btrfs_set_path_blocking(path);
6589 if (!PageUptodate(page)) {
6590 if (btrfs_file_extent_compression(leaf, item) !=
6591 BTRFS_COMPRESS_NONE) {
6592 ret = uncompress_inline(path, page, pg_offset,
6593 extent_offset, item);
6600 read_extent_buffer(leaf, map + pg_offset, ptr,
6602 if (pg_offset + copy_size < PAGE_SIZE) {
6603 memset(map + pg_offset + copy_size, 0,
6604 PAGE_SIZE - pg_offset -
6609 flush_dcache_page(page);
6611 set_extent_uptodate(io_tree, em->start,
6612 extent_map_end(em) - 1, NULL, GFP_NOFS);
6617 em->orig_start = start;
6619 em->block_start = EXTENT_MAP_HOLE;
6621 btrfs_release_path(path);
6622 if (em->start > start || extent_map_end(em) <= start) {
6624 "bad extent! em: [%llu %llu] passed [%llu %llu]",
6625 em->start, em->len, start, len);
6631 write_lock(&em_tree->lock);
6632 err = btrfs_add_extent_mapping(fs_info, em_tree, &em, start, len);
6633 write_unlock(&em_tree->lock);
6635 btrfs_free_path(path);
6637 trace_btrfs_get_extent(root, inode, em);
6640 free_extent_map(em);
6641 return ERR_PTR(err);
6643 BUG_ON(!em); /* Error is always set */
6647 struct extent_map *btrfs_get_extent_fiemap(struct btrfs_inode *inode,
6650 struct extent_map *em;
6651 struct extent_map *hole_em = NULL;
6652 u64 delalloc_start = start;
6658 em = btrfs_get_extent(inode, NULL, 0, start, len);
6662 * If our em maps to:
6664 * - a pre-alloc extent,
6665 * there might actually be delalloc bytes behind it.
6667 if (em->block_start != EXTENT_MAP_HOLE &&
6668 !test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
6673 /* check to see if we've wrapped (len == -1 or similar) */
6682 /* ok, we didn't find anything, lets look for delalloc */
6683 delalloc_len = count_range_bits(&inode->io_tree, &delalloc_start,
6684 end, len, EXTENT_DELALLOC, 1);
6685 delalloc_end = delalloc_start + delalloc_len;
6686 if (delalloc_end < delalloc_start)
6687 delalloc_end = (u64)-1;
6690 * We didn't find anything useful, return the original results from
6693 if (delalloc_start > end || delalloc_end <= start) {
6700 * Adjust the delalloc_start to make sure it doesn't go backwards from
6701 * the start they passed in
6703 delalloc_start = max(start, delalloc_start);
6704 delalloc_len = delalloc_end - delalloc_start;
6706 if (delalloc_len > 0) {
6709 const u64 hole_end = extent_map_end(hole_em);
6711 em = alloc_extent_map();
6719 * When btrfs_get_extent can't find anything it returns one
6722 * Make sure what it found really fits our range, and adjust to
6723 * make sure it is based on the start from the caller
6725 if (hole_end <= start || hole_em->start > end) {
6726 free_extent_map(hole_em);
6729 hole_start = max(hole_em->start, start);
6730 hole_len = hole_end - hole_start;
6733 if (hole_em && delalloc_start > hole_start) {
6735 * Our hole starts before our delalloc, so we have to
6736 * return just the parts of the hole that go until the
6739 em->len = min(hole_len, delalloc_start - hole_start);
6740 em->start = hole_start;
6741 em->orig_start = hole_start;
6743 * Don't adjust block start at all, it is fixed at
6746 em->block_start = hole_em->block_start;
6747 em->block_len = hole_len;
6748 if (test_bit(EXTENT_FLAG_PREALLOC, &hole_em->flags))
6749 set_bit(EXTENT_FLAG_PREALLOC, &em->flags);
6752 * Hole is out of passed range or it starts after
6755 em->start = delalloc_start;
6756 em->len = delalloc_len;
6757 em->orig_start = delalloc_start;
6758 em->block_start = EXTENT_MAP_DELALLOC;
6759 em->block_len = delalloc_len;
6766 free_extent_map(hole_em);
6768 free_extent_map(em);
6769 return ERR_PTR(err);
6774 static struct extent_map *btrfs_create_dio_extent(struct inode *inode,
6777 const u64 orig_start,
6778 const u64 block_start,
6779 const u64 block_len,
6780 const u64 orig_block_len,
6781 const u64 ram_bytes,
6784 struct extent_map *em = NULL;
6787 if (type != BTRFS_ORDERED_NOCOW) {
6788 em = create_io_em(inode, start, len, orig_start,
6789 block_start, block_len, orig_block_len,
6791 BTRFS_COMPRESS_NONE, /* compress_type */
6796 ret = btrfs_add_ordered_extent_dio(inode, start, block_start,
6797 len, block_len, type);
6800 free_extent_map(em);
6801 btrfs_drop_extent_cache(BTRFS_I(inode), start,
6802 start + len - 1, 0);
6811 static struct extent_map *btrfs_new_extent_direct(struct inode *inode,
6814 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
6815 struct btrfs_root *root = BTRFS_I(inode)->root;
6816 struct extent_map *em;
6817 struct btrfs_key ins;
6821 alloc_hint = get_extent_allocation_hint(inode, start, len);
6822 ret = btrfs_reserve_extent(root, len, len, fs_info->sectorsize,
6823 0, alloc_hint, &ins, 1, 1);
6825 return ERR_PTR(ret);
6827 em = btrfs_create_dio_extent(inode, start, ins.offset, start,
6828 ins.objectid, ins.offset, ins.offset,
6829 ins.offset, BTRFS_ORDERED_REGULAR);
6830 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
6832 btrfs_free_reserved_extent(fs_info, ins.objectid,
6839 * returns 1 when the nocow is safe, < 1 on error, 0 if the
6840 * block must be cow'd
6842 noinline int can_nocow_extent(struct inode *inode, u64 offset, u64 *len,
6843 u64 *orig_start, u64 *orig_block_len,
6846 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
6847 struct btrfs_path *path;
6849 struct extent_buffer *leaf;
6850 struct btrfs_root *root = BTRFS_I(inode)->root;
6851 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
6852 struct btrfs_file_extent_item *fi;
6853 struct btrfs_key key;
6860 bool nocow = (BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW);
6862 path = btrfs_alloc_path();
6866 ret = btrfs_lookup_file_extent(NULL, root, path,
6867 btrfs_ino(BTRFS_I(inode)), offset, 0);
6871 slot = path->slots[0];
6874 /* can't find the item, must cow */
6881 leaf = path->nodes[0];
6882 btrfs_item_key_to_cpu(leaf, &key, slot);
6883 if (key.objectid != btrfs_ino(BTRFS_I(inode)) ||
6884 key.type != BTRFS_EXTENT_DATA_KEY) {
6885 /* not our file or wrong item type, must cow */
6889 if (key.offset > offset) {
6890 /* Wrong offset, must cow */
6894 fi = btrfs_item_ptr(leaf, slot, struct btrfs_file_extent_item);
6895 found_type = btrfs_file_extent_type(leaf, fi);
6896 if (found_type != BTRFS_FILE_EXTENT_REG &&
6897 found_type != BTRFS_FILE_EXTENT_PREALLOC) {
6898 /* not a regular extent, must cow */
6902 if (!nocow && found_type == BTRFS_FILE_EXTENT_REG)
6905 extent_end = key.offset + btrfs_file_extent_num_bytes(leaf, fi);
6906 if (extent_end <= offset)
6909 disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
6910 if (disk_bytenr == 0)
6913 if (btrfs_file_extent_compression(leaf, fi) ||
6914 btrfs_file_extent_encryption(leaf, fi) ||
6915 btrfs_file_extent_other_encoding(leaf, fi))
6919 * Do the same check as in btrfs_cross_ref_exist but without the
6920 * unnecessary search.
6922 if (btrfs_file_extent_generation(leaf, fi) <=
6923 btrfs_root_last_snapshot(&root->root_item))
6926 backref_offset = btrfs_file_extent_offset(leaf, fi);
6929 *orig_start = key.offset - backref_offset;
6930 *orig_block_len = btrfs_file_extent_disk_num_bytes(leaf, fi);
6931 *ram_bytes = btrfs_file_extent_ram_bytes(leaf, fi);
6934 if (btrfs_extent_readonly(fs_info, disk_bytenr))
6937 num_bytes = min(offset + *len, extent_end) - offset;
6938 if (!nocow && found_type == BTRFS_FILE_EXTENT_PREALLOC) {
6941 range_end = round_up(offset + num_bytes,
6942 root->fs_info->sectorsize) - 1;
6943 ret = test_range_bit(io_tree, offset, range_end,
6944 EXTENT_DELALLOC, 0, NULL);
6951 btrfs_release_path(path);
6954 * look for other files referencing this extent, if we
6955 * find any we must cow
6958 ret = btrfs_cross_ref_exist(root, btrfs_ino(BTRFS_I(inode)),
6959 key.offset - backref_offset, disk_bytenr);
6966 * adjust disk_bytenr and num_bytes to cover just the bytes
6967 * in this extent we are about to write. If there
6968 * are any csums in that range we have to cow in order
6969 * to keep the csums correct
6971 disk_bytenr += backref_offset;
6972 disk_bytenr += offset - key.offset;
6973 if (csum_exist_in_range(fs_info, disk_bytenr, num_bytes))
6976 * all of the above have passed, it is safe to overwrite this extent
6982 btrfs_free_path(path);
6986 static int lock_extent_direct(struct inode *inode, u64 lockstart, u64 lockend,
6987 struct extent_state **cached_state, int writing)
6989 struct btrfs_ordered_extent *ordered;
6993 lock_extent_bits(&BTRFS_I(inode)->io_tree, lockstart, lockend,
6996 * We're concerned with the entire range that we're going to be
6997 * doing DIO to, so we need to make sure there's no ordered
6998 * extents in this range.
7000 ordered = btrfs_lookup_ordered_range(BTRFS_I(inode), lockstart,
7001 lockend - lockstart + 1);
7004 * We need to make sure there are no buffered pages in this
7005 * range either, we could have raced between the invalidate in
7006 * generic_file_direct_write and locking the extent. The
7007 * invalidate needs to happen so that reads after a write do not
7011 (!writing || !filemap_range_has_page(inode->i_mapping,
7012 lockstart, lockend)))
7015 unlock_extent_cached(&BTRFS_I(inode)->io_tree, lockstart, lockend,
7020 * If we are doing a DIO read and the ordered extent we
7021 * found is for a buffered write, we can not wait for it
7022 * to complete and retry, because if we do so we can
7023 * deadlock with concurrent buffered writes on page
7024 * locks. This happens only if our DIO read covers more
7025 * than one extent map, if at this point has already
7026 * created an ordered extent for a previous extent map
7027 * and locked its range in the inode's io tree, and a
7028 * concurrent write against that previous extent map's
7029 * range and this range started (we unlock the ranges
7030 * in the io tree only when the bios complete and
7031 * buffered writes always lock pages before attempting
7032 * to lock range in the io tree).
7035 test_bit(BTRFS_ORDERED_DIRECT, &ordered->flags))
7036 btrfs_start_ordered_extent(inode, ordered, 1);
7039 btrfs_put_ordered_extent(ordered);
7042 * We could trigger writeback for this range (and wait
7043 * for it to complete) and then invalidate the pages for
7044 * this range (through invalidate_inode_pages2_range()),
7045 * but that can lead us to a deadlock with a concurrent
7046 * call to readpages() (a buffered read or a defrag call
7047 * triggered a readahead) on a page lock due to an
7048 * ordered dio extent we created before but did not have
7049 * yet a corresponding bio submitted (whence it can not
7050 * complete), which makes readpages() wait for that
7051 * ordered extent to complete while holding a lock on
7066 /* The callers of this must take lock_extent() */
7067 static struct extent_map *create_io_em(struct inode *inode, u64 start, u64 len,
7068 u64 orig_start, u64 block_start,
7069 u64 block_len, u64 orig_block_len,
7070 u64 ram_bytes, int compress_type,
7073 struct extent_map_tree *em_tree;
7074 struct extent_map *em;
7077 ASSERT(type == BTRFS_ORDERED_PREALLOC ||
7078 type == BTRFS_ORDERED_COMPRESSED ||
7079 type == BTRFS_ORDERED_NOCOW ||
7080 type == BTRFS_ORDERED_REGULAR);
7082 em_tree = &BTRFS_I(inode)->extent_tree;
7083 em = alloc_extent_map();
7085 return ERR_PTR(-ENOMEM);
7088 em->orig_start = orig_start;
7090 em->block_len = block_len;
7091 em->block_start = block_start;
7092 em->orig_block_len = orig_block_len;
7093 em->ram_bytes = ram_bytes;
7094 em->generation = -1;
7095 set_bit(EXTENT_FLAG_PINNED, &em->flags);
7096 if (type == BTRFS_ORDERED_PREALLOC) {
7097 set_bit(EXTENT_FLAG_FILLING, &em->flags);
7098 } else if (type == BTRFS_ORDERED_COMPRESSED) {
7099 set_bit(EXTENT_FLAG_COMPRESSED, &em->flags);
7100 em->compress_type = compress_type;
7104 btrfs_drop_extent_cache(BTRFS_I(inode), em->start,
7105 em->start + em->len - 1, 0);
7106 write_lock(&em_tree->lock);
7107 ret = add_extent_mapping(em_tree, em, 1);
7108 write_unlock(&em_tree->lock);
7110 * The caller has taken lock_extent(), who could race with us
7113 } while (ret == -EEXIST);
7116 free_extent_map(em);
7117 return ERR_PTR(ret);
7120 /* em got 2 refs now, callers needs to do free_extent_map once. */
7125 static int btrfs_get_blocks_direct_read(struct extent_map *em,
7126 struct buffer_head *bh_result,
7127 struct inode *inode,
7130 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7132 if (em->block_start == EXTENT_MAP_HOLE ||
7133 test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
7136 len = min(len, em->len - (start - em->start));
7138 bh_result->b_blocknr = (em->block_start + (start - em->start)) >>
7140 bh_result->b_size = len;
7141 bh_result->b_bdev = fs_info->fs_devices->latest_bdev;
7142 set_buffer_mapped(bh_result);
7147 static int btrfs_get_blocks_direct_write(struct extent_map **map,
7148 struct buffer_head *bh_result,
7149 struct inode *inode,
7150 struct btrfs_dio_data *dio_data,
7153 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7154 struct extent_map *em = *map;
7158 * We don't allocate a new extent in the following cases
7160 * 1) The inode is marked as NODATACOW. In this case we'll just use the
7162 * 2) The extent is marked as PREALLOC. We're good to go here and can
7163 * just use the extent.
7166 if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags) ||
7167 ((BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW) &&
7168 em->block_start != EXTENT_MAP_HOLE)) {
7170 u64 block_start, orig_start, orig_block_len, ram_bytes;
7172 if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
7173 type = BTRFS_ORDERED_PREALLOC;
7175 type = BTRFS_ORDERED_NOCOW;
7176 len = min(len, em->len - (start - em->start));
7177 block_start = em->block_start + (start - em->start);
7179 if (can_nocow_extent(inode, start, &len, &orig_start,
7180 &orig_block_len, &ram_bytes) == 1 &&
7181 btrfs_inc_nocow_writers(fs_info, block_start)) {
7182 struct extent_map *em2;
7184 em2 = btrfs_create_dio_extent(inode, start, len,
7185 orig_start, block_start,
7186 len, orig_block_len,
7188 btrfs_dec_nocow_writers(fs_info, block_start);
7189 if (type == BTRFS_ORDERED_PREALLOC) {
7190 free_extent_map(em);
7194 if (em2 && IS_ERR(em2)) {
7199 * For inode marked NODATACOW or extent marked PREALLOC,
7200 * use the existing or preallocated extent, so does not
7201 * need to adjust btrfs_space_info's bytes_may_use.
7203 btrfs_free_reserved_data_space_noquota(inode, start,
7209 /* this will cow the extent */
7210 len = bh_result->b_size;
7211 free_extent_map(em);
7212 *map = em = btrfs_new_extent_direct(inode, start, len);
7218 len = min(len, em->len - (start - em->start));
7221 bh_result->b_blocknr = (em->block_start + (start - em->start)) >>
7223 bh_result->b_size = len;
7224 bh_result->b_bdev = fs_info->fs_devices->latest_bdev;
7225 set_buffer_mapped(bh_result);
7227 if (!test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
7228 set_buffer_new(bh_result);
7231 * Need to update the i_size under the extent lock so buffered
7232 * readers will get the updated i_size when we unlock.
7234 if (!dio_data->overwrite && start + len > i_size_read(inode))
7235 i_size_write(inode, start + len);
7237 WARN_ON(dio_data->reserve < len);
7238 dio_data->reserve -= len;
7239 dio_data->unsubmitted_oe_range_end = start + len;
7240 current->journal_info = dio_data;
7245 static int btrfs_get_blocks_direct(struct inode *inode, sector_t iblock,
7246 struct buffer_head *bh_result, int create)
7248 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7249 struct extent_map *em;
7250 struct extent_state *cached_state = NULL;
7251 struct btrfs_dio_data *dio_data = NULL;
7252 u64 start = iblock << inode->i_blkbits;
7253 u64 lockstart, lockend;
7254 u64 len = bh_result->b_size;
7258 len = min_t(u64, len, fs_info->sectorsize);
7261 lockend = start + len - 1;
7263 if (current->journal_info) {
7265 * Need to pull our outstanding extents and set journal_info to NULL so
7266 * that anything that needs to check if there's a transaction doesn't get
7269 dio_data = current->journal_info;
7270 current->journal_info = NULL;
7274 * If this errors out it's because we couldn't invalidate pagecache for
7275 * this range and we need to fallback to buffered.
7277 if (lock_extent_direct(inode, lockstart, lockend, &cached_state,
7283 em = btrfs_get_extent(BTRFS_I(inode), NULL, 0, start, len);
7290 * Ok for INLINE and COMPRESSED extents we need to fallback on buffered
7291 * io. INLINE is special, and we could probably kludge it in here, but
7292 * it's still buffered so for safety lets just fall back to the generic
7295 * For COMPRESSED we _have_ to read the entire extent in so we can
7296 * decompress it, so there will be buffering required no matter what we
7297 * do, so go ahead and fallback to buffered.
7299 * We return -ENOTBLK because that's what makes DIO go ahead and go back
7300 * to buffered IO. Don't blame me, this is the price we pay for using
7303 if (test_bit(EXTENT_FLAG_COMPRESSED, &em->flags) ||
7304 em->block_start == EXTENT_MAP_INLINE) {
7305 free_extent_map(em);
7311 ret = btrfs_get_blocks_direct_write(&em, bh_result, inode,
7312 dio_data, start, len);
7316 unlock_extent_cached(&BTRFS_I(inode)->io_tree, lockstart,
7317 lockend, &cached_state);
7319 ret = btrfs_get_blocks_direct_read(em, bh_result, inode,
7321 /* Can be negative only if we read from a hole */
7324 free_extent_map(em);
7328 * We need to unlock only the end area that we aren't using.
7329 * The rest is going to be unlocked by the endio routine.
7331 lockstart = start + bh_result->b_size;
7332 if (lockstart < lockend) {
7333 unlock_extent_cached(&BTRFS_I(inode)->io_tree,
7334 lockstart, lockend, &cached_state);
7336 free_extent_state(cached_state);
7340 free_extent_map(em);
7345 unlock_extent_cached(&BTRFS_I(inode)->io_tree, lockstart, lockend,
7349 current->journal_info = dio_data;
7353 static void btrfs_dio_private_put(struct btrfs_dio_private *dip)
7356 * This implies a barrier so that stores to dio_bio->bi_status before
7357 * this and loads of dio_bio->bi_status after this are fully ordered.
7359 if (!refcount_dec_and_test(&dip->refs))
7362 if (bio_op(dip->dio_bio) == REQ_OP_WRITE) {
7363 __endio_write_update_ordered(dip->inode, dip->logical_offset,
7365 !dip->dio_bio->bi_status);
7367 unlock_extent(&BTRFS_I(dip->inode)->io_tree,
7368 dip->logical_offset,
7369 dip->logical_offset + dip->bytes - 1);
7372 dio_end_io(dip->dio_bio);
7376 static blk_status_t submit_dio_repair_bio(struct inode *inode, struct bio *bio,
7378 unsigned long bio_flags)
7380 struct btrfs_dio_private *dip = bio->bi_private;
7381 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7384 BUG_ON(bio_op(bio) == REQ_OP_WRITE);
7386 ret = btrfs_bio_wq_end_io(fs_info, bio, BTRFS_WQ_ENDIO_DATA);
7390 refcount_inc(&dip->refs);
7391 ret = btrfs_map_bio(fs_info, bio, mirror_num);
7393 refcount_dec(&dip->refs);
7397 static blk_status_t btrfs_check_read_dio_bio(struct inode *inode,
7398 struct btrfs_io_bio *io_bio,
7399 const bool uptodate)
7401 struct btrfs_fs_info *fs_info = BTRFS_I(inode)->root->fs_info;
7402 const u32 sectorsize = fs_info->sectorsize;
7403 struct extent_io_tree *failure_tree = &BTRFS_I(inode)->io_failure_tree;
7404 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
7405 const bool csum = !(BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM);
7406 struct bio_vec bvec;
7407 struct bvec_iter iter;
7408 u64 start = io_bio->logical;
7410 blk_status_t err = BLK_STS_OK;
7412 __bio_for_each_segment(bvec, &io_bio->bio, iter, io_bio->iter) {
7413 unsigned int i, nr_sectors, pgoff;
7415 nr_sectors = BTRFS_BYTES_TO_BLKS(fs_info, bvec.bv_len);
7416 pgoff = bvec.bv_offset;
7417 for (i = 0; i < nr_sectors; i++) {
7418 ASSERT(pgoff < PAGE_SIZE);
7420 (!csum || !check_data_csum(inode, io_bio, icsum,
7421 bvec.bv_page, pgoff,
7422 start, sectorsize))) {
7423 clean_io_failure(fs_info, failure_tree, io_tree,
7424 start, bvec.bv_page,
7425 btrfs_ino(BTRFS_I(inode)),
7428 blk_status_t status;
7430 status = btrfs_submit_read_repair(inode,
7432 start - io_bio->logical,
7433 bvec.bv_page, pgoff,
7435 start + sectorsize - 1,
7437 submit_dio_repair_bio);
7441 start += sectorsize;
7443 pgoff += sectorsize;
7449 static void __endio_write_update_ordered(struct inode *inode,
7450 const u64 offset, const u64 bytes,
7451 const bool uptodate)
7453 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7454 struct btrfs_ordered_extent *ordered = NULL;
7455 struct btrfs_workqueue *wq;
7456 u64 ordered_offset = offset;
7457 u64 ordered_bytes = bytes;
7460 if (btrfs_is_free_space_inode(BTRFS_I(inode)))
7461 wq = fs_info->endio_freespace_worker;
7463 wq = fs_info->endio_write_workers;
7465 while (ordered_offset < offset + bytes) {
7466 last_offset = ordered_offset;
7467 if (btrfs_dec_test_first_ordered_pending(inode, &ordered,
7471 btrfs_init_work(&ordered->work, finish_ordered_fn, NULL,
7473 btrfs_queue_work(wq, &ordered->work);
7476 * If btrfs_dec_test_ordered_pending does not find any ordered
7477 * extent in the range, we can exit.
7479 if (ordered_offset == last_offset)
7482 * Our bio might span multiple ordered extents. In this case
7483 * we keep going until we have accounted the whole dio.
7485 if (ordered_offset < offset + bytes) {
7486 ordered_bytes = offset + bytes - ordered_offset;
7492 static blk_status_t btrfs_submit_bio_start_direct_io(void *private_data,
7493 struct bio *bio, u64 offset)
7495 struct inode *inode = private_data;
7497 ret = btrfs_csum_one_bio(inode, bio, offset, 1);
7498 BUG_ON(ret); /* -ENOMEM */
7502 static void btrfs_end_dio_bio(struct bio *bio)
7504 struct btrfs_dio_private *dip = bio->bi_private;
7505 blk_status_t err = bio->bi_status;
7508 btrfs_warn(BTRFS_I(dip->inode)->root->fs_info,
7509 "direct IO failed ino %llu rw %d,%u sector %#Lx len %u err no %d",
7510 btrfs_ino(BTRFS_I(dip->inode)), bio_op(bio),
7512 (unsigned long long)bio->bi_iter.bi_sector,
7513 bio->bi_iter.bi_size, err);
7515 if (bio_op(bio) == REQ_OP_READ) {
7516 err = btrfs_check_read_dio_bio(dip->inode, btrfs_io_bio(bio),
7521 dip->dio_bio->bi_status = err;
7524 btrfs_dio_private_put(dip);
7527 static inline blk_status_t btrfs_submit_dio_bio(struct bio *bio,
7528 struct inode *inode, u64 file_offset, int async_submit)
7530 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7531 struct btrfs_dio_private *dip = bio->bi_private;
7532 bool write = bio_op(bio) == REQ_OP_WRITE;
7535 /* Check btrfs_submit_bio_hook() for rules about async submit. */
7537 async_submit = !atomic_read(&BTRFS_I(inode)->sync_writers);
7540 ret = btrfs_bio_wq_end_io(fs_info, bio, BTRFS_WQ_ENDIO_DATA);
7545 if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)
7548 if (write && async_submit) {
7549 ret = btrfs_wq_submit_bio(fs_info, bio, 0, 0,
7551 btrfs_submit_bio_start_direct_io);
7555 * If we aren't doing async submit, calculate the csum of the
7558 ret = btrfs_csum_one_bio(inode, bio, file_offset, 1);
7564 csum_offset = file_offset - dip->logical_offset;
7565 csum_offset >>= inode->i_sb->s_blocksize_bits;
7566 csum_offset *= btrfs_super_csum_size(fs_info->super_copy);
7567 btrfs_io_bio(bio)->csum = dip->csums + csum_offset;
7570 ret = btrfs_map_bio(fs_info, bio, 0);
7576 * If this succeeds, the btrfs_dio_private is responsible for cleaning up locked
7577 * or ordered extents whether or not we submit any bios.
7579 static struct btrfs_dio_private *btrfs_create_dio_private(struct bio *dio_bio,
7580 struct inode *inode,
7583 const bool write = (bio_op(dio_bio) == REQ_OP_WRITE);
7584 const bool csum = !(BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM);
7586 struct btrfs_dio_private *dip;
7588 dip_size = sizeof(*dip);
7589 if (!write && csum) {
7590 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7591 const u16 csum_size = btrfs_super_csum_size(fs_info->super_copy);
7594 nblocks = dio_bio->bi_iter.bi_size >> inode->i_sb->s_blocksize_bits;
7595 dip_size += csum_size * nblocks;
7598 dip = kzalloc(dip_size, GFP_NOFS);
7603 dip->logical_offset = file_offset;
7604 dip->bytes = dio_bio->bi_iter.bi_size;
7605 dip->disk_bytenr = (u64)dio_bio->bi_iter.bi_sector << 9;
7606 dip->dio_bio = dio_bio;
7607 refcount_set(&dip->refs, 1);
7610 struct btrfs_dio_data *dio_data = current->journal_info;
7613 * Setting range start and end to the same value means that
7614 * no cleanup will happen in btrfs_direct_IO
7616 dio_data->unsubmitted_oe_range_end = dip->logical_offset +
7618 dio_data->unsubmitted_oe_range_start =
7619 dio_data->unsubmitted_oe_range_end;
7624 static void btrfs_submit_direct(struct bio *dio_bio, struct inode *inode,
7627 const bool write = (bio_op(dio_bio) == REQ_OP_WRITE);
7628 const bool csum = !(BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM);
7629 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7630 const bool raid56 = (btrfs_data_alloc_profile(fs_info) &
7631 BTRFS_BLOCK_GROUP_RAID56_MASK);
7632 struct btrfs_dio_private *dip;
7635 int async_submit = 0;
7637 int clone_offset = 0;
7640 blk_status_t status;
7641 struct btrfs_io_geometry geom;
7643 dip = btrfs_create_dio_private(dio_bio, inode, file_offset);
7646 unlock_extent(&BTRFS_I(inode)->io_tree, file_offset,
7647 file_offset + dio_bio->bi_iter.bi_size - 1);
7649 dio_bio->bi_status = BLK_STS_RESOURCE;
7650 dio_end_io(dio_bio);
7654 if (!write && csum) {
7656 * Load the csums up front to reduce csum tree searches and
7657 * contention when submitting bios.
7659 status = btrfs_lookup_bio_sums(inode, dio_bio, file_offset,
7661 if (status != BLK_STS_OK)
7665 start_sector = dio_bio->bi_iter.bi_sector;
7666 submit_len = dio_bio->bi_iter.bi_size;
7669 ret = btrfs_get_io_geometry(fs_info, btrfs_op(dio_bio),
7670 start_sector << 9, submit_len,
7673 status = errno_to_blk_status(ret);
7676 ASSERT(geom.len <= INT_MAX);
7678 clone_len = min_t(int, submit_len, geom.len);
7681 * This will never fail as it's passing GPF_NOFS and
7682 * the allocation is backed by btrfs_bioset.
7684 bio = btrfs_bio_clone_partial(dio_bio, clone_offset, clone_len);
7685 bio->bi_private = dip;
7686 bio->bi_end_io = btrfs_end_dio_bio;
7687 btrfs_io_bio(bio)->logical = file_offset;
7689 ASSERT(submit_len >= clone_len);
7690 submit_len -= clone_len;
7693 * Increase the count before we submit the bio so we know
7694 * the end IO handler won't happen before we increase the
7695 * count. Otherwise, the dip might get freed before we're
7696 * done setting it up.
7698 * We transfer the initial reference to the last bio, so we
7699 * don't need to increment the reference count for the last one.
7701 if (submit_len > 0) {
7702 refcount_inc(&dip->refs);
7704 * If we are submitting more than one bio, submit them
7705 * all asynchronously. The exception is RAID 5 or 6, as
7706 * asynchronous checksums make it difficult to collect
7707 * full stripe writes.
7713 status = btrfs_submit_dio_bio(bio, inode, file_offset,
7718 refcount_dec(&dip->refs);
7722 clone_offset += clone_len;
7723 start_sector += clone_len >> 9;
7724 file_offset += clone_len;
7725 } while (submit_len > 0);
7729 dip->dio_bio->bi_status = status;
7730 btrfs_dio_private_put(dip);
7733 static ssize_t check_direct_IO(struct btrfs_fs_info *fs_info,
7734 const struct iov_iter *iter, loff_t offset)
7738 unsigned int blocksize_mask = fs_info->sectorsize - 1;
7739 ssize_t retval = -EINVAL;
7741 if (offset & blocksize_mask)
7744 if (iov_iter_alignment(iter) & blocksize_mask)
7747 /* If this is a write we don't need to check anymore */
7748 if (iov_iter_rw(iter) != READ || !iter_is_iovec(iter))
7751 * Check to make sure we don't have duplicate iov_base's in this
7752 * iovec, if so return EINVAL, otherwise we'll get csum errors
7753 * when reading back.
7755 for (seg = 0; seg < iter->nr_segs; seg++) {
7756 for (i = seg + 1; i < iter->nr_segs; i++) {
7757 if (iter->iov[seg].iov_base == iter->iov[i].iov_base)
7766 static ssize_t btrfs_direct_IO(struct kiocb *iocb, struct iov_iter *iter)
7768 struct file *file = iocb->ki_filp;
7769 struct inode *inode = file->f_mapping->host;
7770 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7771 struct btrfs_dio_data dio_data = { 0 };
7772 struct extent_changeset *data_reserved = NULL;
7773 loff_t offset = iocb->ki_pos;
7777 bool relock = false;
7780 if (check_direct_IO(fs_info, iter, offset))
7783 inode_dio_begin(inode);
7786 * The generic stuff only does filemap_write_and_wait_range, which
7787 * isn't enough if we've written compressed pages to this area, so
7788 * we need to flush the dirty pages again to make absolutely sure
7789 * that any outstanding dirty pages are on disk.
7791 count = iov_iter_count(iter);
7792 if (test_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
7793 &BTRFS_I(inode)->runtime_flags))
7794 filemap_fdatawrite_range(inode->i_mapping, offset,
7795 offset + count - 1);
7797 if (iov_iter_rw(iter) == WRITE) {
7799 * If the write DIO is beyond the EOF, we need update
7800 * the isize, but it is protected by i_mutex. So we can
7801 * not unlock the i_mutex at this case.
7803 if (offset + count <= inode->i_size) {
7804 dio_data.overwrite = 1;
7805 inode_unlock(inode);
7807 } else if (iocb->ki_flags & IOCB_NOWAIT) {
7811 ret = btrfs_delalloc_reserve_space(inode, &data_reserved,
7817 * We need to know how many extents we reserved so that we can
7818 * do the accounting properly if we go over the number we
7819 * originally calculated. Abuse current->journal_info for this.
7821 dio_data.reserve = round_up(count,
7822 fs_info->sectorsize);
7823 dio_data.unsubmitted_oe_range_start = (u64)offset;
7824 dio_data.unsubmitted_oe_range_end = (u64)offset;
7825 current->journal_info = &dio_data;
7826 down_read(&BTRFS_I(inode)->dio_sem);
7827 } else if (test_bit(BTRFS_INODE_READDIO_NEED_LOCK,
7828 &BTRFS_I(inode)->runtime_flags)) {
7829 inode_dio_end(inode);
7830 flags = DIO_LOCKING | DIO_SKIP_HOLES;
7834 ret = __blockdev_direct_IO(iocb, inode,
7835 fs_info->fs_devices->latest_bdev,
7836 iter, btrfs_get_blocks_direct, NULL,
7837 btrfs_submit_direct, flags);
7838 if (iov_iter_rw(iter) == WRITE) {
7839 up_read(&BTRFS_I(inode)->dio_sem);
7840 current->journal_info = NULL;
7841 if (ret < 0 && ret != -EIOCBQUEUED) {
7842 if (dio_data.reserve)
7843 btrfs_delalloc_release_space(inode, data_reserved,
7844 offset, dio_data.reserve, true);
7846 * On error we might have left some ordered extents
7847 * without submitting corresponding bios for them, so
7848 * cleanup them up to avoid other tasks getting them
7849 * and waiting for them to complete forever.
7851 if (dio_data.unsubmitted_oe_range_start <
7852 dio_data.unsubmitted_oe_range_end)
7853 __endio_write_update_ordered(inode,
7854 dio_data.unsubmitted_oe_range_start,
7855 dio_data.unsubmitted_oe_range_end -
7856 dio_data.unsubmitted_oe_range_start,
7858 } else if (ret >= 0 && (size_t)ret < count)
7859 btrfs_delalloc_release_space(inode, data_reserved,
7860 offset, count - (size_t)ret, true);
7861 btrfs_delalloc_release_extents(BTRFS_I(inode), count);
7865 inode_dio_end(inode);
7869 extent_changeset_free(data_reserved);
7873 #define BTRFS_FIEMAP_FLAGS (FIEMAP_FLAG_SYNC)
7875 static int btrfs_fiemap(struct inode *inode, struct fiemap_extent_info *fieinfo,
7876 __u64 start, __u64 len)
7880 ret = fiemap_check_flags(fieinfo, BTRFS_FIEMAP_FLAGS);
7884 return extent_fiemap(inode, fieinfo, start, len);
7887 int btrfs_readpage(struct file *file, struct page *page)
7889 return extent_read_full_page(page, btrfs_get_extent, 0);
7892 static int btrfs_writepage(struct page *page, struct writeback_control *wbc)
7894 struct inode *inode = page->mapping->host;
7897 if (current->flags & PF_MEMALLOC) {
7898 redirty_page_for_writepage(wbc, page);
7904 * If we are under memory pressure we will call this directly from the
7905 * VM, we need to make sure we have the inode referenced for the ordered
7906 * extent. If not just return like we didn't do anything.
7908 if (!igrab(inode)) {
7909 redirty_page_for_writepage(wbc, page);
7910 return AOP_WRITEPAGE_ACTIVATE;
7912 ret = extent_write_full_page(page, wbc);
7913 btrfs_add_delayed_iput(inode);
7917 static int btrfs_writepages(struct address_space *mapping,
7918 struct writeback_control *wbc)
7920 return extent_writepages(mapping, wbc);
7924 btrfs_readpages(struct file *file, struct address_space *mapping,
7925 struct list_head *pages, unsigned nr_pages)
7927 return extent_readpages(mapping, pages, nr_pages);
7930 static int __btrfs_releasepage(struct page *page, gfp_t gfp_flags)
7932 int ret = try_release_extent_mapping(page, gfp_flags);
7934 ClearPagePrivate(page);
7935 set_page_private(page, 0);
7941 static int btrfs_releasepage(struct page *page, gfp_t gfp_flags)
7943 if (PageWriteback(page) || PageDirty(page))
7945 return __btrfs_releasepage(page, gfp_flags);
7948 #ifdef CONFIG_MIGRATION
7949 static int btrfs_migratepage(struct address_space *mapping,
7950 struct page *newpage, struct page *page,
7951 enum migrate_mode mode)
7955 ret = migrate_page_move_mapping(mapping, newpage, page, 0);
7956 if (ret != MIGRATEPAGE_SUCCESS)
7959 if (page_has_private(page)) {
7960 ClearPagePrivate(page);
7962 set_page_private(newpage, page_private(page));
7963 set_page_private(page, 0);
7965 SetPagePrivate(newpage);
7968 if (PagePrivate2(page)) {
7969 ClearPagePrivate2(page);
7970 SetPagePrivate2(newpage);
7973 if (mode != MIGRATE_SYNC_NO_COPY)
7974 migrate_page_copy(newpage, page);
7976 migrate_page_states(newpage, page);
7977 return MIGRATEPAGE_SUCCESS;
7981 static void btrfs_invalidatepage(struct page *page, unsigned int offset,
7982 unsigned int length)
7984 struct inode *inode = page->mapping->host;
7985 struct extent_io_tree *tree;
7986 struct btrfs_ordered_extent *ordered;
7987 struct extent_state *cached_state = NULL;
7988 u64 page_start = page_offset(page);
7989 u64 page_end = page_start + PAGE_SIZE - 1;
7992 int inode_evicting = inode->i_state & I_FREEING;
7995 * we have the page locked, so new writeback can't start,
7996 * and the dirty bit won't be cleared while we are here.
7998 * Wait for IO on this page so that we can safely clear
7999 * the PagePrivate2 bit and do ordered accounting
8001 wait_on_page_writeback(page);
8003 tree = &BTRFS_I(inode)->io_tree;
8005 btrfs_releasepage(page, GFP_NOFS);
8009 if (!inode_evicting)
8010 lock_extent_bits(tree, page_start, page_end, &cached_state);
8013 ordered = btrfs_lookup_ordered_range(BTRFS_I(inode), start,
8014 page_end - start + 1);
8017 ordered->file_offset + ordered->num_bytes - 1);
8019 * IO on this page will never be started, so we need
8020 * to account for any ordered extents now
8022 if (!inode_evicting)
8023 clear_extent_bit(tree, start, end,
8024 EXTENT_DELALLOC | EXTENT_DELALLOC_NEW |
8025 EXTENT_LOCKED | EXTENT_DO_ACCOUNTING |
8026 EXTENT_DEFRAG, 1, 0, &cached_state);
8028 * whoever cleared the private bit is responsible
8029 * for the finish_ordered_io
8031 if (TestClearPagePrivate2(page)) {
8032 struct btrfs_ordered_inode_tree *tree;
8035 tree = &BTRFS_I(inode)->ordered_tree;
8037 spin_lock_irq(&tree->lock);
8038 set_bit(BTRFS_ORDERED_TRUNCATED, &ordered->flags);
8039 new_len = start - ordered->file_offset;
8040 if (new_len < ordered->truncated_len)
8041 ordered->truncated_len = new_len;
8042 spin_unlock_irq(&tree->lock);
8044 if (btrfs_dec_test_ordered_pending(inode, &ordered,
8046 end - start + 1, 1))
8047 btrfs_finish_ordered_io(ordered);
8049 btrfs_put_ordered_extent(ordered);
8050 if (!inode_evicting) {
8051 cached_state = NULL;
8052 lock_extent_bits(tree, start, end,
8057 if (start < page_end)
8062 * Qgroup reserved space handler
8063 * Page here will be either
8064 * 1) Already written to disk
8065 * In this case, its reserved space is released from data rsv map
8066 * and will be freed by delayed_ref handler finally.
8067 * So even we call qgroup_free_data(), it won't decrease reserved
8069 * 2) Not written to disk
8070 * This means the reserved space should be freed here. However,
8071 * if a truncate invalidates the page (by clearing PageDirty)
8072 * and the page is accounted for while allocating extent
8073 * in btrfs_check_data_free_space() we let delayed_ref to
8074 * free the entire extent.
8076 if (PageDirty(page))
8077 btrfs_qgroup_free_data(inode, NULL, page_start, PAGE_SIZE);
8078 if (!inode_evicting) {
8079 clear_extent_bit(tree, page_start, page_end, EXTENT_LOCKED |
8080 EXTENT_DELALLOC | EXTENT_DELALLOC_NEW |
8081 EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG, 1, 1,
8084 __btrfs_releasepage(page, GFP_NOFS);
8087 ClearPageChecked(page);
8088 if (PagePrivate(page)) {
8089 ClearPagePrivate(page);
8090 set_page_private(page, 0);
8096 * btrfs_page_mkwrite() is not allowed to change the file size as it gets
8097 * called from a page fault handler when a page is first dirtied. Hence we must
8098 * be careful to check for EOF conditions here. We set the page up correctly
8099 * for a written page which means we get ENOSPC checking when writing into
8100 * holes and correct delalloc and unwritten extent mapping on filesystems that
8101 * support these features.
8103 * We are not allowed to take the i_mutex here so we have to play games to
8104 * protect against truncate races as the page could now be beyond EOF. Because
8105 * truncate_setsize() writes the inode size before removing pages, once we have
8106 * the page lock we can determine safely if the page is beyond EOF. If it is not
8107 * beyond EOF, then the page is guaranteed safe against truncation until we
8110 vm_fault_t btrfs_page_mkwrite(struct vm_fault *vmf)
8112 struct page *page = vmf->page;
8113 struct inode *inode = file_inode(vmf->vma->vm_file);
8114 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
8115 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
8116 struct btrfs_ordered_extent *ordered;
8117 struct extent_state *cached_state = NULL;
8118 struct extent_changeset *data_reserved = NULL;
8120 unsigned long zero_start;
8130 reserved_space = PAGE_SIZE;
8132 sb_start_pagefault(inode->i_sb);
8133 page_start = page_offset(page);
8134 page_end = page_start + PAGE_SIZE - 1;
8138 * Reserving delalloc space after obtaining the page lock can lead to
8139 * deadlock. For example, if a dirty page is locked by this function
8140 * and the call to btrfs_delalloc_reserve_space() ends up triggering
8141 * dirty page write out, then the btrfs_writepage() function could
8142 * end up waiting indefinitely to get a lock on the page currently
8143 * being processed by btrfs_page_mkwrite() function.
8145 ret2 = btrfs_delalloc_reserve_space(inode, &data_reserved, page_start,
8148 ret2 = file_update_time(vmf->vma->vm_file);
8152 ret = vmf_error(ret2);
8158 ret = VM_FAULT_NOPAGE; /* make the VM retry the fault */
8161 size = i_size_read(inode);
8163 if ((page->mapping != inode->i_mapping) ||
8164 (page_start >= size)) {
8165 /* page got truncated out from underneath us */
8168 wait_on_page_writeback(page);
8170 lock_extent_bits(io_tree, page_start, page_end, &cached_state);
8171 set_page_extent_mapped(page);
8174 * we can't set the delalloc bits if there are pending ordered
8175 * extents. Drop our locks and wait for them to finish
8177 ordered = btrfs_lookup_ordered_range(BTRFS_I(inode), page_start,
8180 unlock_extent_cached(io_tree, page_start, page_end,
8183 btrfs_start_ordered_extent(inode, ordered, 1);
8184 btrfs_put_ordered_extent(ordered);
8188 if (page->index == ((size - 1) >> PAGE_SHIFT)) {
8189 reserved_space = round_up(size - page_start,
8190 fs_info->sectorsize);
8191 if (reserved_space < PAGE_SIZE) {
8192 end = page_start + reserved_space - 1;
8193 btrfs_delalloc_release_space(inode, data_reserved,
8194 page_start, PAGE_SIZE - reserved_space,
8200 * page_mkwrite gets called when the page is firstly dirtied after it's
8201 * faulted in, but write(2) could also dirty a page and set delalloc
8202 * bits, thus in this case for space account reason, we still need to
8203 * clear any delalloc bits within this page range since we have to
8204 * reserve data&meta space before lock_page() (see above comments).
8206 clear_extent_bit(&BTRFS_I(inode)->io_tree, page_start, end,
8207 EXTENT_DELALLOC | EXTENT_DO_ACCOUNTING |
8208 EXTENT_DEFRAG, 0, 0, &cached_state);
8210 ret2 = btrfs_set_extent_delalloc(inode, page_start, end, 0,
8213 unlock_extent_cached(io_tree, page_start, page_end,
8215 ret = VM_FAULT_SIGBUS;
8219 /* page is wholly or partially inside EOF */
8220 if (page_start + PAGE_SIZE > size)
8221 zero_start = offset_in_page(size);
8223 zero_start = PAGE_SIZE;
8225 if (zero_start != PAGE_SIZE) {
8227 memset(kaddr + zero_start, 0, PAGE_SIZE - zero_start);
8228 flush_dcache_page(page);
8231 ClearPageChecked(page);
8232 set_page_dirty(page);
8233 SetPageUptodate(page);
8235 BTRFS_I(inode)->last_trans = fs_info->generation;
8236 BTRFS_I(inode)->last_sub_trans = BTRFS_I(inode)->root->log_transid;
8237 BTRFS_I(inode)->last_log_commit = BTRFS_I(inode)->root->last_log_commit;
8239 unlock_extent_cached(io_tree, page_start, page_end, &cached_state);
8241 btrfs_delalloc_release_extents(BTRFS_I(inode), PAGE_SIZE);
8242 sb_end_pagefault(inode->i_sb);
8243 extent_changeset_free(data_reserved);
8244 return VM_FAULT_LOCKED;
8249 btrfs_delalloc_release_extents(BTRFS_I(inode), PAGE_SIZE);
8250 btrfs_delalloc_release_space(inode, data_reserved, page_start,
8251 reserved_space, (ret != 0));
8253 sb_end_pagefault(inode->i_sb);
8254 extent_changeset_free(data_reserved);
8258 static int btrfs_truncate(struct inode *inode, bool skip_writeback)
8260 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
8261 struct btrfs_root *root = BTRFS_I(inode)->root;
8262 struct btrfs_block_rsv *rsv;
8264 struct btrfs_trans_handle *trans;
8265 u64 mask = fs_info->sectorsize - 1;
8266 u64 min_size = btrfs_calc_metadata_size(fs_info, 1);
8268 if (!skip_writeback) {
8269 ret = btrfs_wait_ordered_range(inode, inode->i_size & (~mask),
8276 * Yes ladies and gentlemen, this is indeed ugly. We have a couple of
8277 * things going on here:
8279 * 1) We need to reserve space to update our inode.
8281 * 2) We need to have something to cache all the space that is going to
8282 * be free'd up by the truncate operation, but also have some slack
8283 * space reserved in case it uses space during the truncate (thank you
8284 * very much snapshotting).
8286 * And we need these to be separate. The fact is we can use a lot of
8287 * space doing the truncate, and we have no earthly idea how much space
8288 * we will use, so we need the truncate reservation to be separate so it
8289 * doesn't end up using space reserved for updating the inode. We also
8290 * need to be able to stop the transaction and start a new one, which
8291 * means we need to be able to update the inode several times, and we
8292 * have no idea of knowing how many times that will be, so we can't just
8293 * reserve 1 item for the entirety of the operation, so that has to be
8294 * done separately as well.
8296 * So that leaves us with
8298 * 1) rsv - for the truncate reservation, which we will steal from the
8299 * transaction reservation.
8300 * 2) fs_info->trans_block_rsv - this will have 1 items worth left for
8301 * updating the inode.
8303 rsv = btrfs_alloc_block_rsv(fs_info, BTRFS_BLOCK_RSV_TEMP);
8306 rsv->size = min_size;
8310 * 1 for the truncate slack space
8311 * 1 for updating the inode.
8313 trans = btrfs_start_transaction(root, 2);
8314 if (IS_ERR(trans)) {
8315 ret = PTR_ERR(trans);
8319 /* Migrate the slack space for the truncate to our reserve */
8320 ret = btrfs_block_rsv_migrate(&fs_info->trans_block_rsv, rsv,
8325 * So if we truncate and then write and fsync we normally would just
8326 * write the extents that changed, which is a problem if we need to
8327 * first truncate that entire inode. So set this flag so we write out
8328 * all of the extents in the inode to the sync log so we're completely
8331 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &BTRFS_I(inode)->runtime_flags);
8332 trans->block_rsv = rsv;
8335 ret = btrfs_truncate_inode_items(trans, root, inode,
8337 BTRFS_EXTENT_DATA_KEY);
8338 trans->block_rsv = &fs_info->trans_block_rsv;
8339 if (ret != -ENOSPC && ret != -EAGAIN)
8342 ret = btrfs_update_inode(trans, root, inode);
8346 btrfs_end_transaction(trans);
8347 btrfs_btree_balance_dirty(fs_info);
8349 trans = btrfs_start_transaction(root, 2);
8350 if (IS_ERR(trans)) {
8351 ret = PTR_ERR(trans);
8356 btrfs_block_rsv_release(fs_info, rsv, -1, NULL);
8357 ret = btrfs_block_rsv_migrate(&fs_info->trans_block_rsv,
8358 rsv, min_size, false);
8359 BUG_ON(ret); /* shouldn't happen */
8360 trans->block_rsv = rsv;
8364 * We can't call btrfs_truncate_block inside a trans handle as we could
8365 * deadlock with freeze, if we got NEED_TRUNCATE_BLOCK then we know
8366 * we've truncated everything except the last little bit, and can do
8367 * btrfs_truncate_block and then update the disk_i_size.
8369 if (ret == NEED_TRUNCATE_BLOCK) {
8370 btrfs_end_transaction(trans);
8371 btrfs_btree_balance_dirty(fs_info);
8373 ret = btrfs_truncate_block(inode, inode->i_size, 0, 0);
8376 trans = btrfs_start_transaction(root, 1);
8377 if (IS_ERR(trans)) {
8378 ret = PTR_ERR(trans);
8381 btrfs_inode_safe_disk_i_size_write(inode, 0);
8387 trans->block_rsv = &fs_info->trans_block_rsv;
8388 ret2 = btrfs_update_inode(trans, root, inode);
8392 ret2 = btrfs_end_transaction(trans);
8395 btrfs_btree_balance_dirty(fs_info);
8398 btrfs_free_block_rsv(fs_info, rsv);
8404 * create a new subvolume directory/inode (helper for the ioctl).
8406 int btrfs_create_subvol_root(struct btrfs_trans_handle *trans,
8407 struct btrfs_root *new_root,
8408 struct btrfs_root *parent_root,
8411 struct inode *inode;
8415 inode = btrfs_new_inode(trans, new_root, NULL, "..", 2,
8416 new_dirid, new_dirid,
8417 S_IFDIR | (~current_umask() & S_IRWXUGO),
8420 return PTR_ERR(inode);
8421 inode->i_op = &btrfs_dir_inode_operations;
8422 inode->i_fop = &btrfs_dir_file_operations;
8424 set_nlink(inode, 1);
8425 btrfs_i_size_write(BTRFS_I(inode), 0);
8426 unlock_new_inode(inode);
8428 err = btrfs_subvol_inherit_props(trans, new_root, parent_root);
8430 btrfs_err(new_root->fs_info,
8431 "error inheriting subvolume %llu properties: %d",
8432 new_root->root_key.objectid, err);
8434 err = btrfs_update_inode(trans, new_root, inode);
8440 struct inode *btrfs_alloc_inode(struct super_block *sb)
8442 struct btrfs_fs_info *fs_info = btrfs_sb(sb);
8443 struct btrfs_inode *ei;
8444 struct inode *inode;
8446 ei = kmem_cache_alloc(btrfs_inode_cachep, GFP_KERNEL);
8453 ei->last_sub_trans = 0;
8454 ei->logged_trans = 0;
8455 ei->delalloc_bytes = 0;
8456 ei->new_delalloc_bytes = 0;
8457 ei->defrag_bytes = 0;
8458 ei->disk_i_size = 0;
8461 ei->index_cnt = (u64)-1;
8463 ei->last_unlink_trans = 0;
8464 ei->last_log_commit = 0;
8466 spin_lock_init(&ei->lock);
8467 ei->outstanding_extents = 0;
8468 if (sb->s_magic != BTRFS_TEST_MAGIC)
8469 btrfs_init_metadata_block_rsv(fs_info, &ei->block_rsv,
8470 BTRFS_BLOCK_RSV_DELALLOC);
8471 ei->runtime_flags = 0;
8472 ei->prop_compress = BTRFS_COMPRESS_NONE;
8473 ei->defrag_compress = BTRFS_COMPRESS_NONE;
8475 ei->delayed_node = NULL;
8477 ei->i_otime.tv_sec = 0;
8478 ei->i_otime.tv_nsec = 0;
8480 inode = &ei->vfs_inode;
8481 extent_map_tree_init(&ei->extent_tree);
8482 extent_io_tree_init(fs_info, &ei->io_tree, IO_TREE_INODE_IO, inode);
8483 extent_io_tree_init(fs_info, &ei->io_failure_tree,
8484 IO_TREE_INODE_IO_FAILURE, inode);
8485 extent_io_tree_init(fs_info, &ei->file_extent_tree,
8486 IO_TREE_INODE_FILE_EXTENT, inode);
8487 ei->io_tree.track_uptodate = true;
8488 ei->io_failure_tree.track_uptodate = true;
8489 atomic_set(&ei->sync_writers, 0);
8490 mutex_init(&ei->log_mutex);
8491 btrfs_ordered_inode_tree_init(&ei->ordered_tree);
8492 INIT_LIST_HEAD(&ei->delalloc_inodes);
8493 INIT_LIST_HEAD(&ei->delayed_iput);
8494 RB_CLEAR_NODE(&ei->rb_node);
8495 init_rwsem(&ei->dio_sem);
8500 #ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
8501 void btrfs_test_destroy_inode(struct inode *inode)
8503 btrfs_drop_extent_cache(BTRFS_I(inode), 0, (u64)-1, 0);
8504 kmem_cache_free(btrfs_inode_cachep, BTRFS_I(inode));
8508 void btrfs_free_inode(struct inode *inode)
8510 kmem_cache_free(btrfs_inode_cachep, BTRFS_I(inode));
8513 void btrfs_destroy_inode(struct inode *inode)
8515 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
8516 struct btrfs_ordered_extent *ordered;
8517 struct btrfs_root *root = BTRFS_I(inode)->root;
8519 WARN_ON(!hlist_empty(&inode->i_dentry));
8520 WARN_ON(inode->i_data.nrpages);
8521 WARN_ON(BTRFS_I(inode)->block_rsv.reserved);
8522 WARN_ON(BTRFS_I(inode)->block_rsv.size);
8523 WARN_ON(BTRFS_I(inode)->outstanding_extents);
8524 WARN_ON(BTRFS_I(inode)->delalloc_bytes);
8525 WARN_ON(BTRFS_I(inode)->new_delalloc_bytes);
8526 WARN_ON(BTRFS_I(inode)->csum_bytes);
8527 WARN_ON(BTRFS_I(inode)->defrag_bytes);
8530 * This can happen where we create an inode, but somebody else also
8531 * created the same inode and we need to destroy the one we already
8538 ordered = btrfs_lookup_first_ordered_extent(inode, (u64)-1);
8543 "found ordered extent %llu %llu on inode cleanup",
8544 ordered->file_offset, ordered->num_bytes);
8545 btrfs_remove_ordered_extent(inode, ordered);
8546 btrfs_put_ordered_extent(ordered);
8547 btrfs_put_ordered_extent(ordered);
8550 btrfs_qgroup_check_reserved_leak(inode);
8551 inode_tree_del(inode);
8552 btrfs_drop_extent_cache(BTRFS_I(inode), 0, (u64)-1, 0);
8553 btrfs_inode_clear_file_extent_range(BTRFS_I(inode), 0, (u64)-1);
8554 btrfs_put_root(BTRFS_I(inode)->root);
8557 int btrfs_drop_inode(struct inode *inode)
8559 struct btrfs_root *root = BTRFS_I(inode)->root;
8564 /* the snap/subvol tree is on deleting */
8565 if (btrfs_root_refs(&root->root_item) == 0)
8568 return generic_drop_inode(inode);
8571 static void init_once(void *foo)
8573 struct btrfs_inode *ei = (struct btrfs_inode *) foo;
8575 inode_init_once(&ei->vfs_inode);
8578 void __cold btrfs_destroy_cachep(void)
8581 * Make sure all delayed rcu free inodes are flushed before we
8585 kmem_cache_destroy(btrfs_inode_cachep);
8586 kmem_cache_destroy(btrfs_trans_handle_cachep);
8587 kmem_cache_destroy(btrfs_path_cachep);
8588 kmem_cache_destroy(btrfs_free_space_cachep);
8589 kmem_cache_destroy(btrfs_free_space_bitmap_cachep);
8592 int __init btrfs_init_cachep(void)
8594 btrfs_inode_cachep = kmem_cache_create("btrfs_inode",
8595 sizeof(struct btrfs_inode), 0,
8596 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD | SLAB_ACCOUNT,
8598 if (!btrfs_inode_cachep)
8601 btrfs_trans_handle_cachep = kmem_cache_create("btrfs_trans_handle",
8602 sizeof(struct btrfs_trans_handle), 0,
8603 SLAB_TEMPORARY | SLAB_MEM_SPREAD, NULL);
8604 if (!btrfs_trans_handle_cachep)
8607 btrfs_path_cachep = kmem_cache_create("btrfs_path",
8608 sizeof(struct btrfs_path), 0,
8609 SLAB_MEM_SPREAD, NULL);
8610 if (!btrfs_path_cachep)
8613 btrfs_free_space_cachep = kmem_cache_create("btrfs_free_space",
8614 sizeof(struct btrfs_free_space), 0,
8615 SLAB_MEM_SPREAD, NULL);
8616 if (!btrfs_free_space_cachep)
8619 btrfs_free_space_bitmap_cachep = kmem_cache_create("btrfs_free_space_bitmap",
8620 PAGE_SIZE, PAGE_SIZE,
8621 SLAB_RED_ZONE, NULL);
8622 if (!btrfs_free_space_bitmap_cachep)
8627 btrfs_destroy_cachep();
8631 static int btrfs_getattr(const struct path *path, struct kstat *stat,
8632 u32 request_mask, unsigned int flags)
8635 struct inode *inode = d_inode(path->dentry);
8636 u32 blocksize = inode->i_sb->s_blocksize;
8637 u32 bi_flags = BTRFS_I(inode)->flags;
8639 stat->result_mask |= STATX_BTIME;
8640 stat->btime.tv_sec = BTRFS_I(inode)->i_otime.tv_sec;
8641 stat->btime.tv_nsec = BTRFS_I(inode)->i_otime.tv_nsec;
8642 if (bi_flags & BTRFS_INODE_APPEND)
8643 stat->attributes |= STATX_ATTR_APPEND;
8644 if (bi_flags & BTRFS_INODE_COMPRESS)
8645 stat->attributes |= STATX_ATTR_COMPRESSED;
8646 if (bi_flags & BTRFS_INODE_IMMUTABLE)
8647 stat->attributes |= STATX_ATTR_IMMUTABLE;
8648 if (bi_flags & BTRFS_INODE_NODUMP)
8649 stat->attributes |= STATX_ATTR_NODUMP;
8651 stat->attributes_mask |= (STATX_ATTR_APPEND |
8652 STATX_ATTR_COMPRESSED |
8653 STATX_ATTR_IMMUTABLE |
8656 generic_fillattr(inode, stat);
8657 stat->dev = BTRFS_I(inode)->root->anon_dev;
8659 spin_lock(&BTRFS_I(inode)->lock);
8660 delalloc_bytes = BTRFS_I(inode)->new_delalloc_bytes;
8661 spin_unlock(&BTRFS_I(inode)->lock);
8662 stat->blocks = (ALIGN(inode_get_bytes(inode), blocksize) +
8663 ALIGN(delalloc_bytes, blocksize)) >> 9;
8667 static int btrfs_rename_exchange(struct inode *old_dir,
8668 struct dentry *old_dentry,
8669 struct inode *new_dir,
8670 struct dentry *new_dentry)
8672 struct btrfs_fs_info *fs_info = btrfs_sb(old_dir->i_sb);
8673 struct btrfs_trans_handle *trans;
8674 struct btrfs_root *root = BTRFS_I(old_dir)->root;
8675 struct btrfs_root *dest = BTRFS_I(new_dir)->root;
8676 struct inode *new_inode = new_dentry->d_inode;
8677 struct inode *old_inode = old_dentry->d_inode;
8678 struct timespec64 ctime = current_time(old_inode);
8679 struct dentry *parent;
8680 u64 old_ino = btrfs_ino(BTRFS_I(old_inode));
8681 u64 new_ino = btrfs_ino(BTRFS_I(new_inode));
8685 bool root_log_pinned = false;
8686 bool dest_log_pinned = false;
8687 struct btrfs_log_ctx ctx_root;
8688 struct btrfs_log_ctx ctx_dest;
8689 bool sync_log_root = false;
8690 bool sync_log_dest = false;
8691 bool commit_transaction = false;
8693 /* we only allow rename subvolume link between subvolumes */
8694 if (old_ino != BTRFS_FIRST_FREE_OBJECTID && root != dest)
8697 btrfs_init_log_ctx(&ctx_root, old_inode);
8698 btrfs_init_log_ctx(&ctx_dest, new_inode);
8700 /* close the race window with snapshot create/destroy ioctl */
8701 if (old_ino == BTRFS_FIRST_FREE_OBJECTID ||
8702 new_ino == BTRFS_FIRST_FREE_OBJECTID)
8703 down_read(&fs_info->subvol_sem);
8706 * We want to reserve the absolute worst case amount of items. So if
8707 * both inodes are subvols and we need to unlink them then that would
8708 * require 4 item modifications, but if they are both normal inodes it
8709 * would require 5 item modifications, so we'll assume their normal
8710 * inodes. So 5 * 2 is 10, plus 2 for the new links, so 12 total items
8711 * should cover the worst case number of items we'll modify.
8713 trans = btrfs_start_transaction(root, 12);
8714 if (IS_ERR(trans)) {
8715 ret = PTR_ERR(trans);
8720 btrfs_record_root_in_trans(trans, dest);
8723 * We need to find a free sequence number both in the source and
8724 * in the destination directory for the exchange.
8726 ret = btrfs_set_inode_index(BTRFS_I(new_dir), &old_idx);
8729 ret = btrfs_set_inode_index(BTRFS_I(old_dir), &new_idx);
8733 BTRFS_I(old_inode)->dir_index = 0ULL;
8734 BTRFS_I(new_inode)->dir_index = 0ULL;
8736 /* Reference for the source. */
8737 if (old_ino == BTRFS_FIRST_FREE_OBJECTID) {
8738 /* force full log commit if subvolume involved. */
8739 btrfs_set_log_full_commit(trans);
8741 btrfs_pin_log_trans(root);
8742 root_log_pinned = true;
8743 ret = btrfs_insert_inode_ref(trans, dest,
8744 new_dentry->d_name.name,
8745 new_dentry->d_name.len,
8747 btrfs_ino(BTRFS_I(new_dir)),
8753 /* And now for the dest. */
8754 if (new_ino == BTRFS_FIRST_FREE_OBJECTID) {
8755 /* force full log commit if subvolume involved. */
8756 btrfs_set_log_full_commit(trans);
8758 btrfs_pin_log_trans(dest);
8759 dest_log_pinned = true;
8760 ret = btrfs_insert_inode_ref(trans, root,
8761 old_dentry->d_name.name,
8762 old_dentry->d_name.len,
8764 btrfs_ino(BTRFS_I(old_dir)),
8770 /* Update inode version and ctime/mtime. */
8771 inode_inc_iversion(old_dir);
8772 inode_inc_iversion(new_dir);
8773 inode_inc_iversion(old_inode);
8774 inode_inc_iversion(new_inode);
8775 old_dir->i_ctime = old_dir->i_mtime = ctime;
8776 new_dir->i_ctime = new_dir->i_mtime = ctime;
8777 old_inode->i_ctime = ctime;
8778 new_inode->i_ctime = ctime;
8780 if (old_dentry->d_parent != new_dentry->d_parent) {
8781 btrfs_record_unlink_dir(trans, BTRFS_I(old_dir),
8782 BTRFS_I(old_inode), 1);
8783 btrfs_record_unlink_dir(trans, BTRFS_I(new_dir),
8784 BTRFS_I(new_inode), 1);
8787 /* src is a subvolume */
8788 if (old_ino == BTRFS_FIRST_FREE_OBJECTID) {
8789 ret = btrfs_unlink_subvol(trans, old_dir, old_dentry);
8790 } else { /* src is an inode */
8791 ret = __btrfs_unlink_inode(trans, root, BTRFS_I(old_dir),
8792 BTRFS_I(old_dentry->d_inode),
8793 old_dentry->d_name.name,
8794 old_dentry->d_name.len);
8796 ret = btrfs_update_inode(trans, root, old_inode);
8799 btrfs_abort_transaction(trans, ret);
8803 /* dest is a subvolume */
8804 if (new_ino == BTRFS_FIRST_FREE_OBJECTID) {
8805 ret = btrfs_unlink_subvol(trans, new_dir, new_dentry);
8806 } else { /* dest is an inode */
8807 ret = __btrfs_unlink_inode(trans, dest, BTRFS_I(new_dir),
8808 BTRFS_I(new_dentry->d_inode),
8809 new_dentry->d_name.name,
8810 new_dentry->d_name.len);
8812 ret = btrfs_update_inode(trans, dest, new_inode);
8815 btrfs_abort_transaction(trans, ret);
8819 ret = btrfs_add_link(trans, BTRFS_I(new_dir), BTRFS_I(old_inode),
8820 new_dentry->d_name.name,
8821 new_dentry->d_name.len, 0, old_idx);
8823 btrfs_abort_transaction(trans, ret);
8827 ret = btrfs_add_link(trans, BTRFS_I(old_dir), BTRFS_I(new_inode),
8828 old_dentry->d_name.name,
8829 old_dentry->d_name.len, 0, new_idx);
8831 btrfs_abort_transaction(trans, ret);
8835 if (old_inode->i_nlink == 1)
8836 BTRFS_I(old_inode)->dir_index = old_idx;
8837 if (new_inode->i_nlink == 1)
8838 BTRFS_I(new_inode)->dir_index = new_idx;
8840 if (root_log_pinned) {
8841 parent = new_dentry->d_parent;
8842 ret = btrfs_log_new_name(trans, BTRFS_I(old_inode),
8843 BTRFS_I(old_dir), parent,
8845 if (ret == BTRFS_NEED_LOG_SYNC)
8846 sync_log_root = true;
8847 else if (ret == BTRFS_NEED_TRANS_COMMIT)
8848 commit_transaction = true;
8850 btrfs_end_log_trans(root);
8851 root_log_pinned = false;
8853 if (dest_log_pinned) {
8854 if (!commit_transaction) {
8855 parent = old_dentry->d_parent;
8856 ret = btrfs_log_new_name(trans, BTRFS_I(new_inode),
8857 BTRFS_I(new_dir), parent,
8859 if (ret == BTRFS_NEED_LOG_SYNC)
8860 sync_log_dest = true;
8861 else if (ret == BTRFS_NEED_TRANS_COMMIT)
8862 commit_transaction = true;
8865 btrfs_end_log_trans(dest);
8866 dest_log_pinned = false;
8870 * If we have pinned a log and an error happened, we unpin tasks
8871 * trying to sync the log and force them to fallback to a transaction
8872 * commit if the log currently contains any of the inodes involved in
8873 * this rename operation (to ensure we do not persist a log with an
8874 * inconsistent state for any of these inodes or leading to any
8875 * inconsistencies when replayed). If the transaction was aborted, the
8876 * abortion reason is propagated to userspace when attempting to commit
8877 * the transaction. If the log does not contain any of these inodes, we
8878 * allow the tasks to sync it.
8880 if (ret && (root_log_pinned || dest_log_pinned)) {
8881 if (btrfs_inode_in_log(BTRFS_I(old_dir), fs_info->generation) ||
8882 btrfs_inode_in_log(BTRFS_I(new_dir), fs_info->generation) ||
8883 btrfs_inode_in_log(BTRFS_I(old_inode), fs_info->generation) ||
8885 btrfs_inode_in_log(BTRFS_I(new_inode), fs_info->generation)))
8886 btrfs_set_log_full_commit(trans);
8888 if (root_log_pinned) {
8889 btrfs_end_log_trans(root);
8890 root_log_pinned = false;
8892 if (dest_log_pinned) {
8893 btrfs_end_log_trans(dest);
8894 dest_log_pinned = false;
8897 if (!ret && sync_log_root && !commit_transaction) {
8898 ret = btrfs_sync_log(trans, BTRFS_I(old_inode)->root,
8901 commit_transaction = true;
8903 if (!ret && sync_log_dest && !commit_transaction) {
8904 ret = btrfs_sync_log(trans, BTRFS_I(new_inode)->root,
8907 commit_transaction = true;
8909 if (commit_transaction) {
8911 * We may have set commit_transaction when logging the new name
8912 * in the destination root, in which case we left the source
8913 * root context in the list of log contextes. So make sure we
8914 * remove it to avoid invalid memory accesses, since the context
8915 * was allocated in our stack frame.
8917 if (sync_log_root) {
8918 mutex_lock(&root->log_mutex);
8919 list_del_init(&ctx_root.list);
8920 mutex_unlock(&root->log_mutex);
8922 ret = btrfs_commit_transaction(trans);
8926 ret2 = btrfs_end_transaction(trans);
8927 ret = ret ? ret : ret2;
8930 if (new_ino == BTRFS_FIRST_FREE_OBJECTID ||
8931 old_ino == BTRFS_FIRST_FREE_OBJECTID)
8932 up_read(&fs_info->subvol_sem);
8934 ASSERT(list_empty(&ctx_root.list));
8935 ASSERT(list_empty(&ctx_dest.list));
8940 static int btrfs_whiteout_for_rename(struct btrfs_trans_handle *trans,
8941 struct btrfs_root *root,
8943 struct dentry *dentry)
8946 struct inode *inode;
8950 ret = btrfs_find_free_ino(root, &objectid);
8954 inode = btrfs_new_inode(trans, root, dir,
8955 dentry->d_name.name,
8957 btrfs_ino(BTRFS_I(dir)),
8959 S_IFCHR | WHITEOUT_MODE,
8962 if (IS_ERR(inode)) {
8963 ret = PTR_ERR(inode);
8967 inode->i_op = &btrfs_special_inode_operations;
8968 init_special_inode(inode, inode->i_mode,
8971 ret = btrfs_init_inode_security(trans, inode, dir,
8976 ret = btrfs_add_nondir(trans, BTRFS_I(dir), dentry,
8977 BTRFS_I(inode), 0, index);
8981 ret = btrfs_update_inode(trans, root, inode);
8983 unlock_new_inode(inode);
8985 inode_dec_link_count(inode);
8991 static int btrfs_rename(struct inode *old_dir, struct dentry *old_dentry,
8992 struct inode *new_dir, struct dentry *new_dentry,
8995 struct btrfs_fs_info *fs_info = btrfs_sb(old_dir->i_sb);
8996 struct btrfs_trans_handle *trans;
8997 unsigned int trans_num_items;
8998 struct btrfs_root *root = BTRFS_I(old_dir)->root;
8999 struct btrfs_root *dest = BTRFS_I(new_dir)->root;
9000 struct inode *new_inode = d_inode(new_dentry);
9001 struct inode *old_inode = d_inode(old_dentry);
9004 u64 old_ino = btrfs_ino(BTRFS_I(old_inode));
9005 bool log_pinned = false;
9006 struct btrfs_log_ctx ctx;
9007 bool sync_log = false;
9008 bool commit_transaction = false;
9010 if (btrfs_ino(BTRFS_I(new_dir)) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)
9013 /* we only allow rename subvolume link between subvolumes */
9014 if (old_ino != BTRFS_FIRST_FREE_OBJECTID && root != dest)
9017 if (old_ino == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID ||
9018 (new_inode && btrfs_ino(BTRFS_I(new_inode)) == BTRFS_FIRST_FREE_OBJECTID))
9021 if (S_ISDIR(old_inode->i_mode) && new_inode &&
9022 new_inode->i_size > BTRFS_EMPTY_DIR_SIZE)
9026 /* check for collisions, even if the name isn't there */
9027 ret = btrfs_check_dir_item_collision(dest, new_dir->i_ino,
9028 new_dentry->d_name.name,
9029 new_dentry->d_name.len);
9032 if (ret == -EEXIST) {
9034 * eexist without a new_inode */
9035 if (WARN_ON(!new_inode)) {
9039 /* maybe -EOVERFLOW */
9046 * we're using rename to replace one file with another. Start IO on it
9047 * now so we don't add too much work to the end of the transaction
9049 if (new_inode && S_ISREG(old_inode->i_mode) && new_inode->i_size)
9050 filemap_flush(old_inode->i_mapping);
9052 /* close the racy window with snapshot create/destroy ioctl */
9053 if (old_ino == BTRFS_FIRST_FREE_OBJECTID)
9054 down_read(&fs_info->subvol_sem);
9056 * We want to reserve the absolute worst case amount of items. So if
9057 * both inodes are subvols and we need to unlink them then that would
9058 * require 4 item modifications, but if they are both normal inodes it
9059 * would require 5 item modifications, so we'll assume they are normal
9060 * inodes. So 5 * 2 is 10, plus 1 for the new link, so 11 total items
9061 * should cover the worst case number of items we'll modify.
9062 * If our rename has the whiteout flag, we need more 5 units for the
9063 * new inode (1 inode item, 1 inode ref, 2 dir items and 1 xattr item
9064 * when selinux is enabled).
9066 trans_num_items = 11;
9067 if (flags & RENAME_WHITEOUT)
9068 trans_num_items += 5;
9069 trans = btrfs_start_transaction(root, trans_num_items);
9070 if (IS_ERR(trans)) {
9071 ret = PTR_ERR(trans);
9076 btrfs_record_root_in_trans(trans, dest);
9078 ret = btrfs_set_inode_index(BTRFS_I(new_dir), &index);
9082 BTRFS_I(old_inode)->dir_index = 0ULL;
9083 if (unlikely(old_ino == BTRFS_FIRST_FREE_OBJECTID)) {
9084 /* force full log commit if subvolume involved. */
9085 btrfs_set_log_full_commit(trans);
9087 btrfs_pin_log_trans(root);
9089 ret = btrfs_insert_inode_ref(trans, dest,
9090 new_dentry->d_name.name,
9091 new_dentry->d_name.len,
9093 btrfs_ino(BTRFS_I(new_dir)), index);
9098 inode_inc_iversion(old_dir);
9099 inode_inc_iversion(new_dir);
9100 inode_inc_iversion(old_inode);
9101 old_dir->i_ctime = old_dir->i_mtime =
9102 new_dir->i_ctime = new_dir->i_mtime =
9103 old_inode->i_ctime = current_time(old_dir);
9105 if (old_dentry->d_parent != new_dentry->d_parent)
9106 btrfs_record_unlink_dir(trans, BTRFS_I(old_dir),
9107 BTRFS_I(old_inode), 1);
9109 if (unlikely(old_ino == BTRFS_FIRST_FREE_OBJECTID)) {
9110 ret = btrfs_unlink_subvol(trans, old_dir, old_dentry);
9112 ret = __btrfs_unlink_inode(trans, root, BTRFS_I(old_dir),
9113 BTRFS_I(d_inode(old_dentry)),
9114 old_dentry->d_name.name,
9115 old_dentry->d_name.len);
9117 ret = btrfs_update_inode(trans, root, old_inode);
9120 btrfs_abort_transaction(trans, ret);
9125 inode_inc_iversion(new_inode);
9126 new_inode->i_ctime = current_time(new_inode);
9127 if (unlikely(btrfs_ino(BTRFS_I(new_inode)) ==
9128 BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)) {
9129 ret = btrfs_unlink_subvol(trans, new_dir, new_dentry);
9130 BUG_ON(new_inode->i_nlink == 0);
9132 ret = btrfs_unlink_inode(trans, dest, BTRFS_I(new_dir),
9133 BTRFS_I(d_inode(new_dentry)),
9134 new_dentry->d_name.name,
9135 new_dentry->d_name.len);
9137 if (!ret && new_inode->i_nlink == 0)
9138 ret = btrfs_orphan_add(trans,
9139 BTRFS_I(d_inode(new_dentry)));
9141 btrfs_abort_transaction(trans, ret);
9146 ret = btrfs_add_link(trans, BTRFS_I(new_dir), BTRFS_I(old_inode),
9147 new_dentry->d_name.name,
9148 new_dentry->d_name.len, 0, index);
9150 btrfs_abort_transaction(trans, ret);
9154 if (old_inode->i_nlink == 1)
9155 BTRFS_I(old_inode)->dir_index = index;
9158 struct dentry *parent = new_dentry->d_parent;
9160 btrfs_init_log_ctx(&ctx, old_inode);
9161 ret = btrfs_log_new_name(trans, BTRFS_I(old_inode),
9162 BTRFS_I(old_dir), parent,
9164 if (ret == BTRFS_NEED_LOG_SYNC)
9166 else if (ret == BTRFS_NEED_TRANS_COMMIT)
9167 commit_transaction = true;
9169 btrfs_end_log_trans(root);
9173 if (flags & RENAME_WHITEOUT) {
9174 ret = btrfs_whiteout_for_rename(trans, root, old_dir,
9178 btrfs_abort_transaction(trans, ret);
9184 * If we have pinned the log and an error happened, we unpin tasks
9185 * trying to sync the log and force them to fallback to a transaction
9186 * commit if the log currently contains any of the inodes involved in
9187 * this rename operation (to ensure we do not persist a log with an
9188 * inconsistent state for any of these inodes or leading to any
9189 * inconsistencies when replayed). If the transaction was aborted, the
9190 * abortion reason is propagated to userspace when attempting to commit
9191 * the transaction. If the log does not contain any of these inodes, we
9192 * allow the tasks to sync it.
9194 if (ret && log_pinned) {
9195 if (btrfs_inode_in_log(BTRFS_I(old_dir), fs_info->generation) ||
9196 btrfs_inode_in_log(BTRFS_I(new_dir), fs_info->generation) ||
9197 btrfs_inode_in_log(BTRFS_I(old_inode), fs_info->generation) ||
9199 btrfs_inode_in_log(BTRFS_I(new_inode), fs_info->generation)))
9200 btrfs_set_log_full_commit(trans);
9202 btrfs_end_log_trans(root);
9205 if (!ret && sync_log) {
9206 ret = btrfs_sync_log(trans, BTRFS_I(old_inode)->root, &ctx);
9208 commit_transaction = true;
9209 } else if (sync_log) {
9210 mutex_lock(&root->log_mutex);
9211 list_del(&ctx.list);
9212 mutex_unlock(&root->log_mutex);
9214 if (commit_transaction) {
9215 ret = btrfs_commit_transaction(trans);
9219 ret2 = btrfs_end_transaction(trans);
9220 ret = ret ? ret : ret2;
9223 if (old_ino == BTRFS_FIRST_FREE_OBJECTID)
9224 up_read(&fs_info->subvol_sem);
9229 static int btrfs_rename2(struct inode *old_dir, struct dentry *old_dentry,
9230 struct inode *new_dir, struct dentry *new_dentry,
9233 if (flags & ~(RENAME_NOREPLACE | RENAME_EXCHANGE | RENAME_WHITEOUT))
9236 if (flags & RENAME_EXCHANGE)
9237 return btrfs_rename_exchange(old_dir, old_dentry, new_dir,
9240 return btrfs_rename(old_dir, old_dentry, new_dir, new_dentry, flags);
9243 struct btrfs_delalloc_work {
9244 struct inode *inode;
9245 struct completion completion;
9246 struct list_head list;
9247 struct btrfs_work work;
9250 static void btrfs_run_delalloc_work(struct btrfs_work *work)
9252 struct btrfs_delalloc_work *delalloc_work;
9253 struct inode *inode;
9255 delalloc_work = container_of(work, struct btrfs_delalloc_work,
9257 inode = delalloc_work->inode;
9258 filemap_flush(inode->i_mapping);
9259 if (test_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
9260 &BTRFS_I(inode)->runtime_flags))
9261 filemap_flush(inode->i_mapping);
9264 complete(&delalloc_work->completion);
9267 static struct btrfs_delalloc_work *btrfs_alloc_delalloc_work(struct inode *inode)
9269 struct btrfs_delalloc_work *work;
9271 work = kmalloc(sizeof(*work), GFP_NOFS);
9275 init_completion(&work->completion);
9276 INIT_LIST_HEAD(&work->list);
9277 work->inode = inode;
9278 btrfs_init_work(&work->work, btrfs_run_delalloc_work, NULL, NULL);
9284 * some fairly slow code that needs optimization. This walks the list
9285 * of all the inodes with pending delalloc and forces them to disk.
9287 static int start_delalloc_inodes(struct btrfs_root *root, int nr, bool snapshot)
9289 struct btrfs_inode *binode;
9290 struct inode *inode;
9291 struct btrfs_delalloc_work *work, *next;
9292 struct list_head works;
9293 struct list_head splice;
9296 INIT_LIST_HEAD(&works);
9297 INIT_LIST_HEAD(&splice);
9299 mutex_lock(&root->delalloc_mutex);
9300 spin_lock(&root->delalloc_lock);
9301 list_splice_init(&root->delalloc_inodes, &splice);
9302 while (!list_empty(&splice)) {
9303 binode = list_entry(splice.next, struct btrfs_inode,
9306 list_move_tail(&binode->delalloc_inodes,
9307 &root->delalloc_inodes);
9308 inode = igrab(&binode->vfs_inode);
9310 cond_resched_lock(&root->delalloc_lock);
9313 spin_unlock(&root->delalloc_lock);
9316 set_bit(BTRFS_INODE_SNAPSHOT_FLUSH,
9317 &binode->runtime_flags);
9318 work = btrfs_alloc_delalloc_work(inode);
9324 list_add_tail(&work->list, &works);
9325 btrfs_queue_work(root->fs_info->flush_workers,
9328 if (nr != -1 && ret >= nr)
9331 spin_lock(&root->delalloc_lock);
9333 spin_unlock(&root->delalloc_lock);
9336 list_for_each_entry_safe(work, next, &works, list) {
9337 list_del_init(&work->list);
9338 wait_for_completion(&work->completion);
9342 if (!list_empty(&splice)) {
9343 spin_lock(&root->delalloc_lock);
9344 list_splice_tail(&splice, &root->delalloc_inodes);
9345 spin_unlock(&root->delalloc_lock);
9347 mutex_unlock(&root->delalloc_mutex);
9351 int btrfs_start_delalloc_snapshot(struct btrfs_root *root)
9353 struct btrfs_fs_info *fs_info = root->fs_info;
9356 if (test_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state))
9359 ret = start_delalloc_inodes(root, -1, true);
9365 int btrfs_start_delalloc_roots(struct btrfs_fs_info *fs_info, int nr)
9367 struct btrfs_root *root;
9368 struct list_head splice;
9371 if (test_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state))
9374 INIT_LIST_HEAD(&splice);
9376 mutex_lock(&fs_info->delalloc_root_mutex);
9377 spin_lock(&fs_info->delalloc_root_lock);
9378 list_splice_init(&fs_info->delalloc_roots, &splice);
9379 while (!list_empty(&splice) && nr) {
9380 root = list_first_entry(&splice, struct btrfs_root,
9382 root = btrfs_grab_root(root);
9384 list_move_tail(&root->delalloc_root,
9385 &fs_info->delalloc_roots);
9386 spin_unlock(&fs_info->delalloc_root_lock);
9388 ret = start_delalloc_inodes(root, nr, false);
9389 btrfs_put_root(root);
9397 spin_lock(&fs_info->delalloc_root_lock);
9399 spin_unlock(&fs_info->delalloc_root_lock);
9403 if (!list_empty(&splice)) {
9404 spin_lock(&fs_info->delalloc_root_lock);
9405 list_splice_tail(&splice, &fs_info->delalloc_roots);
9406 spin_unlock(&fs_info->delalloc_root_lock);
9408 mutex_unlock(&fs_info->delalloc_root_mutex);
9412 static int btrfs_symlink(struct inode *dir, struct dentry *dentry,
9413 const char *symname)
9415 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
9416 struct btrfs_trans_handle *trans;
9417 struct btrfs_root *root = BTRFS_I(dir)->root;
9418 struct btrfs_path *path;
9419 struct btrfs_key key;
9420 struct inode *inode = NULL;
9427 struct btrfs_file_extent_item *ei;
9428 struct extent_buffer *leaf;
9430 name_len = strlen(symname);
9431 if (name_len > BTRFS_MAX_INLINE_DATA_SIZE(fs_info))
9432 return -ENAMETOOLONG;
9435 * 2 items for inode item and ref
9436 * 2 items for dir items
9437 * 1 item for updating parent inode item
9438 * 1 item for the inline extent item
9439 * 1 item for xattr if selinux is on
9441 trans = btrfs_start_transaction(root, 7);
9443 return PTR_ERR(trans);
9445 err = btrfs_find_free_ino(root, &objectid);
9449 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
9450 dentry->d_name.len, btrfs_ino(BTRFS_I(dir)),
9451 objectid, S_IFLNK|S_IRWXUGO, &index);
9452 if (IS_ERR(inode)) {
9453 err = PTR_ERR(inode);
9459 * If the active LSM wants to access the inode during
9460 * d_instantiate it needs these. Smack checks to see
9461 * if the filesystem supports xattrs by looking at the
9464 inode->i_fop = &btrfs_file_operations;
9465 inode->i_op = &btrfs_file_inode_operations;
9466 inode->i_mapping->a_ops = &btrfs_aops;
9467 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
9469 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
9473 path = btrfs_alloc_path();
9478 key.objectid = btrfs_ino(BTRFS_I(inode));
9480 key.type = BTRFS_EXTENT_DATA_KEY;
9481 datasize = btrfs_file_extent_calc_inline_size(name_len);
9482 err = btrfs_insert_empty_item(trans, root, path, &key,
9485 btrfs_free_path(path);
9488 leaf = path->nodes[0];
9489 ei = btrfs_item_ptr(leaf, path->slots[0],
9490 struct btrfs_file_extent_item);
9491 btrfs_set_file_extent_generation(leaf, ei, trans->transid);
9492 btrfs_set_file_extent_type(leaf, ei,
9493 BTRFS_FILE_EXTENT_INLINE);
9494 btrfs_set_file_extent_encryption(leaf, ei, 0);
9495 btrfs_set_file_extent_compression(leaf, ei, 0);
9496 btrfs_set_file_extent_other_encoding(leaf, ei, 0);
9497 btrfs_set_file_extent_ram_bytes(leaf, ei, name_len);
9499 ptr = btrfs_file_extent_inline_start(ei);
9500 write_extent_buffer(leaf, symname, ptr, name_len);
9501 btrfs_mark_buffer_dirty(leaf);
9502 btrfs_free_path(path);
9504 inode->i_op = &btrfs_symlink_inode_operations;
9505 inode_nohighmem(inode);
9506 inode_set_bytes(inode, name_len);
9507 btrfs_i_size_write(BTRFS_I(inode), name_len);
9508 err = btrfs_update_inode(trans, root, inode);
9510 * Last step, add directory indexes for our symlink inode. This is the
9511 * last step to avoid extra cleanup of these indexes if an error happens
9515 err = btrfs_add_nondir(trans, BTRFS_I(dir), dentry,
9516 BTRFS_I(inode), 0, index);
9520 d_instantiate_new(dentry, inode);
9523 btrfs_end_transaction(trans);
9525 inode_dec_link_count(inode);
9526 discard_new_inode(inode);
9528 btrfs_btree_balance_dirty(fs_info);
9532 static int __btrfs_prealloc_file_range(struct inode *inode, int mode,
9533 u64 start, u64 num_bytes, u64 min_size,
9534 loff_t actual_len, u64 *alloc_hint,
9535 struct btrfs_trans_handle *trans)
9537 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
9538 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
9539 struct extent_map *em;
9540 struct btrfs_root *root = BTRFS_I(inode)->root;
9541 struct btrfs_key ins;
9542 u64 cur_offset = start;
9543 u64 clear_offset = start;
9546 u64 last_alloc = (u64)-1;
9548 bool own_trans = true;
9549 u64 end = start + num_bytes - 1;
9553 while (num_bytes > 0) {
9555 trans = btrfs_start_transaction(root, 3);
9556 if (IS_ERR(trans)) {
9557 ret = PTR_ERR(trans);
9562 cur_bytes = min_t(u64, num_bytes, SZ_256M);
9563 cur_bytes = max(cur_bytes, min_size);
9565 * If we are severely fragmented we could end up with really
9566 * small allocations, so if the allocator is returning small
9567 * chunks lets make its job easier by only searching for those
9570 cur_bytes = min(cur_bytes, last_alloc);
9571 ret = btrfs_reserve_extent(root, cur_bytes, cur_bytes,
9572 min_size, 0, *alloc_hint, &ins, 1, 0);
9575 btrfs_end_transaction(trans);
9580 * We've reserved this space, and thus converted it from
9581 * ->bytes_may_use to ->bytes_reserved. Any error that happens
9582 * from here on out we will only need to clear our reservation
9583 * for the remaining unreserved area, so advance our
9584 * clear_offset by our extent size.
9586 clear_offset += ins.offset;
9587 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
9589 last_alloc = ins.offset;
9590 ret = insert_reserved_file_extent(trans, inode,
9591 cur_offset, ins.objectid,
9592 ins.offset, ins.offset,
9593 ins.offset, 0, 0, 0,
9594 BTRFS_FILE_EXTENT_PREALLOC);
9596 btrfs_free_reserved_extent(fs_info, ins.objectid,
9598 btrfs_abort_transaction(trans, ret);
9600 btrfs_end_transaction(trans);
9604 btrfs_drop_extent_cache(BTRFS_I(inode), cur_offset,
9605 cur_offset + ins.offset -1, 0);
9607 em = alloc_extent_map();
9609 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
9610 &BTRFS_I(inode)->runtime_flags);
9614 em->start = cur_offset;
9615 em->orig_start = cur_offset;
9616 em->len = ins.offset;
9617 em->block_start = ins.objectid;
9618 em->block_len = ins.offset;
9619 em->orig_block_len = ins.offset;
9620 em->ram_bytes = ins.offset;
9621 set_bit(EXTENT_FLAG_PREALLOC, &em->flags);
9622 em->generation = trans->transid;
9625 write_lock(&em_tree->lock);
9626 ret = add_extent_mapping(em_tree, em, 1);
9627 write_unlock(&em_tree->lock);
9630 btrfs_drop_extent_cache(BTRFS_I(inode), cur_offset,
9631 cur_offset + ins.offset - 1,
9634 free_extent_map(em);
9636 num_bytes -= ins.offset;
9637 cur_offset += ins.offset;
9638 *alloc_hint = ins.objectid + ins.offset;
9640 inode_inc_iversion(inode);
9641 inode->i_ctime = current_time(inode);
9642 BTRFS_I(inode)->flags |= BTRFS_INODE_PREALLOC;
9643 if (!(mode & FALLOC_FL_KEEP_SIZE) &&
9644 (actual_len > inode->i_size) &&
9645 (cur_offset > inode->i_size)) {
9646 if (cur_offset > actual_len)
9647 i_size = actual_len;
9649 i_size = cur_offset;
9650 i_size_write(inode, i_size);
9651 btrfs_inode_safe_disk_i_size_write(inode, 0);
9654 ret = btrfs_update_inode(trans, root, inode);
9657 btrfs_abort_transaction(trans, ret);
9659 btrfs_end_transaction(trans);
9664 btrfs_end_transaction(trans);
9666 if (clear_offset < end)
9667 btrfs_free_reserved_data_space(inode, NULL, clear_offset,
9668 end - clear_offset + 1);
9672 int btrfs_prealloc_file_range(struct inode *inode, int mode,
9673 u64 start, u64 num_bytes, u64 min_size,
9674 loff_t actual_len, u64 *alloc_hint)
9676 return __btrfs_prealloc_file_range(inode, mode, start, num_bytes,
9677 min_size, actual_len, alloc_hint,
9681 int btrfs_prealloc_file_range_trans(struct inode *inode,
9682 struct btrfs_trans_handle *trans, int mode,
9683 u64 start, u64 num_bytes, u64 min_size,
9684 loff_t actual_len, u64 *alloc_hint)
9686 return __btrfs_prealloc_file_range(inode, mode, start, num_bytes,
9687 min_size, actual_len, alloc_hint, trans);
9690 static int btrfs_set_page_dirty(struct page *page)
9692 return __set_page_dirty_nobuffers(page);
9695 static int btrfs_permission(struct inode *inode, int mask)
9697 struct btrfs_root *root = BTRFS_I(inode)->root;
9698 umode_t mode = inode->i_mode;
9700 if (mask & MAY_WRITE &&
9701 (S_ISREG(mode) || S_ISDIR(mode) || S_ISLNK(mode))) {
9702 if (btrfs_root_readonly(root))
9704 if (BTRFS_I(inode)->flags & BTRFS_INODE_READONLY)
9707 return generic_permission(inode, mask);
9710 static int btrfs_tmpfile(struct inode *dir, struct dentry *dentry, umode_t mode)
9712 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
9713 struct btrfs_trans_handle *trans;
9714 struct btrfs_root *root = BTRFS_I(dir)->root;
9715 struct inode *inode = NULL;
9721 * 5 units required for adding orphan entry
9723 trans = btrfs_start_transaction(root, 5);
9725 return PTR_ERR(trans);
9727 ret = btrfs_find_free_ino(root, &objectid);
9731 inode = btrfs_new_inode(trans, root, dir, NULL, 0,
9732 btrfs_ino(BTRFS_I(dir)), objectid, mode, &index);
9733 if (IS_ERR(inode)) {
9734 ret = PTR_ERR(inode);
9739 inode->i_fop = &btrfs_file_operations;
9740 inode->i_op = &btrfs_file_inode_operations;
9742 inode->i_mapping->a_ops = &btrfs_aops;
9743 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
9745 ret = btrfs_init_inode_security(trans, inode, dir, NULL);
9749 ret = btrfs_update_inode(trans, root, inode);
9752 ret = btrfs_orphan_add(trans, BTRFS_I(inode));
9757 * We set number of links to 0 in btrfs_new_inode(), and here we set
9758 * it to 1 because d_tmpfile() will issue a warning if the count is 0,
9761 * d_tmpfile() -> inode_dec_link_count() -> drop_nlink()
9763 set_nlink(inode, 1);
9764 d_tmpfile(dentry, inode);
9765 unlock_new_inode(inode);
9766 mark_inode_dirty(inode);
9768 btrfs_end_transaction(trans);
9770 discard_new_inode(inode);
9771 btrfs_btree_balance_dirty(fs_info);
9775 void btrfs_set_range_writeback(struct extent_io_tree *tree, u64 start, u64 end)
9777 struct inode *inode = tree->private_data;
9778 unsigned long index = start >> PAGE_SHIFT;
9779 unsigned long end_index = end >> PAGE_SHIFT;
9782 while (index <= end_index) {
9783 page = find_get_page(inode->i_mapping, index);
9784 ASSERT(page); /* Pages should be in the extent_io_tree */
9785 set_page_writeback(page);
9793 * Add an entry indicating a block group or device which is pinned by a
9794 * swapfile. Returns 0 on success, 1 if there is already an entry for it, or a
9795 * negative errno on failure.
9797 static int btrfs_add_swapfile_pin(struct inode *inode, void *ptr,
9798 bool is_block_group)
9800 struct btrfs_fs_info *fs_info = BTRFS_I(inode)->root->fs_info;
9801 struct btrfs_swapfile_pin *sp, *entry;
9803 struct rb_node *parent = NULL;
9805 sp = kmalloc(sizeof(*sp), GFP_NOFS);
9810 sp->is_block_group = is_block_group;
9812 spin_lock(&fs_info->swapfile_pins_lock);
9813 p = &fs_info->swapfile_pins.rb_node;
9816 entry = rb_entry(parent, struct btrfs_swapfile_pin, node);
9817 if (sp->ptr < entry->ptr ||
9818 (sp->ptr == entry->ptr && sp->inode < entry->inode)) {
9820 } else if (sp->ptr > entry->ptr ||
9821 (sp->ptr == entry->ptr && sp->inode > entry->inode)) {
9822 p = &(*p)->rb_right;
9824 spin_unlock(&fs_info->swapfile_pins_lock);
9829 rb_link_node(&sp->node, parent, p);
9830 rb_insert_color(&sp->node, &fs_info->swapfile_pins);
9831 spin_unlock(&fs_info->swapfile_pins_lock);
9835 /* Free all of the entries pinned by this swapfile. */
9836 static void btrfs_free_swapfile_pins(struct inode *inode)
9838 struct btrfs_fs_info *fs_info = BTRFS_I(inode)->root->fs_info;
9839 struct btrfs_swapfile_pin *sp;
9840 struct rb_node *node, *next;
9842 spin_lock(&fs_info->swapfile_pins_lock);
9843 node = rb_first(&fs_info->swapfile_pins);
9845 next = rb_next(node);
9846 sp = rb_entry(node, struct btrfs_swapfile_pin, node);
9847 if (sp->inode == inode) {
9848 rb_erase(&sp->node, &fs_info->swapfile_pins);
9849 if (sp->is_block_group)
9850 btrfs_put_block_group(sp->ptr);
9855 spin_unlock(&fs_info->swapfile_pins_lock);
9858 struct btrfs_swap_info {
9864 unsigned long nr_pages;
9868 static int btrfs_add_swap_extent(struct swap_info_struct *sis,
9869 struct btrfs_swap_info *bsi)
9871 unsigned long nr_pages;
9872 u64 first_ppage, first_ppage_reported, next_ppage;
9875 first_ppage = ALIGN(bsi->block_start, PAGE_SIZE) >> PAGE_SHIFT;
9876 next_ppage = ALIGN_DOWN(bsi->block_start + bsi->block_len,
9877 PAGE_SIZE) >> PAGE_SHIFT;
9879 if (first_ppage >= next_ppage)
9881 nr_pages = next_ppage - first_ppage;
9883 first_ppage_reported = first_ppage;
9884 if (bsi->start == 0)
9885 first_ppage_reported++;
9886 if (bsi->lowest_ppage > first_ppage_reported)
9887 bsi->lowest_ppage = first_ppage_reported;
9888 if (bsi->highest_ppage < (next_ppage - 1))
9889 bsi->highest_ppage = next_ppage - 1;
9891 ret = add_swap_extent(sis, bsi->nr_pages, nr_pages, first_ppage);
9894 bsi->nr_extents += ret;
9895 bsi->nr_pages += nr_pages;
9899 static void btrfs_swap_deactivate(struct file *file)
9901 struct inode *inode = file_inode(file);
9903 btrfs_free_swapfile_pins(inode);
9904 atomic_dec(&BTRFS_I(inode)->root->nr_swapfiles);
9907 static int btrfs_swap_activate(struct swap_info_struct *sis, struct file *file,
9910 struct inode *inode = file_inode(file);
9911 struct btrfs_fs_info *fs_info = BTRFS_I(inode)->root->fs_info;
9912 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
9913 struct extent_state *cached_state = NULL;
9914 struct extent_map *em = NULL;
9915 struct btrfs_device *device = NULL;
9916 struct btrfs_swap_info bsi = {
9917 .lowest_ppage = (sector_t)-1ULL,
9924 * If the swap file was just created, make sure delalloc is done. If the
9925 * file changes again after this, the user is doing something stupid and
9926 * we don't really care.
9928 ret = btrfs_wait_ordered_range(inode, 0, (u64)-1);
9933 * The inode is locked, so these flags won't change after we check them.
9935 if (BTRFS_I(inode)->flags & BTRFS_INODE_COMPRESS) {
9936 btrfs_warn(fs_info, "swapfile must not be compressed");
9939 if (!(BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW)) {
9940 btrfs_warn(fs_info, "swapfile must not be copy-on-write");
9943 if (!(BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)) {
9944 btrfs_warn(fs_info, "swapfile must not be checksummed");
9949 * Balance or device remove/replace/resize can move stuff around from
9950 * under us. The EXCL_OP flag makes sure they aren't running/won't run
9951 * concurrently while we are mapping the swap extents, and
9952 * fs_info->swapfile_pins prevents them from running while the swap file
9953 * is active and moving the extents. Note that this also prevents a
9954 * concurrent device add which isn't actually necessary, but it's not
9955 * really worth the trouble to allow it.
9957 if (test_and_set_bit(BTRFS_FS_EXCL_OP, &fs_info->flags)) {
9959 "cannot activate swapfile while exclusive operation is running");
9963 * Snapshots can create extents which require COW even if NODATACOW is
9964 * set. We use this counter to prevent snapshots. We must increment it
9965 * before walking the extents because we don't want a concurrent
9966 * snapshot to run after we've already checked the extents.
9968 atomic_inc(&BTRFS_I(inode)->root->nr_swapfiles);
9970 isize = ALIGN_DOWN(inode->i_size, fs_info->sectorsize);
9972 lock_extent_bits(io_tree, 0, isize - 1, &cached_state);
9974 while (start < isize) {
9975 u64 logical_block_start, physical_block_start;
9976 struct btrfs_block_group *bg;
9977 u64 len = isize - start;
9979 em = btrfs_get_extent(BTRFS_I(inode), NULL, 0, start, len);
9985 if (em->block_start == EXTENT_MAP_HOLE) {
9986 btrfs_warn(fs_info, "swapfile must not have holes");
9990 if (em->block_start == EXTENT_MAP_INLINE) {
9992 * It's unlikely we'll ever actually find ourselves
9993 * here, as a file small enough to fit inline won't be
9994 * big enough to store more than the swap header, but in
9995 * case something changes in the future, let's catch it
9996 * here rather than later.
9998 btrfs_warn(fs_info, "swapfile must not be inline");
10002 if (test_bit(EXTENT_FLAG_COMPRESSED, &em->flags)) {
10003 btrfs_warn(fs_info, "swapfile must not be compressed");
10008 logical_block_start = em->block_start + (start - em->start);
10009 len = min(len, em->len - (start - em->start));
10010 free_extent_map(em);
10013 ret = can_nocow_extent(inode, start, &len, NULL, NULL, NULL);
10019 btrfs_warn(fs_info,
10020 "swapfile must not be copy-on-write");
10025 em = btrfs_get_chunk_map(fs_info, logical_block_start, len);
10031 if (em->map_lookup->type & BTRFS_BLOCK_GROUP_PROFILE_MASK) {
10032 btrfs_warn(fs_info,
10033 "swapfile must have single data profile");
10038 if (device == NULL) {
10039 device = em->map_lookup->stripes[0].dev;
10040 ret = btrfs_add_swapfile_pin(inode, device, false);
10045 } else if (device != em->map_lookup->stripes[0].dev) {
10046 btrfs_warn(fs_info, "swapfile must be on one device");
10051 physical_block_start = (em->map_lookup->stripes[0].physical +
10052 (logical_block_start - em->start));
10053 len = min(len, em->len - (logical_block_start - em->start));
10054 free_extent_map(em);
10057 bg = btrfs_lookup_block_group(fs_info, logical_block_start);
10059 btrfs_warn(fs_info,
10060 "could not find block group containing swapfile");
10065 ret = btrfs_add_swapfile_pin(inode, bg, true);
10067 btrfs_put_block_group(bg);
10074 if (bsi.block_len &&
10075 bsi.block_start + bsi.block_len == physical_block_start) {
10076 bsi.block_len += len;
10078 if (bsi.block_len) {
10079 ret = btrfs_add_swap_extent(sis, &bsi);
10084 bsi.block_start = physical_block_start;
10085 bsi.block_len = len;
10092 ret = btrfs_add_swap_extent(sis, &bsi);
10095 if (!IS_ERR_OR_NULL(em))
10096 free_extent_map(em);
10098 unlock_extent_cached(io_tree, 0, isize - 1, &cached_state);
10101 btrfs_swap_deactivate(file);
10103 clear_bit(BTRFS_FS_EXCL_OP, &fs_info->flags);
10109 sis->bdev = device->bdev;
10110 *span = bsi.highest_ppage - bsi.lowest_ppage + 1;
10111 sis->max = bsi.nr_pages;
10112 sis->pages = bsi.nr_pages - 1;
10113 sis->highest_bit = bsi.nr_pages - 1;
10114 return bsi.nr_extents;
10117 static void btrfs_swap_deactivate(struct file *file)
10121 static int btrfs_swap_activate(struct swap_info_struct *sis, struct file *file,
10124 return -EOPNOTSUPP;
10128 static const struct inode_operations btrfs_dir_inode_operations = {
10129 .getattr = btrfs_getattr,
10130 .lookup = btrfs_lookup,
10131 .create = btrfs_create,
10132 .unlink = btrfs_unlink,
10133 .link = btrfs_link,
10134 .mkdir = btrfs_mkdir,
10135 .rmdir = btrfs_rmdir,
10136 .rename = btrfs_rename2,
10137 .symlink = btrfs_symlink,
10138 .setattr = btrfs_setattr,
10139 .mknod = btrfs_mknod,
10140 .listxattr = btrfs_listxattr,
10141 .permission = btrfs_permission,
10142 .get_acl = btrfs_get_acl,
10143 .set_acl = btrfs_set_acl,
10144 .update_time = btrfs_update_time,
10145 .tmpfile = btrfs_tmpfile,
10148 static const struct file_operations btrfs_dir_file_operations = {
10149 .llseek = generic_file_llseek,
10150 .read = generic_read_dir,
10151 .iterate_shared = btrfs_real_readdir,
10152 .open = btrfs_opendir,
10153 .unlocked_ioctl = btrfs_ioctl,
10154 #ifdef CONFIG_COMPAT
10155 .compat_ioctl = btrfs_compat_ioctl,
10157 .release = btrfs_release_file,
10158 .fsync = btrfs_sync_file,
10161 static const struct extent_io_ops btrfs_extent_io_ops = {
10162 /* mandatory callbacks */
10163 .submit_bio_hook = btrfs_submit_bio_hook,
10164 .readpage_end_io_hook = btrfs_readpage_end_io_hook,
10168 * btrfs doesn't support the bmap operation because swapfiles
10169 * use bmap to make a mapping of extents in the file. They assume
10170 * these extents won't change over the life of the file and they
10171 * use the bmap result to do IO directly to the drive.
10173 * the btrfs bmap call would return logical addresses that aren't
10174 * suitable for IO and they also will change frequently as COW
10175 * operations happen. So, swapfile + btrfs == corruption.
10177 * For now we're avoiding this by dropping bmap.
10179 static const struct address_space_operations btrfs_aops = {
10180 .readpage = btrfs_readpage,
10181 .writepage = btrfs_writepage,
10182 .writepages = btrfs_writepages,
10183 .readpages = btrfs_readpages,
10184 .direct_IO = btrfs_direct_IO,
10185 .invalidatepage = btrfs_invalidatepage,
10186 .releasepage = btrfs_releasepage,
10187 #ifdef CONFIG_MIGRATION
10188 .migratepage = btrfs_migratepage,
10190 .set_page_dirty = btrfs_set_page_dirty,
10191 .error_remove_page = generic_error_remove_page,
10192 .swap_activate = btrfs_swap_activate,
10193 .swap_deactivate = btrfs_swap_deactivate,
10196 static const struct inode_operations btrfs_file_inode_operations = {
10197 .getattr = btrfs_getattr,
10198 .setattr = btrfs_setattr,
10199 .listxattr = btrfs_listxattr,
10200 .permission = btrfs_permission,
10201 .fiemap = btrfs_fiemap,
10202 .get_acl = btrfs_get_acl,
10203 .set_acl = btrfs_set_acl,
10204 .update_time = btrfs_update_time,
10206 static const struct inode_operations btrfs_special_inode_operations = {
10207 .getattr = btrfs_getattr,
10208 .setattr = btrfs_setattr,
10209 .permission = btrfs_permission,
10210 .listxattr = btrfs_listxattr,
10211 .get_acl = btrfs_get_acl,
10212 .set_acl = btrfs_set_acl,
10213 .update_time = btrfs_update_time,
10215 static const struct inode_operations btrfs_symlink_inode_operations = {
10216 .get_link = page_get_link,
10217 .getattr = btrfs_getattr,
10218 .setattr = btrfs_setattr,
10219 .permission = btrfs_permission,
10220 .listxattr = btrfs_listxattr,
10221 .update_time = btrfs_update_time,
10224 const struct dentry_operations btrfs_dentry_operations = {
10225 .d_delete = btrfs_dentry_delete,