1 // SPDX-License-Identifier: GPL-2.0
3 * Copyright (C) 2007 Oracle. All rights reserved.
6 #include <linux/kernel.h>
8 #include <linux/file.h>
10 #include <linux/pagemap.h>
11 #include <linux/highmem.h>
12 #include <linux/time.h>
13 #include <linux/init.h>
14 #include <linux/string.h>
15 #include <linux/backing-dev.h>
16 #include <linux/writeback.h>
17 #include <linux/compat.h>
18 #include <linux/xattr.h>
19 #include <linux/posix_acl.h>
20 #include <linux/falloc.h>
21 #include <linux/slab.h>
22 #include <linux/ratelimit.h>
23 #include <linux/btrfs.h>
24 #include <linux/blkdev.h>
25 #include <linux/posix_acl_xattr.h>
26 #include <linux/uio.h>
27 #include <linux/magic.h>
28 #include <linux/iversion.h>
29 #include <linux/swap.h>
30 #include <linux/migrate.h>
31 #include <linux/sched/mm.h>
32 #include <asm/unaligned.h>
36 #include "transaction.h"
37 #include "btrfs_inode.h"
38 #include "print-tree.h"
39 #include "ordered-data.h"
43 #include "compression.h"
45 #include "free-space-cache.h"
46 #include "inode-map.h"
49 #include "delalloc-space.h"
50 #include "block-group.h"
51 #include "space-info.h"
53 struct btrfs_iget_args {
55 struct btrfs_root *root;
58 struct btrfs_dio_data {
62 struct extent_changeset *data_reserved;
65 static const struct inode_operations btrfs_dir_inode_operations;
66 static const struct inode_operations btrfs_symlink_inode_operations;
67 static const struct inode_operations btrfs_special_inode_operations;
68 static const struct inode_operations btrfs_file_inode_operations;
69 static const struct address_space_operations btrfs_aops;
70 static const struct file_operations btrfs_dir_file_operations;
71 static const struct extent_io_ops btrfs_extent_io_ops;
73 static struct kmem_cache *btrfs_inode_cachep;
74 struct kmem_cache *btrfs_trans_handle_cachep;
75 struct kmem_cache *btrfs_path_cachep;
76 struct kmem_cache *btrfs_free_space_cachep;
77 struct kmem_cache *btrfs_free_space_bitmap_cachep;
79 static int btrfs_setsize(struct inode *inode, struct iattr *attr);
80 static int btrfs_truncate(struct inode *inode, bool skip_writeback);
81 static int btrfs_finish_ordered_io(struct btrfs_ordered_extent *ordered_extent);
82 static noinline int cow_file_range(struct inode *inode,
83 struct page *locked_page,
84 u64 start, u64 end, int *page_started,
85 unsigned long *nr_written, int unlock);
86 static struct extent_map *create_io_em(struct inode *inode, u64 start, u64 len,
87 u64 orig_start, u64 block_start,
88 u64 block_len, u64 orig_block_len,
89 u64 ram_bytes, int compress_type,
92 static void __endio_write_update_ordered(struct inode *inode,
93 const u64 offset, const u64 bytes,
97 * Cleanup all submitted ordered extents in specified range to handle errors
98 * from the btrfs_run_delalloc_range() callback.
100 * NOTE: caller must ensure that when an error happens, it can not call
101 * extent_clear_unlock_delalloc() to clear both the bits EXTENT_DO_ACCOUNTING
102 * and EXTENT_DELALLOC simultaneously, because that causes the reserved metadata
103 * to be released, which we want to happen only when finishing the ordered
104 * extent (btrfs_finish_ordered_io()).
106 static inline void btrfs_cleanup_ordered_extents(struct inode *inode,
107 struct page *locked_page,
108 u64 offset, u64 bytes)
110 unsigned long index = offset >> PAGE_SHIFT;
111 unsigned long end_index = (offset + bytes - 1) >> PAGE_SHIFT;
112 u64 page_start = page_offset(locked_page);
113 u64 page_end = page_start + PAGE_SIZE - 1;
117 while (index <= end_index) {
118 page = find_get_page(inode->i_mapping, index);
122 ClearPagePrivate2(page);
127 * In case this page belongs to the delalloc range being instantiated
128 * then skip it, since the first page of a range is going to be
129 * properly cleaned up by the caller of run_delalloc_range
131 if (page_start >= offset && page_end <= (offset + bytes - 1)) {
136 return __endio_write_update_ordered(inode, offset, bytes, false);
139 static int btrfs_dirty_inode(struct inode *inode);
141 #ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
142 void btrfs_test_inode_set_ops(struct inode *inode)
144 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
148 static int btrfs_init_inode_security(struct btrfs_trans_handle *trans,
149 struct inode *inode, struct inode *dir,
150 const struct qstr *qstr)
154 err = btrfs_init_acl(trans, inode, dir);
156 err = btrfs_xattr_security_init(trans, inode, dir, qstr);
161 * this does all the hard work for inserting an inline extent into
162 * the btree. The caller should have done a btrfs_drop_extents so that
163 * no overlapping inline items exist in the btree
165 static int insert_inline_extent(struct btrfs_trans_handle *trans,
166 struct btrfs_path *path, int extent_inserted,
167 struct btrfs_root *root, struct inode *inode,
168 u64 start, size_t size, size_t compressed_size,
170 struct page **compressed_pages)
172 struct extent_buffer *leaf;
173 struct page *page = NULL;
176 struct btrfs_file_extent_item *ei;
178 size_t cur_size = size;
179 unsigned long offset;
181 ASSERT((compressed_size > 0 && compressed_pages) ||
182 (compressed_size == 0 && !compressed_pages));
184 if (compressed_size && compressed_pages)
185 cur_size = compressed_size;
187 inode_add_bytes(inode, size);
189 if (!extent_inserted) {
190 struct btrfs_key key;
193 key.objectid = btrfs_ino(BTRFS_I(inode));
195 key.type = BTRFS_EXTENT_DATA_KEY;
197 datasize = btrfs_file_extent_calc_inline_size(cur_size);
198 path->leave_spinning = 1;
199 ret = btrfs_insert_empty_item(trans, root, path, &key,
204 leaf = path->nodes[0];
205 ei = btrfs_item_ptr(leaf, path->slots[0],
206 struct btrfs_file_extent_item);
207 btrfs_set_file_extent_generation(leaf, ei, trans->transid);
208 btrfs_set_file_extent_type(leaf, ei, BTRFS_FILE_EXTENT_INLINE);
209 btrfs_set_file_extent_encryption(leaf, ei, 0);
210 btrfs_set_file_extent_other_encoding(leaf, ei, 0);
211 btrfs_set_file_extent_ram_bytes(leaf, ei, size);
212 ptr = btrfs_file_extent_inline_start(ei);
214 if (compress_type != BTRFS_COMPRESS_NONE) {
217 while (compressed_size > 0) {
218 cpage = compressed_pages[i];
219 cur_size = min_t(unsigned long, compressed_size,
222 kaddr = kmap_atomic(cpage);
223 write_extent_buffer(leaf, kaddr, ptr, cur_size);
224 kunmap_atomic(kaddr);
228 compressed_size -= cur_size;
230 btrfs_set_file_extent_compression(leaf, ei,
233 page = find_get_page(inode->i_mapping,
234 start >> PAGE_SHIFT);
235 btrfs_set_file_extent_compression(leaf, ei, 0);
236 kaddr = kmap_atomic(page);
237 offset = offset_in_page(start);
238 write_extent_buffer(leaf, kaddr + offset, ptr, size);
239 kunmap_atomic(kaddr);
242 btrfs_mark_buffer_dirty(leaf);
243 btrfs_release_path(path);
246 * We align size to sectorsize for inline extents just for simplicity
249 size = ALIGN(size, root->fs_info->sectorsize);
250 ret = btrfs_inode_set_file_extent_range(BTRFS_I(inode), start, size);
255 * we're an inline extent, so nobody can
256 * extend the file past i_size without locking
257 * a page we already have locked.
259 * We must do any isize and inode updates
260 * before we unlock the pages. Otherwise we
261 * could end up racing with unlink.
263 BTRFS_I(inode)->disk_i_size = inode->i_size;
264 ret = btrfs_update_inode(trans, root, inode);
272 * conditionally insert an inline extent into the file. This
273 * does the checks required to make sure the data is small enough
274 * to fit as an inline extent.
276 static noinline int cow_file_range_inline(struct inode *inode, u64 start,
277 u64 end, size_t compressed_size,
279 struct page **compressed_pages)
281 struct btrfs_root *root = BTRFS_I(inode)->root;
282 struct btrfs_fs_info *fs_info = root->fs_info;
283 struct btrfs_trans_handle *trans;
284 u64 isize = i_size_read(inode);
285 u64 actual_end = min(end + 1, isize);
286 u64 inline_len = actual_end - start;
287 u64 aligned_end = ALIGN(end, fs_info->sectorsize);
288 u64 data_len = inline_len;
290 struct btrfs_path *path;
291 int extent_inserted = 0;
292 u32 extent_item_size;
295 data_len = compressed_size;
298 actual_end > fs_info->sectorsize ||
299 data_len > BTRFS_MAX_INLINE_DATA_SIZE(fs_info) ||
301 (actual_end & (fs_info->sectorsize - 1)) == 0) ||
303 data_len > fs_info->max_inline) {
307 path = btrfs_alloc_path();
311 trans = btrfs_join_transaction(root);
313 btrfs_free_path(path);
314 return PTR_ERR(trans);
316 trans->block_rsv = &BTRFS_I(inode)->block_rsv;
318 if (compressed_size && compressed_pages)
319 extent_item_size = btrfs_file_extent_calc_inline_size(
322 extent_item_size = btrfs_file_extent_calc_inline_size(
325 ret = __btrfs_drop_extents(trans, root, inode, path,
326 start, aligned_end, NULL,
327 1, 1, extent_item_size, &extent_inserted);
329 btrfs_abort_transaction(trans, ret);
333 if (isize > actual_end)
334 inline_len = min_t(u64, isize, actual_end);
335 ret = insert_inline_extent(trans, path, extent_inserted,
337 inline_len, compressed_size,
338 compress_type, compressed_pages);
339 if (ret && ret != -ENOSPC) {
340 btrfs_abort_transaction(trans, ret);
342 } else if (ret == -ENOSPC) {
347 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &BTRFS_I(inode)->runtime_flags);
348 btrfs_drop_extent_cache(BTRFS_I(inode), start, aligned_end - 1, 0);
351 * Don't forget to free the reserved space, as for inlined extent
352 * it won't count as data extent, free them directly here.
353 * And at reserve time, it's always aligned to page size, so
354 * just free one page here.
356 btrfs_qgroup_free_data(inode, NULL, 0, PAGE_SIZE);
357 btrfs_free_path(path);
358 btrfs_end_transaction(trans);
362 struct async_extent {
367 unsigned long nr_pages;
369 struct list_head list;
374 struct page *locked_page;
377 unsigned int write_flags;
378 struct list_head extents;
379 struct cgroup_subsys_state *blkcg_css;
380 struct btrfs_work work;
385 /* Number of chunks in flight; must be first in the structure */
387 struct async_chunk chunks[];
390 static noinline int add_async_extent(struct async_chunk *cow,
391 u64 start, u64 ram_size,
394 unsigned long nr_pages,
397 struct async_extent *async_extent;
399 async_extent = kmalloc(sizeof(*async_extent), GFP_NOFS);
400 BUG_ON(!async_extent); /* -ENOMEM */
401 async_extent->start = start;
402 async_extent->ram_size = ram_size;
403 async_extent->compressed_size = compressed_size;
404 async_extent->pages = pages;
405 async_extent->nr_pages = nr_pages;
406 async_extent->compress_type = compress_type;
407 list_add_tail(&async_extent->list, &cow->extents);
412 * Check if the inode has flags compatible with compression
414 static inline bool inode_can_compress(struct inode *inode)
416 if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW ||
417 BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)
423 * Check if the inode needs to be submitted to compression, based on mount
424 * options, defragmentation, properties or heuristics.
426 static inline int inode_need_compress(struct inode *inode, u64 start, u64 end)
428 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
430 if (!inode_can_compress(inode)) {
431 WARN(IS_ENABLED(CONFIG_BTRFS_DEBUG),
432 KERN_ERR "BTRFS: unexpected compression for ino %llu\n",
433 btrfs_ino(BTRFS_I(inode)));
437 if (btrfs_test_opt(fs_info, FORCE_COMPRESS))
440 if (BTRFS_I(inode)->defrag_compress)
442 /* bad compression ratios */
443 if (BTRFS_I(inode)->flags & BTRFS_INODE_NOCOMPRESS)
445 if (btrfs_test_opt(fs_info, COMPRESS) ||
446 BTRFS_I(inode)->flags & BTRFS_INODE_COMPRESS ||
447 BTRFS_I(inode)->prop_compress)
448 return btrfs_compress_heuristic(inode, start, end);
452 static inline void inode_should_defrag(struct btrfs_inode *inode,
453 u64 start, u64 end, u64 num_bytes, u64 small_write)
455 /* If this is a small write inside eof, kick off a defrag */
456 if (num_bytes < small_write &&
457 (start > 0 || end + 1 < inode->disk_i_size))
458 btrfs_add_inode_defrag(NULL, inode);
462 * we create compressed extents in two phases. The first
463 * phase compresses a range of pages that have already been
464 * locked (both pages and state bits are locked).
466 * This is done inside an ordered work queue, and the compression
467 * is spread across many cpus. The actual IO submission is step
468 * two, and the ordered work queue takes care of making sure that
469 * happens in the same order things were put onto the queue by
470 * writepages and friends.
472 * If this code finds it can't get good compression, it puts an
473 * entry onto the work queue to write the uncompressed bytes. This
474 * makes sure that both compressed inodes and uncompressed inodes
475 * are written in the same order that the flusher thread sent them
478 static noinline int compress_file_range(struct async_chunk *async_chunk)
480 struct inode *inode = async_chunk->inode;
481 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
482 u64 blocksize = fs_info->sectorsize;
483 u64 start = async_chunk->start;
484 u64 end = async_chunk->end;
488 struct page **pages = NULL;
489 unsigned long nr_pages;
490 unsigned long total_compressed = 0;
491 unsigned long total_in = 0;
494 int compress_type = fs_info->compress_type;
495 int compressed_extents = 0;
498 inode_should_defrag(BTRFS_I(inode), start, end, end - start + 1,
502 * We need to save i_size before now because it could change in between
503 * us evaluating the size and assigning it. This is because we lock and
504 * unlock the page in truncate and fallocate, and then modify the i_size
507 * The barriers are to emulate READ_ONCE, remove that once i_size_read
511 i_size = i_size_read(inode);
513 actual_end = min_t(u64, i_size, end + 1);
516 nr_pages = (end >> PAGE_SHIFT) - (start >> PAGE_SHIFT) + 1;
517 BUILD_BUG_ON((BTRFS_MAX_COMPRESSED % PAGE_SIZE) != 0);
518 nr_pages = min_t(unsigned long, nr_pages,
519 BTRFS_MAX_COMPRESSED / PAGE_SIZE);
522 * we don't want to send crud past the end of i_size through
523 * compression, that's just a waste of CPU time. So, if the
524 * end of the file is before the start of our current
525 * requested range of bytes, we bail out to the uncompressed
526 * cleanup code that can deal with all of this.
528 * It isn't really the fastest way to fix things, but this is a
529 * very uncommon corner.
531 if (actual_end <= start)
532 goto cleanup_and_bail_uncompressed;
534 total_compressed = actual_end - start;
537 * skip compression for a small file range(<=blocksize) that
538 * isn't an inline extent, since it doesn't save disk space at all.
540 if (total_compressed <= blocksize &&
541 (start > 0 || end + 1 < BTRFS_I(inode)->disk_i_size))
542 goto cleanup_and_bail_uncompressed;
544 total_compressed = min_t(unsigned long, total_compressed,
545 BTRFS_MAX_UNCOMPRESSED);
550 * we do compression for mount -o compress and when the
551 * inode has not been flagged as nocompress. This flag can
552 * change at any time if we discover bad compression ratios.
554 if (inode_need_compress(inode, start, end)) {
556 pages = kcalloc(nr_pages, sizeof(struct page *), GFP_NOFS);
558 /* just bail out to the uncompressed code */
563 if (BTRFS_I(inode)->defrag_compress)
564 compress_type = BTRFS_I(inode)->defrag_compress;
565 else if (BTRFS_I(inode)->prop_compress)
566 compress_type = BTRFS_I(inode)->prop_compress;
569 * we need to call clear_page_dirty_for_io on each
570 * page in the range. Otherwise applications with the file
571 * mmap'd can wander in and change the page contents while
572 * we are compressing them.
574 * If the compression fails for any reason, we set the pages
575 * dirty again later on.
577 * Note that the remaining part is redirtied, the start pointer
578 * has moved, the end is the original one.
581 extent_range_clear_dirty_for_io(inode, start, end);
585 /* Compression level is applied here and only here */
586 ret = btrfs_compress_pages(
587 compress_type | (fs_info->compress_level << 4),
588 inode->i_mapping, start,
595 unsigned long offset = offset_in_page(total_compressed);
596 struct page *page = pages[nr_pages - 1];
599 /* zero the tail end of the last page, we might be
600 * sending it down to disk
603 kaddr = kmap_atomic(page);
604 memset(kaddr + offset, 0,
606 kunmap_atomic(kaddr);
613 /* lets try to make an inline extent */
614 if (ret || total_in < actual_end) {
615 /* we didn't compress the entire range, try
616 * to make an uncompressed inline extent.
618 ret = cow_file_range_inline(inode, start, end, 0,
619 BTRFS_COMPRESS_NONE, NULL);
621 /* try making a compressed inline extent */
622 ret = cow_file_range_inline(inode, start, end,
624 compress_type, pages);
627 unsigned long clear_flags = EXTENT_DELALLOC |
628 EXTENT_DELALLOC_NEW | EXTENT_DEFRAG |
629 EXTENT_DO_ACCOUNTING;
630 unsigned long page_error_op;
632 page_error_op = ret < 0 ? PAGE_SET_ERROR : 0;
635 * inline extent creation worked or returned error,
636 * we don't need to create any more async work items.
637 * Unlock and free up our temp pages.
639 * We use DO_ACCOUNTING here because we need the
640 * delalloc_release_metadata to be done _after_ we drop
641 * our outstanding extent for clearing delalloc for this
644 extent_clear_unlock_delalloc(inode, start, end, NULL,
652 for (i = 0; i < nr_pages; i++) {
653 WARN_ON(pages[i]->mapping);
664 * we aren't doing an inline extent round the compressed size
665 * up to a block size boundary so the allocator does sane
668 total_compressed = ALIGN(total_compressed, blocksize);
671 * one last check to make sure the compression is really a
672 * win, compare the page count read with the blocks on disk,
673 * compression must free at least one sector size
675 total_in = ALIGN(total_in, PAGE_SIZE);
676 if (total_compressed + blocksize <= total_in) {
677 compressed_extents++;
680 * The async work queues will take care of doing actual
681 * allocation on disk for these compressed pages, and
682 * will submit them to the elevator.
684 add_async_extent(async_chunk, start, total_in,
685 total_compressed, pages, nr_pages,
688 if (start + total_in < end) {
694 return compressed_extents;
699 * the compression code ran but failed to make things smaller,
700 * free any pages it allocated and our page pointer array
702 for (i = 0; i < nr_pages; i++) {
703 WARN_ON(pages[i]->mapping);
708 total_compressed = 0;
711 /* flag the file so we don't compress in the future */
712 if (!btrfs_test_opt(fs_info, FORCE_COMPRESS) &&
713 !(BTRFS_I(inode)->prop_compress)) {
714 BTRFS_I(inode)->flags |= BTRFS_INODE_NOCOMPRESS;
717 cleanup_and_bail_uncompressed:
719 * No compression, but we still need to write the pages in the file
720 * we've been given so far. redirty the locked page if it corresponds
721 * to our extent and set things up for the async work queue to run
722 * cow_file_range to do the normal delalloc dance.
724 if (async_chunk->locked_page &&
725 (page_offset(async_chunk->locked_page) >= start &&
726 page_offset(async_chunk->locked_page)) <= end) {
727 __set_page_dirty_nobuffers(async_chunk->locked_page);
728 /* unlocked later on in the async handlers */
732 extent_range_redirty_for_io(inode, start, end);
733 add_async_extent(async_chunk, start, end - start + 1, 0, NULL, 0,
734 BTRFS_COMPRESS_NONE);
735 compressed_extents++;
737 return compressed_extents;
740 static void free_async_extent_pages(struct async_extent *async_extent)
744 if (!async_extent->pages)
747 for (i = 0; i < async_extent->nr_pages; i++) {
748 WARN_ON(async_extent->pages[i]->mapping);
749 put_page(async_extent->pages[i]);
751 kfree(async_extent->pages);
752 async_extent->nr_pages = 0;
753 async_extent->pages = NULL;
757 * phase two of compressed writeback. This is the ordered portion
758 * of the code, which only gets called in the order the work was
759 * queued. We walk all the async extents created by compress_file_range
760 * and send them down to the disk.
762 static noinline void submit_compressed_extents(struct async_chunk *async_chunk)
764 struct inode *inode = async_chunk->inode;
765 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
766 struct async_extent *async_extent;
768 struct btrfs_key ins;
769 struct extent_map *em;
770 struct btrfs_root *root = BTRFS_I(inode)->root;
771 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
775 while (!list_empty(&async_chunk->extents)) {
776 async_extent = list_entry(async_chunk->extents.next,
777 struct async_extent, list);
778 list_del(&async_extent->list);
781 lock_extent(io_tree, async_extent->start,
782 async_extent->start + async_extent->ram_size - 1);
783 /* did the compression code fall back to uncompressed IO? */
784 if (!async_extent->pages) {
785 int page_started = 0;
786 unsigned long nr_written = 0;
788 /* allocate blocks */
789 ret = cow_file_range(inode, async_chunk->locked_page,
791 async_extent->start +
792 async_extent->ram_size - 1,
793 &page_started, &nr_written, 0);
798 * if page_started, cow_file_range inserted an
799 * inline extent and took care of all the unlocking
800 * and IO for us. Otherwise, we need to submit
801 * all those pages down to the drive.
803 if (!page_started && !ret)
804 extent_write_locked_range(inode,
806 async_extent->start +
807 async_extent->ram_size - 1,
809 else if (ret && async_chunk->locked_page)
810 unlock_page(async_chunk->locked_page);
816 ret = btrfs_reserve_extent(root, async_extent->ram_size,
817 async_extent->compressed_size,
818 async_extent->compressed_size,
819 0, alloc_hint, &ins, 1, 1);
821 free_async_extent_pages(async_extent);
823 if (ret == -ENOSPC) {
824 unlock_extent(io_tree, async_extent->start,
825 async_extent->start +
826 async_extent->ram_size - 1);
829 * we need to redirty the pages if we decide to
830 * fallback to uncompressed IO, otherwise we
831 * will not submit these pages down to lower
834 extent_range_redirty_for_io(inode,
836 async_extent->start +
837 async_extent->ram_size - 1);
844 * here we're doing allocation and writeback of the
847 em = create_io_em(inode, async_extent->start,
848 async_extent->ram_size, /* len */
849 async_extent->start, /* orig_start */
850 ins.objectid, /* block_start */
851 ins.offset, /* block_len */
852 ins.offset, /* orig_block_len */
853 async_extent->ram_size, /* ram_bytes */
854 async_extent->compress_type,
855 BTRFS_ORDERED_COMPRESSED);
857 /* ret value is not necessary due to void function */
858 goto out_free_reserve;
861 ret = btrfs_add_ordered_extent_compress(inode,
864 async_extent->ram_size,
866 BTRFS_ORDERED_COMPRESSED,
867 async_extent->compress_type);
869 btrfs_drop_extent_cache(BTRFS_I(inode),
871 async_extent->start +
872 async_extent->ram_size - 1, 0);
873 goto out_free_reserve;
875 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
878 * clear dirty, set writeback and unlock the pages.
880 extent_clear_unlock_delalloc(inode, async_extent->start,
881 async_extent->start +
882 async_extent->ram_size - 1,
883 NULL, EXTENT_LOCKED | EXTENT_DELALLOC,
884 PAGE_UNLOCK | PAGE_CLEAR_DIRTY |
886 if (btrfs_submit_compressed_write(inode,
888 async_extent->ram_size,
890 ins.offset, async_extent->pages,
891 async_extent->nr_pages,
892 async_chunk->write_flags,
893 async_chunk->blkcg_css)) {
894 struct page *p = async_extent->pages[0];
895 const u64 start = async_extent->start;
896 const u64 end = start + async_extent->ram_size - 1;
898 p->mapping = inode->i_mapping;
899 btrfs_writepage_endio_finish_ordered(p, start, end, 0);
902 extent_clear_unlock_delalloc(inode, start, end,
906 free_async_extent_pages(async_extent);
908 alloc_hint = ins.objectid + ins.offset;
914 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
915 btrfs_free_reserved_extent(fs_info, ins.objectid, ins.offset, 1);
917 extent_clear_unlock_delalloc(inode, async_extent->start,
918 async_extent->start +
919 async_extent->ram_size - 1,
920 NULL, EXTENT_LOCKED | EXTENT_DELALLOC |
921 EXTENT_DELALLOC_NEW |
922 EXTENT_DEFRAG | EXTENT_DO_ACCOUNTING,
923 PAGE_UNLOCK | PAGE_CLEAR_DIRTY |
924 PAGE_SET_WRITEBACK | PAGE_END_WRITEBACK |
926 free_async_extent_pages(async_extent);
931 static u64 get_extent_allocation_hint(struct inode *inode, u64 start,
934 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
935 struct extent_map *em;
938 read_lock(&em_tree->lock);
939 em = search_extent_mapping(em_tree, start, num_bytes);
942 * if block start isn't an actual block number then find the
943 * first block in this inode and use that as a hint. If that
944 * block is also bogus then just don't worry about it.
946 if (em->block_start >= EXTENT_MAP_LAST_BYTE) {
948 em = search_extent_mapping(em_tree, 0, 0);
949 if (em && em->block_start < EXTENT_MAP_LAST_BYTE)
950 alloc_hint = em->block_start;
954 alloc_hint = em->block_start;
958 read_unlock(&em_tree->lock);
964 * when extent_io.c finds a delayed allocation range in the file,
965 * the call backs end up in this code. The basic idea is to
966 * allocate extents on disk for the range, and create ordered data structs
967 * in ram to track those extents.
969 * locked_page is the page that writepage had locked already. We use
970 * it to make sure we don't do extra locks or unlocks.
972 * *page_started is set to one if we unlock locked_page and do everything
973 * required to start IO on it. It may be clean and already done with
976 static noinline int cow_file_range(struct inode *inode,
977 struct page *locked_page,
978 u64 start, u64 end, int *page_started,
979 unsigned long *nr_written, int unlock)
981 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
982 struct btrfs_root *root = BTRFS_I(inode)->root;
985 unsigned long ram_size;
986 u64 cur_alloc_size = 0;
987 u64 blocksize = fs_info->sectorsize;
988 struct btrfs_key ins;
989 struct extent_map *em;
991 unsigned long page_ops;
992 bool extent_reserved = false;
995 if (btrfs_is_free_space_inode(BTRFS_I(inode))) {
1001 num_bytes = ALIGN(end - start + 1, blocksize);
1002 num_bytes = max(blocksize, num_bytes);
1003 ASSERT(num_bytes <= btrfs_super_total_bytes(fs_info->super_copy));
1005 inode_should_defrag(BTRFS_I(inode), start, end, num_bytes, SZ_64K);
1008 /* lets try to make an inline extent */
1009 ret = cow_file_range_inline(inode, start, end, 0,
1010 BTRFS_COMPRESS_NONE, NULL);
1013 * We use DO_ACCOUNTING here because we need the
1014 * delalloc_release_metadata to be run _after_ we drop
1015 * our outstanding extent for clearing delalloc for this
1018 extent_clear_unlock_delalloc(inode, start, end, NULL,
1019 EXTENT_LOCKED | EXTENT_DELALLOC |
1020 EXTENT_DELALLOC_NEW | EXTENT_DEFRAG |
1021 EXTENT_DO_ACCOUNTING, PAGE_UNLOCK |
1022 PAGE_CLEAR_DIRTY | PAGE_SET_WRITEBACK |
1023 PAGE_END_WRITEBACK);
1024 *nr_written = *nr_written +
1025 (end - start + PAGE_SIZE) / PAGE_SIZE;
1028 } else if (ret < 0) {
1033 alloc_hint = get_extent_allocation_hint(inode, start, num_bytes);
1034 btrfs_drop_extent_cache(BTRFS_I(inode), start,
1035 start + num_bytes - 1, 0);
1037 while (num_bytes > 0) {
1038 cur_alloc_size = num_bytes;
1039 ret = btrfs_reserve_extent(root, cur_alloc_size, cur_alloc_size,
1040 fs_info->sectorsize, 0, alloc_hint,
1044 cur_alloc_size = ins.offset;
1045 extent_reserved = true;
1047 ram_size = ins.offset;
1048 em = create_io_em(inode, start, ins.offset, /* len */
1049 start, /* orig_start */
1050 ins.objectid, /* block_start */
1051 ins.offset, /* block_len */
1052 ins.offset, /* orig_block_len */
1053 ram_size, /* ram_bytes */
1054 BTRFS_COMPRESS_NONE, /* compress_type */
1055 BTRFS_ORDERED_REGULAR /* type */);
1060 free_extent_map(em);
1062 ret = btrfs_add_ordered_extent(inode, start, ins.objectid,
1063 ram_size, cur_alloc_size, 0);
1065 goto out_drop_extent_cache;
1067 if (root->root_key.objectid ==
1068 BTRFS_DATA_RELOC_TREE_OBJECTID) {
1069 ret = btrfs_reloc_clone_csums(inode, start,
1072 * Only drop cache here, and process as normal.
1074 * We must not allow extent_clear_unlock_delalloc()
1075 * at out_unlock label to free meta of this ordered
1076 * extent, as its meta should be freed by
1077 * btrfs_finish_ordered_io().
1079 * So we must continue until @start is increased to
1080 * skip current ordered extent.
1083 btrfs_drop_extent_cache(BTRFS_I(inode), start,
1084 start + ram_size - 1, 0);
1087 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
1089 /* we're not doing compressed IO, don't unlock the first
1090 * page (which the caller expects to stay locked), don't
1091 * clear any dirty bits and don't set any writeback bits
1093 * Do set the Private2 bit so we know this page was properly
1094 * setup for writepage
1096 page_ops = unlock ? PAGE_UNLOCK : 0;
1097 page_ops |= PAGE_SET_PRIVATE2;
1099 extent_clear_unlock_delalloc(inode, start,
1100 start + ram_size - 1,
1102 EXTENT_LOCKED | EXTENT_DELALLOC,
1104 if (num_bytes < cur_alloc_size)
1107 num_bytes -= cur_alloc_size;
1108 alloc_hint = ins.objectid + ins.offset;
1109 start += cur_alloc_size;
1110 extent_reserved = false;
1113 * btrfs_reloc_clone_csums() error, since start is increased
1114 * extent_clear_unlock_delalloc() at out_unlock label won't
1115 * free metadata of current ordered extent, we're OK to exit.
1123 out_drop_extent_cache:
1124 btrfs_drop_extent_cache(BTRFS_I(inode), start, start + ram_size - 1, 0);
1126 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
1127 btrfs_free_reserved_extent(fs_info, ins.objectid, ins.offset, 1);
1129 clear_bits = EXTENT_LOCKED | EXTENT_DELALLOC | EXTENT_DELALLOC_NEW |
1130 EXTENT_DEFRAG | EXTENT_CLEAR_META_RESV;
1131 page_ops = PAGE_UNLOCK | PAGE_CLEAR_DIRTY | PAGE_SET_WRITEBACK |
1134 * If we reserved an extent for our delalloc range (or a subrange) and
1135 * failed to create the respective ordered extent, then it means that
1136 * when we reserved the extent we decremented the extent's size from
1137 * the data space_info's bytes_may_use counter and incremented the
1138 * space_info's bytes_reserved counter by the same amount. We must make
1139 * sure extent_clear_unlock_delalloc() does not try to decrement again
1140 * the data space_info's bytes_may_use counter, therefore we do not pass
1141 * it the flag EXTENT_CLEAR_DATA_RESV.
1143 if (extent_reserved) {
1144 extent_clear_unlock_delalloc(inode, start,
1145 start + cur_alloc_size - 1,
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);
1358 static int fallback_to_cow(struct inode *inode, struct page *locked_page,
1359 const u64 start, const u64 end,
1360 int *page_started, unsigned long *nr_written)
1362 const bool is_space_ino = btrfs_is_free_space_inode(BTRFS_I(inode));
1363 const u64 range_bytes = end + 1 - start;
1364 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
1365 u64 range_start = start;
1369 * If EXTENT_NORESERVE is set it means that when the buffered write was
1370 * made we had not enough available data space and therefore we did not
1371 * reserve data space for it, since we though we could do NOCOW for the
1372 * respective file range (either there is prealloc extent or the inode
1373 * has the NOCOW bit set).
1375 * However when we need to fallback to COW mode (because for example the
1376 * block group for the corresponding extent was turned to RO mode by a
1377 * scrub or relocation) we need to do the following:
1379 * 1) We increment the bytes_may_use counter of the data space info.
1380 * If COW succeeds, it allocates a new data extent and after doing
1381 * that it decrements the space info's bytes_may_use counter and
1382 * increments its bytes_reserved counter by the same amount (we do
1383 * this at btrfs_add_reserved_bytes()). So we need to increment the
1384 * bytes_may_use counter to compensate (when space is reserved at
1385 * buffered write time, the bytes_may_use counter is incremented);
1387 * 2) We clear the EXTENT_NORESERVE bit from the range. We do this so
1388 * that if the COW path fails for any reason, it decrements (through
1389 * extent_clear_unlock_delalloc()) the bytes_may_use counter of the
1390 * data space info, which we incremented in the step above.
1392 * If we need to fallback to cow and the inode corresponds to a free
1393 * space cache inode, we must also increment bytes_may_use of the data
1394 * space_info for the same reason. Space caches always get a prealloc
1395 * extent for them, however scrub or balance may have set the block
1396 * group that contains that extent to RO mode.
1398 count = count_range_bits(io_tree, &range_start, end, range_bytes,
1399 EXTENT_NORESERVE, 0);
1400 if (count > 0 || is_space_ino) {
1401 const u64 bytes = is_space_ino ? range_bytes : count;
1402 struct btrfs_fs_info *fs_info = BTRFS_I(inode)->root->fs_info;
1403 struct btrfs_space_info *sinfo = fs_info->data_sinfo;
1405 spin_lock(&sinfo->lock);
1406 btrfs_space_info_update_bytes_may_use(fs_info, sinfo, bytes);
1407 spin_unlock(&sinfo->lock);
1410 clear_extent_bit(io_tree, start, end, EXTENT_NORESERVE,
1414 return cow_file_range(inode, locked_page, start, end, page_started,
1419 * when nowcow writeback call back. This checks for snapshots or COW copies
1420 * of the extents that exist in the file, and COWs the file as required.
1422 * If no cow copies or snapshots exist, we write directly to the existing
1425 static noinline int run_delalloc_nocow(struct inode *inode,
1426 struct page *locked_page,
1427 const u64 start, const u64 end,
1428 int *page_started, int force,
1429 unsigned long *nr_written)
1431 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1432 struct btrfs_root *root = BTRFS_I(inode)->root;
1433 struct btrfs_path *path;
1434 u64 cow_start = (u64)-1;
1435 u64 cur_offset = start;
1437 bool check_prev = true;
1438 const bool freespace_inode = btrfs_is_free_space_inode(BTRFS_I(inode));
1439 u64 ino = btrfs_ino(BTRFS_I(inode));
1441 u64 disk_bytenr = 0;
1443 path = btrfs_alloc_path();
1445 extent_clear_unlock_delalloc(inode, start, end, locked_page,
1446 EXTENT_LOCKED | EXTENT_DELALLOC |
1447 EXTENT_DO_ACCOUNTING |
1448 EXTENT_DEFRAG, PAGE_UNLOCK |
1450 PAGE_SET_WRITEBACK |
1451 PAGE_END_WRITEBACK);
1456 struct btrfs_key found_key;
1457 struct btrfs_file_extent_item *fi;
1458 struct extent_buffer *leaf;
1468 ret = btrfs_lookup_file_extent(NULL, root, path, ino,
1474 * If there is no extent for our range when doing the initial
1475 * search, then go back to the previous slot as it will be the
1476 * one containing the search offset
1478 if (ret > 0 && path->slots[0] > 0 && check_prev) {
1479 leaf = path->nodes[0];
1480 btrfs_item_key_to_cpu(leaf, &found_key,
1481 path->slots[0] - 1);
1482 if (found_key.objectid == ino &&
1483 found_key.type == BTRFS_EXTENT_DATA_KEY)
1488 /* Go to next leaf if we have exhausted the current one */
1489 leaf = path->nodes[0];
1490 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
1491 ret = btrfs_next_leaf(root, path);
1493 if (cow_start != (u64)-1)
1494 cur_offset = cow_start;
1499 leaf = path->nodes[0];
1502 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
1504 /* Didn't find anything for our INO */
1505 if (found_key.objectid > ino)
1508 * Keep searching until we find an EXTENT_ITEM or there are no
1509 * more extents for this inode
1511 if (WARN_ON_ONCE(found_key.objectid < ino) ||
1512 found_key.type < BTRFS_EXTENT_DATA_KEY) {
1517 /* Found key is not EXTENT_DATA_KEY or starts after req range */
1518 if (found_key.type > BTRFS_EXTENT_DATA_KEY ||
1519 found_key.offset > end)
1523 * If the found extent starts after requested offset, then
1524 * adjust extent_end to be right before this extent begins
1526 if (found_key.offset > cur_offset) {
1527 extent_end = found_key.offset;
1533 * Found extent which begins before our range and potentially
1536 fi = btrfs_item_ptr(leaf, path->slots[0],
1537 struct btrfs_file_extent_item);
1538 extent_type = btrfs_file_extent_type(leaf, fi);
1540 ram_bytes = btrfs_file_extent_ram_bytes(leaf, fi);
1541 if (extent_type == BTRFS_FILE_EXTENT_REG ||
1542 extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
1543 disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
1544 extent_offset = btrfs_file_extent_offset(leaf, fi);
1545 extent_end = found_key.offset +
1546 btrfs_file_extent_num_bytes(leaf, fi);
1548 btrfs_file_extent_disk_num_bytes(leaf, fi);
1550 * If the extent we got ends before our current offset,
1551 * skip to the next extent.
1553 if (extent_end <= cur_offset) {
1558 if (disk_bytenr == 0)
1560 /* Skip compressed/encrypted/encoded extents */
1561 if (btrfs_file_extent_compression(leaf, fi) ||
1562 btrfs_file_extent_encryption(leaf, fi) ||
1563 btrfs_file_extent_other_encoding(leaf, fi))
1566 * If extent is created before the last volume's snapshot
1567 * this implies the extent is shared, hence we can't do
1568 * nocow. This is the same check as in
1569 * btrfs_cross_ref_exist but without calling
1570 * btrfs_search_slot.
1572 if (!freespace_inode &&
1573 btrfs_file_extent_generation(leaf, fi) <=
1574 btrfs_root_last_snapshot(&root->root_item))
1576 if (extent_type == BTRFS_FILE_EXTENT_REG && !force)
1578 /* If extent is RO, we must COW it */
1579 if (btrfs_extent_readonly(fs_info, disk_bytenr))
1581 ret = btrfs_cross_ref_exist(root, ino,
1583 extent_offset, disk_bytenr);
1586 * ret could be -EIO if the above fails to read
1590 if (cow_start != (u64)-1)
1591 cur_offset = cow_start;
1595 WARN_ON_ONCE(freespace_inode);
1598 disk_bytenr += extent_offset;
1599 disk_bytenr += cur_offset - found_key.offset;
1600 num_bytes = min(end + 1, extent_end) - cur_offset;
1602 * If there are pending snapshots for this root, we
1603 * fall into common COW way
1605 if (!freespace_inode && atomic_read(&root->snapshot_force_cow))
1608 * force cow if csum exists in the range.
1609 * this ensure that csum for a given extent are
1610 * either valid or do not exist.
1612 ret = csum_exist_in_range(fs_info, disk_bytenr,
1616 * ret could be -EIO if the above fails to read
1620 if (cow_start != (u64)-1)
1621 cur_offset = cow_start;
1624 WARN_ON_ONCE(freespace_inode);
1627 if (!btrfs_inc_nocow_writers(fs_info, disk_bytenr))
1630 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
1631 extent_end = found_key.offset + ram_bytes;
1632 extent_end = ALIGN(extent_end, fs_info->sectorsize);
1633 /* Skip extents outside of our requested range */
1634 if (extent_end <= start) {
1639 /* If this triggers then we have a memory corruption */
1644 * If nocow is false then record the beginning of the range
1645 * that needs to be COWed
1648 if (cow_start == (u64)-1)
1649 cow_start = cur_offset;
1650 cur_offset = extent_end;
1651 if (cur_offset > end)
1657 btrfs_release_path(path);
1660 * COW range from cow_start to found_key.offset - 1. As the key
1661 * will contain the beginning of the first extent that can be
1662 * NOCOW, following one which needs to be COW'ed
1664 if (cow_start != (u64)-1) {
1665 ret = fallback_to_cow(inode, locked_page, cow_start,
1666 found_key.offset - 1,
1667 page_started, nr_written);
1670 btrfs_dec_nocow_writers(fs_info,
1674 cow_start = (u64)-1;
1677 if (extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
1678 u64 orig_start = found_key.offset - extent_offset;
1679 struct extent_map *em;
1681 em = create_io_em(inode, cur_offset, num_bytes,
1683 disk_bytenr, /* block_start */
1684 num_bytes, /* block_len */
1685 disk_num_bytes, /* orig_block_len */
1686 ram_bytes, BTRFS_COMPRESS_NONE,
1687 BTRFS_ORDERED_PREALLOC);
1690 btrfs_dec_nocow_writers(fs_info,
1695 free_extent_map(em);
1696 ret = btrfs_add_ordered_extent(inode, cur_offset,
1697 disk_bytenr, num_bytes,
1699 BTRFS_ORDERED_PREALLOC);
1701 btrfs_drop_extent_cache(BTRFS_I(inode),
1703 cur_offset + num_bytes - 1,
1708 ret = btrfs_add_ordered_extent(inode, cur_offset,
1709 disk_bytenr, num_bytes,
1711 BTRFS_ORDERED_NOCOW);
1717 btrfs_dec_nocow_writers(fs_info, disk_bytenr);
1720 if (root->root_key.objectid ==
1721 BTRFS_DATA_RELOC_TREE_OBJECTID)
1723 * Error handled later, as we must prevent
1724 * extent_clear_unlock_delalloc() in error handler
1725 * from freeing metadata of created ordered extent.
1727 ret = btrfs_reloc_clone_csums(inode, cur_offset,
1730 extent_clear_unlock_delalloc(inode, cur_offset,
1731 cur_offset + num_bytes - 1,
1732 locked_page, EXTENT_LOCKED |
1734 EXTENT_CLEAR_DATA_RESV,
1735 PAGE_UNLOCK | PAGE_SET_PRIVATE2);
1737 cur_offset = extent_end;
1740 * btrfs_reloc_clone_csums() error, now we're OK to call error
1741 * handler, as metadata for created ordered extent will only
1742 * be freed by btrfs_finish_ordered_io().
1746 if (cur_offset > end)
1749 btrfs_release_path(path);
1751 if (cur_offset <= end && cow_start == (u64)-1)
1752 cow_start = cur_offset;
1754 if (cow_start != (u64)-1) {
1756 ret = fallback_to_cow(inode, locked_page, cow_start, end,
1757 page_started, nr_written);
1764 btrfs_dec_nocow_writers(fs_info, disk_bytenr);
1766 if (ret && cur_offset < end)
1767 extent_clear_unlock_delalloc(inode, cur_offset, end,
1768 locked_page, EXTENT_LOCKED |
1769 EXTENT_DELALLOC | EXTENT_DEFRAG |
1770 EXTENT_DO_ACCOUNTING, PAGE_UNLOCK |
1772 PAGE_SET_WRITEBACK |
1773 PAGE_END_WRITEBACK);
1774 btrfs_free_path(path);
1778 static inline int need_force_cow(struct inode *inode, u64 start, u64 end)
1781 if (!(BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW) &&
1782 !(BTRFS_I(inode)->flags & BTRFS_INODE_PREALLOC))
1786 * @defrag_bytes is a hint value, no spinlock held here,
1787 * if is not zero, it means the file is defragging.
1788 * Force cow if given extent needs to be defragged.
1790 if (BTRFS_I(inode)->defrag_bytes &&
1791 test_range_bit(&BTRFS_I(inode)->io_tree, start, end,
1792 EXTENT_DEFRAG, 0, NULL))
1799 * Function to process delayed allocation (create CoW) for ranges which are
1800 * being touched for the first time.
1802 int btrfs_run_delalloc_range(struct inode *inode, struct page *locked_page,
1803 u64 start, u64 end, int *page_started, unsigned long *nr_written,
1804 struct writeback_control *wbc)
1807 int force_cow = need_force_cow(inode, start, end);
1809 if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW && !force_cow) {
1810 ret = run_delalloc_nocow(inode, locked_page, start, end,
1811 page_started, 1, nr_written);
1812 } else if (BTRFS_I(inode)->flags & BTRFS_INODE_PREALLOC && !force_cow) {
1813 ret = run_delalloc_nocow(inode, locked_page, start, end,
1814 page_started, 0, nr_written);
1815 } else if (!inode_can_compress(inode) ||
1816 !inode_need_compress(inode, start, end)) {
1817 ret = cow_file_range(inode, locked_page, start, end,
1818 page_started, nr_written, 1);
1820 set_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
1821 &BTRFS_I(inode)->runtime_flags);
1822 ret = cow_file_range_async(inode, wbc, locked_page, start, end,
1823 page_started, nr_written);
1826 btrfs_cleanup_ordered_extents(inode, locked_page, start,
1831 void btrfs_split_delalloc_extent(struct inode *inode,
1832 struct extent_state *orig, u64 split)
1836 /* not delalloc, ignore it */
1837 if (!(orig->state & EXTENT_DELALLOC))
1840 size = orig->end - orig->start + 1;
1841 if (size > BTRFS_MAX_EXTENT_SIZE) {
1846 * See the explanation in btrfs_merge_delalloc_extent, the same
1847 * applies here, just in reverse.
1849 new_size = orig->end - split + 1;
1850 num_extents = count_max_extents(new_size);
1851 new_size = split - orig->start;
1852 num_extents += count_max_extents(new_size);
1853 if (count_max_extents(size) >= num_extents)
1857 spin_lock(&BTRFS_I(inode)->lock);
1858 btrfs_mod_outstanding_extents(BTRFS_I(inode), 1);
1859 spin_unlock(&BTRFS_I(inode)->lock);
1863 * Handle merged delayed allocation extents so we can keep track of new extents
1864 * that are just merged onto old extents, such as when we are doing sequential
1865 * writes, so we can properly account for the metadata space we'll need.
1867 void btrfs_merge_delalloc_extent(struct inode *inode, struct extent_state *new,
1868 struct extent_state *other)
1870 u64 new_size, old_size;
1873 /* not delalloc, ignore it */
1874 if (!(other->state & EXTENT_DELALLOC))
1877 if (new->start > other->start)
1878 new_size = new->end - other->start + 1;
1880 new_size = other->end - new->start + 1;
1882 /* we're not bigger than the max, unreserve the space and go */
1883 if (new_size <= BTRFS_MAX_EXTENT_SIZE) {
1884 spin_lock(&BTRFS_I(inode)->lock);
1885 btrfs_mod_outstanding_extents(BTRFS_I(inode), -1);
1886 spin_unlock(&BTRFS_I(inode)->lock);
1891 * We have to add up either side to figure out how many extents were
1892 * accounted for before we merged into one big extent. If the number of
1893 * extents we accounted for is <= the amount we need for the new range
1894 * then we can return, otherwise drop. Think of it like this
1898 * So we've grown the extent by a MAX_SIZE extent, this would mean we
1899 * need 2 outstanding extents, on one side we have 1 and the other side
1900 * we have 1 so they are == and we can return. But in this case
1902 * [MAX_SIZE+4k][MAX_SIZE+4k]
1904 * Each range on their own accounts for 2 extents, but merged together
1905 * they are only 3 extents worth of accounting, so we need to drop in
1908 old_size = other->end - other->start + 1;
1909 num_extents = count_max_extents(old_size);
1910 old_size = new->end - new->start + 1;
1911 num_extents += count_max_extents(old_size);
1912 if (count_max_extents(new_size) >= num_extents)
1915 spin_lock(&BTRFS_I(inode)->lock);
1916 btrfs_mod_outstanding_extents(BTRFS_I(inode), -1);
1917 spin_unlock(&BTRFS_I(inode)->lock);
1920 static void btrfs_add_delalloc_inodes(struct btrfs_root *root,
1921 struct inode *inode)
1923 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1925 spin_lock(&root->delalloc_lock);
1926 if (list_empty(&BTRFS_I(inode)->delalloc_inodes)) {
1927 list_add_tail(&BTRFS_I(inode)->delalloc_inodes,
1928 &root->delalloc_inodes);
1929 set_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1930 &BTRFS_I(inode)->runtime_flags);
1931 root->nr_delalloc_inodes++;
1932 if (root->nr_delalloc_inodes == 1) {
1933 spin_lock(&fs_info->delalloc_root_lock);
1934 BUG_ON(!list_empty(&root->delalloc_root));
1935 list_add_tail(&root->delalloc_root,
1936 &fs_info->delalloc_roots);
1937 spin_unlock(&fs_info->delalloc_root_lock);
1940 spin_unlock(&root->delalloc_lock);
1944 void __btrfs_del_delalloc_inode(struct btrfs_root *root,
1945 struct btrfs_inode *inode)
1947 struct btrfs_fs_info *fs_info = root->fs_info;
1949 if (!list_empty(&inode->delalloc_inodes)) {
1950 list_del_init(&inode->delalloc_inodes);
1951 clear_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1952 &inode->runtime_flags);
1953 root->nr_delalloc_inodes--;
1954 if (!root->nr_delalloc_inodes) {
1955 ASSERT(list_empty(&root->delalloc_inodes));
1956 spin_lock(&fs_info->delalloc_root_lock);
1957 BUG_ON(list_empty(&root->delalloc_root));
1958 list_del_init(&root->delalloc_root);
1959 spin_unlock(&fs_info->delalloc_root_lock);
1964 static void btrfs_del_delalloc_inode(struct btrfs_root *root,
1965 struct btrfs_inode *inode)
1967 spin_lock(&root->delalloc_lock);
1968 __btrfs_del_delalloc_inode(root, inode);
1969 spin_unlock(&root->delalloc_lock);
1973 * Properly track delayed allocation bytes in the inode and to maintain the
1974 * list of inodes that have pending delalloc work to be done.
1976 void btrfs_set_delalloc_extent(struct inode *inode, struct extent_state *state,
1979 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1981 if ((*bits & EXTENT_DEFRAG) && !(*bits & EXTENT_DELALLOC))
1984 * set_bit and clear bit hooks normally require _irqsave/restore
1985 * but in this case, we are only testing for the DELALLOC
1986 * bit, which is only set or cleared with irqs on
1988 if (!(state->state & EXTENT_DELALLOC) && (*bits & EXTENT_DELALLOC)) {
1989 struct btrfs_root *root = BTRFS_I(inode)->root;
1990 u64 len = state->end + 1 - state->start;
1991 u32 num_extents = count_max_extents(len);
1992 bool do_list = !btrfs_is_free_space_inode(BTRFS_I(inode));
1994 spin_lock(&BTRFS_I(inode)->lock);
1995 btrfs_mod_outstanding_extents(BTRFS_I(inode), num_extents);
1996 spin_unlock(&BTRFS_I(inode)->lock);
1998 /* For sanity tests */
1999 if (btrfs_is_testing(fs_info))
2002 percpu_counter_add_batch(&fs_info->delalloc_bytes, len,
2003 fs_info->delalloc_batch);
2004 spin_lock(&BTRFS_I(inode)->lock);
2005 BTRFS_I(inode)->delalloc_bytes += len;
2006 if (*bits & EXTENT_DEFRAG)
2007 BTRFS_I(inode)->defrag_bytes += len;
2008 if (do_list && !test_bit(BTRFS_INODE_IN_DELALLOC_LIST,
2009 &BTRFS_I(inode)->runtime_flags))
2010 btrfs_add_delalloc_inodes(root, inode);
2011 spin_unlock(&BTRFS_I(inode)->lock);
2014 if (!(state->state & EXTENT_DELALLOC_NEW) &&
2015 (*bits & EXTENT_DELALLOC_NEW)) {
2016 spin_lock(&BTRFS_I(inode)->lock);
2017 BTRFS_I(inode)->new_delalloc_bytes += state->end + 1 -
2019 spin_unlock(&BTRFS_I(inode)->lock);
2024 * Once a range is no longer delalloc this function ensures that proper
2025 * accounting happens.
2027 void btrfs_clear_delalloc_extent(struct inode *vfs_inode,
2028 struct extent_state *state, unsigned *bits)
2030 struct btrfs_inode *inode = BTRFS_I(vfs_inode);
2031 struct btrfs_fs_info *fs_info = btrfs_sb(vfs_inode->i_sb);
2032 u64 len = state->end + 1 - state->start;
2033 u32 num_extents = count_max_extents(len);
2035 if ((state->state & EXTENT_DEFRAG) && (*bits & EXTENT_DEFRAG)) {
2036 spin_lock(&inode->lock);
2037 inode->defrag_bytes -= len;
2038 spin_unlock(&inode->lock);
2042 * set_bit and clear bit hooks normally require _irqsave/restore
2043 * but in this case, we are only testing for the DELALLOC
2044 * bit, which is only set or cleared with irqs on
2046 if ((state->state & EXTENT_DELALLOC) && (*bits & EXTENT_DELALLOC)) {
2047 struct btrfs_root *root = inode->root;
2048 bool do_list = !btrfs_is_free_space_inode(inode);
2050 spin_lock(&inode->lock);
2051 btrfs_mod_outstanding_extents(inode, -num_extents);
2052 spin_unlock(&inode->lock);
2055 * We don't reserve metadata space for space cache inodes so we
2056 * don't need to call delalloc_release_metadata if there is an
2059 if (*bits & EXTENT_CLEAR_META_RESV &&
2060 root != fs_info->tree_root)
2061 btrfs_delalloc_release_metadata(inode, len, false);
2063 /* For sanity tests. */
2064 if (btrfs_is_testing(fs_info))
2067 if (root->root_key.objectid != BTRFS_DATA_RELOC_TREE_OBJECTID &&
2068 do_list && !(state->state & EXTENT_NORESERVE) &&
2069 (*bits & EXTENT_CLEAR_DATA_RESV))
2070 btrfs_free_reserved_data_space_noquota(
2074 percpu_counter_add_batch(&fs_info->delalloc_bytes, -len,
2075 fs_info->delalloc_batch);
2076 spin_lock(&inode->lock);
2077 inode->delalloc_bytes -= len;
2078 if (do_list && inode->delalloc_bytes == 0 &&
2079 test_bit(BTRFS_INODE_IN_DELALLOC_LIST,
2080 &inode->runtime_flags))
2081 btrfs_del_delalloc_inode(root, inode);
2082 spin_unlock(&inode->lock);
2085 if ((state->state & EXTENT_DELALLOC_NEW) &&
2086 (*bits & EXTENT_DELALLOC_NEW)) {
2087 spin_lock(&inode->lock);
2088 ASSERT(inode->new_delalloc_bytes >= len);
2089 inode->new_delalloc_bytes -= len;
2090 spin_unlock(&inode->lock);
2095 * btrfs_bio_fits_in_stripe - Checks whether the size of the given bio will fit
2096 * in a chunk's stripe. This function ensures that bios do not span a
2099 * @page - The page we are about to add to the bio
2100 * @size - size we want to add to the bio
2101 * @bio - bio we want to ensure is smaller than a stripe
2102 * @bio_flags - flags of the bio
2104 * return 1 if page cannot be added to the bio
2105 * return 0 if page can be added to the bio
2106 * return error otherwise
2108 int btrfs_bio_fits_in_stripe(struct page *page, size_t size, struct bio *bio,
2109 unsigned long bio_flags)
2111 struct inode *inode = page->mapping->host;
2112 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2113 u64 logical = (u64)bio->bi_iter.bi_sector << 9;
2117 struct btrfs_io_geometry geom;
2119 if (bio_flags & EXTENT_BIO_COMPRESSED)
2122 length = bio->bi_iter.bi_size;
2123 map_length = length;
2124 ret = btrfs_get_io_geometry(fs_info, btrfs_op(bio), logical, map_length,
2129 if (geom.len < length + size)
2135 * in order to insert checksums into the metadata in large chunks,
2136 * we wait until bio submission time. All the pages in the bio are
2137 * checksummed and sums are attached onto the ordered extent record.
2139 * At IO completion time the cums attached on the ordered extent record
2140 * are inserted into the btree
2142 static blk_status_t btrfs_submit_bio_start(void *private_data, struct bio *bio,
2145 struct inode *inode = private_data;
2146 blk_status_t ret = 0;
2148 ret = btrfs_csum_one_bio(inode, bio, 0, 0);
2149 BUG_ON(ret); /* -ENOMEM */
2154 * extent_io.c submission hook. This does the right thing for csum calculation
2155 * on write, or reading the csums from the tree before a read.
2157 * Rules about async/sync submit,
2158 * a) read: sync submit
2160 * b) write without checksum: sync submit
2162 * c) write with checksum:
2163 * c-1) if bio is issued by fsync: sync submit
2164 * (sync_writers != 0)
2166 * c-2) if root is reloc root: sync submit
2167 * (only in case of buffered IO)
2169 * c-3) otherwise: async submit
2171 static blk_status_t btrfs_submit_bio_hook(struct inode *inode, struct bio *bio,
2173 unsigned long bio_flags)
2176 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2177 struct btrfs_root *root = BTRFS_I(inode)->root;
2178 enum btrfs_wq_endio_type metadata = BTRFS_WQ_ENDIO_DATA;
2179 blk_status_t ret = 0;
2181 int async = !atomic_read(&BTRFS_I(inode)->sync_writers);
2183 skip_sum = BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM;
2185 if (btrfs_is_free_space_inode(BTRFS_I(inode)))
2186 metadata = BTRFS_WQ_ENDIO_FREE_SPACE;
2188 if (bio_op(bio) != REQ_OP_WRITE) {
2189 ret = btrfs_bio_wq_end_io(fs_info, bio, metadata);
2193 if (bio_flags & EXTENT_BIO_COMPRESSED) {
2194 ret = btrfs_submit_compressed_read(inode, bio,
2198 } else if (!skip_sum) {
2199 ret = btrfs_lookup_bio_sums(inode, bio, (u64)-1, NULL);
2204 } else if (async && !skip_sum) {
2205 /* csum items have already been cloned */
2206 if (root->root_key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID)
2208 /* we're doing a write, do the async checksumming */
2209 ret = btrfs_wq_submit_bio(fs_info, bio, mirror_num, bio_flags,
2210 0, inode, btrfs_submit_bio_start);
2212 } else if (!skip_sum) {
2213 ret = btrfs_csum_one_bio(inode, bio, 0, 0);
2219 ret = btrfs_map_bio(fs_info, bio, mirror_num);
2223 bio->bi_status = ret;
2230 * given a list of ordered sums record them in the inode. This happens
2231 * at IO completion time based on sums calculated at bio submission time.
2233 static noinline int add_pending_csums(struct btrfs_trans_handle *trans,
2234 struct inode *inode, struct list_head *list)
2236 struct btrfs_ordered_sum *sum;
2239 list_for_each_entry(sum, list, list) {
2240 trans->adding_csums = true;
2241 ret = btrfs_csum_file_blocks(trans,
2242 BTRFS_I(inode)->root->fs_info->csum_root, sum);
2243 trans->adding_csums = false;
2250 int btrfs_set_extent_delalloc(struct inode *inode, u64 start, u64 end,
2251 unsigned int extra_bits,
2252 struct extent_state **cached_state)
2254 WARN_ON(PAGE_ALIGNED(end));
2255 return set_extent_delalloc(&BTRFS_I(inode)->io_tree, start, end,
2256 extra_bits, cached_state);
2259 /* see btrfs_writepage_start_hook for details on why this is required */
2260 struct btrfs_writepage_fixup {
2262 struct inode *inode;
2263 struct btrfs_work work;
2266 static void btrfs_writepage_fixup_worker(struct btrfs_work *work)
2268 struct btrfs_writepage_fixup *fixup;
2269 struct btrfs_ordered_extent *ordered;
2270 struct extent_state *cached_state = NULL;
2271 struct extent_changeset *data_reserved = NULL;
2273 struct inode *inode;
2277 bool free_delalloc_space = true;
2279 fixup = container_of(work, struct btrfs_writepage_fixup, work);
2281 inode = fixup->inode;
2282 page_start = page_offset(page);
2283 page_end = page_offset(page) + PAGE_SIZE - 1;
2286 * This is similar to page_mkwrite, we need to reserve the space before
2287 * we take the page lock.
2289 ret = btrfs_delalloc_reserve_space(inode, &data_reserved, page_start,
2295 * Before we queued this fixup, we took a reference on the page.
2296 * page->mapping may go NULL, but it shouldn't be moved to a different
2299 if (!page->mapping || !PageDirty(page) || !PageChecked(page)) {
2301 * Unfortunately this is a little tricky, either
2303 * 1) We got here and our page had already been dealt with and
2304 * we reserved our space, thus ret == 0, so we need to just
2305 * drop our space reservation and bail. This can happen the
2306 * first time we come into the fixup worker, or could happen
2307 * while waiting for the ordered extent.
2308 * 2) Our page was already dealt with, but we happened to get an
2309 * ENOSPC above from the btrfs_delalloc_reserve_space. In
2310 * this case we obviously don't have anything to release, but
2311 * because the page was already dealt with we don't want to
2312 * mark the page with an error, so make sure we're resetting
2313 * ret to 0. This is why we have this check _before_ the ret
2314 * check, because we do not want to have a surprise ENOSPC
2315 * when the page was already properly dealt with.
2318 btrfs_delalloc_release_extents(BTRFS_I(inode),
2320 btrfs_delalloc_release_space(inode, data_reserved,
2321 page_start, PAGE_SIZE,
2329 * We can't mess with the page state unless it is locked, so now that
2330 * it is locked bail if we failed to make our space reservation.
2335 lock_extent_bits(&BTRFS_I(inode)->io_tree, page_start, page_end,
2338 /* already ordered? We're done */
2339 if (PagePrivate2(page))
2342 ordered = btrfs_lookup_ordered_range(BTRFS_I(inode), page_start,
2345 unlock_extent_cached(&BTRFS_I(inode)->io_tree, page_start,
2346 page_end, &cached_state);
2348 btrfs_start_ordered_extent(inode, ordered, 1);
2349 btrfs_put_ordered_extent(ordered);
2353 ret = btrfs_set_extent_delalloc(inode, page_start, page_end, 0,
2359 * Everything went as planned, we're now the owner of a dirty page with
2360 * delayed allocation bits set and space reserved for our COW
2363 * The page was dirty when we started, nothing should have cleaned it.
2365 BUG_ON(!PageDirty(page));
2366 free_delalloc_space = false;
2368 btrfs_delalloc_release_extents(BTRFS_I(inode), PAGE_SIZE);
2369 if (free_delalloc_space)
2370 btrfs_delalloc_release_space(inode, data_reserved, page_start,
2372 unlock_extent_cached(&BTRFS_I(inode)->io_tree, page_start, page_end,
2377 * We hit ENOSPC or other errors. Update the mapping and page
2378 * to reflect the errors and clean the page.
2380 mapping_set_error(page->mapping, ret);
2381 end_extent_writepage(page, ret, page_start, page_end);
2382 clear_page_dirty_for_io(page);
2385 ClearPageChecked(page);
2389 extent_changeset_free(data_reserved);
2391 * As a precaution, do a delayed iput in case it would be the last iput
2392 * that could need flushing space. Recursing back to fixup worker would
2395 btrfs_add_delayed_iput(inode);
2399 * There are a few paths in the higher layers of the kernel that directly
2400 * set the page dirty bit without asking the filesystem if it is a
2401 * good idea. This causes problems because we want to make sure COW
2402 * properly happens and the data=ordered rules are followed.
2404 * In our case any range that doesn't have the ORDERED bit set
2405 * hasn't been properly setup for IO. We kick off an async process
2406 * to fix it up. The async helper will wait for ordered extents, set
2407 * the delalloc bit and make it safe to write the page.
2409 int btrfs_writepage_cow_fixup(struct page *page, u64 start, u64 end)
2411 struct inode *inode = page->mapping->host;
2412 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2413 struct btrfs_writepage_fixup *fixup;
2415 /* this page is properly in the ordered list */
2416 if (TestClearPagePrivate2(page))
2420 * PageChecked is set below when we create a fixup worker for this page,
2421 * don't try to create another one if we're already PageChecked()
2423 * The extent_io writepage code will redirty the page if we send back
2426 if (PageChecked(page))
2429 fixup = kzalloc(sizeof(*fixup), GFP_NOFS);
2434 * We are already holding a reference to this inode from
2435 * write_cache_pages. We need to hold it because the space reservation
2436 * takes place outside of the page lock, and we can't trust
2437 * page->mapping outside of the page lock.
2440 SetPageChecked(page);
2442 btrfs_init_work(&fixup->work, btrfs_writepage_fixup_worker, NULL, NULL);
2444 fixup->inode = inode;
2445 btrfs_queue_work(fs_info->fixup_workers, &fixup->work);
2450 static int insert_reserved_file_extent(struct btrfs_trans_handle *trans,
2451 struct inode *inode, u64 file_pos,
2452 u64 disk_bytenr, u64 disk_num_bytes,
2453 u64 num_bytes, u64 ram_bytes,
2454 u8 compression, u8 encryption,
2455 u16 other_encoding, int extent_type)
2457 struct btrfs_root *root = BTRFS_I(inode)->root;
2458 struct btrfs_file_extent_item *fi;
2459 struct btrfs_path *path;
2460 struct extent_buffer *leaf;
2461 struct btrfs_key ins;
2463 int extent_inserted = 0;
2466 path = btrfs_alloc_path();
2471 * we may be replacing one extent in the tree with another.
2472 * The new extent is pinned in the extent map, and we don't want
2473 * to drop it from the cache until it is completely in the btree.
2475 * So, tell btrfs_drop_extents to leave this extent in the cache.
2476 * the caller is expected to unpin it and allow it to be merged
2479 ret = __btrfs_drop_extents(trans, root, inode, path, file_pos,
2480 file_pos + num_bytes, NULL, 0,
2481 1, sizeof(*fi), &extent_inserted);
2485 if (!extent_inserted) {
2486 ins.objectid = btrfs_ino(BTRFS_I(inode));
2487 ins.offset = file_pos;
2488 ins.type = BTRFS_EXTENT_DATA_KEY;
2490 path->leave_spinning = 1;
2491 ret = btrfs_insert_empty_item(trans, root, path, &ins,
2496 leaf = path->nodes[0];
2497 fi = btrfs_item_ptr(leaf, path->slots[0],
2498 struct btrfs_file_extent_item);
2499 btrfs_set_file_extent_generation(leaf, fi, trans->transid);
2500 btrfs_set_file_extent_type(leaf, fi, extent_type);
2501 btrfs_set_file_extent_disk_bytenr(leaf, fi, disk_bytenr);
2502 btrfs_set_file_extent_disk_num_bytes(leaf, fi, disk_num_bytes);
2503 btrfs_set_file_extent_offset(leaf, fi, 0);
2504 btrfs_set_file_extent_num_bytes(leaf, fi, num_bytes);
2505 btrfs_set_file_extent_ram_bytes(leaf, fi, ram_bytes);
2506 btrfs_set_file_extent_compression(leaf, fi, compression);
2507 btrfs_set_file_extent_encryption(leaf, fi, encryption);
2508 btrfs_set_file_extent_other_encoding(leaf, fi, other_encoding);
2510 btrfs_mark_buffer_dirty(leaf);
2511 btrfs_release_path(path);
2513 inode_add_bytes(inode, num_bytes);
2515 ins.objectid = disk_bytenr;
2516 ins.offset = disk_num_bytes;
2517 ins.type = BTRFS_EXTENT_ITEM_KEY;
2519 ret = btrfs_inode_set_file_extent_range(BTRFS_I(inode), file_pos,
2525 * Release the reserved range from inode dirty range map, as it is
2526 * already moved into delayed_ref_head
2528 ret = btrfs_qgroup_release_data(inode, file_pos, ram_bytes);
2532 ret = btrfs_alloc_reserved_file_extent(trans, root,
2533 btrfs_ino(BTRFS_I(inode)),
2534 file_pos, qg_released, &ins);
2536 btrfs_free_path(path);
2541 static void btrfs_release_delalloc_bytes(struct btrfs_fs_info *fs_info,
2544 struct btrfs_block_group *cache;
2546 cache = btrfs_lookup_block_group(fs_info, start);
2549 spin_lock(&cache->lock);
2550 cache->delalloc_bytes -= len;
2551 spin_unlock(&cache->lock);
2553 btrfs_put_block_group(cache);
2556 /* as ordered data IO finishes, this gets called so we can finish
2557 * an ordered extent if the range of bytes in the file it covers are
2560 static int btrfs_finish_ordered_io(struct btrfs_ordered_extent *ordered_extent)
2562 struct inode *inode = ordered_extent->inode;
2563 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2564 struct btrfs_root *root = BTRFS_I(inode)->root;
2565 struct btrfs_trans_handle *trans = NULL;
2566 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
2567 struct extent_state *cached_state = NULL;
2569 int compress_type = 0;
2571 u64 logical_len = ordered_extent->num_bytes;
2572 bool freespace_inode;
2573 bool truncated = false;
2574 bool range_locked = false;
2575 bool clear_new_delalloc_bytes = false;
2576 bool clear_reserved_extent = true;
2577 unsigned int clear_bits;
2579 start = ordered_extent->file_offset;
2580 end = start + ordered_extent->num_bytes - 1;
2582 if (!test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags) &&
2583 !test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags) &&
2584 !test_bit(BTRFS_ORDERED_DIRECT, &ordered_extent->flags))
2585 clear_new_delalloc_bytes = true;
2587 freespace_inode = btrfs_is_free_space_inode(BTRFS_I(inode));
2589 if (test_bit(BTRFS_ORDERED_IOERR, &ordered_extent->flags)) {
2594 btrfs_free_io_failure_record(BTRFS_I(inode), start, end);
2596 if (test_bit(BTRFS_ORDERED_TRUNCATED, &ordered_extent->flags)) {
2598 logical_len = ordered_extent->truncated_len;
2599 /* Truncated the entire extent, don't bother adding */
2604 if (test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags)) {
2605 BUG_ON(!list_empty(&ordered_extent->list)); /* Logic error */
2608 * For mwrite(mmap + memset to write) case, we still reserve
2609 * space for NOCOW range.
2610 * As NOCOW won't cause a new delayed ref, just free the space
2612 btrfs_qgroup_free_data(inode, NULL, start,
2613 ordered_extent->num_bytes);
2614 btrfs_inode_safe_disk_i_size_write(inode, 0);
2615 if (freespace_inode)
2616 trans = btrfs_join_transaction_spacecache(root);
2618 trans = btrfs_join_transaction(root);
2619 if (IS_ERR(trans)) {
2620 ret = PTR_ERR(trans);
2624 trans->block_rsv = &BTRFS_I(inode)->block_rsv;
2625 ret = btrfs_update_inode_fallback(trans, root, inode);
2626 if (ret) /* -ENOMEM or corruption */
2627 btrfs_abort_transaction(trans, ret);
2631 range_locked = true;
2632 lock_extent_bits(io_tree, start, end, &cached_state);
2634 if (freespace_inode)
2635 trans = btrfs_join_transaction_spacecache(root);
2637 trans = btrfs_join_transaction(root);
2638 if (IS_ERR(trans)) {
2639 ret = PTR_ERR(trans);
2644 trans->block_rsv = &BTRFS_I(inode)->block_rsv;
2646 if (test_bit(BTRFS_ORDERED_COMPRESSED, &ordered_extent->flags))
2647 compress_type = ordered_extent->compress_type;
2648 if (test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags)) {
2649 BUG_ON(compress_type);
2650 btrfs_qgroup_free_data(inode, NULL, start,
2651 ordered_extent->num_bytes);
2652 ret = btrfs_mark_extent_written(trans, BTRFS_I(inode),
2653 ordered_extent->file_offset,
2654 ordered_extent->file_offset +
2657 BUG_ON(root == fs_info->tree_root);
2658 ret = insert_reserved_file_extent(trans, inode, start,
2659 ordered_extent->disk_bytenr,
2660 ordered_extent->disk_num_bytes,
2661 logical_len, logical_len,
2662 compress_type, 0, 0,
2663 BTRFS_FILE_EXTENT_REG);
2665 clear_reserved_extent = false;
2666 btrfs_release_delalloc_bytes(fs_info,
2667 ordered_extent->disk_bytenr,
2668 ordered_extent->disk_num_bytes);
2671 unpin_extent_cache(&BTRFS_I(inode)->extent_tree,
2672 ordered_extent->file_offset,
2673 ordered_extent->num_bytes, trans->transid);
2675 btrfs_abort_transaction(trans, ret);
2679 ret = add_pending_csums(trans, inode, &ordered_extent->list);
2681 btrfs_abort_transaction(trans, ret);
2685 btrfs_inode_safe_disk_i_size_write(inode, 0);
2686 ret = btrfs_update_inode_fallback(trans, root, inode);
2687 if (ret) { /* -ENOMEM or corruption */
2688 btrfs_abort_transaction(trans, ret);
2693 clear_bits = EXTENT_DEFRAG;
2695 clear_bits |= EXTENT_LOCKED;
2696 if (clear_new_delalloc_bytes)
2697 clear_bits |= EXTENT_DELALLOC_NEW;
2698 clear_extent_bit(&BTRFS_I(inode)->io_tree, start, end, clear_bits,
2699 (clear_bits & EXTENT_LOCKED) ? 1 : 0, 0,
2703 btrfs_end_transaction(trans);
2705 if (ret || truncated) {
2706 u64 unwritten_start = start;
2709 unwritten_start += logical_len;
2710 clear_extent_uptodate(io_tree, unwritten_start, end, NULL);
2712 /* Drop the cache for the part of the extent we didn't write. */
2713 btrfs_drop_extent_cache(BTRFS_I(inode), unwritten_start, end, 0);
2716 * If the ordered extent had an IOERR or something else went
2717 * wrong we need to return the space for this ordered extent
2718 * back to the allocator. We only free the extent in the
2719 * truncated case if we didn't write out the extent at all.
2721 * If we made it past insert_reserved_file_extent before we
2722 * errored out then we don't need to do this as the accounting
2723 * has already been done.
2725 if ((ret || !logical_len) &&
2726 clear_reserved_extent &&
2727 !test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags) &&
2728 !test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags)) {
2730 * Discard the range before returning it back to the
2733 if (ret && btrfs_test_opt(fs_info, DISCARD_SYNC))
2734 btrfs_discard_extent(fs_info,
2735 ordered_extent->disk_bytenr,
2736 ordered_extent->disk_num_bytes,
2738 btrfs_free_reserved_extent(fs_info,
2739 ordered_extent->disk_bytenr,
2740 ordered_extent->disk_num_bytes, 1);
2745 * This needs to be done to make sure anybody waiting knows we are done
2746 * updating everything for this ordered extent.
2748 btrfs_remove_ordered_extent(inode, ordered_extent);
2751 btrfs_put_ordered_extent(ordered_extent);
2752 /* once for the tree */
2753 btrfs_put_ordered_extent(ordered_extent);
2758 static void finish_ordered_fn(struct btrfs_work *work)
2760 struct btrfs_ordered_extent *ordered_extent;
2761 ordered_extent = container_of(work, struct btrfs_ordered_extent, work);
2762 btrfs_finish_ordered_io(ordered_extent);
2765 void btrfs_writepage_endio_finish_ordered(struct page *page, u64 start,
2766 u64 end, int uptodate)
2768 struct inode *inode = page->mapping->host;
2769 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2770 struct btrfs_ordered_extent *ordered_extent = NULL;
2771 struct btrfs_workqueue *wq;
2773 trace_btrfs_writepage_end_io_hook(page, start, end, uptodate);
2775 ClearPagePrivate2(page);
2776 if (!btrfs_dec_test_ordered_pending(inode, &ordered_extent, start,
2777 end - start + 1, uptodate))
2780 if (btrfs_is_free_space_inode(BTRFS_I(inode)))
2781 wq = fs_info->endio_freespace_worker;
2783 wq = fs_info->endio_write_workers;
2785 btrfs_init_work(&ordered_extent->work, finish_ordered_fn, NULL, NULL);
2786 btrfs_queue_work(wq, &ordered_extent->work);
2789 static int check_data_csum(struct inode *inode, struct btrfs_io_bio *io_bio,
2790 int icsum, struct page *page, int pgoff, u64 start,
2793 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2794 SHASH_DESC_ON_STACK(shash, fs_info->csum_shash);
2796 u16 csum_size = btrfs_super_csum_size(fs_info->super_copy);
2798 u8 csum[BTRFS_CSUM_SIZE];
2800 csum_expected = ((u8 *)io_bio->csum) + icsum * csum_size;
2802 kaddr = kmap_atomic(page);
2803 shash->tfm = fs_info->csum_shash;
2805 crypto_shash_digest(shash, kaddr + pgoff, len, csum);
2807 if (memcmp(csum, csum_expected, csum_size))
2810 kunmap_atomic(kaddr);
2813 btrfs_print_data_csum_error(BTRFS_I(inode), start, csum, csum_expected,
2814 io_bio->mirror_num);
2815 memset(kaddr + pgoff, 1, len);
2816 flush_dcache_page(page);
2817 kunmap_atomic(kaddr);
2822 * when reads are done, we need to check csums to verify the data is correct
2823 * if there's a match, we allow the bio to finish. If not, the code in
2824 * extent_io.c will try to find good copies for us.
2826 static int btrfs_readpage_end_io_hook(struct btrfs_io_bio *io_bio,
2827 u64 phy_offset, struct page *page,
2828 u64 start, u64 end, int mirror)
2830 size_t offset = start - page_offset(page);
2831 struct inode *inode = page->mapping->host;
2832 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
2833 struct btrfs_root *root = BTRFS_I(inode)->root;
2835 if (PageChecked(page)) {
2836 ClearPageChecked(page);
2840 if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)
2843 if (root->root_key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID &&
2844 test_range_bit(io_tree, start, end, EXTENT_NODATASUM, 1, NULL)) {
2845 clear_extent_bits(io_tree, start, end, EXTENT_NODATASUM);
2849 phy_offset >>= inode->i_sb->s_blocksize_bits;
2850 return check_data_csum(inode, io_bio, phy_offset, page, offset, start,
2851 (size_t)(end - start + 1));
2855 * btrfs_add_delayed_iput - perform a delayed iput on @inode
2857 * @inode: The inode we want to perform iput on
2859 * This function uses the generic vfs_inode::i_count to track whether we should
2860 * just decrement it (in case it's > 1) or if this is the last iput then link
2861 * the inode to the delayed iput machinery. Delayed iputs are processed at
2862 * transaction commit time/superblock commit/cleaner kthread.
2864 void btrfs_add_delayed_iput(struct inode *inode)
2866 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2867 struct btrfs_inode *binode = BTRFS_I(inode);
2869 if (atomic_add_unless(&inode->i_count, -1, 1))
2872 atomic_inc(&fs_info->nr_delayed_iputs);
2873 spin_lock(&fs_info->delayed_iput_lock);
2874 ASSERT(list_empty(&binode->delayed_iput));
2875 list_add_tail(&binode->delayed_iput, &fs_info->delayed_iputs);
2876 spin_unlock(&fs_info->delayed_iput_lock);
2877 if (!test_bit(BTRFS_FS_CLEANER_RUNNING, &fs_info->flags))
2878 wake_up_process(fs_info->cleaner_kthread);
2881 static void run_delayed_iput_locked(struct btrfs_fs_info *fs_info,
2882 struct btrfs_inode *inode)
2884 list_del_init(&inode->delayed_iput);
2885 spin_unlock(&fs_info->delayed_iput_lock);
2886 iput(&inode->vfs_inode);
2887 if (atomic_dec_and_test(&fs_info->nr_delayed_iputs))
2888 wake_up(&fs_info->delayed_iputs_wait);
2889 spin_lock(&fs_info->delayed_iput_lock);
2892 static void btrfs_run_delayed_iput(struct btrfs_fs_info *fs_info,
2893 struct btrfs_inode *inode)
2895 if (!list_empty(&inode->delayed_iput)) {
2896 spin_lock(&fs_info->delayed_iput_lock);
2897 if (!list_empty(&inode->delayed_iput))
2898 run_delayed_iput_locked(fs_info, inode);
2899 spin_unlock(&fs_info->delayed_iput_lock);
2903 void btrfs_run_delayed_iputs(struct btrfs_fs_info *fs_info)
2906 spin_lock(&fs_info->delayed_iput_lock);
2907 while (!list_empty(&fs_info->delayed_iputs)) {
2908 struct btrfs_inode *inode;
2910 inode = list_first_entry(&fs_info->delayed_iputs,
2911 struct btrfs_inode, delayed_iput);
2912 run_delayed_iput_locked(fs_info, inode);
2914 spin_unlock(&fs_info->delayed_iput_lock);
2918 * btrfs_wait_on_delayed_iputs - wait on the delayed iputs to be done running
2919 * @fs_info - the fs_info for this fs
2920 * @return - EINTR if we were killed, 0 if nothing's pending
2922 * This will wait on any delayed iputs that are currently running with KILLABLE
2923 * set. Once they are all done running we will return, unless we are killed in
2924 * which case we return EINTR. This helps in user operations like fallocate etc
2925 * that might get blocked on the iputs.
2927 int btrfs_wait_on_delayed_iputs(struct btrfs_fs_info *fs_info)
2929 int ret = wait_event_killable(fs_info->delayed_iputs_wait,
2930 atomic_read(&fs_info->nr_delayed_iputs) == 0);
2937 * This creates an orphan entry for the given inode in case something goes wrong
2938 * in the middle of an unlink.
2940 int btrfs_orphan_add(struct btrfs_trans_handle *trans,
2941 struct btrfs_inode *inode)
2945 ret = btrfs_insert_orphan_item(trans, inode->root, btrfs_ino(inode));
2946 if (ret && ret != -EEXIST) {
2947 btrfs_abort_transaction(trans, ret);
2955 * We have done the delete so we can go ahead and remove the orphan item for
2956 * this particular inode.
2958 static int btrfs_orphan_del(struct btrfs_trans_handle *trans,
2959 struct btrfs_inode *inode)
2961 return btrfs_del_orphan_item(trans, inode->root, btrfs_ino(inode));
2965 * this cleans up any orphans that may be left on the list from the last use
2968 int btrfs_orphan_cleanup(struct btrfs_root *root)
2970 struct btrfs_fs_info *fs_info = root->fs_info;
2971 struct btrfs_path *path;
2972 struct extent_buffer *leaf;
2973 struct btrfs_key key, found_key;
2974 struct btrfs_trans_handle *trans;
2975 struct inode *inode;
2976 u64 last_objectid = 0;
2977 int ret = 0, nr_unlink = 0;
2979 if (cmpxchg(&root->orphan_cleanup_state, 0, ORPHAN_CLEANUP_STARTED))
2982 path = btrfs_alloc_path();
2987 path->reada = READA_BACK;
2989 key.objectid = BTRFS_ORPHAN_OBJECTID;
2990 key.type = BTRFS_ORPHAN_ITEM_KEY;
2991 key.offset = (u64)-1;
2994 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2999 * if ret == 0 means we found what we were searching for, which
3000 * is weird, but possible, so only screw with path if we didn't
3001 * find the key and see if we have stuff that matches
3005 if (path->slots[0] == 0)
3010 /* pull out the item */
3011 leaf = path->nodes[0];
3012 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
3014 /* make sure the item matches what we want */
3015 if (found_key.objectid != BTRFS_ORPHAN_OBJECTID)
3017 if (found_key.type != BTRFS_ORPHAN_ITEM_KEY)
3020 /* release the path since we're done with it */
3021 btrfs_release_path(path);
3024 * this is where we are basically btrfs_lookup, without the
3025 * crossing root thing. we store the inode number in the
3026 * offset of the orphan item.
3029 if (found_key.offset == last_objectid) {
3031 "Error removing orphan entry, stopping orphan cleanup");
3036 last_objectid = found_key.offset;
3038 found_key.objectid = found_key.offset;
3039 found_key.type = BTRFS_INODE_ITEM_KEY;
3040 found_key.offset = 0;
3041 inode = btrfs_iget(fs_info->sb, last_objectid, root);
3042 ret = PTR_ERR_OR_ZERO(inode);
3043 if (ret && ret != -ENOENT)
3046 if (ret == -ENOENT && root == fs_info->tree_root) {
3047 struct btrfs_root *dead_root;
3048 struct btrfs_fs_info *fs_info = root->fs_info;
3049 int is_dead_root = 0;
3052 * this is an orphan in the tree root. Currently these
3053 * could come from 2 sources:
3054 * a) a snapshot deletion in progress
3055 * b) a free space cache inode
3056 * We need to distinguish those two, as the snapshot
3057 * orphan must not get deleted.
3058 * find_dead_roots already ran before us, so if this
3059 * is a snapshot deletion, we should find the root
3060 * in the fs_roots radix tree.
3063 spin_lock(&fs_info->fs_roots_radix_lock);
3064 dead_root = radix_tree_lookup(&fs_info->fs_roots_radix,
3065 (unsigned long)found_key.objectid);
3066 if (dead_root && btrfs_root_refs(&dead_root->root_item) == 0)
3068 spin_unlock(&fs_info->fs_roots_radix_lock);
3071 /* prevent this orphan from being found again */
3072 key.offset = found_key.objectid - 1;
3079 * If we have an inode with links, there are a couple of
3080 * possibilities. Old kernels (before v3.12) used to create an
3081 * orphan item for truncate indicating that there were possibly
3082 * extent items past i_size that needed to be deleted. In v3.12,
3083 * truncate was changed to update i_size in sync with the extent
3084 * items, but the (useless) orphan item was still created. Since
3085 * v4.18, we don't create the orphan item for truncate at all.
3087 * So, this item could mean that we need to do a truncate, but
3088 * only if this filesystem was last used on a pre-v3.12 kernel
3089 * and was not cleanly unmounted. The odds of that are quite
3090 * slim, and it's a pain to do the truncate now, so just delete
3093 * It's also possible that this orphan item was supposed to be
3094 * deleted but wasn't. The inode number may have been reused,
3095 * but either way, we can delete the orphan item.
3097 if (ret == -ENOENT || inode->i_nlink) {
3100 trans = btrfs_start_transaction(root, 1);
3101 if (IS_ERR(trans)) {
3102 ret = PTR_ERR(trans);
3105 btrfs_debug(fs_info, "auto deleting %Lu",
3106 found_key.objectid);
3107 ret = btrfs_del_orphan_item(trans, root,
3108 found_key.objectid);
3109 btrfs_end_transaction(trans);
3117 /* this will do delete_inode and everything for us */
3120 /* release the path since we're done with it */
3121 btrfs_release_path(path);
3123 root->orphan_cleanup_state = ORPHAN_CLEANUP_DONE;
3125 if (test_bit(BTRFS_ROOT_ORPHAN_ITEM_INSERTED, &root->state)) {
3126 trans = btrfs_join_transaction(root);
3128 btrfs_end_transaction(trans);
3132 btrfs_debug(fs_info, "unlinked %d orphans", nr_unlink);
3136 btrfs_err(fs_info, "could not do orphan cleanup %d", ret);
3137 btrfs_free_path(path);
3142 * very simple check to peek ahead in the leaf looking for xattrs. If we
3143 * don't find any xattrs, we know there can't be any acls.
3145 * slot is the slot the inode is in, objectid is the objectid of the inode
3147 static noinline int acls_after_inode_item(struct extent_buffer *leaf,
3148 int slot, u64 objectid,
3149 int *first_xattr_slot)
3151 u32 nritems = btrfs_header_nritems(leaf);
3152 struct btrfs_key found_key;
3153 static u64 xattr_access = 0;
3154 static u64 xattr_default = 0;
3157 if (!xattr_access) {
3158 xattr_access = btrfs_name_hash(XATTR_NAME_POSIX_ACL_ACCESS,
3159 strlen(XATTR_NAME_POSIX_ACL_ACCESS));
3160 xattr_default = btrfs_name_hash(XATTR_NAME_POSIX_ACL_DEFAULT,
3161 strlen(XATTR_NAME_POSIX_ACL_DEFAULT));
3165 *first_xattr_slot = -1;
3166 while (slot < nritems) {
3167 btrfs_item_key_to_cpu(leaf, &found_key, slot);
3169 /* we found a different objectid, there must not be acls */
3170 if (found_key.objectid != objectid)
3173 /* we found an xattr, assume we've got an acl */
3174 if (found_key.type == BTRFS_XATTR_ITEM_KEY) {
3175 if (*first_xattr_slot == -1)
3176 *first_xattr_slot = slot;
3177 if (found_key.offset == xattr_access ||
3178 found_key.offset == xattr_default)
3183 * we found a key greater than an xattr key, there can't
3184 * be any acls later on
3186 if (found_key.type > BTRFS_XATTR_ITEM_KEY)
3193 * it goes inode, inode backrefs, xattrs, extents,
3194 * so if there are a ton of hard links to an inode there can
3195 * be a lot of backrefs. Don't waste time searching too hard,
3196 * this is just an optimization
3201 /* we hit the end of the leaf before we found an xattr or
3202 * something larger than an xattr. We have to assume the inode
3205 if (*first_xattr_slot == -1)
3206 *first_xattr_slot = slot;
3211 * read an inode from the btree into the in-memory inode
3213 static int btrfs_read_locked_inode(struct inode *inode,
3214 struct btrfs_path *in_path)
3216 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
3217 struct btrfs_path *path = in_path;
3218 struct extent_buffer *leaf;
3219 struct btrfs_inode_item *inode_item;
3220 struct btrfs_root *root = BTRFS_I(inode)->root;
3221 struct btrfs_key location;
3226 bool filled = false;
3227 int first_xattr_slot;
3229 ret = btrfs_fill_inode(inode, &rdev);
3234 path = btrfs_alloc_path();
3239 memcpy(&location, &BTRFS_I(inode)->location, sizeof(location));
3241 ret = btrfs_lookup_inode(NULL, root, path, &location, 0);
3243 if (path != in_path)
3244 btrfs_free_path(path);
3248 leaf = path->nodes[0];
3253 inode_item = btrfs_item_ptr(leaf, path->slots[0],
3254 struct btrfs_inode_item);
3255 inode->i_mode = btrfs_inode_mode(leaf, inode_item);
3256 set_nlink(inode, btrfs_inode_nlink(leaf, inode_item));
3257 i_uid_write(inode, btrfs_inode_uid(leaf, inode_item));
3258 i_gid_write(inode, btrfs_inode_gid(leaf, inode_item));
3259 btrfs_i_size_write(BTRFS_I(inode), btrfs_inode_size(leaf, inode_item));
3260 btrfs_inode_set_file_extent_range(BTRFS_I(inode), 0,
3261 round_up(i_size_read(inode), fs_info->sectorsize));
3263 inode->i_atime.tv_sec = btrfs_timespec_sec(leaf, &inode_item->atime);
3264 inode->i_atime.tv_nsec = btrfs_timespec_nsec(leaf, &inode_item->atime);
3266 inode->i_mtime.tv_sec = btrfs_timespec_sec(leaf, &inode_item->mtime);
3267 inode->i_mtime.tv_nsec = btrfs_timespec_nsec(leaf, &inode_item->mtime);
3269 inode->i_ctime.tv_sec = btrfs_timespec_sec(leaf, &inode_item->ctime);
3270 inode->i_ctime.tv_nsec = btrfs_timespec_nsec(leaf, &inode_item->ctime);
3272 BTRFS_I(inode)->i_otime.tv_sec =
3273 btrfs_timespec_sec(leaf, &inode_item->otime);
3274 BTRFS_I(inode)->i_otime.tv_nsec =
3275 btrfs_timespec_nsec(leaf, &inode_item->otime);
3277 inode_set_bytes(inode, btrfs_inode_nbytes(leaf, inode_item));
3278 BTRFS_I(inode)->generation = btrfs_inode_generation(leaf, inode_item);
3279 BTRFS_I(inode)->last_trans = btrfs_inode_transid(leaf, inode_item);
3281 inode_set_iversion_queried(inode,
3282 btrfs_inode_sequence(leaf, inode_item));
3283 inode->i_generation = BTRFS_I(inode)->generation;
3285 rdev = btrfs_inode_rdev(leaf, inode_item);
3287 BTRFS_I(inode)->index_cnt = (u64)-1;
3288 BTRFS_I(inode)->flags = btrfs_inode_flags(leaf, inode_item);
3292 * If we were modified in the current generation and evicted from memory
3293 * and then re-read we need to do a full sync since we don't have any
3294 * idea about which extents were modified before we were evicted from
3297 * This is required for both inode re-read from disk and delayed inode
3298 * in delayed_nodes_tree.
3300 if (BTRFS_I(inode)->last_trans == fs_info->generation)
3301 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
3302 &BTRFS_I(inode)->runtime_flags);
3305 * We don't persist the id of the transaction where an unlink operation
3306 * against the inode was last made. So here we assume the inode might
3307 * have been evicted, and therefore the exact value of last_unlink_trans
3308 * lost, and set it to last_trans to avoid metadata inconsistencies
3309 * between the inode and its parent if the inode is fsync'ed and the log
3310 * replayed. For example, in the scenario:
3313 * ln mydir/foo mydir/bar
3316 * echo 2 > /proc/sys/vm/drop_caches # evicts inode
3317 * xfs_io -c fsync mydir/foo
3319 * mount fs, triggers fsync log replay
3321 * We must make sure that when we fsync our inode foo we also log its
3322 * parent inode, otherwise after log replay the parent still has the
3323 * dentry with the "bar" name but our inode foo has a link count of 1
3324 * and doesn't have an inode ref with the name "bar" anymore.
3326 * Setting last_unlink_trans to last_trans is a pessimistic approach,
3327 * but it guarantees correctness at the expense of occasional full
3328 * transaction commits on fsync if our inode is a directory, or if our
3329 * inode is not a directory, logging its parent unnecessarily.
3331 BTRFS_I(inode)->last_unlink_trans = BTRFS_I(inode)->last_trans;
3334 if (inode->i_nlink != 1 ||
3335 path->slots[0] >= btrfs_header_nritems(leaf))
3338 btrfs_item_key_to_cpu(leaf, &location, path->slots[0]);
3339 if (location.objectid != btrfs_ino(BTRFS_I(inode)))
3342 ptr = btrfs_item_ptr_offset(leaf, path->slots[0]);
3343 if (location.type == BTRFS_INODE_REF_KEY) {
3344 struct btrfs_inode_ref *ref;
3346 ref = (struct btrfs_inode_ref *)ptr;
3347 BTRFS_I(inode)->dir_index = btrfs_inode_ref_index(leaf, ref);
3348 } else if (location.type == BTRFS_INODE_EXTREF_KEY) {
3349 struct btrfs_inode_extref *extref;
3351 extref = (struct btrfs_inode_extref *)ptr;
3352 BTRFS_I(inode)->dir_index = btrfs_inode_extref_index(leaf,
3357 * try to precache a NULL acl entry for files that don't have
3358 * any xattrs or acls
3360 maybe_acls = acls_after_inode_item(leaf, path->slots[0],
3361 btrfs_ino(BTRFS_I(inode)), &first_xattr_slot);
3362 if (first_xattr_slot != -1) {
3363 path->slots[0] = first_xattr_slot;
3364 ret = btrfs_load_inode_props(inode, path);
3367 "error loading props for ino %llu (root %llu): %d",
3368 btrfs_ino(BTRFS_I(inode)),
3369 root->root_key.objectid, ret);
3371 if (path != in_path)
3372 btrfs_free_path(path);
3375 cache_no_acl(inode);
3377 switch (inode->i_mode & S_IFMT) {
3379 inode->i_mapping->a_ops = &btrfs_aops;
3380 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
3381 inode->i_fop = &btrfs_file_operations;
3382 inode->i_op = &btrfs_file_inode_operations;
3385 inode->i_fop = &btrfs_dir_file_operations;
3386 inode->i_op = &btrfs_dir_inode_operations;
3389 inode->i_op = &btrfs_symlink_inode_operations;
3390 inode_nohighmem(inode);
3391 inode->i_mapping->a_ops = &btrfs_aops;
3394 inode->i_op = &btrfs_special_inode_operations;
3395 init_special_inode(inode, inode->i_mode, rdev);
3399 btrfs_sync_inode_flags_to_i_flags(inode);
3404 * given a leaf and an inode, copy the inode fields into the leaf
3406 static void fill_inode_item(struct btrfs_trans_handle *trans,
3407 struct extent_buffer *leaf,
3408 struct btrfs_inode_item *item,
3409 struct inode *inode)
3411 struct btrfs_map_token token;
3413 btrfs_init_map_token(&token, leaf);
3415 btrfs_set_token_inode_uid(&token, item, i_uid_read(inode));
3416 btrfs_set_token_inode_gid(&token, item, i_gid_read(inode));
3417 btrfs_set_token_inode_size(&token, item, BTRFS_I(inode)->disk_i_size);
3418 btrfs_set_token_inode_mode(&token, item, inode->i_mode);
3419 btrfs_set_token_inode_nlink(&token, item, inode->i_nlink);
3421 btrfs_set_token_timespec_sec(&token, &item->atime,
3422 inode->i_atime.tv_sec);
3423 btrfs_set_token_timespec_nsec(&token, &item->atime,
3424 inode->i_atime.tv_nsec);
3426 btrfs_set_token_timespec_sec(&token, &item->mtime,
3427 inode->i_mtime.tv_sec);
3428 btrfs_set_token_timespec_nsec(&token, &item->mtime,
3429 inode->i_mtime.tv_nsec);
3431 btrfs_set_token_timespec_sec(&token, &item->ctime,
3432 inode->i_ctime.tv_sec);
3433 btrfs_set_token_timespec_nsec(&token, &item->ctime,
3434 inode->i_ctime.tv_nsec);
3436 btrfs_set_token_timespec_sec(&token, &item->otime,
3437 BTRFS_I(inode)->i_otime.tv_sec);
3438 btrfs_set_token_timespec_nsec(&token, &item->otime,
3439 BTRFS_I(inode)->i_otime.tv_nsec);
3441 btrfs_set_token_inode_nbytes(&token, item, inode_get_bytes(inode));
3442 btrfs_set_token_inode_generation(&token, item,
3443 BTRFS_I(inode)->generation);
3444 btrfs_set_token_inode_sequence(&token, item, inode_peek_iversion(inode));
3445 btrfs_set_token_inode_transid(&token, item, trans->transid);
3446 btrfs_set_token_inode_rdev(&token, item, inode->i_rdev);
3447 btrfs_set_token_inode_flags(&token, item, BTRFS_I(inode)->flags);
3448 btrfs_set_token_inode_block_group(&token, item, 0);
3452 * copy everything in the in-memory inode into the btree.
3454 static noinline int btrfs_update_inode_item(struct btrfs_trans_handle *trans,
3455 struct btrfs_root *root, struct inode *inode)
3457 struct btrfs_inode_item *inode_item;
3458 struct btrfs_path *path;
3459 struct extent_buffer *leaf;
3462 path = btrfs_alloc_path();
3466 path->leave_spinning = 1;
3467 ret = btrfs_lookup_inode(trans, root, path, &BTRFS_I(inode)->location,
3475 leaf = path->nodes[0];
3476 inode_item = btrfs_item_ptr(leaf, path->slots[0],
3477 struct btrfs_inode_item);
3479 fill_inode_item(trans, leaf, inode_item, inode);
3480 btrfs_mark_buffer_dirty(leaf);
3481 btrfs_set_inode_last_trans(trans, inode);
3484 btrfs_free_path(path);
3489 * copy everything in the in-memory inode into the btree.
3491 noinline int btrfs_update_inode(struct btrfs_trans_handle *trans,
3492 struct btrfs_root *root, struct inode *inode)
3494 struct btrfs_fs_info *fs_info = root->fs_info;
3498 * If the inode is a free space inode, we can deadlock during commit
3499 * if we put it into the delayed code.
3501 * The data relocation inode should also be directly updated
3504 if (!btrfs_is_free_space_inode(BTRFS_I(inode))
3505 && root->root_key.objectid != BTRFS_DATA_RELOC_TREE_OBJECTID
3506 && !test_bit(BTRFS_FS_LOG_RECOVERING, &fs_info->flags)) {
3507 btrfs_update_root_times(trans, root);
3509 ret = btrfs_delayed_update_inode(trans, root, inode);
3511 btrfs_set_inode_last_trans(trans, inode);
3515 return btrfs_update_inode_item(trans, root, inode);
3518 noinline int btrfs_update_inode_fallback(struct btrfs_trans_handle *trans,
3519 struct btrfs_root *root,
3520 struct inode *inode)
3524 ret = btrfs_update_inode(trans, root, inode);
3526 return btrfs_update_inode_item(trans, root, inode);
3531 * unlink helper that gets used here in inode.c and in the tree logging
3532 * recovery code. It remove a link in a directory with a given name, and
3533 * also drops the back refs in the inode to the directory
3535 static int __btrfs_unlink_inode(struct btrfs_trans_handle *trans,
3536 struct btrfs_root *root,
3537 struct btrfs_inode *dir,
3538 struct btrfs_inode *inode,
3539 const char *name, int name_len)
3541 struct btrfs_fs_info *fs_info = root->fs_info;
3542 struct btrfs_path *path;
3544 struct btrfs_dir_item *di;
3546 u64 ino = btrfs_ino(inode);
3547 u64 dir_ino = btrfs_ino(dir);
3549 path = btrfs_alloc_path();
3555 path->leave_spinning = 1;
3556 di = btrfs_lookup_dir_item(trans, root, path, dir_ino,
3557 name, name_len, -1);
3558 if (IS_ERR_OR_NULL(di)) {
3559 ret = di ? PTR_ERR(di) : -ENOENT;
3562 ret = btrfs_delete_one_dir_name(trans, root, path, di);
3565 btrfs_release_path(path);
3568 * If we don't have dir index, we have to get it by looking up
3569 * the inode ref, since we get the inode ref, remove it directly,
3570 * it is unnecessary to do delayed deletion.
3572 * But if we have dir index, needn't search inode ref to get it.
3573 * Since the inode ref is close to the inode item, it is better
3574 * that we delay to delete it, and just do this deletion when
3575 * we update the inode item.
3577 if (inode->dir_index) {
3578 ret = btrfs_delayed_delete_inode_ref(inode);
3580 index = inode->dir_index;
3585 ret = btrfs_del_inode_ref(trans, root, name, name_len, ino,
3589 "failed to delete reference to %.*s, inode %llu parent %llu",
3590 name_len, name, ino, dir_ino);
3591 btrfs_abort_transaction(trans, ret);
3595 ret = btrfs_delete_delayed_dir_index(trans, dir, index);
3597 btrfs_abort_transaction(trans, ret);
3601 ret = btrfs_del_inode_ref_in_log(trans, root, name, name_len, inode,
3603 if (ret != 0 && ret != -ENOENT) {
3604 btrfs_abort_transaction(trans, ret);
3608 ret = btrfs_del_dir_entries_in_log(trans, root, name, name_len, dir,
3613 btrfs_abort_transaction(trans, ret);
3616 * If we have a pending delayed iput we could end up with the final iput
3617 * being run in btrfs-cleaner context. If we have enough of these built
3618 * up we can end up burning a lot of time in btrfs-cleaner without any
3619 * way to throttle the unlinks. Since we're currently holding a ref on
3620 * the inode we can run the delayed iput here without any issues as the
3621 * final iput won't be done until after we drop the ref we're currently
3624 btrfs_run_delayed_iput(fs_info, inode);
3626 btrfs_free_path(path);
3630 btrfs_i_size_write(dir, dir->vfs_inode.i_size - name_len * 2);
3631 inode_inc_iversion(&inode->vfs_inode);
3632 inode_inc_iversion(&dir->vfs_inode);
3633 inode->vfs_inode.i_ctime = dir->vfs_inode.i_mtime =
3634 dir->vfs_inode.i_ctime = current_time(&inode->vfs_inode);
3635 ret = btrfs_update_inode(trans, root, &dir->vfs_inode);
3640 int btrfs_unlink_inode(struct btrfs_trans_handle *trans,
3641 struct btrfs_root *root,
3642 struct btrfs_inode *dir, struct btrfs_inode *inode,
3643 const char *name, int name_len)
3646 ret = __btrfs_unlink_inode(trans, root, dir, inode, name, name_len);
3648 drop_nlink(&inode->vfs_inode);
3649 ret = btrfs_update_inode(trans, root, &inode->vfs_inode);
3655 * helper to start transaction for unlink and rmdir.
3657 * unlink and rmdir are special in btrfs, they do not always free space, so
3658 * if we cannot make our reservations the normal way try and see if there is
3659 * plenty of slack room in the global reserve to migrate, otherwise we cannot
3660 * allow the unlink to occur.
3662 static struct btrfs_trans_handle *__unlink_start_trans(struct inode *dir)
3664 struct btrfs_root *root = BTRFS_I(dir)->root;
3667 * 1 for the possible orphan item
3668 * 1 for the dir item
3669 * 1 for the dir index
3670 * 1 for the inode ref
3673 return btrfs_start_transaction_fallback_global_rsv(root, 5);
3676 static int btrfs_unlink(struct inode *dir, struct dentry *dentry)
3678 struct btrfs_root *root = BTRFS_I(dir)->root;
3679 struct btrfs_trans_handle *trans;
3680 struct inode *inode = d_inode(dentry);
3683 trans = __unlink_start_trans(dir);
3685 return PTR_ERR(trans);
3687 btrfs_record_unlink_dir(trans, BTRFS_I(dir), BTRFS_I(d_inode(dentry)),
3690 ret = btrfs_unlink_inode(trans, root, BTRFS_I(dir),
3691 BTRFS_I(d_inode(dentry)), dentry->d_name.name,
3692 dentry->d_name.len);
3696 if (inode->i_nlink == 0) {
3697 ret = btrfs_orphan_add(trans, BTRFS_I(inode));
3703 btrfs_end_transaction(trans);
3704 btrfs_btree_balance_dirty(root->fs_info);
3708 static int btrfs_unlink_subvol(struct btrfs_trans_handle *trans,
3709 struct inode *dir, struct dentry *dentry)
3711 struct btrfs_root *root = BTRFS_I(dir)->root;
3712 struct btrfs_inode *inode = BTRFS_I(d_inode(dentry));
3713 struct btrfs_path *path;
3714 struct extent_buffer *leaf;
3715 struct btrfs_dir_item *di;
3716 struct btrfs_key key;
3717 const char *name = dentry->d_name.name;
3718 int name_len = dentry->d_name.len;
3722 u64 dir_ino = btrfs_ino(BTRFS_I(dir));
3724 if (btrfs_ino(inode) == BTRFS_FIRST_FREE_OBJECTID) {
3725 objectid = inode->root->root_key.objectid;
3726 } else if (btrfs_ino(inode) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID) {
3727 objectid = inode->location.objectid;
3733 path = btrfs_alloc_path();
3737 di = btrfs_lookup_dir_item(trans, root, path, dir_ino,
3738 name, name_len, -1);
3739 if (IS_ERR_OR_NULL(di)) {
3740 ret = di ? PTR_ERR(di) : -ENOENT;
3744 leaf = path->nodes[0];
3745 btrfs_dir_item_key_to_cpu(leaf, di, &key);
3746 WARN_ON(key.type != BTRFS_ROOT_ITEM_KEY || key.objectid != objectid);
3747 ret = btrfs_delete_one_dir_name(trans, root, path, di);
3749 btrfs_abort_transaction(trans, ret);
3752 btrfs_release_path(path);
3755 * This is a placeholder inode for a subvolume we didn't have a
3756 * reference to at the time of the snapshot creation. In the meantime
3757 * we could have renamed the real subvol link into our snapshot, so
3758 * depending on btrfs_del_root_ref to return -ENOENT here is incorret.
3759 * Instead simply lookup the dir_index_item for this entry so we can
3760 * remove it. Otherwise we know we have a ref to the root and we can
3761 * call btrfs_del_root_ref, and it _shouldn't_ fail.
3763 if (btrfs_ino(inode) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID) {
3764 di = btrfs_search_dir_index_item(root, path, dir_ino,
3766 if (IS_ERR_OR_NULL(di)) {
3771 btrfs_abort_transaction(trans, ret);
3775 leaf = path->nodes[0];
3776 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
3778 btrfs_release_path(path);
3780 ret = btrfs_del_root_ref(trans, objectid,
3781 root->root_key.objectid, dir_ino,
3782 &index, name, name_len);
3784 btrfs_abort_transaction(trans, ret);
3789 ret = btrfs_delete_delayed_dir_index(trans, BTRFS_I(dir), index);
3791 btrfs_abort_transaction(trans, ret);
3795 btrfs_i_size_write(BTRFS_I(dir), dir->i_size - name_len * 2);
3796 inode_inc_iversion(dir);
3797 dir->i_mtime = dir->i_ctime = current_time(dir);
3798 ret = btrfs_update_inode_fallback(trans, root, dir);
3800 btrfs_abort_transaction(trans, ret);
3802 btrfs_free_path(path);
3807 * Helper to check if the subvolume references other subvolumes or if it's
3810 static noinline int may_destroy_subvol(struct btrfs_root *root)
3812 struct btrfs_fs_info *fs_info = root->fs_info;
3813 struct btrfs_path *path;
3814 struct btrfs_dir_item *di;
3815 struct btrfs_key key;
3819 path = btrfs_alloc_path();
3823 /* Make sure this root isn't set as the default subvol */
3824 dir_id = btrfs_super_root_dir(fs_info->super_copy);
3825 di = btrfs_lookup_dir_item(NULL, fs_info->tree_root, path,
3826 dir_id, "default", 7, 0);
3827 if (di && !IS_ERR(di)) {
3828 btrfs_dir_item_key_to_cpu(path->nodes[0], di, &key);
3829 if (key.objectid == root->root_key.objectid) {
3832 "deleting default subvolume %llu is not allowed",
3836 btrfs_release_path(path);
3839 key.objectid = root->root_key.objectid;
3840 key.type = BTRFS_ROOT_REF_KEY;
3841 key.offset = (u64)-1;
3843 ret = btrfs_search_slot(NULL, fs_info->tree_root, &key, path, 0, 0);
3849 if (path->slots[0] > 0) {
3851 btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
3852 if (key.objectid == root->root_key.objectid &&
3853 key.type == BTRFS_ROOT_REF_KEY)
3857 btrfs_free_path(path);
3861 /* Delete all dentries for inodes belonging to the root */
3862 static void btrfs_prune_dentries(struct btrfs_root *root)
3864 struct btrfs_fs_info *fs_info = root->fs_info;
3865 struct rb_node *node;
3866 struct rb_node *prev;
3867 struct btrfs_inode *entry;
3868 struct inode *inode;
3871 if (!test_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state))
3872 WARN_ON(btrfs_root_refs(&root->root_item) != 0);
3874 spin_lock(&root->inode_lock);
3876 node = root->inode_tree.rb_node;
3880 entry = rb_entry(node, struct btrfs_inode, rb_node);
3882 if (objectid < btrfs_ino(entry))
3883 node = node->rb_left;
3884 else if (objectid > btrfs_ino(entry))
3885 node = node->rb_right;
3891 entry = rb_entry(prev, struct btrfs_inode, rb_node);
3892 if (objectid <= btrfs_ino(entry)) {
3896 prev = rb_next(prev);
3900 entry = rb_entry(node, struct btrfs_inode, rb_node);
3901 objectid = btrfs_ino(entry) + 1;
3902 inode = igrab(&entry->vfs_inode);
3904 spin_unlock(&root->inode_lock);
3905 if (atomic_read(&inode->i_count) > 1)
3906 d_prune_aliases(inode);
3908 * btrfs_drop_inode will have it removed from the inode
3909 * cache when its usage count hits zero.
3913 spin_lock(&root->inode_lock);
3917 if (cond_resched_lock(&root->inode_lock))
3920 node = rb_next(node);
3922 spin_unlock(&root->inode_lock);
3925 int btrfs_delete_subvolume(struct inode *dir, struct dentry *dentry)
3927 struct btrfs_fs_info *fs_info = btrfs_sb(dentry->d_sb);
3928 struct btrfs_root *root = BTRFS_I(dir)->root;
3929 struct inode *inode = d_inode(dentry);
3930 struct btrfs_root *dest = BTRFS_I(inode)->root;
3931 struct btrfs_trans_handle *trans;
3932 struct btrfs_block_rsv block_rsv;
3938 * Don't allow to delete a subvolume with send in progress. This is
3939 * inside the inode lock so the error handling that has to drop the bit
3940 * again is not run concurrently.
3942 spin_lock(&dest->root_item_lock);
3943 if (dest->send_in_progress) {
3944 spin_unlock(&dest->root_item_lock);
3946 "attempt to delete subvolume %llu during send",
3947 dest->root_key.objectid);
3950 root_flags = btrfs_root_flags(&dest->root_item);
3951 btrfs_set_root_flags(&dest->root_item,
3952 root_flags | BTRFS_ROOT_SUBVOL_DEAD);
3953 spin_unlock(&dest->root_item_lock);
3955 down_write(&fs_info->subvol_sem);
3957 err = may_destroy_subvol(dest);
3961 btrfs_init_block_rsv(&block_rsv, BTRFS_BLOCK_RSV_TEMP);
3963 * One for dir inode,
3964 * two for dir entries,
3965 * two for root ref/backref.
3967 err = btrfs_subvolume_reserve_metadata(root, &block_rsv, 5, true);
3971 trans = btrfs_start_transaction(root, 0);
3972 if (IS_ERR(trans)) {
3973 err = PTR_ERR(trans);
3976 trans->block_rsv = &block_rsv;
3977 trans->bytes_reserved = block_rsv.size;
3979 btrfs_record_snapshot_destroy(trans, BTRFS_I(dir));
3981 ret = btrfs_unlink_subvol(trans, dir, dentry);
3984 btrfs_abort_transaction(trans, ret);
3988 btrfs_record_root_in_trans(trans, dest);
3990 memset(&dest->root_item.drop_progress, 0,
3991 sizeof(dest->root_item.drop_progress));
3992 dest->root_item.drop_level = 0;
3993 btrfs_set_root_refs(&dest->root_item, 0);
3995 if (!test_and_set_bit(BTRFS_ROOT_ORPHAN_ITEM_INSERTED, &dest->state)) {
3996 ret = btrfs_insert_orphan_item(trans,
3998 dest->root_key.objectid);
4000 btrfs_abort_transaction(trans, ret);
4006 ret = btrfs_uuid_tree_remove(trans, dest->root_item.uuid,
4007 BTRFS_UUID_KEY_SUBVOL,
4008 dest->root_key.objectid);
4009 if (ret && ret != -ENOENT) {
4010 btrfs_abort_transaction(trans, ret);
4014 if (!btrfs_is_empty_uuid(dest->root_item.received_uuid)) {
4015 ret = btrfs_uuid_tree_remove(trans,
4016 dest->root_item.received_uuid,
4017 BTRFS_UUID_KEY_RECEIVED_SUBVOL,
4018 dest->root_key.objectid);
4019 if (ret && ret != -ENOENT) {
4020 btrfs_abort_transaction(trans, ret);
4027 trans->block_rsv = NULL;
4028 trans->bytes_reserved = 0;
4029 ret = btrfs_end_transaction(trans);
4032 inode->i_flags |= S_DEAD;
4034 btrfs_subvolume_release_metadata(fs_info, &block_rsv);
4036 up_write(&fs_info->subvol_sem);
4038 spin_lock(&dest->root_item_lock);
4039 root_flags = btrfs_root_flags(&dest->root_item);
4040 btrfs_set_root_flags(&dest->root_item,
4041 root_flags & ~BTRFS_ROOT_SUBVOL_DEAD);
4042 spin_unlock(&dest->root_item_lock);
4044 d_invalidate(dentry);
4045 btrfs_prune_dentries(dest);
4046 ASSERT(dest->send_in_progress == 0);
4049 if (dest->ino_cache_inode) {
4050 iput(dest->ino_cache_inode);
4051 dest->ino_cache_inode = NULL;
4058 static int btrfs_rmdir(struct inode *dir, struct dentry *dentry)
4060 struct inode *inode = d_inode(dentry);
4062 struct btrfs_root *root = BTRFS_I(dir)->root;
4063 struct btrfs_trans_handle *trans;
4064 u64 last_unlink_trans;
4066 if (inode->i_size > BTRFS_EMPTY_DIR_SIZE)
4068 if (btrfs_ino(BTRFS_I(inode)) == BTRFS_FIRST_FREE_OBJECTID)
4069 return btrfs_delete_subvolume(dir, dentry);
4071 trans = __unlink_start_trans(dir);
4073 return PTR_ERR(trans);
4075 if (unlikely(btrfs_ino(BTRFS_I(inode)) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)) {
4076 err = btrfs_unlink_subvol(trans, dir, dentry);
4080 err = btrfs_orphan_add(trans, BTRFS_I(inode));
4084 last_unlink_trans = BTRFS_I(inode)->last_unlink_trans;
4086 /* now the directory is empty */
4087 err = btrfs_unlink_inode(trans, root, BTRFS_I(dir),
4088 BTRFS_I(d_inode(dentry)), dentry->d_name.name,
4089 dentry->d_name.len);
4091 btrfs_i_size_write(BTRFS_I(inode), 0);
4093 * Propagate the last_unlink_trans value of the deleted dir to
4094 * its parent directory. This is to prevent an unrecoverable
4095 * log tree in the case we do something like this:
4097 * 2) create snapshot under dir foo
4098 * 3) delete the snapshot
4101 * 6) fsync foo or some file inside foo
4103 if (last_unlink_trans >= trans->transid)
4104 BTRFS_I(dir)->last_unlink_trans = last_unlink_trans;
4107 btrfs_end_transaction(trans);
4108 btrfs_btree_balance_dirty(root->fs_info);
4114 * Return this if we need to call truncate_block for the last bit of the
4117 #define NEED_TRUNCATE_BLOCK 1
4120 * this can truncate away extent items, csum items and directory items.
4121 * It starts at a high offset and removes keys until it can't find
4122 * any higher than new_size
4124 * csum items that cross the new i_size are truncated to the new size
4127 * min_type is the minimum key type to truncate down to. If set to 0, this
4128 * will kill all the items on this inode, including the INODE_ITEM_KEY.
4130 int btrfs_truncate_inode_items(struct btrfs_trans_handle *trans,
4131 struct btrfs_root *root,
4132 struct inode *inode,
4133 u64 new_size, u32 min_type)
4135 struct btrfs_fs_info *fs_info = root->fs_info;
4136 struct btrfs_path *path;
4137 struct extent_buffer *leaf;
4138 struct btrfs_file_extent_item *fi;
4139 struct btrfs_key key;
4140 struct btrfs_key found_key;
4141 u64 extent_start = 0;
4142 u64 extent_num_bytes = 0;
4143 u64 extent_offset = 0;
4145 u64 last_size = new_size;
4146 u32 found_type = (u8)-1;
4149 int pending_del_nr = 0;
4150 int pending_del_slot = 0;
4151 int extent_type = -1;
4153 u64 ino = btrfs_ino(BTRFS_I(inode));
4154 u64 bytes_deleted = 0;
4155 bool be_nice = false;
4156 bool should_throttle = false;
4157 const u64 lock_start = ALIGN_DOWN(new_size, fs_info->sectorsize);
4158 struct extent_state *cached_state = NULL;
4160 BUG_ON(new_size > 0 && min_type != BTRFS_EXTENT_DATA_KEY);
4163 * For non-free space inodes and non-shareable roots, we want to back
4164 * off from time to time. This means all inodes in subvolume roots,
4165 * reloc roots, and data reloc roots.
4167 if (!btrfs_is_free_space_inode(BTRFS_I(inode)) &&
4168 test_bit(BTRFS_ROOT_SHAREABLE, &root->state))
4171 path = btrfs_alloc_path();
4174 path->reada = READA_BACK;
4176 if (root->root_key.objectid != BTRFS_TREE_LOG_OBJECTID) {
4177 lock_extent_bits(&BTRFS_I(inode)->io_tree, lock_start, (u64)-1,
4181 * We want to drop from the next block forward in case this
4182 * new size is not block aligned since we will be keeping the
4183 * last block of the extent just the way it is.
4185 btrfs_drop_extent_cache(BTRFS_I(inode), ALIGN(new_size,
4186 fs_info->sectorsize),
4191 * This function is also used to drop the items in the log tree before
4192 * we relog the inode, so if root != BTRFS_I(inode)->root, it means
4193 * it is used to drop the logged items. So we shouldn't kill the delayed
4196 if (min_type == 0 && root == BTRFS_I(inode)->root)
4197 btrfs_kill_delayed_inode_items(BTRFS_I(inode));
4200 key.offset = (u64)-1;
4205 * with a 16K leaf size and 128MB extents, you can actually queue
4206 * up a huge file in a single leaf. Most of the time that
4207 * bytes_deleted is > 0, it will be huge by the time we get here
4209 if (be_nice && bytes_deleted > SZ_32M &&
4210 btrfs_should_end_transaction(trans)) {
4215 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
4221 /* there are no items in the tree for us to truncate, we're
4224 if (path->slots[0] == 0)
4230 u64 clear_start = 0, clear_len = 0;
4233 leaf = path->nodes[0];
4234 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
4235 found_type = found_key.type;
4237 if (found_key.objectid != ino)
4240 if (found_type < min_type)
4243 item_end = found_key.offset;
4244 if (found_type == BTRFS_EXTENT_DATA_KEY) {
4245 fi = btrfs_item_ptr(leaf, path->slots[0],
4246 struct btrfs_file_extent_item);
4247 extent_type = btrfs_file_extent_type(leaf, fi);
4248 if (extent_type != BTRFS_FILE_EXTENT_INLINE) {
4250 btrfs_file_extent_num_bytes(leaf, fi);
4252 trace_btrfs_truncate_show_fi_regular(
4253 BTRFS_I(inode), leaf, fi,
4255 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
4256 item_end += btrfs_file_extent_ram_bytes(leaf,
4259 trace_btrfs_truncate_show_fi_inline(
4260 BTRFS_I(inode), leaf, fi, path->slots[0],
4265 if (found_type > min_type) {
4268 if (item_end < new_size)
4270 if (found_key.offset >= new_size)
4276 /* FIXME, shrink the extent if the ref count is only 1 */
4277 if (found_type != BTRFS_EXTENT_DATA_KEY)
4280 if (extent_type != BTRFS_FILE_EXTENT_INLINE) {
4283 clear_start = found_key.offset;
4284 extent_start = btrfs_file_extent_disk_bytenr(leaf, fi);
4286 u64 orig_num_bytes =
4287 btrfs_file_extent_num_bytes(leaf, fi);
4288 extent_num_bytes = ALIGN(new_size -
4290 fs_info->sectorsize);
4291 clear_start = ALIGN(new_size, fs_info->sectorsize);
4292 btrfs_set_file_extent_num_bytes(leaf, fi,
4294 num_dec = (orig_num_bytes -
4296 if (test_bit(BTRFS_ROOT_SHAREABLE,
4299 inode_sub_bytes(inode, num_dec);
4300 btrfs_mark_buffer_dirty(leaf);
4303 btrfs_file_extent_disk_num_bytes(leaf,
4305 extent_offset = found_key.offset -
4306 btrfs_file_extent_offset(leaf, fi);
4308 /* FIXME blocksize != 4096 */
4309 num_dec = btrfs_file_extent_num_bytes(leaf, fi);
4310 if (extent_start != 0) {
4312 if (test_bit(BTRFS_ROOT_SHAREABLE,
4314 inode_sub_bytes(inode, num_dec);
4317 clear_len = num_dec;
4318 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
4320 * we can't truncate inline items that have had
4324 btrfs_file_extent_encryption(leaf, fi) == 0 &&
4325 btrfs_file_extent_other_encoding(leaf, fi) == 0 &&
4326 btrfs_file_extent_compression(leaf, fi) == 0) {
4327 u32 size = (u32)(new_size - found_key.offset);
4329 btrfs_set_file_extent_ram_bytes(leaf, fi, size);
4330 size = btrfs_file_extent_calc_inline_size(size);
4331 btrfs_truncate_item(path, size, 1);
4332 } else if (!del_item) {
4334 * We have to bail so the last_size is set to
4335 * just before this extent.
4337 ret = NEED_TRUNCATE_BLOCK;
4341 * Inline extents are special, we just treat
4342 * them as a full sector worth in the file
4343 * extent tree just for simplicity sake.
4345 clear_len = fs_info->sectorsize;
4348 if (test_bit(BTRFS_ROOT_SHAREABLE, &root->state))
4349 inode_sub_bytes(inode, item_end + 1 - new_size);
4353 * We use btrfs_truncate_inode_items() to clean up log trees for
4354 * multiple fsyncs, and in this case we don't want to clear the
4355 * file extent range because it's just the log.
4357 if (root == BTRFS_I(inode)->root) {
4358 ret = btrfs_inode_clear_file_extent_range(BTRFS_I(inode),
4359 clear_start, clear_len);
4361 btrfs_abort_transaction(trans, ret);
4367 last_size = found_key.offset;
4369 last_size = new_size;
4371 if (!pending_del_nr) {
4372 /* no pending yet, add ourselves */
4373 pending_del_slot = path->slots[0];
4375 } else if (pending_del_nr &&
4376 path->slots[0] + 1 == pending_del_slot) {
4377 /* hop on the pending chunk */
4379 pending_del_slot = path->slots[0];
4386 should_throttle = false;
4389 root->root_key.objectid != BTRFS_TREE_LOG_OBJECTID) {
4390 struct btrfs_ref ref = { 0 };
4392 bytes_deleted += extent_num_bytes;
4394 btrfs_init_generic_ref(&ref, BTRFS_DROP_DELAYED_REF,
4395 extent_start, extent_num_bytes, 0);
4396 ref.real_root = root->root_key.objectid;
4397 btrfs_init_data_ref(&ref, btrfs_header_owner(leaf),
4398 ino, extent_offset);
4399 ret = btrfs_free_extent(trans, &ref);
4401 btrfs_abort_transaction(trans, ret);
4405 if (btrfs_should_throttle_delayed_refs(trans))
4406 should_throttle = true;
4410 if (found_type == BTRFS_INODE_ITEM_KEY)
4413 if (path->slots[0] == 0 ||
4414 path->slots[0] != pending_del_slot ||
4416 if (pending_del_nr) {
4417 ret = btrfs_del_items(trans, root, path,
4421 btrfs_abort_transaction(trans, ret);
4426 btrfs_release_path(path);
4429 * We can generate a lot of delayed refs, so we need to
4430 * throttle every once and a while and make sure we're
4431 * adding enough space to keep up with the work we are
4432 * generating. Since we hold a transaction here we
4433 * can't flush, and we don't want to FLUSH_LIMIT because
4434 * we could have generated too many delayed refs to
4435 * actually allocate, so just bail if we're short and
4436 * let the normal reservation dance happen higher up.
4438 if (should_throttle) {
4439 ret = btrfs_delayed_refs_rsv_refill(fs_info,
4440 BTRFS_RESERVE_NO_FLUSH);
4452 if (ret >= 0 && pending_del_nr) {
4455 err = btrfs_del_items(trans, root, path, pending_del_slot,
4458 btrfs_abort_transaction(trans, err);
4462 if (root->root_key.objectid != BTRFS_TREE_LOG_OBJECTID) {
4463 ASSERT(last_size >= new_size);
4464 if (!ret && last_size > new_size)
4465 last_size = new_size;
4466 btrfs_inode_safe_disk_i_size_write(inode, last_size);
4467 unlock_extent_cached(&BTRFS_I(inode)->io_tree, lock_start,
4468 (u64)-1, &cached_state);
4471 btrfs_free_path(path);
4476 * btrfs_truncate_block - read, zero a chunk and write a block
4477 * @inode - inode that we're zeroing
4478 * @from - the offset to start zeroing
4479 * @len - the length to zero, 0 to zero the entire range respective to the
4481 * @front - zero up to the offset instead of from the offset on
4483 * This will find the block for the "from" offset and cow the block and zero the
4484 * part we want to zero. This is used with truncate and hole punching.
4486 int btrfs_truncate_block(struct inode *inode, loff_t from, loff_t len,
4489 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
4490 struct address_space *mapping = inode->i_mapping;
4491 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
4492 struct btrfs_ordered_extent *ordered;
4493 struct extent_state *cached_state = NULL;
4494 struct extent_changeset *data_reserved = NULL;
4496 u32 blocksize = fs_info->sectorsize;
4497 pgoff_t index = from >> PAGE_SHIFT;
4498 unsigned offset = from & (blocksize - 1);
4500 gfp_t mask = btrfs_alloc_write_mask(mapping);
4505 if (IS_ALIGNED(offset, blocksize) &&
4506 (!len || IS_ALIGNED(len, blocksize)))
4509 block_start = round_down(from, blocksize);
4510 block_end = block_start + blocksize - 1;
4512 ret = btrfs_delalloc_reserve_space(inode, &data_reserved,
4513 block_start, blocksize);
4518 page = find_or_create_page(mapping, index, mask);
4520 btrfs_delalloc_release_space(inode, data_reserved,
4521 block_start, blocksize, true);
4522 btrfs_delalloc_release_extents(BTRFS_I(inode), blocksize);
4527 if (!PageUptodate(page)) {
4528 ret = btrfs_readpage(NULL, page);
4530 if (page->mapping != mapping) {
4535 if (!PageUptodate(page)) {
4540 wait_on_page_writeback(page);
4542 lock_extent_bits(io_tree, block_start, block_end, &cached_state);
4543 set_page_extent_mapped(page);
4545 ordered = btrfs_lookup_ordered_extent(inode, block_start);
4547 unlock_extent_cached(io_tree, block_start, block_end,
4551 btrfs_start_ordered_extent(inode, ordered, 1);
4552 btrfs_put_ordered_extent(ordered);
4556 clear_extent_bit(&BTRFS_I(inode)->io_tree, block_start, block_end,
4557 EXTENT_DELALLOC | EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG,
4558 0, 0, &cached_state);
4560 ret = btrfs_set_extent_delalloc(inode, block_start, block_end, 0,
4563 unlock_extent_cached(io_tree, block_start, block_end,
4568 if (offset != blocksize) {
4570 len = blocksize - offset;
4573 memset(kaddr + (block_start - page_offset(page)),
4576 memset(kaddr + (block_start - page_offset(page)) + offset,
4578 flush_dcache_page(page);
4581 ClearPageChecked(page);
4582 set_page_dirty(page);
4583 unlock_extent_cached(io_tree, block_start, block_end, &cached_state);
4587 btrfs_delalloc_release_space(inode, data_reserved, block_start,
4589 btrfs_delalloc_release_extents(BTRFS_I(inode), blocksize);
4593 extent_changeset_free(data_reserved);
4597 static int maybe_insert_hole(struct btrfs_root *root, struct inode *inode,
4598 u64 offset, u64 len)
4600 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
4601 struct btrfs_trans_handle *trans;
4605 * Still need to make sure the inode looks like it's been updated so
4606 * that any holes get logged if we fsync.
4608 if (btrfs_fs_incompat(fs_info, NO_HOLES)) {
4609 BTRFS_I(inode)->last_trans = fs_info->generation;
4610 BTRFS_I(inode)->last_sub_trans = root->log_transid;
4611 BTRFS_I(inode)->last_log_commit = root->last_log_commit;
4616 * 1 - for the one we're dropping
4617 * 1 - for the one we're adding
4618 * 1 - for updating the inode.
4620 trans = btrfs_start_transaction(root, 3);
4622 return PTR_ERR(trans);
4624 ret = btrfs_drop_extents(trans, root, inode, offset, offset + len, 1);
4626 btrfs_abort_transaction(trans, ret);
4627 btrfs_end_transaction(trans);
4631 ret = btrfs_insert_file_extent(trans, root, btrfs_ino(BTRFS_I(inode)),
4632 offset, 0, 0, len, 0, len, 0, 0, 0);
4634 btrfs_abort_transaction(trans, ret);
4636 btrfs_update_inode(trans, root, inode);
4637 btrfs_end_transaction(trans);
4642 * This function puts in dummy file extents for the area we're creating a hole
4643 * for. So if we are truncating this file to a larger size we need to insert
4644 * these file extents so that btrfs_get_extent will return a EXTENT_MAP_HOLE for
4645 * the range between oldsize and size
4647 int btrfs_cont_expand(struct inode *inode, loff_t oldsize, loff_t size)
4649 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
4650 struct btrfs_root *root = BTRFS_I(inode)->root;
4651 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
4652 struct extent_map *em = NULL;
4653 struct extent_state *cached_state = NULL;
4654 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
4655 u64 hole_start = ALIGN(oldsize, fs_info->sectorsize);
4656 u64 block_end = ALIGN(size, fs_info->sectorsize);
4663 * If our size started in the middle of a block we need to zero out the
4664 * rest of the block before we expand the i_size, otherwise we could
4665 * expose stale data.
4667 err = btrfs_truncate_block(inode, oldsize, 0, 0);
4671 if (size <= hole_start)
4674 btrfs_lock_and_flush_ordered_range(BTRFS_I(inode), hole_start,
4675 block_end - 1, &cached_state);
4676 cur_offset = hole_start;
4678 em = btrfs_get_extent(BTRFS_I(inode), NULL, 0, cur_offset,
4679 block_end - cur_offset);
4685 last_byte = min(extent_map_end(em), block_end);
4686 last_byte = ALIGN(last_byte, fs_info->sectorsize);
4687 hole_size = last_byte - cur_offset;
4689 if (!test_bit(EXTENT_FLAG_PREALLOC, &em->flags)) {
4690 struct extent_map *hole_em;
4692 err = maybe_insert_hole(root, inode, cur_offset,
4697 err = btrfs_inode_set_file_extent_range(BTRFS_I(inode),
4698 cur_offset, hole_size);
4702 btrfs_drop_extent_cache(BTRFS_I(inode), cur_offset,
4703 cur_offset + hole_size - 1, 0);
4704 hole_em = alloc_extent_map();
4706 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
4707 &BTRFS_I(inode)->runtime_flags);
4710 hole_em->start = cur_offset;
4711 hole_em->len = hole_size;
4712 hole_em->orig_start = cur_offset;
4714 hole_em->block_start = EXTENT_MAP_HOLE;
4715 hole_em->block_len = 0;
4716 hole_em->orig_block_len = 0;
4717 hole_em->ram_bytes = hole_size;
4718 hole_em->compress_type = BTRFS_COMPRESS_NONE;
4719 hole_em->generation = fs_info->generation;
4722 write_lock(&em_tree->lock);
4723 err = add_extent_mapping(em_tree, hole_em, 1);
4724 write_unlock(&em_tree->lock);
4727 btrfs_drop_extent_cache(BTRFS_I(inode),
4732 free_extent_map(hole_em);
4734 err = btrfs_inode_set_file_extent_range(BTRFS_I(inode),
4735 cur_offset, hole_size);
4740 free_extent_map(em);
4742 cur_offset = last_byte;
4743 if (cur_offset >= block_end)
4746 free_extent_map(em);
4747 unlock_extent_cached(io_tree, hole_start, block_end - 1, &cached_state);
4751 static int btrfs_setsize(struct inode *inode, struct iattr *attr)
4753 struct btrfs_root *root = BTRFS_I(inode)->root;
4754 struct btrfs_trans_handle *trans;
4755 loff_t oldsize = i_size_read(inode);
4756 loff_t newsize = attr->ia_size;
4757 int mask = attr->ia_valid;
4761 * The regular truncate() case without ATTR_CTIME and ATTR_MTIME is a
4762 * special case where we need to update the times despite not having
4763 * these flags set. For all other operations the VFS set these flags
4764 * explicitly if it wants a timestamp update.
4766 if (newsize != oldsize) {
4767 inode_inc_iversion(inode);
4768 if (!(mask & (ATTR_CTIME | ATTR_MTIME)))
4769 inode->i_ctime = inode->i_mtime =
4770 current_time(inode);
4773 if (newsize > oldsize) {
4775 * Don't do an expanding truncate while snapshotting is ongoing.
4776 * This is to ensure the snapshot captures a fully consistent
4777 * state of this file - if the snapshot captures this expanding
4778 * truncation, it must capture all writes that happened before
4781 btrfs_drew_write_lock(&root->snapshot_lock);
4782 ret = btrfs_cont_expand(inode, oldsize, newsize);
4784 btrfs_drew_write_unlock(&root->snapshot_lock);
4788 trans = btrfs_start_transaction(root, 1);
4789 if (IS_ERR(trans)) {
4790 btrfs_drew_write_unlock(&root->snapshot_lock);
4791 return PTR_ERR(trans);
4794 i_size_write(inode, newsize);
4795 btrfs_inode_safe_disk_i_size_write(inode, 0);
4796 pagecache_isize_extended(inode, oldsize, newsize);
4797 ret = btrfs_update_inode(trans, root, inode);
4798 btrfs_drew_write_unlock(&root->snapshot_lock);
4799 btrfs_end_transaction(trans);
4803 * We're truncating a file that used to have good data down to
4804 * zero. Make sure it gets into the ordered flush list so that
4805 * any new writes get down to disk quickly.
4808 set_bit(BTRFS_INODE_ORDERED_DATA_CLOSE,
4809 &BTRFS_I(inode)->runtime_flags);
4811 truncate_setsize(inode, newsize);
4813 inode_dio_wait(inode);
4815 ret = btrfs_truncate(inode, newsize == oldsize);
4816 if (ret && inode->i_nlink) {
4820 * Truncate failed, so fix up the in-memory size. We
4821 * adjusted disk_i_size down as we removed extents, so
4822 * wait for disk_i_size to be stable and then update the
4823 * in-memory size to match.
4825 err = btrfs_wait_ordered_range(inode, 0, (u64)-1);
4828 i_size_write(inode, BTRFS_I(inode)->disk_i_size);
4835 static int btrfs_setattr(struct dentry *dentry, struct iattr *attr)
4837 struct inode *inode = d_inode(dentry);
4838 struct btrfs_root *root = BTRFS_I(inode)->root;
4841 if (btrfs_root_readonly(root))
4844 err = setattr_prepare(dentry, attr);
4848 if (S_ISREG(inode->i_mode) && (attr->ia_valid & ATTR_SIZE)) {
4849 err = btrfs_setsize(inode, attr);
4854 if (attr->ia_valid) {
4855 setattr_copy(inode, attr);
4856 inode_inc_iversion(inode);
4857 err = btrfs_dirty_inode(inode);
4859 if (!err && attr->ia_valid & ATTR_MODE)
4860 err = posix_acl_chmod(inode, inode->i_mode);
4867 * While truncating the inode pages during eviction, we get the VFS calling
4868 * btrfs_invalidatepage() against each page of the inode. This is slow because
4869 * the calls to btrfs_invalidatepage() result in a huge amount of calls to
4870 * lock_extent_bits() and clear_extent_bit(), which keep merging and splitting
4871 * extent_state structures over and over, wasting lots of time.
4873 * Therefore if the inode is being evicted, let btrfs_invalidatepage() skip all
4874 * those expensive operations on a per page basis and do only the ordered io
4875 * finishing, while we release here the extent_map and extent_state structures,
4876 * without the excessive merging and splitting.
4878 static void evict_inode_truncate_pages(struct inode *inode)
4880 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
4881 struct extent_map_tree *map_tree = &BTRFS_I(inode)->extent_tree;
4882 struct rb_node *node;
4884 ASSERT(inode->i_state & I_FREEING);
4885 truncate_inode_pages_final(&inode->i_data);
4887 write_lock(&map_tree->lock);
4888 while (!RB_EMPTY_ROOT(&map_tree->map.rb_root)) {
4889 struct extent_map *em;
4891 node = rb_first_cached(&map_tree->map);
4892 em = rb_entry(node, struct extent_map, rb_node);
4893 clear_bit(EXTENT_FLAG_PINNED, &em->flags);
4894 clear_bit(EXTENT_FLAG_LOGGING, &em->flags);
4895 remove_extent_mapping(map_tree, em);
4896 free_extent_map(em);
4897 if (need_resched()) {
4898 write_unlock(&map_tree->lock);
4900 write_lock(&map_tree->lock);
4903 write_unlock(&map_tree->lock);
4906 * Keep looping until we have no more ranges in the io tree.
4907 * We can have ongoing bios started by readahead that have
4908 * their endio callback (extent_io.c:end_bio_extent_readpage)
4909 * still in progress (unlocked the pages in the bio but did not yet
4910 * unlocked the ranges in the io tree). Therefore this means some
4911 * ranges can still be locked and eviction started because before
4912 * submitting those bios, which are executed by a separate task (work
4913 * queue kthread), inode references (inode->i_count) were not taken
4914 * (which would be dropped in the end io callback of each bio).
4915 * Therefore here we effectively end up waiting for those bios and
4916 * anyone else holding locked ranges without having bumped the inode's
4917 * reference count - if we don't do it, when they access the inode's
4918 * io_tree to unlock a range it may be too late, leading to an
4919 * use-after-free issue.
4921 spin_lock(&io_tree->lock);
4922 while (!RB_EMPTY_ROOT(&io_tree->state)) {
4923 struct extent_state *state;
4924 struct extent_state *cached_state = NULL;
4927 unsigned state_flags;
4929 node = rb_first(&io_tree->state);
4930 state = rb_entry(node, struct extent_state, rb_node);
4931 start = state->start;
4933 state_flags = state->state;
4934 spin_unlock(&io_tree->lock);
4936 lock_extent_bits(io_tree, start, end, &cached_state);
4939 * If still has DELALLOC flag, the extent didn't reach disk,
4940 * and its reserved space won't be freed by delayed_ref.
4941 * So we need to free its reserved space here.
4942 * (Refer to comment in btrfs_invalidatepage, case 2)
4944 * Note, end is the bytenr of last byte, so we need + 1 here.
4946 if (state_flags & EXTENT_DELALLOC)
4947 btrfs_qgroup_free_data(inode, NULL, start, end - start + 1);
4949 clear_extent_bit(io_tree, start, end,
4950 EXTENT_LOCKED | EXTENT_DELALLOC |
4951 EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG, 1, 1,
4955 spin_lock(&io_tree->lock);
4957 spin_unlock(&io_tree->lock);
4960 static struct btrfs_trans_handle *evict_refill_and_join(struct btrfs_root *root,
4961 struct btrfs_block_rsv *rsv)
4963 struct btrfs_fs_info *fs_info = root->fs_info;
4964 struct btrfs_block_rsv *global_rsv = &fs_info->global_block_rsv;
4965 struct btrfs_trans_handle *trans;
4966 u64 delayed_refs_extra = btrfs_calc_insert_metadata_size(fs_info, 1);
4970 * Eviction should be taking place at some place safe because of our
4971 * delayed iputs. However the normal flushing code will run delayed
4972 * iputs, so we cannot use FLUSH_ALL otherwise we'll deadlock.
4974 * We reserve the delayed_refs_extra here again because we can't use
4975 * btrfs_start_transaction(root, 0) for the same deadlocky reason as
4976 * above. We reserve our extra bit here because we generate a ton of
4977 * delayed refs activity by truncating.
4979 * If we cannot make our reservation we'll attempt to steal from the
4980 * global reserve, because we really want to be able to free up space.
4982 ret = btrfs_block_rsv_refill(root, rsv, rsv->size + delayed_refs_extra,
4983 BTRFS_RESERVE_FLUSH_EVICT);
4986 * Try to steal from the global reserve if there is space for
4989 if (btrfs_check_space_for_delayed_refs(fs_info) ||
4990 btrfs_block_rsv_migrate(global_rsv, rsv, rsv->size, 0)) {
4992 "could not allocate space for delete; will truncate on mount");
4993 return ERR_PTR(-ENOSPC);
4995 delayed_refs_extra = 0;
4998 trans = btrfs_join_transaction(root);
5002 if (delayed_refs_extra) {
5003 trans->block_rsv = &fs_info->trans_block_rsv;
5004 trans->bytes_reserved = delayed_refs_extra;
5005 btrfs_block_rsv_migrate(rsv, trans->block_rsv,
5006 delayed_refs_extra, 1);
5011 void btrfs_evict_inode(struct inode *inode)
5013 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
5014 struct btrfs_trans_handle *trans;
5015 struct btrfs_root *root = BTRFS_I(inode)->root;
5016 struct btrfs_block_rsv *rsv;
5019 trace_btrfs_inode_evict(inode);
5026 evict_inode_truncate_pages(inode);
5028 if (inode->i_nlink &&
5029 ((btrfs_root_refs(&root->root_item) != 0 &&
5030 root->root_key.objectid != BTRFS_ROOT_TREE_OBJECTID) ||
5031 btrfs_is_free_space_inode(BTRFS_I(inode))))
5034 if (is_bad_inode(inode))
5037 btrfs_free_io_failure_record(BTRFS_I(inode), 0, (u64)-1);
5039 if (test_bit(BTRFS_FS_LOG_RECOVERING, &fs_info->flags))
5042 if (inode->i_nlink > 0) {
5043 BUG_ON(btrfs_root_refs(&root->root_item) != 0 &&
5044 root->root_key.objectid != BTRFS_ROOT_TREE_OBJECTID);
5048 ret = btrfs_commit_inode_delayed_inode(BTRFS_I(inode));
5052 rsv = btrfs_alloc_block_rsv(fs_info, BTRFS_BLOCK_RSV_TEMP);
5055 rsv->size = btrfs_calc_metadata_size(fs_info, 1);
5058 btrfs_i_size_write(BTRFS_I(inode), 0);
5061 trans = evict_refill_and_join(root, rsv);
5065 trans->block_rsv = rsv;
5067 ret = btrfs_truncate_inode_items(trans, root, inode, 0, 0);
5068 trans->block_rsv = &fs_info->trans_block_rsv;
5069 btrfs_end_transaction(trans);
5070 btrfs_btree_balance_dirty(fs_info);
5071 if (ret && ret != -ENOSPC && ret != -EAGAIN)
5078 * Errors here aren't a big deal, it just means we leave orphan items in
5079 * the tree. They will be cleaned up on the next mount. If the inode
5080 * number gets reused, cleanup deletes the orphan item without doing
5081 * anything, and unlink reuses the existing orphan item.
5083 * If it turns out that we are dropping too many of these, we might want
5084 * to add a mechanism for retrying these after a commit.
5086 trans = evict_refill_and_join(root, rsv);
5087 if (!IS_ERR(trans)) {
5088 trans->block_rsv = rsv;
5089 btrfs_orphan_del(trans, BTRFS_I(inode));
5090 trans->block_rsv = &fs_info->trans_block_rsv;
5091 btrfs_end_transaction(trans);
5094 if (!(root == fs_info->tree_root ||
5095 root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID))
5096 btrfs_return_ino(root, btrfs_ino(BTRFS_I(inode)));
5099 btrfs_free_block_rsv(fs_info, rsv);
5102 * If we didn't successfully delete, the orphan item will still be in
5103 * the tree and we'll retry on the next mount. Again, we might also want
5104 * to retry these periodically in the future.
5106 btrfs_remove_delayed_node(BTRFS_I(inode));
5111 * Return the key found in the dir entry in the location pointer, fill @type
5112 * with BTRFS_FT_*, and return 0.
5114 * If no dir entries were found, returns -ENOENT.
5115 * If found a corrupted location in dir entry, returns -EUCLEAN.
5117 static int btrfs_inode_by_name(struct inode *dir, struct dentry *dentry,
5118 struct btrfs_key *location, u8 *type)
5120 const char *name = dentry->d_name.name;
5121 int namelen = dentry->d_name.len;
5122 struct btrfs_dir_item *di;
5123 struct btrfs_path *path;
5124 struct btrfs_root *root = BTRFS_I(dir)->root;
5127 path = btrfs_alloc_path();
5131 di = btrfs_lookup_dir_item(NULL, root, path, btrfs_ino(BTRFS_I(dir)),
5133 if (IS_ERR_OR_NULL(di)) {
5134 ret = di ? PTR_ERR(di) : -ENOENT;
5138 btrfs_dir_item_key_to_cpu(path->nodes[0], di, location);
5139 if (location->type != BTRFS_INODE_ITEM_KEY &&
5140 location->type != BTRFS_ROOT_ITEM_KEY) {
5142 btrfs_warn(root->fs_info,
5143 "%s gets something invalid in DIR_ITEM (name %s, directory ino %llu, location(%llu %u %llu))",
5144 __func__, name, btrfs_ino(BTRFS_I(dir)),
5145 location->objectid, location->type, location->offset);
5148 *type = btrfs_dir_type(path->nodes[0], di);
5150 btrfs_free_path(path);
5155 * when we hit a tree root in a directory, the btrfs part of the inode
5156 * needs to be changed to reflect the root directory of the tree root. This
5157 * is kind of like crossing a mount point.
5159 static int fixup_tree_root_location(struct btrfs_fs_info *fs_info,
5161 struct dentry *dentry,
5162 struct btrfs_key *location,
5163 struct btrfs_root **sub_root)
5165 struct btrfs_path *path;
5166 struct btrfs_root *new_root;
5167 struct btrfs_root_ref *ref;
5168 struct extent_buffer *leaf;
5169 struct btrfs_key key;
5173 path = btrfs_alloc_path();
5180 key.objectid = BTRFS_I(dir)->root->root_key.objectid;
5181 key.type = BTRFS_ROOT_REF_KEY;
5182 key.offset = location->objectid;
5184 ret = btrfs_search_slot(NULL, fs_info->tree_root, &key, path, 0, 0);
5191 leaf = path->nodes[0];
5192 ref = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_root_ref);
5193 if (btrfs_root_ref_dirid(leaf, ref) != btrfs_ino(BTRFS_I(dir)) ||
5194 btrfs_root_ref_name_len(leaf, ref) != dentry->d_name.len)
5197 ret = memcmp_extent_buffer(leaf, dentry->d_name.name,
5198 (unsigned long)(ref + 1),
5199 dentry->d_name.len);
5203 btrfs_release_path(path);
5205 new_root = btrfs_get_fs_root(fs_info, location->objectid, true);
5206 if (IS_ERR(new_root)) {
5207 err = PTR_ERR(new_root);
5211 *sub_root = new_root;
5212 location->objectid = btrfs_root_dirid(&new_root->root_item);
5213 location->type = BTRFS_INODE_ITEM_KEY;
5214 location->offset = 0;
5217 btrfs_free_path(path);
5221 static void inode_tree_add(struct inode *inode)
5223 struct btrfs_root *root = BTRFS_I(inode)->root;
5224 struct btrfs_inode *entry;
5226 struct rb_node *parent;
5227 struct rb_node *new = &BTRFS_I(inode)->rb_node;
5228 u64 ino = btrfs_ino(BTRFS_I(inode));
5230 if (inode_unhashed(inode))
5233 spin_lock(&root->inode_lock);
5234 p = &root->inode_tree.rb_node;
5237 entry = rb_entry(parent, struct btrfs_inode, rb_node);
5239 if (ino < btrfs_ino(entry))
5240 p = &parent->rb_left;
5241 else if (ino > btrfs_ino(entry))
5242 p = &parent->rb_right;
5244 WARN_ON(!(entry->vfs_inode.i_state &
5245 (I_WILL_FREE | I_FREEING)));
5246 rb_replace_node(parent, new, &root->inode_tree);
5247 RB_CLEAR_NODE(parent);
5248 spin_unlock(&root->inode_lock);
5252 rb_link_node(new, parent, p);
5253 rb_insert_color(new, &root->inode_tree);
5254 spin_unlock(&root->inode_lock);
5257 static void inode_tree_del(struct inode *inode)
5259 struct btrfs_root *root = BTRFS_I(inode)->root;
5262 spin_lock(&root->inode_lock);
5263 if (!RB_EMPTY_NODE(&BTRFS_I(inode)->rb_node)) {
5264 rb_erase(&BTRFS_I(inode)->rb_node, &root->inode_tree);
5265 RB_CLEAR_NODE(&BTRFS_I(inode)->rb_node);
5266 empty = RB_EMPTY_ROOT(&root->inode_tree);
5268 spin_unlock(&root->inode_lock);
5270 if (empty && btrfs_root_refs(&root->root_item) == 0) {
5271 spin_lock(&root->inode_lock);
5272 empty = RB_EMPTY_ROOT(&root->inode_tree);
5273 spin_unlock(&root->inode_lock);
5275 btrfs_add_dead_root(root);
5280 static int btrfs_init_locked_inode(struct inode *inode, void *p)
5282 struct btrfs_iget_args *args = p;
5284 inode->i_ino = args->ino;
5285 BTRFS_I(inode)->location.objectid = args->ino;
5286 BTRFS_I(inode)->location.type = BTRFS_INODE_ITEM_KEY;
5287 BTRFS_I(inode)->location.offset = 0;
5288 BTRFS_I(inode)->root = btrfs_grab_root(args->root);
5289 BUG_ON(args->root && !BTRFS_I(inode)->root);
5293 static int btrfs_find_actor(struct inode *inode, void *opaque)
5295 struct btrfs_iget_args *args = opaque;
5297 return args->ino == BTRFS_I(inode)->location.objectid &&
5298 args->root == BTRFS_I(inode)->root;
5301 static struct inode *btrfs_iget_locked(struct super_block *s, u64 ino,
5302 struct btrfs_root *root)
5304 struct inode *inode;
5305 struct btrfs_iget_args args;
5306 unsigned long hashval = btrfs_inode_hash(ino, root);
5311 inode = iget5_locked(s, hashval, btrfs_find_actor,
5312 btrfs_init_locked_inode,
5318 * Get an inode object given its inode number and corresponding root.
5319 * Path can be preallocated to prevent recursing back to iget through
5320 * allocator. NULL is also valid but may require an additional allocation
5323 struct inode *btrfs_iget_path(struct super_block *s, u64 ino,
5324 struct btrfs_root *root, struct btrfs_path *path)
5326 struct inode *inode;
5328 inode = btrfs_iget_locked(s, ino, root);
5330 return ERR_PTR(-ENOMEM);
5332 if (inode->i_state & I_NEW) {
5335 ret = btrfs_read_locked_inode(inode, path);
5337 inode_tree_add(inode);
5338 unlock_new_inode(inode);
5342 * ret > 0 can come from btrfs_search_slot called by
5343 * btrfs_read_locked_inode, this means the inode item
5348 inode = ERR_PTR(ret);
5355 struct inode *btrfs_iget(struct super_block *s, u64 ino, struct btrfs_root *root)
5357 return btrfs_iget_path(s, ino, root, NULL);
5360 static struct inode *new_simple_dir(struct super_block *s,
5361 struct btrfs_key *key,
5362 struct btrfs_root *root)
5364 struct inode *inode = new_inode(s);
5367 return ERR_PTR(-ENOMEM);
5369 BTRFS_I(inode)->root = btrfs_grab_root(root);
5370 memcpy(&BTRFS_I(inode)->location, key, sizeof(*key));
5371 set_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags);
5373 inode->i_ino = BTRFS_EMPTY_SUBVOL_DIR_OBJECTID;
5375 * We only need lookup, the rest is read-only and there's no inode
5376 * associated with the dentry
5378 inode->i_op = &simple_dir_inode_operations;
5379 inode->i_opflags &= ~IOP_XATTR;
5380 inode->i_fop = &simple_dir_operations;
5381 inode->i_mode = S_IFDIR | S_IRUGO | S_IWUSR | S_IXUGO;
5382 inode->i_mtime = current_time(inode);
5383 inode->i_atime = inode->i_mtime;
5384 inode->i_ctime = inode->i_mtime;
5385 BTRFS_I(inode)->i_otime = inode->i_mtime;
5390 static inline u8 btrfs_inode_type(struct inode *inode)
5393 * Compile-time asserts that generic FT_* types still match
5396 BUILD_BUG_ON(BTRFS_FT_UNKNOWN != FT_UNKNOWN);
5397 BUILD_BUG_ON(BTRFS_FT_REG_FILE != FT_REG_FILE);
5398 BUILD_BUG_ON(BTRFS_FT_DIR != FT_DIR);
5399 BUILD_BUG_ON(BTRFS_FT_CHRDEV != FT_CHRDEV);
5400 BUILD_BUG_ON(BTRFS_FT_BLKDEV != FT_BLKDEV);
5401 BUILD_BUG_ON(BTRFS_FT_FIFO != FT_FIFO);
5402 BUILD_BUG_ON(BTRFS_FT_SOCK != FT_SOCK);
5403 BUILD_BUG_ON(BTRFS_FT_SYMLINK != FT_SYMLINK);
5405 return fs_umode_to_ftype(inode->i_mode);
5408 struct inode *btrfs_lookup_dentry(struct inode *dir, struct dentry *dentry)
5410 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
5411 struct inode *inode;
5412 struct btrfs_root *root = BTRFS_I(dir)->root;
5413 struct btrfs_root *sub_root = root;
5414 struct btrfs_key location;
5418 if (dentry->d_name.len > BTRFS_NAME_LEN)
5419 return ERR_PTR(-ENAMETOOLONG);
5421 ret = btrfs_inode_by_name(dir, dentry, &location, &di_type);
5423 return ERR_PTR(ret);
5425 if (location.type == BTRFS_INODE_ITEM_KEY) {
5426 inode = btrfs_iget(dir->i_sb, location.objectid, root);
5430 /* Do extra check against inode mode with di_type */
5431 if (btrfs_inode_type(inode) != di_type) {
5433 "inode mode mismatch with dir: inode mode=0%o btrfs type=%u dir type=%u",
5434 inode->i_mode, btrfs_inode_type(inode),
5437 return ERR_PTR(-EUCLEAN);
5442 ret = fixup_tree_root_location(fs_info, dir, dentry,
5443 &location, &sub_root);
5446 inode = ERR_PTR(ret);
5448 inode = new_simple_dir(dir->i_sb, &location, sub_root);
5450 inode = btrfs_iget(dir->i_sb, location.objectid, sub_root);
5452 if (root != sub_root)
5453 btrfs_put_root(sub_root);
5455 if (!IS_ERR(inode) && root != sub_root) {
5456 down_read(&fs_info->cleanup_work_sem);
5457 if (!sb_rdonly(inode->i_sb))
5458 ret = btrfs_orphan_cleanup(sub_root);
5459 up_read(&fs_info->cleanup_work_sem);
5462 inode = ERR_PTR(ret);
5469 static int btrfs_dentry_delete(const struct dentry *dentry)
5471 struct btrfs_root *root;
5472 struct inode *inode = d_inode(dentry);
5474 if (!inode && !IS_ROOT(dentry))
5475 inode = d_inode(dentry->d_parent);
5478 root = BTRFS_I(inode)->root;
5479 if (btrfs_root_refs(&root->root_item) == 0)
5482 if (btrfs_ino(BTRFS_I(inode)) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)
5488 static struct dentry *btrfs_lookup(struct inode *dir, struct dentry *dentry,
5491 struct inode *inode = btrfs_lookup_dentry(dir, dentry);
5493 if (inode == ERR_PTR(-ENOENT))
5495 return d_splice_alias(inode, dentry);
5499 * All this infrastructure exists because dir_emit can fault, and we are holding
5500 * the tree lock when doing readdir. For now just allocate a buffer and copy
5501 * our information into that, and then dir_emit from the buffer. This is
5502 * similar to what NFS does, only we don't keep the buffer around in pagecache
5503 * because I'm afraid I'll mess that up. Long term we need to make filldir do
5504 * copy_to_user_inatomic so we don't have to worry about page faulting under the
5507 static int btrfs_opendir(struct inode *inode, struct file *file)
5509 struct btrfs_file_private *private;
5511 private = kzalloc(sizeof(struct btrfs_file_private), GFP_KERNEL);
5514 private->filldir_buf = kzalloc(PAGE_SIZE, GFP_KERNEL);
5515 if (!private->filldir_buf) {
5519 file->private_data = private;
5530 static int btrfs_filldir(void *addr, int entries, struct dir_context *ctx)
5533 struct dir_entry *entry = addr;
5534 char *name = (char *)(entry + 1);
5536 ctx->pos = get_unaligned(&entry->offset);
5537 if (!dir_emit(ctx, name, get_unaligned(&entry->name_len),
5538 get_unaligned(&entry->ino),
5539 get_unaligned(&entry->type)))
5541 addr += sizeof(struct dir_entry) +
5542 get_unaligned(&entry->name_len);
5548 static int btrfs_real_readdir(struct file *file, struct dir_context *ctx)
5550 struct inode *inode = file_inode(file);
5551 struct btrfs_root *root = BTRFS_I(inode)->root;
5552 struct btrfs_file_private *private = file->private_data;
5553 struct btrfs_dir_item *di;
5554 struct btrfs_key key;
5555 struct btrfs_key found_key;
5556 struct btrfs_path *path;
5558 struct list_head ins_list;
5559 struct list_head del_list;
5561 struct extent_buffer *leaf;
5568 struct btrfs_key location;
5570 if (!dir_emit_dots(file, ctx))
5573 path = btrfs_alloc_path();
5577 addr = private->filldir_buf;
5578 path->reada = READA_FORWARD;
5580 INIT_LIST_HEAD(&ins_list);
5581 INIT_LIST_HEAD(&del_list);
5582 put = btrfs_readdir_get_delayed_items(inode, &ins_list, &del_list);
5585 key.type = BTRFS_DIR_INDEX_KEY;
5586 key.offset = ctx->pos;
5587 key.objectid = btrfs_ino(BTRFS_I(inode));
5589 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
5594 struct dir_entry *entry;
5596 leaf = path->nodes[0];
5597 slot = path->slots[0];
5598 if (slot >= btrfs_header_nritems(leaf)) {
5599 ret = btrfs_next_leaf(root, path);
5607 btrfs_item_key_to_cpu(leaf, &found_key, slot);
5609 if (found_key.objectid != key.objectid)
5611 if (found_key.type != BTRFS_DIR_INDEX_KEY)
5613 if (found_key.offset < ctx->pos)
5615 if (btrfs_should_delete_dir_index(&del_list, found_key.offset))
5617 di = btrfs_item_ptr(leaf, slot, struct btrfs_dir_item);
5618 name_len = btrfs_dir_name_len(leaf, di);
5619 if ((total_len + sizeof(struct dir_entry) + name_len) >=
5621 btrfs_release_path(path);
5622 ret = btrfs_filldir(private->filldir_buf, entries, ctx);
5625 addr = private->filldir_buf;
5632 put_unaligned(name_len, &entry->name_len);
5633 name_ptr = (char *)(entry + 1);
5634 read_extent_buffer(leaf, name_ptr, (unsigned long)(di + 1),
5636 put_unaligned(fs_ftype_to_dtype(btrfs_dir_type(leaf, di)),
5638 btrfs_dir_item_key_to_cpu(leaf, di, &location);
5639 put_unaligned(location.objectid, &entry->ino);
5640 put_unaligned(found_key.offset, &entry->offset);
5642 addr += sizeof(struct dir_entry) + name_len;
5643 total_len += sizeof(struct dir_entry) + name_len;
5647 btrfs_release_path(path);
5649 ret = btrfs_filldir(private->filldir_buf, entries, ctx);
5653 ret = btrfs_readdir_delayed_dir_index(ctx, &ins_list);
5658 * Stop new entries from being returned after we return the last
5661 * New directory entries are assigned a strictly increasing
5662 * offset. This means that new entries created during readdir
5663 * are *guaranteed* to be seen in the future by that readdir.
5664 * This has broken buggy programs which operate on names as
5665 * they're returned by readdir. Until we re-use freed offsets
5666 * we have this hack to stop new entries from being returned
5667 * under the assumption that they'll never reach this huge
5670 * This is being careful not to overflow 32bit loff_t unless the
5671 * last entry requires it because doing so has broken 32bit apps
5674 if (ctx->pos >= INT_MAX)
5675 ctx->pos = LLONG_MAX;
5682 btrfs_readdir_put_delayed_items(inode, &ins_list, &del_list);
5683 btrfs_free_path(path);
5688 * This is somewhat expensive, updating the tree every time the
5689 * inode changes. But, it is most likely to find the inode in cache.
5690 * FIXME, needs more benchmarking...there are no reasons other than performance
5691 * to keep or drop this code.
5693 static int btrfs_dirty_inode(struct inode *inode)
5695 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
5696 struct btrfs_root *root = BTRFS_I(inode)->root;
5697 struct btrfs_trans_handle *trans;
5700 if (test_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags))
5703 trans = btrfs_join_transaction(root);
5705 return PTR_ERR(trans);
5707 ret = btrfs_update_inode(trans, root, inode);
5708 if (ret && ret == -ENOSPC) {
5709 /* whoops, lets try again with the full transaction */
5710 btrfs_end_transaction(trans);
5711 trans = btrfs_start_transaction(root, 1);
5713 return PTR_ERR(trans);
5715 ret = btrfs_update_inode(trans, root, inode);
5717 btrfs_end_transaction(trans);
5718 if (BTRFS_I(inode)->delayed_node)
5719 btrfs_balance_delayed_items(fs_info);
5725 * This is a copy of file_update_time. We need this so we can return error on
5726 * ENOSPC for updating the inode in the case of file write and mmap writes.
5728 static int btrfs_update_time(struct inode *inode, struct timespec64 *now,
5731 struct btrfs_root *root = BTRFS_I(inode)->root;
5732 bool dirty = flags & ~S_VERSION;
5734 if (btrfs_root_readonly(root))
5737 if (flags & S_VERSION)
5738 dirty |= inode_maybe_inc_iversion(inode, dirty);
5739 if (flags & S_CTIME)
5740 inode->i_ctime = *now;
5741 if (flags & S_MTIME)
5742 inode->i_mtime = *now;
5743 if (flags & S_ATIME)
5744 inode->i_atime = *now;
5745 return dirty ? btrfs_dirty_inode(inode) : 0;
5749 * find the highest existing sequence number in a directory
5750 * and then set the in-memory index_cnt variable to reflect
5751 * free sequence numbers
5753 static int btrfs_set_inode_index_count(struct btrfs_inode *inode)
5755 struct btrfs_root *root = inode->root;
5756 struct btrfs_key key, found_key;
5757 struct btrfs_path *path;
5758 struct extent_buffer *leaf;
5761 key.objectid = btrfs_ino(inode);
5762 key.type = BTRFS_DIR_INDEX_KEY;
5763 key.offset = (u64)-1;
5765 path = btrfs_alloc_path();
5769 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
5772 /* FIXME: we should be able to handle this */
5778 * MAGIC NUMBER EXPLANATION:
5779 * since we search a directory based on f_pos we have to start at 2
5780 * since '.' and '..' have f_pos of 0 and 1 respectively, so everybody
5781 * else has to start at 2
5783 if (path->slots[0] == 0) {
5784 inode->index_cnt = 2;
5790 leaf = path->nodes[0];
5791 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
5793 if (found_key.objectid != btrfs_ino(inode) ||
5794 found_key.type != BTRFS_DIR_INDEX_KEY) {
5795 inode->index_cnt = 2;
5799 inode->index_cnt = found_key.offset + 1;
5801 btrfs_free_path(path);
5806 * helper to find a free sequence number in a given directory. This current
5807 * code is very simple, later versions will do smarter things in the btree
5809 int btrfs_set_inode_index(struct btrfs_inode *dir, u64 *index)
5813 if (dir->index_cnt == (u64)-1) {
5814 ret = btrfs_inode_delayed_dir_index_count(dir);
5816 ret = btrfs_set_inode_index_count(dir);
5822 *index = dir->index_cnt;
5828 static int btrfs_insert_inode_locked(struct inode *inode)
5830 struct btrfs_iget_args args;
5832 args.ino = BTRFS_I(inode)->location.objectid;
5833 args.root = BTRFS_I(inode)->root;
5835 return insert_inode_locked4(inode,
5836 btrfs_inode_hash(inode->i_ino, BTRFS_I(inode)->root),
5837 btrfs_find_actor, &args);
5841 * Inherit flags from the parent inode.
5843 * Currently only the compression flags and the cow flags are inherited.
5845 static void btrfs_inherit_iflags(struct inode *inode, struct inode *dir)
5852 flags = BTRFS_I(dir)->flags;
5854 if (flags & BTRFS_INODE_NOCOMPRESS) {
5855 BTRFS_I(inode)->flags &= ~BTRFS_INODE_COMPRESS;
5856 BTRFS_I(inode)->flags |= BTRFS_INODE_NOCOMPRESS;
5857 } else if (flags & BTRFS_INODE_COMPRESS) {
5858 BTRFS_I(inode)->flags &= ~BTRFS_INODE_NOCOMPRESS;
5859 BTRFS_I(inode)->flags |= BTRFS_INODE_COMPRESS;
5862 if (flags & BTRFS_INODE_NODATACOW) {
5863 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATACOW;
5864 if (S_ISREG(inode->i_mode))
5865 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATASUM;
5868 btrfs_sync_inode_flags_to_i_flags(inode);
5871 static struct inode *btrfs_new_inode(struct btrfs_trans_handle *trans,
5872 struct btrfs_root *root,
5874 const char *name, int name_len,
5875 u64 ref_objectid, u64 objectid,
5876 umode_t mode, u64 *index)
5878 struct btrfs_fs_info *fs_info = root->fs_info;
5879 struct inode *inode;
5880 struct btrfs_inode_item *inode_item;
5881 struct btrfs_key *location;
5882 struct btrfs_path *path;
5883 struct btrfs_inode_ref *ref;
5884 struct btrfs_key key[2];
5886 int nitems = name ? 2 : 1;
5888 unsigned int nofs_flag;
5891 path = btrfs_alloc_path();
5893 return ERR_PTR(-ENOMEM);
5895 nofs_flag = memalloc_nofs_save();
5896 inode = new_inode(fs_info->sb);
5897 memalloc_nofs_restore(nofs_flag);
5899 btrfs_free_path(path);
5900 return ERR_PTR(-ENOMEM);
5904 * O_TMPFILE, set link count to 0, so that after this point,
5905 * we fill in an inode item with the correct link count.
5908 set_nlink(inode, 0);
5911 * we have to initialize this early, so we can reclaim the inode
5912 * number if we fail afterwards in this function.
5914 inode->i_ino = objectid;
5917 trace_btrfs_inode_request(dir);
5919 ret = btrfs_set_inode_index(BTRFS_I(dir), index);
5921 btrfs_free_path(path);
5923 return ERR_PTR(ret);
5929 * index_cnt is ignored for everything but a dir,
5930 * btrfs_set_inode_index_count has an explanation for the magic
5933 BTRFS_I(inode)->index_cnt = 2;
5934 BTRFS_I(inode)->dir_index = *index;
5935 BTRFS_I(inode)->root = btrfs_grab_root(root);
5936 BTRFS_I(inode)->generation = trans->transid;
5937 inode->i_generation = BTRFS_I(inode)->generation;
5940 * We could have gotten an inode number from somebody who was fsynced
5941 * and then removed in this same transaction, so let's just set full
5942 * sync since it will be a full sync anyway and this will blow away the
5943 * old info in the log.
5945 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &BTRFS_I(inode)->runtime_flags);
5947 key[0].objectid = objectid;
5948 key[0].type = BTRFS_INODE_ITEM_KEY;
5951 sizes[0] = sizeof(struct btrfs_inode_item);
5955 * Start new inodes with an inode_ref. This is slightly more
5956 * efficient for small numbers of hard links since they will
5957 * be packed into one item. Extended refs will kick in if we
5958 * add more hard links than can fit in the ref item.
5960 key[1].objectid = objectid;
5961 key[1].type = BTRFS_INODE_REF_KEY;
5962 key[1].offset = ref_objectid;
5964 sizes[1] = name_len + sizeof(*ref);
5967 location = &BTRFS_I(inode)->location;
5968 location->objectid = objectid;
5969 location->offset = 0;
5970 location->type = BTRFS_INODE_ITEM_KEY;
5972 ret = btrfs_insert_inode_locked(inode);
5978 path->leave_spinning = 1;
5979 ret = btrfs_insert_empty_items(trans, root, path, key, sizes, nitems);
5983 inode_init_owner(inode, dir, mode);
5984 inode_set_bytes(inode, 0);
5986 inode->i_mtime = current_time(inode);
5987 inode->i_atime = inode->i_mtime;
5988 inode->i_ctime = inode->i_mtime;
5989 BTRFS_I(inode)->i_otime = inode->i_mtime;
5991 inode_item = btrfs_item_ptr(path->nodes[0], path->slots[0],
5992 struct btrfs_inode_item);
5993 memzero_extent_buffer(path->nodes[0], (unsigned long)inode_item,
5994 sizeof(*inode_item));
5995 fill_inode_item(trans, path->nodes[0], inode_item, inode);
5998 ref = btrfs_item_ptr(path->nodes[0], path->slots[0] + 1,
5999 struct btrfs_inode_ref);
6000 btrfs_set_inode_ref_name_len(path->nodes[0], ref, name_len);
6001 btrfs_set_inode_ref_index(path->nodes[0], ref, *index);
6002 ptr = (unsigned long)(ref + 1);
6003 write_extent_buffer(path->nodes[0], name, ptr, name_len);
6006 btrfs_mark_buffer_dirty(path->nodes[0]);
6007 btrfs_free_path(path);
6009 btrfs_inherit_iflags(inode, dir);
6011 if (S_ISREG(mode)) {
6012 if (btrfs_test_opt(fs_info, NODATASUM))
6013 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATASUM;
6014 if (btrfs_test_opt(fs_info, NODATACOW))
6015 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATACOW |
6016 BTRFS_INODE_NODATASUM;
6019 inode_tree_add(inode);
6021 trace_btrfs_inode_new(inode);
6022 btrfs_set_inode_last_trans(trans, inode);
6024 btrfs_update_root_times(trans, root);
6026 ret = btrfs_inode_inherit_props(trans, inode, dir);
6029 "error inheriting props for ino %llu (root %llu): %d",
6030 btrfs_ino(BTRFS_I(inode)), root->root_key.objectid, ret);
6035 discard_new_inode(inode);
6038 BTRFS_I(dir)->index_cnt--;
6039 btrfs_free_path(path);
6040 return ERR_PTR(ret);
6044 * utility function to add 'inode' into 'parent_inode' with
6045 * a give name and a given sequence number.
6046 * if 'add_backref' is true, also insert a backref from the
6047 * inode to the parent directory.
6049 int btrfs_add_link(struct btrfs_trans_handle *trans,
6050 struct btrfs_inode *parent_inode, struct btrfs_inode *inode,
6051 const char *name, int name_len, int add_backref, u64 index)
6054 struct btrfs_key key;
6055 struct btrfs_root *root = parent_inode->root;
6056 u64 ino = btrfs_ino(inode);
6057 u64 parent_ino = btrfs_ino(parent_inode);
6059 if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
6060 memcpy(&key, &inode->root->root_key, sizeof(key));
6063 key.type = BTRFS_INODE_ITEM_KEY;
6067 if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
6068 ret = btrfs_add_root_ref(trans, key.objectid,
6069 root->root_key.objectid, parent_ino,
6070 index, name, name_len);
6071 } else if (add_backref) {
6072 ret = btrfs_insert_inode_ref(trans, root, name, name_len, ino,
6076 /* Nothing to clean up yet */
6080 ret = btrfs_insert_dir_item(trans, name, name_len, parent_inode, &key,
6081 btrfs_inode_type(&inode->vfs_inode), index);
6082 if (ret == -EEXIST || ret == -EOVERFLOW)
6085 btrfs_abort_transaction(trans, ret);
6089 btrfs_i_size_write(parent_inode, parent_inode->vfs_inode.i_size +
6091 inode_inc_iversion(&parent_inode->vfs_inode);
6093 * If we are replaying a log tree, we do not want to update the mtime
6094 * and ctime of the parent directory with the current time, since the
6095 * log replay procedure is responsible for setting them to their correct
6096 * values (the ones it had when the fsync was done).
6098 if (!test_bit(BTRFS_FS_LOG_RECOVERING, &root->fs_info->flags)) {
6099 struct timespec64 now = current_time(&parent_inode->vfs_inode);
6101 parent_inode->vfs_inode.i_mtime = now;
6102 parent_inode->vfs_inode.i_ctime = now;
6104 ret = btrfs_update_inode(trans, root, &parent_inode->vfs_inode);
6106 btrfs_abort_transaction(trans, ret);
6110 if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
6113 err = btrfs_del_root_ref(trans, key.objectid,
6114 root->root_key.objectid, parent_ino,
6115 &local_index, name, name_len);
6117 btrfs_abort_transaction(trans, err);
6118 } else if (add_backref) {
6122 err = btrfs_del_inode_ref(trans, root, name, name_len,
6123 ino, parent_ino, &local_index);
6125 btrfs_abort_transaction(trans, err);
6128 /* Return the original error code */
6132 static int btrfs_add_nondir(struct btrfs_trans_handle *trans,
6133 struct btrfs_inode *dir, struct dentry *dentry,
6134 struct btrfs_inode *inode, int backref, u64 index)
6136 int err = btrfs_add_link(trans, dir, inode,
6137 dentry->d_name.name, dentry->d_name.len,
6144 static int btrfs_mknod(struct inode *dir, struct dentry *dentry,
6145 umode_t mode, dev_t rdev)
6147 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
6148 struct btrfs_trans_handle *trans;
6149 struct btrfs_root *root = BTRFS_I(dir)->root;
6150 struct inode *inode = NULL;
6156 * 2 for inode item and ref
6158 * 1 for xattr if selinux is on
6160 trans = btrfs_start_transaction(root, 5);
6162 return PTR_ERR(trans);
6164 err = btrfs_find_free_ino(root, &objectid);
6168 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
6169 dentry->d_name.len, btrfs_ino(BTRFS_I(dir)), objectid,
6171 if (IS_ERR(inode)) {
6172 err = PTR_ERR(inode);
6178 * If the active LSM wants to access the inode during
6179 * d_instantiate it needs these. Smack checks to see
6180 * if the filesystem supports xattrs by looking at the
6183 inode->i_op = &btrfs_special_inode_operations;
6184 init_special_inode(inode, inode->i_mode, rdev);
6186 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
6190 err = btrfs_add_nondir(trans, BTRFS_I(dir), dentry, BTRFS_I(inode),
6195 btrfs_update_inode(trans, root, inode);
6196 d_instantiate_new(dentry, inode);
6199 btrfs_end_transaction(trans);
6200 btrfs_btree_balance_dirty(fs_info);
6202 inode_dec_link_count(inode);
6203 discard_new_inode(inode);
6208 static int btrfs_create(struct inode *dir, struct dentry *dentry,
6209 umode_t mode, bool excl)
6211 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
6212 struct btrfs_trans_handle *trans;
6213 struct btrfs_root *root = BTRFS_I(dir)->root;
6214 struct inode *inode = NULL;
6220 * 2 for inode item and ref
6222 * 1 for xattr if selinux is on
6224 trans = btrfs_start_transaction(root, 5);
6226 return PTR_ERR(trans);
6228 err = btrfs_find_free_ino(root, &objectid);
6232 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
6233 dentry->d_name.len, btrfs_ino(BTRFS_I(dir)), objectid,
6235 if (IS_ERR(inode)) {
6236 err = PTR_ERR(inode);
6241 * If the active LSM wants to access the inode during
6242 * d_instantiate it needs these. Smack checks to see
6243 * if the filesystem supports xattrs by looking at the
6246 inode->i_fop = &btrfs_file_operations;
6247 inode->i_op = &btrfs_file_inode_operations;
6248 inode->i_mapping->a_ops = &btrfs_aops;
6250 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
6254 err = btrfs_update_inode(trans, root, inode);
6258 err = btrfs_add_nondir(trans, BTRFS_I(dir), dentry, BTRFS_I(inode),
6263 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
6264 d_instantiate_new(dentry, inode);
6267 btrfs_end_transaction(trans);
6269 inode_dec_link_count(inode);
6270 discard_new_inode(inode);
6272 btrfs_btree_balance_dirty(fs_info);
6276 static int btrfs_link(struct dentry *old_dentry, struct inode *dir,
6277 struct dentry *dentry)
6279 struct btrfs_trans_handle *trans = NULL;
6280 struct btrfs_root *root = BTRFS_I(dir)->root;
6281 struct inode *inode = d_inode(old_dentry);
6282 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
6287 /* do not allow sys_link's with other subvols of the same device */
6288 if (root->root_key.objectid != BTRFS_I(inode)->root->root_key.objectid)
6291 if (inode->i_nlink >= BTRFS_LINK_MAX)
6294 err = btrfs_set_inode_index(BTRFS_I(dir), &index);
6299 * 2 items for inode and inode ref
6300 * 2 items for dir items
6301 * 1 item for parent inode
6302 * 1 item for orphan item deletion if O_TMPFILE
6304 trans = btrfs_start_transaction(root, inode->i_nlink ? 5 : 6);
6305 if (IS_ERR(trans)) {
6306 err = PTR_ERR(trans);
6311 /* There are several dir indexes for this inode, clear the cache. */
6312 BTRFS_I(inode)->dir_index = 0ULL;
6314 inode_inc_iversion(inode);
6315 inode->i_ctime = current_time(inode);
6317 set_bit(BTRFS_INODE_COPY_EVERYTHING, &BTRFS_I(inode)->runtime_flags);
6319 err = btrfs_add_nondir(trans, BTRFS_I(dir), dentry, BTRFS_I(inode),
6325 struct dentry *parent = dentry->d_parent;
6328 err = btrfs_update_inode(trans, root, inode);
6331 if (inode->i_nlink == 1) {
6333 * If new hard link count is 1, it's a file created
6334 * with open(2) O_TMPFILE flag.
6336 err = btrfs_orphan_del(trans, BTRFS_I(inode));
6340 d_instantiate(dentry, inode);
6341 ret = btrfs_log_new_name(trans, BTRFS_I(inode), NULL, parent,
6343 if (ret == BTRFS_NEED_TRANS_COMMIT) {
6344 err = btrfs_commit_transaction(trans);
6351 btrfs_end_transaction(trans);
6353 inode_dec_link_count(inode);
6356 btrfs_btree_balance_dirty(fs_info);
6360 static int btrfs_mkdir(struct inode *dir, struct dentry *dentry, umode_t mode)
6362 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
6363 struct inode *inode = NULL;
6364 struct btrfs_trans_handle *trans;
6365 struct btrfs_root *root = BTRFS_I(dir)->root;
6371 * 2 items for inode and ref
6372 * 2 items for dir items
6373 * 1 for xattr if selinux is on
6375 trans = btrfs_start_transaction(root, 5);
6377 return PTR_ERR(trans);
6379 err = btrfs_find_free_ino(root, &objectid);
6383 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
6384 dentry->d_name.len, btrfs_ino(BTRFS_I(dir)), objectid,
6385 S_IFDIR | mode, &index);
6386 if (IS_ERR(inode)) {
6387 err = PTR_ERR(inode);
6392 /* these must be set before we unlock the inode */
6393 inode->i_op = &btrfs_dir_inode_operations;
6394 inode->i_fop = &btrfs_dir_file_operations;
6396 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
6400 btrfs_i_size_write(BTRFS_I(inode), 0);
6401 err = btrfs_update_inode(trans, root, inode);
6405 err = btrfs_add_link(trans, BTRFS_I(dir), BTRFS_I(inode),
6406 dentry->d_name.name,
6407 dentry->d_name.len, 0, index);
6411 d_instantiate_new(dentry, inode);
6414 btrfs_end_transaction(trans);
6416 inode_dec_link_count(inode);
6417 discard_new_inode(inode);
6419 btrfs_btree_balance_dirty(fs_info);
6423 static noinline int uncompress_inline(struct btrfs_path *path,
6425 size_t pg_offset, u64 extent_offset,
6426 struct btrfs_file_extent_item *item)
6429 struct extent_buffer *leaf = path->nodes[0];
6432 unsigned long inline_size;
6436 WARN_ON(pg_offset != 0);
6437 compress_type = btrfs_file_extent_compression(leaf, item);
6438 max_size = btrfs_file_extent_ram_bytes(leaf, item);
6439 inline_size = btrfs_file_extent_inline_item_len(leaf,
6440 btrfs_item_nr(path->slots[0]));
6441 tmp = kmalloc(inline_size, GFP_NOFS);
6444 ptr = btrfs_file_extent_inline_start(item);
6446 read_extent_buffer(leaf, tmp, ptr, inline_size);
6448 max_size = min_t(unsigned long, PAGE_SIZE, max_size);
6449 ret = btrfs_decompress(compress_type, tmp, page,
6450 extent_offset, inline_size, max_size);
6453 * decompression code contains a memset to fill in any space between the end
6454 * of the uncompressed data and the end of max_size in case the decompressed
6455 * data ends up shorter than ram_bytes. That doesn't cover the hole between
6456 * the end of an inline extent and the beginning of the next block, so we
6457 * cover that region here.
6460 if (max_size + pg_offset < PAGE_SIZE) {
6461 char *map = kmap(page);
6462 memset(map + pg_offset + max_size, 0, PAGE_SIZE - max_size - pg_offset);
6470 * btrfs_get_extent - Lookup the first extent overlapping a range in a file.
6471 * @inode: file to search in
6472 * @page: page to read extent data into if the extent is inline
6473 * @pg_offset: offset into @page to copy to
6474 * @start: file offset
6475 * @len: length of range starting at @start
6477 * This returns the first &struct extent_map which overlaps with the given
6478 * range, reading it from the B-tree and caching it if necessary. Note that
6479 * there may be more extents which overlap the given range after the returned
6482 * If @page is not NULL and the extent is inline, this also reads the extent
6483 * data directly into the page and marks the extent up to date in the io_tree.
6485 * Return: ERR_PTR on error, non-NULL extent_map on success.
6487 struct extent_map *btrfs_get_extent(struct btrfs_inode *inode,
6488 struct page *page, size_t pg_offset,
6491 struct btrfs_fs_info *fs_info = inode->root->fs_info;
6494 u64 extent_start = 0;
6496 u64 objectid = btrfs_ino(inode);
6497 int extent_type = -1;
6498 struct btrfs_path *path = NULL;
6499 struct btrfs_root *root = inode->root;
6500 struct btrfs_file_extent_item *item;
6501 struct extent_buffer *leaf;
6502 struct btrfs_key found_key;
6503 struct extent_map *em = NULL;
6504 struct extent_map_tree *em_tree = &inode->extent_tree;
6505 struct extent_io_tree *io_tree = &inode->io_tree;
6507 read_lock(&em_tree->lock);
6508 em = lookup_extent_mapping(em_tree, start, len);
6509 read_unlock(&em_tree->lock);
6512 if (em->start > start || em->start + em->len <= start)
6513 free_extent_map(em);
6514 else if (em->block_start == EXTENT_MAP_INLINE && page)
6515 free_extent_map(em);
6519 em = alloc_extent_map();
6524 em->start = EXTENT_MAP_HOLE;
6525 em->orig_start = EXTENT_MAP_HOLE;
6527 em->block_len = (u64)-1;
6529 path = btrfs_alloc_path();
6535 /* Chances are we'll be called again, so go ahead and do readahead */
6536 path->reada = READA_FORWARD;
6539 * Unless we're going to uncompress the inline extent, no sleep would
6542 path->leave_spinning = 1;
6544 ret = btrfs_lookup_file_extent(NULL, root, path, objectid, start, 0);
6548 } else if (ret > 0) {
6549 if (path->slots[0] == 0)
6554 leaf = path->nodes[0];
6555 item = btrfs_item_ptr(leaf, path->slots[0],
6556 struct btrfs_file_extent_item);
6557 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
6558 if (found_key.objectid != objectid ||
6559 found_key.type != BTRFS_EXTENT_DATA_KEY) {
6561 * If we backup past the first extent we want to move forward
6562 * and see if there is an extent in front of us, otherwise we'll
6563 * say there is a hole for our whole search range which can
6570 extent_type = btrfs_file_extent_type(leaf, item);
6571 extent_start = found_key.offset;
6572 extent_end = btrfs_file_extent_end(path);
6573 if (extent_type == BTRFS_FILE_EXTENT_REG ||
6574 extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
6575 /* Only regular file could have regular/prealloc extent */
6576 if (!S_ISREG(inode->vfs_inode.i_mode)) {
6579 "regular/prealloc extent found for non-regular inode %llu",
6583 trace_btrfs_get_extent_show_fi_regular(inode, leaf, item,
6585 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
6586 trace_btrfs_get_extent_show_fi_inline(inode, leaf, item,
6591 if (start >= extent_end) {
6593 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
6594 ret = btrfs_next_leaf(root, path);
6598 } else if (ret > 0) {
6601 leaf = path->nodes[0];
6603 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
6604 if (found_key.objectid != objectid ||
6605 found_key.type != BTRFS_EXTENT_DATA_KEY)
6607 if (start + len <= found_key.offset)
6609 if (start > found_key.offset)
6612 /* New extent overlaps with existing one */
6614 em->orig_start = start;
6615 em->len = found_key.offset - start;
6616 em->block_start = EXTENT_MAP_HOLE;
6620 btrfs_extent_item_to_extent_map(inode, path, item, !page, em);
6622 if (extent_type == BTRFS_FILE_EXTENT_REG ||
6623 extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
6625 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
6629 size_t extent_offset;
6635 size = btrfs_file_extent_ram_bytes(leaf, item);
6636 extent_offset = page_offset(page) + pg_offset - extent_start;
6637 copy_size = min_t(u64, PAGE_SIZE - pg_offset,
6638 size - extent_offset);
6639 em->start = extent_start + extent_offset;
6640 em->len = ALIGN(copy_size, fs_info->sectorsize);
6641 em->orig_block_len = em->len;
6642 em->orig_start = em->start;
6643 ptr = btrfs_file_extent_inline_start(item) + extent_offset;
6645 btrfs_set_path_blocking(path);
6646 if (!PageUptodate(page)) {
6647 if (btrfs_file_extent_compression(leaf, item) !=
6648 BTRFS_COMPRESS_NONE) {
6649 ret = uncompress_inline(path, page, pg_offset,
6650 extent_offset, item);
6657 read_extent_buffer(leaf, map + pg_offset, ptr,
6659 if (pg_offset + copy_size < PAGE_SIZE) {
6660 memset(map + pg_offset + copy_size, 0,
6661 PAGE_SIZE - pg_offset -
6666 flush_dcache_page(page);
6668 set_extent_uptodate(io_tree, em->start,
6669 extent_map_end(em) - 1, NULL, GFP_NOFS);
6674 em->orig_start = start;
6676 em->block_start = EXTENT_MAP_HOLE;
6678 btrfs_release_path(path);
6679 if (em->start > start || extent_map_end(em) <= start) {
6681 "bad extent! em: [%llu %llu] passed [%llu %llu]",
6682 em->start, em->len, start, len);
6688 write_lock(&em_tree->lock);
6689 err = btrfs_add_extent_mapping(fs_info, em_tree, &em, start, len);
6690 write_unlock(&em_tree->lock);
6692 btrfs_free_path(path);
6694 trace_btrfs_get_extent(root, inode, em);
6697 free_extent_map(em);
6698 return ERR_PTR(err);
6700 BUG_ON(!em); /* Error is always set */
6704 struct extent_map *btrfs_get_extent_fiemap(struct btrfs_inode *inode,
6707 struct extent_map *em;
6708 struct extent_map *hole_em = NULL;
6709 u64 delalloc_start = start;
6715 em = btrfs_get_extent(inode, NULL, 0, start, len);
6719 * If our em maps to:
6721 * - a pre-alloc extent,
6722 * there might actually be delalloc bytes behind it.
6724 if (em->block_start != EXTENT_MAP_HOLE &&
6725 !test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
6730 /* check to see if we've wrapped (len == -1 or similar) */
6739 /* ok, we didn't find anything, lets look for delalloc */
6740 delalloc_len = count_range_bits(&inode->io_tree, &delalloc_start,
6741 end, len, EXTENT_DELALLOC, 1);
6742 delalloc_end = delalloc_start + delalloc_len;
6743 if (delalloc_end < delalloc_start)
6744 delalloc_end = (u64)-1;
6747 * We didn't find anything useful, return the original results from
6750 if (delalloc_start > end || delalloc_end <= start) {
6757 * Adjust the delalloc_start to make sure it doesn't go backwards from
6758 * the start they passed in
6760 delalloc_start = max(start, delalloc_start);
6761 delalloc_len = delalloc_end - delalloc_start;
6763 if (delalloc_len > 0) {
6766 const u64 hole_end = extent_map_end(hole_em);
6768 em = alloc_extent_map();
6776 * When btrfs_get_extent can't find anything it returns one
6779 * Make sure what it found really fits our range, and adjust to
6780 * make sure it is based on the start from the caller
6782 if (hole_end <= start || hole_em->start > end) {
6783 free_extent_map(hole_em);
6786 hole_start = max(hole_em->start, start);
6787 hole_len = hole_end - hole_start;
6790 if (hole_em && delalloc_start > hole_start) {
6792 * Our hole starts before our delalloc, so we have to
6793 * return just the parts of the hole that go until the
6796 em->len = min(hole_len, delalloc_start - hole_start);
6797 em->start = hole_start;
6798 em->orig_start = hole_start;
6800 * Don't adjust block start at all, it is fixed at
6803 em->block_start = hole_em->block_start;
6804 em->block_len = hole_len;
6805 if (test_bit(EXTENT_FLAG_PREALLOC, &hole_em->flags))
6806 set_bit(EXTENT_FLAG_PREALLOC, &em->flags);
6809 * Hole is out of passed range or it starts after
6812 em->start = delalloc_start;
6813 em->len = delalloc_len;
6814 em->orig_start = delalloc_start;
6815 em->block_start = EXTENT_MAP_DELALLOC;
6816 em->block_len = delalloc_len;
6823 free_extent_map(hole_em);
6825 free_extent_map(em);
6826 return ERR_PTR(err);
6831 static struct extent_map *btrfs_create_dio_extent(struct inode *inode,
6834 const u64 orig_start,
6835 const u64 block_start,
6836 const u64 block_len,
6837 const u64 orig_block_len,
6838 const u64 ram_bytes,
6841 struct extent_map *em = NULL;
6844 if (type != BTRFS_ORDERED_NOCOW) {
6845 em = create_io_em(inode, start, len, orig_start,
6846 block_start, block_len, orig_block_len,
6848 BTRFS_COMPRESS_NONE, /* compress_type */
6853 ret = btrfs_add_ordered_extent_dio(inode, start, block_start,
6854 len, block_len, type);
6857 free_extent_map(em);
6858 btrfs_drop_extent_cache(BTRFS_I(inode), start,
6859 start + len - 1, 0);
6868 static struct extent_map *btrfs_new_extent_direct(struct inode *inode,
6871 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
6872 struct btrfs_root *root = BTRFS_I(inode)->root;
6873 struct extent_map *em;
6874 struct btrfs_key ins;
6878 alloc_hint = get_extent_allocation_hint(inode, start, len);
6879 ret = btrfs_reserve_extent(root, len, len, fs_info->sectorsize,
6880 0, alloc_hint, &ins, 1, 1);
6882 return ERR_PTR(ret);
6884 em = btrfs_create_dio_extent(inode, start, ins.offset, start,
6885 ins.objectid, ins.offset, ins.offset,
6886 ins.offset, BTRFS_ORDERED_REGULAR);
6887 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
6889 btrfs_free_reserved_extent(fs_info, ins.objectid,
6896 * returns 1 when the nocow is safe, < 1 on error, 0 if the
6897 * block must be cow'd
6899 noinline int can_nocow_extent(struct inode *inode, u64 offset, u64 *len,
6900 u64 *orig_start, u64 *orig_block_len,
6903 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
6904 struct btrfs_path *path;
6906 struct extent_buffer *leaf;
6907 struct btrfs_root *root = BTRFS_I(inode)->root;
6908 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
6909 struct btrfs_file_extent_item *fi;
6910 struct btrfs_key key;
6917 bool nocow = (BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW);
6919 path = btrfs_alloc_path();
6923 ret = btrfs_lookup_file_extent(NULL, root, path,
6924 btrfs_ino(BTRFS_I(inode)), offset, 0);
6928 slot = path->slots[0];
6931 /* can't find the item, must cow */
6938 leaf = path->nodes[0];
6939 btrfs_item_key_to_cpu(leaf, &key, slot);
6940 if (key.objectid != btrfs_ino(BTRFS_I(inode)) ||
6941 key.type != BTRFS_EXTENT_DATA_KEY) {
6942 /* not our file or wrong item type, must cow */
6946 if (key.offset > offset) {
6947 /* Wrong offset, must cow */
6951 fi = btrfs_item_ptr(leaf, slot, struct btrfs_file_extent_item);
6952 found_type = btrfs_file_extent_type(leaf, fi);
6953 if (found_type != BTRFS_FILE_EXTENT_REG &&
6954 found_type != BTRFS_FILE_EXTENT_PREALLOC) {
6955 /* not a regular extent, must cow */
6959 if (!nocow && found_type == BTRFS_FILE_EXTENT_REG)
6962 extent_end = key.offset + btrfs_file_extent_num_bytes(leaf, fi);
6963 if (extent_end <= offset)
6966 disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
6967 if (disk_bytenr == 0)
6970 if (btrfs_file_extent_compression(leaf, fi) ||
6971 btrfs_file_extent_encryption(leaf, fi) ||
6972 btrfs_file_extent_other_encoding(leaf, fi))
6976 * Do the same check as in btrfs_cross_ref_exist but without the
6977 * unnecessary search.
6979 if (btrfs_file_extent_generation(leaf, fi) <=
6980 btrfs_root_last_snapshot(&root->root_item))
6983 backref_offset = btrfs_file_extent_offset(leaf, fi);
6986 *orig_start = key.offset - backref_offset;
6987 *orig_block_len = btrfs_file_extent_disk_num_bytes(leaf, fi);
6988 *ram_bytes = btrfs_file_extent_ram_bytes(leaf, fi);
6991 if (btrfs_extent_readonly(fs_info, disk_bytenr))
6994 num_bytes = min(offset + *len, extent_end) - offset;
6995 if (!nocow && found_type == BTRFS_FILE_EXTENT_PREALLOC) {
6998 range_end = round_up(offset + num_bytes,
6999 root->fs_info->sectorsize) - 1;
7000 ret = test_range_bit(io_tree, offset, range_end,
7001 EXTENT_DELALLOC, 0, NULL);
7008 btrfs_release_path(path);
7011 * look for other files referencing this extent, if we
7012 * find any we must cow
7015 ret = btrfs_cross_ref_exist(root, btrfs_ino(BTRFS_I(inode)),
7016 key.offset - backref_offset, disk_bytenr);
7023 * adjust disk_bytenr and num_bytes to cover just the bytes
7024 * in this extent we are about to write. If there
7025 * are any csums in that range we have to cow in order
7026 * to keep the csums correct
7028 disk_bytenr += backref_offset;
7029 disk_bytenr += offset - key.offset;
7030 if (csum_exist_in_range(fs_info, disk_bytenr, num_bytes))
7033 * all of the above have passed, it is safe to overwrite this extent
7039 btrfs_free_path(path);
7043 static int lock_extent_direct(struct inode *inode, u64 lockstart, u64 lockend,
7044 struct extent_state **cached_state, bool writing)
7046 struct btrfs_ordered_extent *ordered;
7050 lock_extent_bits(&BTRFS_I(inode)->io_tree, lockstart, lockend,
7053 * We're concerned with the entire range that we're going to be
7054 * doing DIO to, so we need to make sure there's no ordered
7055 * extents in this range.
7057 ordered = btrfs_lookup_ordered_range(BTRFS_I(inode), lockstart,
7058 lockend - lockstart + 1);
7061 * We need to make sure there are no buffered pages in this
7062 * range either, we could have raced between the invalidate in
7063 * generic_file_direct_write and locking the extent. The
7064 * invalidate needs to happen so that reads after a write do not
7068 (!writing || !filemap_range_has_page(inode->i_mapping,
7069 lockstart, lockend)))
7072 unlock_extent_cached(&BTRFS_I(inode)->io_tree, lockstart, lockend,
7077 * If we are doing a DIO read and the ordered extent we
7078 * found is for a buffered write, we can not wait for it
7079 * to complete and retry, because if we do so we can
7080 * deadlock with concurrent buffered writes on page
7081 * locks. This happens only if our DIO read covers more
7082 * than one extent map, if at this point has already
7083 * created an ordered extent for a previous extent map
7084 * and locked its range in the inode's io tree, and a
7085 * concurrent write against that previous extent map's
7086 * range and this range started (we unlock the ranges
7087 * in the io tree only when the bios complete and
7088 * buffered writes always lock pages before attempting
7089 * to lock range in the io tree).
7092 test_bit(BTRFS_ORDERED_DIRECT, &ordered->flags))
7093 btrfs_start_ordered_extent(inode, ordered, 1);
7096 btrfs_put_ordered_extent(ordered);
7099 * We could trigger writeback for this range (and wait
7100 * for it to complete) and then invalidate the pages for
7101 * this range (through invalidate_inode_pages2_range()),
7102 * but that can lead us to a deadlock with a concurrent
7103 * call to readahead (a buffered read or a defrag call
7104 * triggered a readahead) on a page lock due to an
7105 * ordered dio extent we created before but did not have
7106 * yet a corresponding bio submitted (whence it can not
7107 * complete), which makes readahead wait for that
7108 * ordered extent to complete while holding a lock on
7123 /* The callers of this must take lock_extent() */
7124 static struct extent_map *create_io_em(struct inode *inode, u64 start, u64 len,
7125 u64 orig_start, u64 block_start,
7126 u64 block_len, u64 orig_block_len,
7127 u64 ram_bytes, int compress_type,
7130 struct extent_map_tree *em_tree;
7131 struct extent_map *em;
7134 ASSERT(type == BTRFS_ORDERED_PREALLOC ||
7135 type == BTRFS_ORDERED_COMPRESSED ||
7136 type == BTRFS_ORDERED_NOCOW ||
7137 type == BTRFS_ORDERED_REGULAR);
7139 em_tree = &BTRFS_I(inode)->extent_tree;
7140 em = alloc_extent_map();
7142 return ERR_PTR(-ENOMEM);
7145 em->orig_start = orig_start;
7147 em->block_len = block_len;
7148 em->block_start = block_start;
7149 em->orig_block_len = orig_block_len;
7150 em->ram_bytes = ram_bytes;
7151 em->generation = -1;
7152 set_bit(EXTENT_FLAG_PINNED, &em->flags);
7153 if (type == BTRFS_ORDERED_PREALLOC) {
7154 set_bit(EXTENT_FLAG_FILLING, &em->flags);
7155 } else if (type == BTRFS_ORDERED_COMPRESSED) {
7156 set_bit(EXTENT_FLAG_COMPRESSED, &em->flags);
7157 em->compress_type = compress_type;
7161 btrfs_drop_extent_cache(BTRFS_I(inode), em->start,
7162 em->start + em->len - 1, 0);
7163 write_lock(&em_tree->lock);
7164 ret = add_extent_mapping(em_tree, em, 1);
7165 write_unlock(&em_tree->lock);
7167 * The caller has taken lock_extent(), who could race with us
7170 } while (ret == -EEXIST);
7173 free_extent_map(em);
7174 return ERR_PTR(ret);
7177 /* em got 2 refs now, callers needs to do free_extent_map once. */
7182 static int btrfs_get_blocks_direct_write(struct extent_map **map,
7183 struct inode *inode,
7184 struct btrfs_dio_data *dio_data,
7187 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7188 struct extent_map *em = *map;
7192 * We don't allocate a new extent in the following cases
7194 * 1) The inode is marked as NODATACOW. In this case we'll just use the
7196 * 2) The extent is marked as PREALLOC. We're good to go here and can
7197 * just use the extent.
7200 if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags) ||
7201 ((BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW) &&
7202 em->block_start != EXTENT_MAP_HOLE)) {
7204 u64 block_start, orig_start, orig_block_len, ram_bytes;
7206 if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
7207 type = BTRFS_ORDERED_PREALLOC;
7209 type = BTRFS_ORDERED_NOCOW;
7210 len = min(len, em->len - (start - em->start));
7211 block_start = em->block_start + (start - em->start);
7213 if (can_nocow_extent(inode, start, &len, &orig_start,
7214 &orig_block_len, &ram_bytes) == 1 &&
7215 btrfs_inc_nocow_writers(fs_info, block_start)) {
7216 struct extent_map *em2;
7218 em2 = btrfs_create_dio_extent(inode, start, len,
7219 orig_start, block_start,
7220 len, orig_block_len,
7222 btrfs_dec_nocow_writers(fs_info, block_start);
7223 if (type == BTRFS_ORDERED_PREALLOC) {
7224 free_extent_map(em);
7228 if (em2 && IS_ERR(em2)) {
7233 * For inode marked NODATACOW or extent marked PREALLOC,
7234 * use the existing or preallocated extent, so does not
7235 * need to adjust btrfs_space_info's bytes_may_use.
7237 btrfs_free_reserved_data_space_noquota(inode, start,
7243 /* this will cow the extent */
7244 free_extent_map(em);
7245 *map = em = btrfs_new_extent_direct(inode, start, len);
7251 len = min(len, em->len - (start - em->start));
7255 * Need to update the i_size under the extent lock so buffered
7256 * readers will get the updated i_size when we unlock.
7258 if (start + len > i_size_read(inode))
7259 i_size_write(inode, start + len);
7261 dio_data->reserve -= len;
7266 static int btrfs_dio_iomap_begin(struct inode *inode, loff_t start,
7267 loff_t length, unsigned flags, struct iomap *iomap,
7268 struct iomap *srcmap)
7270 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7271 struct extent_map *em;
7272 struct extent_state *cached_state = NULL;
7273 struct btrfs_dio_data *dio_data = NULL;
7274 u64 lockstart, lockend;
7275 const bool write = !!(flags & IOMAP_WRITE);
7278 bool unlock_extents = false;
7281 len = min_t(u64, len, fs_info->sectorsize);
7284 lockend = start + len - 1;
7287 * The generic stuff only does filemap_write_and_wait_range, which
7288 * isn't enough if we've written compressed pages to this area, so we
7289 * need to flush the dirty pages again to make absolutely sure that any
7290 * outstanding dirty pages are on disk.
7292 if (test_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
7293 &BTRFS_I(inode)->runtime_flags))
7294 ret = filemap_fdatawrite_range(inode->i_mapping, start,
7295 start + length - 1);
7297 dio_data = kzalloc(sizeof(*dio_data), GFP_NOFS);
7301 dio_data->length = length;
7303 dio_data->reserve = round_up(length, fs_info->sectorsize);
7304 ret = btrfs_delalloc_reserve_space(inode,
7305 &dio_data->data_reserved,
7306 start, dio_data->reserve);
7308 extent_changeset_free(dio_data->data_reserved);
7313 iomap->private = dio_data;
7317 * If this errors out it's because we couldn't invalidate pagecache for
7318 * this range and we need to fallback to buffered.
7320 if (lock_extent_direct(inode, lockstart, lockend, &cached_state, write)) {
7325 em = btrfs_get_extent(BTRFS_I(inode), NULL, 0, start, len);
7332 * Ok for INLINE and COMPRESSED extents we need to fallback on buffered
7333 * io. INLINE is special, and we could probably kludge it in here, but
7334 * it's still buffered so for safety lets just fall back to the generic
7337 * For COMPRESSED we _have_ to read the entire extent in so we can
7338 * decompress it, so there will be buffering required no matter what we
7339 * do, so go ahead and fallback to buffered.
7341 * We return -ENOTBLK because that's what makes DIO go ahead and go back
7342 * to buffered IO. Don't blame me, this is the price we pay for using
7345 if (test_bit(EXTENT_FLAG_COMPRESSED, &em->flags) ||
7346 em->block_start == EXTENT_MAP_INLINE) {
7347 free_extent_map(em);
7352 len = min(len, em->len - (start - em->start));
7354 ret = btrfs_get_blocks_direct_write(&em, inode, dio_data,
7358 unlock_extents = true;
7359 /* Recalc len in case the new em is smaller than requested */
7360 len = min(len, em->len - (start - em->start));
7363 * We need to unlock only the end area that we aren't using.
7364 * The rest is going to be unlocked by the endio routine.
7366 lockstart = start + len;
7367 if (lockstart < lockend)
7368 unlock_extents = true;
7372 unlock_extent_cached(&BTRFS_I(inode)->io_tree,
7373 lockstart, lockend, &cached_state);
7375 free_extent_state(cached_state);
7378 * Translate extent map information to iomap.
7379 * We trim the extents (and move the addr) even though iomap code does
7380 * that, since we have locked only the parts we are performing I/O in.
7382 if ((em->block_start == EXTENT_MAP_HOLE) ||
7383 (test_bit(EXTENT_FLAG_PREALLOC, &em->flags) && !write)) {
7384 iomap->addr = IOMAP_NULL_ADDR;
7385 iomap->type = IOMAP_HOLE;
7387 iomap->addr = em->block_start + (start - em->start);
7388 iomap->type = IOMAP_MAPPED;
7390 iomap->offset = start;
7391 iomap->bdev = fs_info->fs_devices->latest_bdev;
7392 iomap->length = len;
7394 free_extent_map(em);
7399 unlock_extent_cached(&BTRFS_I(inode)->io_tree, lockstart, lockend,
7403 btrfs_delalloc_release_space(inode, dio_data->data_reserved,
7404 start, dio_data->reserve, true);
7405 btrfs_delalloc_release_extents(BTRFS_I(inode), dio_data->reserve);
7406 extent_changeset_free(dio_data->data_reserved);
7412 static int btrfs_dio_iomap_end(struct inode *inode, loff_t pos, loff_t length,
7413 ssize_t written, unsigned flags, struct iomap *iomap)
7416 struct btrfs_dio_data *dio_data = iomap->private;
7417 size_t submitted = dio_data->submitted;
7418 const bool write = !!(flags & IOMAP_WRITE);
7420 if (!write && (iomap->type == IOMAP_HOLE)) {
7421 /* If reading from a hole, unlock and return */
7422 unlock_extent(&BTRFS_I(inode)->io_tree, pos, pos + length - 1);
7426 if (submitted < length) {
7428 length -= submitted;
7430 __endio_write_update_ordered(inode, pos, length, false);
7432 unlock_extent(&BTRFS_I(inode)->io_tree, pos,
7438 if (dio_data->reserve)
7439 btrfs_delalloc_release_space(inode,
7440 dio_data->data_reserved, pos,
7441 dio_data->reserve, true);
7442 btrfs_delalloc_release_extents(BTRFS_I(inode), dio_data->length);
7443 extent_changeset_free(dio_data->data_reserved);
7447 iomap->private = NULL;
7452 static void btrfs_dio_private_put(struct btrfs_dio_private *dip)
7455 * This implies a barrier so that stores to dio_bio->bi_status before
7456 * this and loads of dio_bio->bi_status after this are fully ordered.
7458 if (!refcount_dec_and_test(&dip->refs))
7461 if (bio_op(dip->dio_bio) == REQ_OP_WRITE) {
7462 __endio_write_update_ordered(dip->inode, dip->logical_offset,
7464 !dip->dio_bio->bi_status);
7466 unlock_extent(&BTRFS_I(dip->inode)->io_tree,
7467 dip->logical_offset,
7468 dip->logical_offset + dip->bytes - 1);
7471 bio_endio(dip->dio_bio);
7475 static blk_status_t submit_dio_repair_bio(struct inode *inode, struct bio *bio,
7477 unsigned long bio_flags)
7479 struct btrfs_dio_private *dip = bio->bi_private;
7480 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7483 BUG_ON(bio_op(bio) == REQ_OP_WRITE);
7485 ret = btrfs_bio_wq_end_io(fs_info, bio, BTRFS_WQ_ENDIO_DATA);
7489 refcount_inc(&dip->refs);
7490 ret = btrfs_map_bio(fs_info, bio, mirror_num);
7492 refcount_dec(&dip->refs);
7496 static blk_status_t btrfs_check_read_dio_bio(struct inode *inode,
7497 struct btrfs_io_bio *io_bio,
7498 const bool uptodate)
7500 struct btrfs_fs_info *fs_info = BTRFS_I(inode)->root->fs_info;
7501 const u32 sectorsize = fs_info->sectorsize;
7502 struct extent_io_tree *failure_tree = &BTRFS_I(inode)->io_failure_tree;
7503 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
7504 const bool csum = !(BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM);
7505 struct bio_vec bvec;
7506 struct bvec_iter iter;
7507 u64 start = io_bio->logical;
7509 blk_status_t err = BLK_STS_OK;
7511 __bio_for_each_segment(bvec, &io_bio->bio, iter, io_bio->iter) {
7512 unsigned int i, nr_sectors, pgoff;
7514 nr_sectors = BTRFS_BYTES_TO_BLKS(fs_info, bvec.bv_len);
7515 pgoff = bvec.bv_offset;
7516 for (i = 0; i < nr_sectors; i++) {
7517 ASSERT(pgoff < PAGE_SIZE);
7519 (!csum || !check_data_csum(inode, io_bio, icsum,
7520 bvec.bv_page, pgoff,
7521 start, sectorsize))) {
7522 clean_io_failure(fs_info, failure_tree, io_tree,
7523 start, bvec.bv_page,
7524 btrfs_ino(BTRFS_I(inode)),
7527 blk_status_t status;
7529 status = btrfs_submit_read_repair(inode,
7531 start - io_bio->logical,
7532 bvec.bv_page, pgoff,
7534 start + sectorsize - 1,
7536 submit_dio_repair_bio);
7540 start += sectorsize;
7542 pgoff += sectorsize;
7548 static void __endio_write_update_ordered(struct inode *inode,
7549 const u64 offset, const u64 bytes,
7550 const bool uptodate)
7552 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7553 struct btrfs_ordered_extent *ordered = NULL;
7554 struct btrfs_workqueue *wq;
7555 u64 ordered_offset = offset;
7556 u64 ordered_bytes = bytes;
7559 if (btrfs_is_free_space_inode(BTRFS_I(inode)))
7560 wq = fs_info->endio_freespace_worker;
7562 wq = fs_info->endio_write_workers;
7564 while (ordered_offset < offset + bytes) {
7565 last_offset = ordered_offset;
7566 if (btrfs_dec_test_first_ordered_pending(inode, &ordered,
7570 btrfs_init_work(&ordered->work, finish_ordered_fn, NULL,
7572 btrfs_queue_work(wq, &ordered->work);
7575 * If btrfs_dec_test_ordered_pending does not find any ordered
7576 * extent in the range, we can exit.
7578 if (ordered_offset == last_offset)
7581 * Our bio might span multiple ordered extents. In this case
7582 * we keep going until we have accounted the whole dio.
7584 if (ordered_offset < offset + bytes) {
7585 ordered_bytes = offset + bytes - ordered_offset;
7591 static blk_status_t btrfs_submit_bio_start_direct_io(void *private_data,
7592 struct bio *bio, u64 offset)
7594 struct inode *inode = private_data;
7596 ret = btrfs_csum_one_bio(inode, bio, offset, 1);
7597 BUG_ON(ret); /* -ENOMEM */
7601 static void btrfs_end_dio_bio(struct bio *bio)
7603 struct btrfs_dio_private *dip = bio->bi_private;
7604 blk_status_t err = bio->bi_status;
7607 btrfs_warn(BTRFS_I(dip->inode)->root->fs_info,
7608 "direct IO failed ino %llu rw %d,%u sector %#Lx len %u err no %d",
7609 btrfs_ino(BTRFS_I(dip->inode)), bio_op(bio),
7611 (unsigned long long)bio->bi_iter.bi_sector,
7612 bio->bi_iter.bi_size, err);
7614 if (bio_op(bio) == REQ_OP_READ) {
7615 err = btrfs_check_read_dio_bio(dip->inode, btrfs_io_bio(bio),
7620 dip->dio_bio->bi_status = err;
7623 btrfs_dio_private_put(dip);
7626 static inline blk_status_t btrfs_submit_dio_bio(struct bio *bio,
7627 struct inode *inode, u64 file_offset, int async_submit)
7629 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7630 struct btrfs_dio_private *dip = bio->bi_private;
7631 bool write = bio_op(bio) == REQ_OP_WRITE;
7634 /* Check btrfs_submit_bio_hook() for rules about async submit. */
7636 async_submit = !atomic_read(&BTRFS_I(inode)->sync_writers);
7639 ret = btrfs_bio_wq_end_io(fs_info, bio, BTRFS_WQ_ENDIO_DATA);
7644 if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)
7647 if (write && async_submit) {
7648 ret = btrfs_wq_submit_bio(fs_info, bio, 0, 0,
7650 btrfs_submit_bio_start_direct_io);
7654 * If we aren't doing async submit, calculate the csum of the
7657 ret = btrfs_csum_one_bio(inode, bio, file_offset, 1);
7663 csum_offset = file_offset - dip->logical_offset;
7664 csum_offset >>= inode->i_sb->s_blocksize_bits;
7665 csum_offset *= btrfs_super_csum_size(fs_info->super_copy);
7666 btrfs_io_bio(bio)->csum = dip->csums + csum_offset;
7669 ret = btrfs_map_bio(fs_info, bio, 0);
7675 * If this succeeds, the btrfs_dio_private is responsible for cleaning up locked
7676 * or ordered extents whether or not we submit any bios.
7678 static struct btrfs_dio_private *btrfs_create_dio_private(struct bio *dio_bio,
7679 struct inode *inode,
7682 const bool write = (bio_op(dio_bio) == REQ_OP_WRITE);
7683 const bool csum = !(BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM);
7685 struct btrfs_dio_private *dip;
7687 dip_size = sizeof(*dip);
7688 if (!write && csum) {
7689 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7690 const u16 csum_size = btrfs_super_csum_size(fs_info->super_copy);
7693 nblocks = dio_bio->bi_iter.bi_size >> inode->i_sb->s_blocksize_bits;
7694 dip_size += csum_size * nblocks;
7697 dip = kzalloc(dip_size, GFP_NOFS);
7702 dip->logical_offset = file_offset;
7703 dip->bytes = dio_bio->bi_iter.bi_size;
7704 dip->disk_bytenr = (u64)dio_bio->bi_iter.bi_sector << 9;
7705 dip->dio_bio = dio_bio;
7706 refcount_set(&dip->refs, 1);
7710 static blk_qc_t btrfs_submit_direct(struct inode *inode, struct iomap *iomap,
7711 struct bio *dio_bio, loff_t file_offset)
7713 const bool write = (bio_op(dio_bio) == REQ_OP_WRITE);
7714 const bool csum = !(BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM);
7715 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7716 const bool raid56 = (btrfs_data_alloc_profile(fs_info) &
7717 BTRFS_BLOCK_GROUP_RAID56_MASK);
7718 struct btrfs_dio_private *dip;
7721 int async_submit = 0;
7723 int clone_offset = 0;
7726 blk_status_t status;
7727 struct btrfs_io_geometry geom;
7728 struct btrfs_dio_data *dio_data = iomap->private;
7730 dip = btrfs_create_dio_private(dio_bio, inode, file_offset);
7733 unlock_extent(&BTRFS_I(inode)->io_tree, file_offset,
7734 file_offset + dio_bio->bi_iter.bi_size - 1);
7736 dio_bio->bi_status = BLK_STS_RESOURCE;
7738 return BLK_QC_T_NONE;
7741 if (!write && csum) {
7743 * Load the csums up front to reduce csum tree searches and
7744 * contention when submitting bios.
7746 status = btrfs_lookup_bio_sums(inode, dio_bio, file_offset,
7748 if (status != BLK_STS_OK)
7752 start_sector = dio_bio->bi_iter.bi_sector;
7753 submit_len = dio_bio->bi_iter.bi_size;
7756 ret = btrfs_get_io_geometry(fs_info, btrfs_op(dio_bio),
7757 start_sector << 9, submit_len,
7760 status = errno_to_blk_status(ret);
7763 ASSERT(geom.len <= INT_MAX);
7765 clone_len = min_t(int, submit_len, geom.len);
7768 * This will never fail as it's passing GPF_NOFS and
7769 * the allocation is backed by btrfs_bioset.
7771 bio = btrfs_bio_clone_partial(dio_bio, clone_offset, clone_len);
7772 bio->bi_private = dip;
7773 bio->bi_end_io = btrfs_end_dio_bio;
7774 btrfs_io_bio(bio)->logical = file_offset;
7776 ASSERT(submit_len >= clone_len);
7777 submit_len -= clone_len;
7780 * Increase the count before we submit the bio so we know
7781 * the end IO handler won't happen before we increase the
7782 * count. Otherwise, the dip might get freed before we're
7783 * done setting it up.
7785 * We transfer the initial reference to the last bio, so we
7786 * don't need to increment the reference count for the last one.
7788 if (submit_len > 0) {
7789 refcount_inc(&dip->refs);
7791 * If we are submitting more than one bio, submit them
7792 * all asynchronously. The exception is RAID 5 or 6, as
7793 * asynchronous checksums make it difficult to collect
7794 * full stripe writes.
7800 status = btrfs_submit_dio_bio(bio, inode, file_offset,
7805 refcount_dec(&dip->refs);
7809 dio_data->submitted += clone_len;
7810 clone_offset += clone_len;
7811 start_sector += clone_len >> 9;
7812 file_offset += clone_len;
7813 } while (submit_len > 0);
7814 return BLK_QC_T_NONE;
7817 dip->dio_bio->bi_status = status;
7818 btrfs_dio_private_put(dip);
7819 return BLK_QC_T_NONE;
7822 const struct iomap_ops btrfs_dio_iomap_ops = {
7823 .iomap_begin = btrfs_dio_iomap_begin,
7824 .iomap_end = btrfs_dio_iomap_end,
7827 const struct iomap_dio_ops btrfs_dops = {
7828 .submit_io = btrfs_submit_direct,
7831 #define BTRFS_FIEMAP_FLAGS (FIEMAP_FLAG_SYNC)
7833 static int btrfs_fiemap(struct inode *inode, struct fiemap_extent_info *fieinfo,
7834 __u64 start, __u64 len)
7838 ret = fiemap_check_flags(fieinfo, BTRFS_FIEMAP_FLAGS);
7842 return extent_fiemap(inode, fieinfo, start, len);
7845 int btrfs_readpage(struct file *file, struct page *page)
7847 return extent_read_full_page(page, btrfs_get_extent, 0);
7850 static int btrfs_writepage(struct page *page, struct writeback_control *wbc)
7852 struct inode *inode = page->mapping->host;
7855 if (current->flags & PF_MEMALLOC) {
7856 redirty_page_for_writepage(wbc, page);
7862 * If we are under memory pressure we will call this directly from the
7863 * VM, we need to make sure we have the inode referenced for the ordered
7864 * extent. If not just return like we didn't do anything.
7866 if (!igrab(inode)) {
7867 redirty_page_for_writepage(wbc, page);
7868 return AOP_WRITEPAGE_ACTIVATE;
7870 ret = extent_write_full_page(page, wbc);
7871 btrfs_add_delayed_iput(inode);
7875 static int btrfs_writepages(struct address_space *mapping,
7876 struct writeback_control *wbc)
7878 return extent_writepages(mapping, wbc);
7881 static void btrfs_readahead(struct readahead_control *rac)
7883 extent_readahead(rac);
7886 static int __btrfs_releasepage(struct page *page, gfp_t gfp_flags)
7888 int ret = try_release_extent_mapping(page, gfp_flags);
7890 detach_page_private(page);
7894 static int btrfs_releasepage(struct page *page, gfp_t gfp_flags)
7896 if (PageWriteback(page) || PageDirty(page))
7898 return __btrfs_releasepage(page, gfp_flags);
7901 #ifdef CONFIG_MIGRATION
7902 static int btrfs_migratepage(struct address_space *mapping,
7903 struct page *newpage, struct page *page,
7904 enum migrate_mode mode)
7908 ret = migrate_page_move_mapping(mapping, newpage, page, 0);
7909 if (ret != MIGRATEPAGE_SUCCESS)
7912 if (page_has_private(page))
7913 attach_page_private(newpage, detach_page_private(page));
7915 if (PagePrivate2(page)) {
7916 ClearPagePrivate2(page);
7917 SetPagePrivate2(newpage);
7920 if (mode != MIGRATE_SYNC_NO_COPY)
7921 migrate_page_copy(newpage, page);
7923 migrate_page_states(newpage, page);
7924 return MIGRATEPAGE_SUCCESS;
7928 static void btrfs_invalidatepage(struct page *page, unsigned int offset,
7929 unsigned int length)
7931 struct inode *inode = page->mapping->host;
7932 struct extent_io_tree *tree;
7933 struct btrfs_ordered_extent *ordered;
7934 struct extent_state *cached_state = NULL;
7935 u64 page_start = page_offset(page);
7936 u64 page_end = page_start + PAGE_SIZE - 1;
7939 int inode_evicting = inode->i_state & I_FREEING;
7942 * we have the page locked, so new writeback can't start,
7943 * and the dirty bit won't be cleared while we are here.
7945 * Wait for IO on this page so that we can safely clear
7946 * the PagePrivate2 bit and do ordered accounting
7948 wait_on_page_writeback(page);
7950 tree = &BTRFS_I(inode)->io_tree;
7952 btrfs_releasepage(page, GFP_NOFS);
7956 if (!inode_evicting)
7957 lock_extent_bits(tree, page_start, page_end, &cached_state);
7960 ordered = btrfs_lookup_ordered_range(BTRFS_I(inode), start,
7961 page_end - start + 1);
7964 ordered->file_offset + ordered->num_bytes - 1);
7966 * IO on this page will never be started, so we need
7967 * to account for any ordered extents now
7969 if (!inode_evicting)
7970 clear_extent_bit(tree, start, end,
7971 EXTENT_DELALLOC | EXTENT_DELALLOC_NEW |
7972 EXTENT_LOCKED | EXTENT_DO_ACCOUNTING |
7973 EXTENT_DEFRAG, 1, 0, &cached_state);
7975 * whoever cleared the private bit is responsible
7976 * for the finish_ordered_io
7978 if (TestClearPagePrivate2(page)) {
7979 struct btrfs_ordered_inode_tree *tree;
7982 tree = &BTRFS_I(inode)->ordered_tree;
7984 spin_lock_irq(&tree->lock);
7985 set_bit(BTRFS_ORDERED_TRUNCATED, &ordered->flags);
7986 new_len = start - ordered->file_offset;
7987 if (new_len < ordered->truncated_len)
7988 ordered->truncated_len = new_len;
7989 spin_unlock_irq(&tree->lock);
7991 if (btrfs_dec_test_ordered_pending(inode, &ordered,
7993 end - start + 1, 1))
7994 btrfs_finish_ordered_io(ordered);
7996 btrfs_put_ordered_extent(ordered);
7997 if (!inode_evicting) {
7998 cached_state = NULL;
7999 lock_extent_bits(tree, start, end,
8004 if (start < page_end)
8009 * Qgroup reserved space handler
8010 * Page here will be either
8011 * 1) Already written to disk
8012 * In this case, its reserved space is released from data rsv map
8013 * and will be freed by delayed_ref handler finally.
8014 * So even we call qgroup_free_data(), it won't decrease reserved
8016 * 2) Not written to disk
8017 * This means the reserved space should be freed here. However,
8018 * if a truncate invalidates the page (by clearing PageDirty)
8019 * and the page is accounted for while allocating extent
8020 * in btrfs_check_data_free_space() we let delayed_ref to
8021 * free the entire extent.
8023 if (PageDirty(page))
8024 btrfs_qgroup_free_data(inode, NULL, page_start, PAGE_SIZE);
8025 if (!inode_evicting) {
8026 clear_extent_bit(tree, page_start, page_end, EXTENT_LOCKED |
8027 EXTENT_DELALLOC | EXTENT_DELALLOC_NEW |
8028 EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG, 1, 1,
8031 __btrfs_releasepage(page, GFP_NOFS);
8034 ClearPageChecked(page);
8035 detach_page_private(page);
8039 * btrfs_page_mkwrite() is not allowed to change the file size as it gets
8040 * called from a page fault handler when a page is first dirtied. Hence we must
8041 * be careful to check for EOF conditions here. We set the page up correctly
8042 * for a written page which means we get ENOSPC checking when writing into
8043 * holes and correct delalloc and unwritten extent mapping on filesystems that
8044 * support these features.
8046 * We are not allowed to take the i_mutex here so we have to play games to
8047 * protect against truncate races as the page could now be beyond EOF. Because
8048 * truncate_setsize() writes the inode size before removing pages, once we have
8049 * the page lock we can determine safely if the page is beyond EOF. If it is not
8050 * beyond EOF, then the page is guaranteed safe against truncation until we
8053 vm_fault_t btrfs_page_mkwrite(struct vm_fault *vmf)
8055 struct page *page = vmf->page;
8056 struct inode *inode = file_inode(vmf->vma->vm_file);
8057 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
8058 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
8059 struct btrfs_ordered_extent *ordered;
8060 struct extent_state *cached_state = NULL;
8061 struct extent_changeset *data_reserved = NULL;
8063 unsigned long zero_start;
8073 reserved_space = PAGE_SIZE;
8075 sb_start_pagefault(inode->i_sb);
8076 page_start = page_offset(page);
8077 page_end = page_start + PAGE_SIZE - 1;
8081 * Reserving delalloc space after obtaining the page lock can lead to
8082 * deadlock. For example, if a dirty page is locked by this function
8083 * and the call to btrfs_delalloc_reserve_space() ends up triggering
8084 * dirty page write out, then the btrfs_writepage() function could
8085 * end up waiting indefinitely to get a lock on the page currently
8086 * being processed by btrfs_page_mkwrite() function.
8088 ret2 = btrfs_delalloc_reserve_space(inode, &data_reserved, page_start,
8091 ret2 = file_update_time(vmf->vma->vm_file);
8095 ret = vmf_error(ret2);
8101 ret = VM_FAULT_NOPAGE; /* make the VM retry the fault */
8104 size = i_size_read(inode);
8106 if ((page->mapping != inode->i_mapping) ||
8107 (page_start >= size)) {
8108 /* page got truncated out from underneath us */
8111 wait_on_page_writeback(page);
8113 lock_extent_bits(io_tree, page_start, page_end, &cached_state);
8114 set_page_extent_mapped(page);
8117 * we can't set the delalloc bits if there are pending ordered
8118 * extents. Drop our locks and wait for them to finish
8120 ordered = btrfs_lookup_ordered_range(BTRFS_I(inode), page_start,
8123 unlock_extent_cached(io_tree, page_start, page_end,
8126 btrfs_start_ordered_extent(inode, ordered, 1);
8127 btrfs_put_ordered_extent(ordered);
8131 if (page->index == ((size - 1) >> PAGE_SHIFT)) {
8132 reserved_space = round_up(size - page_start,
8133 fs_info->sectorsize);
8134 if (reserved_space < PAGE_SIZE) {
8135 end = page_start + reserved_space - 1;
8136 btrfs_delalloc_release_space(inode, data_reserved,
8137 page_start, PAGE_SIZE - reserved_space,
8143 * page_mkwrite gets called when the page is firstly dirtied after it's
8144 * faulted in, but write(2) could also dirty a page and set delalloc
8145 * bits, thus in this case for space account reason, we still need to
8146 * clear any delalloc bits within this page range since we have to
8147 * reserve data&meta space before lock_page() (see above comments).
8149 clear_extent_bit(&BTRFS_I(inode)->io_tree, page_start, end,
8150 EXTENT_DELALLOC | EXTENT_DO_ACCOUNTING |
8151 EXTENT_DEFRAG, 0, 0, &cached_state);
8153 ret2 = btrfs_set_extent_delalloc(inode, page_start, end, 0,
8156 unlock_extent_cached(io_tree, page_start, page_end,
8158 ret = VM_FAULT_SIGBUS;
8162 /* page is wholly or partially inside EOF */
8163 if (page_start + PAGE_SIZE > size)
8164 zero_start = offset_in_page(size);
8166 zero_start = PAGE_SIZE;
8168 if (zero_start != PAGE_SIZE) {
8170 memset(kaddr + zero_start, 0, PAGE_SIZE - zero_start);
8171 flush_dcache_page(page);
8174 ClearPageChecked(page);
8175 set_page_dirty(page);
8176 SetPageUptodate(page);
8178 BTRFS_I(inode)->last_trans = fs_info->generation;
8179 BTRFS_I(inode)->last_sub_trans = BTRFS_I(inode)->root->log_transid;
8180 BTRFS_I(inode)->last_log_commit = BTRFS_I(inode)->root->last_log_commit;
8182 unlock_extent_cached(io_tree, page_start, page_end, &cached_state);
8184 btrfs_delalloc_release_extents(BTRFS_I(inode), PAGE_SIZE);
8185 sb_end_pagefault(inode->i_sb);
8186 extent_changeset_free(data_reserved);
8187 return VM_FAULT_LOCKED;
8192 btrfs_delalloc_release_extents(BTRFS_I(inode), PAGE_SIZE);
8193 btrfs_delalloc_release_space(inode, data_reserved, page_start,
8194 reserved_space, (ret != 0));
8196 sb_end_pagefault(inode->i_sb);
8197 extent_changeset_free(data_reserved);
8201 static int btrfs_truncate(struct inode *inode, bool skip_writeback)
8203 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
8204 struct btrfs_root *root = BTRFS_I(inode)->root;
8205 struct btrfs_block_rsv *rsv;
8207 struct btrfs_trans_handle *trans;
8208 u64 mask = fs_info->sectorsize - 1;
8209 u64 min_size = btrfs_calc_metadata_size(fs_info, 1);
8211 if (!skip_writeback) {
8212 ret = btrfs_wait_ordered_range(inode, inode->i_size & (~mask),
8219 * Yes ladies and gentlemen, this is indeed ugly. We have a couple of
8220 * things going on here:
8222 * 1) We need to reserve space to update our inode.
8224 * 2) We need to have something to cache all the space that is going to
8225 * be free'd up by the truncate operation, but also have some slack
8226 * space reserved in case it uses space during the truncate (thank you
8227 * very much snapshotting).
8229 * And we need these to be separate. The fact is we can use a lot of
8230 * space doing the truncate, and we have no earthly idea how much space
8231 * we will use, so we need the truncate reservation to be separate so it
8232 * doesn't end up using space reserved for updating the inode. We also
8233 * need to be able to stop the transaction and start a new one, which
8234 * means we need to be able to update the inode several times, and we
8235 * have no idea of knowing how many times that will be, so we can't just
8236 * reserve 1 item for the entirety of the operation, so that has to be
8237 * done separately as well.
8239 * So that leaves us with
8241 * 1) rsv - for the truncate reservation, which we will steal from the
8242 * transaction reservation.
8243 * 2) fs_info->trans_block_rsv - this will have 1 items worth left for
8244 * updating the inode.
8246 rsv = btrfs_alloc_block_rsv(fs_info, BTRFS_BLOCK_RSV_TEMP);
8249 rsv->size = min_size;
8253 * 1 for the truncate slack space
8254 * 1 for updating the inode.
8256 trans = btrfs_start_transaction(root, 2);
8257 if (IS_ERR(trans)) {
8258 ret = PTR_ERR(trans);
8262 /* Migrate the slack space for the truncate to our reserve */
8263 ret = btrfs_block_rsv_migrate(&fs_info->trans_block_rsv, rsv,
8268 * So if we truncate and then write and fsync we normally would just
8269 * write the extents that changed, which is a problem if we need to
8270 * first truncate that entire inode. So set this flag so we write out
8271 * all of the extents in the inode to the sync log so we're completely
8274 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &BTRFS_I(inode)->runtime_flags);
8275 trans->block_rsv = rsv;
8278 ret = btrfs_truncate_inode_items(trans, root, inode,
8280 BTRFS_EXTENT_DATA_KEY);
8281 trans->block_rsv = &fs_info->trans_block_rsv;
8282 if (ret != -ENOSPC && ret != -EAGAIN)
8285 ret = btrfs_update_inode(trans, root, inode);
8289 btrfs_end_transaction(trans);
8290 btrfs_btree_balance_dirty(fs_info);
8292 trans = btrfs_start_transaction(root, 2);
8293 if (IS_ERR(trans)) {
8294 ret = PTR_ERR(trans);
8299 btrfs_block_rsv_release(fs_info, rsv, -1, NULL);
8300 ret = btrfs_block_rsv_migrate(&fs_info->trans_block_rsv,
8301 rsv, min_size, false);
8302 BUG_ON(ret); /* shouldn't happen */
8303 trans->block_rsv = rsv;
8307 * We can't call btrfs_truncate_block inside a trans handle as we could
8308 * deadlock with freeze, if we got NEED_TRUNCATE_BLOCK then we know
8309 * we've truncated everything except the last little bit, and can do
8310 * btrfs_truncate_block and then update the disk_i_size.
8312 if (ret == NEED_TRUNCATE_BLOCK) {
8313 btrfs_end_transaction(trans);
8314 btrfs_btree_balance_dirty(fs_info);
8316 ret = btrfs_truncate_block(inode, inode->i_size, 0, 0);
8319 trans = btrfs_start_transaction(root, 1);
8320 if (IS_ERR(trans)) {
8321 ret = PTR_ERR(trans);
8324 btrfs_inode_safe_disk_i_size_write(inode, 0);
8330 trans->block_rsv = &fs_info->trans_block_rsv;
8331 ret2 = btrfs_update_inode(trans, root, inode);
8335 ret2 = btrfs_end_transaction(trans);
8338 btrfs_btree_balance_dirty(fs_info);
8341 btrfs_free_block_rsv(fs_info, rsv);
8347 * create a new subvolume directory/inode (helper for the ioctl).
8349 int btrfs_create_subvol_root(struct btrfs_trans_handle *trans,
8350 struct btrfs_root *new_root,
8351 struct btrfs_root *parent_root,
8354 struct inode *inode;
8358 inode = btrfs_new_inode(trans, new_root, NULL, "..", 2,
8359 new_dirid, new_dirid,
8360 S_IFDIR | (~current_umask() & S_IRWXUGO),
8363 return PTR_ERR(inode);
8364 inode->i_op = &btrfs_dir_inode_operations;
8365 inode->i_fop = &btrfs_dir_file_operations;
8367 set_nlink(inode, 1);
8368 btrfs_i_size_write(BTRFS_I(inode), 0);
8369 unlock_new_inode(inode);
8371 err = btrfs_subvol_inherit_props(trans, new_root, parent_root);
8373 btrfs_err(new_root->fs_info,
8374 "error inheriting subvolume %llu properties: %d",
8375 new_root->root_key.objectid, err);
8377 err = btrfs_update_inode(trans, new_root, inode);
8383 struct inode *btrfs_alloc_inode(struct super_block *sb)
8385 struct btrfs_fs_info *fs_info = btrfs_sb(sb);
8386 struct btrfs_inode *ei;
8387 struct inode *inode;
8389 ei = kmem_cache_alloc(btrfs_inode_cachep, GFP_KERNEL);
8396 ei->last_sub_trans = 0;
8397 ei->logged_trans = 0;
8398 ei->delalloc_bytes = 0;
8399 ei->new_delalloc_bytes = 0;
8400 ei->defrag_bytes = 0;
8401 ei->disk_i_size = 0;
8404 ei->index_cnt = (u64)-1;
8406 ei->last_unlink_trans = 0;
8407 ei->last_log_commit = 0;
8409 spin_lock_init(&ei->lock);
8410 ei->outstanding_extents = 0;
8411 if (sb->s_magic != BTRFS_TEST_MAGIC)
8412 btrfs_init_metadata_block_rsv(fs_info, &ei->block_rsv,
8413 BTRFS_BLOCK_RSV_DELALLOC);
8414 ei->runtime_flags = 0;
8415 ei->prop_compress = BTRFS_COMPRESS_NONE;
8416 ei->defrag_compress = BTRFS_COMPRESS_NONE;
8418 ei->delayed_node = NULL;
8420 ei->i_otime.tv_sec = 0;
8421 ei->i_otime.tv_nsec = 0;
8423 inode = &ei->vfs_inode;
8424 extent_map_tree_init(&ei->extent_tree);
8425 extent_io_tree_init(fs_info, &ei->io_tree, IO_TREE_INODE_IO, inode);
8426 extent_io_tree_init(fs_info, &ei->io_failure_tree,
8427 IO_TREE_INODE_IO_FAILURE, inode);
8428 extent_io_tree_init(fs_info, &ei->file_extent_tree,
8429 IO_TREE_INODE_FILE_EXTENT, inode);
8430 ei->io_tree.track_uptodate = true;
8431 ei->io_failure_tree.track_uptodate = true;
8432 atomic_set(&ei->sync_writers, 0);
8433 mutex_init(&ei->log_mutex);
8434 btrfs_ordered_inode_tree_init(&ei->ordered_tree);
8435 INIT_LIST_HEAD(&ei->delalloc_inodes);
8436 INIT_LIST_HEAD(&ei->delayed_iput);
8437 RB_CLEAR_NODE(&ei->rb_node);
8438 init_rwsem(&ei->dio_sem);
8443 #ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
8444 void btrfs_test_destroy_inode(struct inode *inode)
8446 btrfs_drop_extent_cache(BTRFS_I(inode), 0, (u64)-1, 0);
8447 kmem_cache_free(btrfs_inode_cachep, BTRFS_I(inode));
8451 void btrfs_free_inode(struct inode *inode)
8453 kmem_cache_free(btrfs_inode_cachep, BTRFS_I(inode));
8456 void btrfs_destroy_inode(struct inode *inode)
8458 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
8459 struct btrfs_ordered_extent *ordered;
8460 struct btrfs_root *root = BTRFS_I(inode)->root;
8462 WARN_ON(!hlist_empty(&inode->i_dentry));
8463 WARN_ON(inode->i_data.nrpages);
8464 WARN_ON(BTRFS_I(inode)->block_rsv.reserved);
8465 WARN_ON(BTRFS_I(inode)->block_rsv.size);
8466 WARN_ON(BTRFS_I(inode)->outstanding_extents);
8467 WARN_ON(BTRFS_I(inode)->delalloc_bytes);
8468 WARN_ON(BTRFS_I(inode)->new_delalloc_bytes);
8469 WARN_ON(BTRFS_I(inode)->csum_bytes);
8470 WARN_ON(BTRFS_I(inode)->defrag_bytes);
8473 * This can happen where we create an inode, but somebody else also
8474 * created the same inode and we need to destroy the one we already
8481 ordered = btrfs_lookup_first_ordered_extent(inode, (u64)-1);
8486 "found ordered extent %llu %llu on inode cleanup",
8487 ordered->file_offset, ordered->num_bytes);
8488 btrfs_remove_ordered_extent(inode, ordered);
8489 btrfs_put_ordered_extent(ordered);
8490 btrfs_put_ordered_extent(ordered);
8493 btrfs_qgroup_check_reserved_leak(inode);
8494 inode_tree_del(inode);
8495 btrfs_drop_extent_cache(BTRFS_I(inode), 0, (u64)-1, 0);
8496 btrfs_inode_clear_file_extent_range(BTRFS_I(inode), 0, (u64)-1);
8497 btrfs_put_root(BTRFS_I(inode)->root);
8500 int btrfs_drop_inode(struct inode *inode)
8502 struct btrfs_root *root = BTRFS_I(inode)->root;
8507 /* the snap/subvol tree is on deleting */
8508 if (btrfs_root_refs(&root->root_item) == 0)
8511 return generic_drop_inode(inode);
8514 static void init_once(void *foo)
8516 struct btrfs_inode *ei = (struct btrfs_inode *) foo;
8518 inode_init_once(&ei->vfs_inode);
8521 void __cold btrfs_destroy_cachep(void)
8524 * Make sure all delayed rcu free inodes are flushed before we
8528 kmem_cache_destroy(btrfs_inode_cachep);
8529 kmem_cache_destroy(btrfs_trans_handle_cachep);
8530 kmem_cache_destroy(btrfs_path_cachep);
8531 kmem_cache_destroy(btrfs_free_space_cachep);
8532 kmem_cache_destroy(btrfs_free_space_bitmap_cachep);
8535 int __init btrfs_init_cachep(void)
8537 btrfs_inode_cachep = kmem_cache_create("btrfs_inode",
8538 sizeof(struct btrfs_inode), 0,
8539 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD | SLAB_ACCOUNT,
8541 if (!btrfs_inode_cachep)
8544 btrfs_trans_handle_cachep = kmem_cache_create("btrfs_trans_handle",
8545 sizeof(struct btrfs_trans_handle), 0,
8546 SLAB_TEMPORARY | SLAB_MEM_SPREAD, NULL);
8547 if (!btrfs_trans_handle_cachep)
8550 btrfs_path_cachep = kmem_cache_create("btrfs_path",
8551 sizeof(struct btrfs_path), 0,
8552 SLAB_MEM_SPREAD, NULL);
8553 if (!btrfs_path_cachep)
8556 btrfs_free_space_cachep = kmem_cache_create("btrfs_free_space",
8557 sizeof(struct btrfs_free_space), 0,
8558 SLAB_MEM_SPREAD, NULL);
8559 if (!btrfs_free_space_cachep)
8562 btrfs_free_space_bitmap_cachep = kmem_cache_create("btrfs_free_space_bitmap",
8563 PAGE_SIZE, PAGE_SIZE,
8564 SLAB_RED_ZONE, NULL);
8565 if (!btrfs_free_space_bitmap_cachep)
8570 btrfs_destroy_cachep();
8574 static int btrfs_getattr(const struct path *path, struct kstat *stat,
8575 u32 request_mask, unsigned int flags)
8578 struct inode *inode = d_inode(path->dentry);
8579 u32 blocksize = inode->i_sb->s_blocksize;
8580 u32 bi_flags = BTRFS_I(inode)->flags;
8582 stat->result_mask |= STATX_BTIME;
8583 stat->btime.tv_sec = BTRFS_I(inode)->i_otime.tv_sec;
8584 stat->btime.tv_nsec = BTRFS_I(inode)->i_otime.tv_nsec;
8585 if (bi_flags & BTRFS_INODE_APPEND)
8586 stat->attributes |= STATX_ATTR_APPEND;
8587 if (bi_flags & BTRFS_INODE_COMPRESS)
8588 stat->attributes |= STATX_ATTR_COMPRESSED;
8589 if (bi_flags & BTRFS_INODE_IMMUTABLE)
8590 stat->attributes |= STATX_ATTR_IMMUTABLE;
8591 if (bi_flags & BTRFS_INODE_NODUMP)
8592 stat->attributes |= STATX_ATTR_NODUMP;
8594 stat->attributes_mask |= (STATX_ATTR_APPEND |
8595 STATX_ATTR_COMPRESSED |
8596 STATX_ATTR_IMMUTABLE |
8599 generic_fillattr(inode, stat);
8600 stat->dev = BTRFS_I(inode)->root->anon_dev;
8602 spin_lock(&BTRFS_I(inode)->lock);
8603 delalloc_bytes = BTRFS_I(inode)->new_delalloc_bytes;
8604 spin_unlock(&BTRFS_I(inode)->lock);
8605 stat->blocks = (ALIGN(inode_get_bytes(inode), blocksize) +
8606 ALIGN(delalloc_bytes, blocksize)) >> 9;
8610 static int btrfs_rename_exchange(struct inode *old_dir,
8611 struct dentry *old_dentry,
8612 struct inode *new_dir,
8613 struct dentry *new_dentry)
8615 struct btrfs_fs_info *fs_info = btrfs_sb(old_dir->i_sb);
8616 struct btrfs_trans_handle *trans;
8617 struct btrfs_root *root = BTRFS_I(old_dir)->root;
8618 struct btrfs_root *dest = BTRFS_I(new_dir)->root;
8619 struct inode *new_inode = new_dentry->d_inode;
8620 struct inode *old_inode = old_dentry->d_inode;
8621 struct timespec64 ctime = current_time(old_inode);
8622 struct dentry *parent;
8623 u64 old_ino = btrfs_ino(BTRFS_I(old_inode));
8624 u64 new_ino = btrfs_ino(BTRFS_I(new_inode));
8628 bool root_log_pinned = false;
8629 bool dest_log_pinned = false;
8630 struct btrfs_log_ctx ctx_root;
8631 struct btrfs_log_ctx ctx_dest;
8632 bool sync_log_root = false;
8633 bool sync_log_dest = false;
8634 bool commit_transaction = false;
8636 /* we only allow rename subvolume link between subvolumes */
8637 if (old_ino != BTRFS_FIRST_FREE_OBJECTID && root != dest)
8640 btrfs_init_log_ctx(&ctx_root, old_inode);
8641 btrfs_init_log_ctx(&ctx_dest, new_inode);
8643 /* close the race window with snapshot create/destroy ioctl */
8644 if (old_ino == BTRFS_FIRST_FREE_OBJECTID ||
8645 new_ino == BTRFS_FIRST_FREE_OBJECTID)
8646 down_read(&fs_info->subvol_sem);
8649 * We want to reserve the absolute worst case amount of items. So if
8650 * both inodes are subvols and we need to unlink them then that would
8651 * require 4 item modifications, but if they are both normal inodes it
8652 * would require 5 item modifications, so we'll assume their normal
8653 * inodes. So 5 * 2 is 10, plus 2 for the new links, so 12 total items
8654 * should cover the worst case number of items we'll modify.
8656 trans = btrfs_start_transaction(root, 12);
8657 if (IS_ERR(trans)) {
8658 ret = PTR_ERR(trans);
8663 btrfs_record_root_in_trans(trans, dest);
8666 * We need to find a free sequence number both in the source and
8667 * in the destination directory for the exchange.
8669 ret = btrfs_set_inode_index(BTRFS_I(new_dir), &old_idx);
8672 ret = btrfs_set_inode_index(BTRFS_I(old_dir), &new_idx);
8676 BTRFS_I(old_inode)->dir_index = 0ULL;
8677 BTRFS_I(new_inode)->dir_index = 0ULL;
8679 /* Reference for the source. */
8680 if (old_ino == BTRFS_FIRST_FREE_OBJECTID) {
8681 /* force full log commit if subvolume involved. */
8682 btrfs_set_log_full_commit(trans);
8684 btrfs_pin_log_trans(root);
8685 root_log_pinned = true;
8686 ret = btrfs_insert_inode_ref(trans, dest,
8687 new_dentry->d_name.name,
8688 new_dentry->d_name.len,
8690 btrfs_ino(BTRFS_I(new_dir)),
8696 /* And now for the dest. */
8697 if (new_ino == BTRFS_FIRST_FREE_OBJECTID) {
8698 /* force full log commit if subvolume involved. */
8699 btrfs_set_log_full_commit(trans);
8701 btrfs_pin_log_trans(dest);
8702 dest_log_pinned = true;
8703 ret = btrfs_insert_inode_ref(trans, root,
8704 old_dentry->d_name.name,
8705 old_dentry->d_name.len,
8707 btrfs_ino(BTRFS_I(old_dir)),
8713 /* Update inode version and ctime/mtime. */
8714 inode_inc_iversion(old_dir);
8715 inode_inc_iversion(new_dir);
8716 inode_inc_iversion(old_inode);
8717 inode_inc_iversion(new_inode);
8718 old_dir->i_ctime = old_dir->i_mtime = ctime;
8719 new_dir->i_ctime = new_dir->i_mtime = ctime;
8720 old_inode->i_ctime = ctime;
8721 new_inode->i_ctime = ctime;
8723 if (old_dentry->d_parent != new_dentry->d_parent) {
8724 btrfs_record_unlink_dir(trans, BTRFS_I(old_dir),
8725 BTRFS_I(old_inode), 1);
8726 btrfs_record_unlink_dir(trans, BTRFS_I(new_dir),
8727 BTRFS_I(new_inode), 1);
8730 /* src is a subvolume */
8731 if (old_ino == BTRFS_FIRST_FREE_OBJECTID) {
8732 ret = btrfs_unlink_subvol(trans, old_dir, old_dentry);
8733 } else { /* src is an inode */
8734 ret = __btrfs_unlink_inode(trans, root, BTRFS_I(old_dir),
8735 BTRFS_I(old_dentry->d_inode),
8736 old_dentry->d_name.name,
8737 old_dentry->d_name.len);
8739 ret = btrfs_update_inode(trans, root, old_inode);
8742 btrfs_abort_transaction(trans, ret);
8746 /* dest is a subvolume */
8747 if (new_ino == BTRFS_FIRST_FREE_OBJECTID) {
8748 ret = btrfs_unlink_subvol(trans, new_dir, new_dentry);
8749 } else { /* dest is an inode */
8750 ret = __btrfs_unlink_inode(trans, dest, BTRFS_I(new_dir),
8751 BTRFS_I(new_dentry->d_inode),
8752 new_dentry->d_name.name,
8753 new_dentry->d_name.len);
8755 ret = btrfs_update_inode(trans, dest, new_inode);
8758 btrfs_abort_transaction(trans, ret);
8762 ret = btrfs_add_link(trans, BTRFS_I(new_dir), BTRFS_I(old_inode),
8763 new_dentry->d_name.name,
8764 new_dentry->d_name.len, 0, old_idx);
8766 btrfs_abort_transaction(trans, ret);
8770 ret = btrfs_add_link(trans, BTRFS_I(old_dir), BTRFS_I(new_inode),
8771 old_dentry->d_name.name,
8772 old_dentry->d_name.len, 0, new_idx);
8774 btrfs_abort_transaction(trans, ret);
8778 if (old_inode->i_nlink == 1)
8779 BTRFS_I(old_inode)->dir_index = old_idx;
8780 if (new_inode->i_nlink == 1)
8781 BTRFS_I(new_inode)->dir_index = new_idx;
8783 if (root_log_pinned) {
8784 parent = new_dentry->d_parent;
8785 ret = btrfs_log_new_name(trans, BTRFS_I(old_inode),
8786 BTRFS_I(old_dir), parent,
8788 if (ret == BTRFS_NEED_LOG_SYNC)
8789 sync_log_root = true;
8790 else if (ret == BTRFS_NEED_TRANS_COMMIT)
8791 commit_transaction = true;
8793 btrfs_end_log_trans(root);
8794 root_log_pinned = false;
8796 if (dest_log_pinned) {
8797 if (!commit_transaction) {
8798 parent = old_dentry->d_parent;
8799 ret = btrfs_log_new_name(trans, BTRFS_I(new_inode),
8800 BTRFS_I(new_dir), parent,
8802 if (ret == BTRFS_NEED_LOG_SYNC)
8803 sync_log_dest = true;
8804 else if (ret == BTRFS_NEED_TRANS_COMMIT)
8805 commit_transaction = true;
8808 btrfs_end_log_trans(dest);
8809 dest_log_pinned = false;
8813 * If we have pinned a log and an error happened, we unpin tasks
8814 * trying to sync the log and force them to fallback to a transaction
8815 * commit if the log currently contains any of the inodes involved in
8816 * this rename operation (to ensure we do not persist a log with an
8817 * inconsistent state for any of these inodes or leading to any
8818 * inconsistencies when replayed). If the transaction was aborted, the
8819 * abortion reason is propagated to userspace when attempting to commit
8820 * the transaction. If the log does not contain any of these inodes, we
8821 * allow the tasks to sync it.
8823 if (ret && (root_log_pinned || dest_log_pinned)) {
8824 if (btrfs_inode_in_log(BTRFS_I(old_dir), fs_info->generation) ||
8825 btrfs_inode_in_log(BTRFS_I(new_dir), fs_info->generation) ||
8826 btrfs_inode_in_log(BTRFS_I(old_inode), fs_info->generation) ||
8828 btrfs_inode_in_log(BTRFS_I(new_inode), fs_info->generation)))
8829 btrfs_set_log_full_commit(trans);
8831 if (root_log_pinned) {
8832 btrfs_end_log_trans(root);
8833 root_log_pinned = false;
8835 if (dest_log_pinned) {
8836 btrfs_end_log_trans(dest);
8837 dest_log_pinned = false;
8840 if (!ret && sync_log_root && !commit_transaction) {
8841 ret = btrfs_sync_log(trans, BTRFS_I(old_inode)->root,
8844 commit_transaction = true;
8846 if (!ret && sync_log_dest && !commit_transaction) {
8847 ret = btrfs_sync_log(trans, BTRFS_I(new_inode)->root,
8850 commit_transaction = true;
8852 if (commit_transaction) {
8854 * We may have set commit_transaction when logging the new name
8855 * in the destination root, in which case we left the source
8856 * root context in the list of log contextes. So make sure we
8857 * remove it to avoid invalid memory accesses, since the context
8858 * was allocated in our stack frame.
8860 if (sync_log_root) {
8861 mutex_lock(&root->log_mutex);
8862 list_del_init(&ctx_root.list);
8863 mutex_unlock(&root->log_mutex);
8865 ret = btrfs_commit_transaction(trans);
8869 ret2 = btrfs_end_transaction(trans);
8870 ret = ret ? ret : ret2;
8873 if (new_ino == BTRFS_FIRST_FREE_OBJECTID ||
8874 old_ino == BTRFS_FIRST_FREE_OBJECTID)
8875 up_read(&fs_info->subvol_sem);
8877 ASSERT(list_empty(&ctx_root.list));
8878 ASSERT(list_empty(&ctx_dest.list));
8883 static int btrfs_whiteout_for_rename(struct btrfs_trans_handle *trans,
8884 struct btrfs_root *root,
8886 struct dentry *dentry)
8889 struct inode *inode;
8893 ret = btrfs_find_free_ino(root, &objectid);
8897 inode = btrfs_new_inode(trans, root, dir,
8898 dentry->d_name.name,
8900 btrfs_ino(BTRFS_I(dir)),
8902 S_IFCHR | WHITEOUT_MODE,
8905 if (IS_ERR(inode)) {
8906 ret = PTR_ERR(inode);
8910 inode->i_op = &btrfs_special_inode_operations;
8911 init_special_inode(inode, inode->i_mode,
8914 ret = btrfs_init_inode_security(trans, inode, dir,
8919 ret = btrfs_add_nondir(trans, BTRFS_I(dir), dentry,
8920 BTRFS_I(inode), 0, index);
8924 ret = btrfs_update_inode(trans, root, inode);
8926 unlock_new_inode(inode);
8928 inode_dec_link_count(inode);
8934 static int btrfs_rename(struct inode *old_dir, struct dentry *old_dentry,
8935 struct inode *new_dir, struct dentry *new_dentry,
8938 struct btrfs_fs_info *fs_info = btrfs_sb(old_dir->i_sb);
8939 struct btrfs_trans_handle *trans;
8940 unsigned int trans_num_items;
8941 struct btrfs_root *root = BTRFS_I(old_dir)->root;
8942 struct btrfs_root *dest = BTRFS_I(new_dir)->root;
8943 struct inode *new_inode = d_inode(new_dentry);
8944 struct inode *old_inode = d_inode(old_dentry);
8947 u64 old_ino = btrfs_ino(BTRFS_I(old_inode));
8948 bool log_pinned = false;
8949 struct btrfs_log_ctx ctx;
8950 bool sync_log = false;
8951 bool commit_transaction = false;
8953 if (btrfs_ino(BTRFS_I(new_dir)) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)
8956 /* we only allow rename subvolume link between subvolumes */
8957 if (old_ino != BTRFS_FIRST_FREE_OBJECTID && root != dest)
8960 if (old_ino == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID ||
8961 (new_inode && btrfs_ino(BTRFS_I(new_inode)) == BTRFS_FIRST_FREE_OBJECTID))
8964 if (S_ISDIR(old_inode->i_mode) && new_inode &&
8965 new_inode->i_size > BTRFS_EMPTY_DIR_SIZE)
8969 /* check for collisions, even if the name isn't there */
8970 ret = btrfs_check_dir_item_collision(dest, new_dir->i_ino,
8971 new_dentry->d_name.name,
8972 new_dentry->d_name.len);
8975 if (ret == -EEXIST) {
8977 * eexist without a new_inode */
8978 if (WARN_ON(!new_inode)) {
8982 /* maybe -EOVERFLOW */
8989 * we're using rename to replace one file with another. Start IO on it
8990 * now so we don't add too much work to the end of the transaction
8992 if (new_inode && S_ISREG(old_inode->i_mode) && new_inode->i_size)
8993 filemap_flush(old_inode->i_mapping);
8995 /* close the racy window with snapshot create/destroy ioctl */
8996 if (old_ino == BTRFS_FIRST_FREE_OBJECTID)
8997 down_read(&fs_info->subvol_sem);
8999 * We want to reserve the absolute worst case amount of items. So if
9000 * both inodes are subvols and we need to unlink them then that would
9001 * require 4 item modifications, but if they are both normal inodes it
9002 * would require 5 item modifications, so we'll assume they are normal
9003 * inodes. So 5 * 2 is 10, plus 1 for the new link, so 11 total items
9004 * should cover the worst case number of items we'll modify.
9005 * If our rename has the whiteout flag, we need more 5 units for the
9006 * new inode (1 inode item, 1 inode ref, 2 dir items and 1 xattr item
9007 * when selinux is enabled).
9009 trans_num_items = 11;
9010 if (flags & RENAME_WHITEOUT)
9011 trans_num_items += 5;
9012 trans = btrfs_start_transaction(root, trans_num_items);
9013 if (IS_ERR(trans)) {
9014 ret = PTR_ERR(trans);
9019 btrfs_record_root_in_trans(trans, dest);
9021 ret = btrfs_set_inode_index(BTRFS_I(new_dir), &index);
9025 BTRFS_I(old_inode)->dir_index = 0ULL;
9026 if (unlikely(old_ino == BTRFS_FIRST_FREE_OBJECTID)) {
9027 /* force full log commit if subvolume involved. */
9028 btrfs_set_log_full_commit(trans);
9030 btrfs_pin_log_trans(root);
9032 ret = btrfs_insert_inode_ref(trans, dest,
9033 new_dentry->d_name.name,
9034 new_dentry->d_name.len,
9036 btrfs_ino(BTRFS_I(new_dir)), index);
9041 inode_inc_iversion(old_dir);
9042 inode_inc_iversion(new_dir);
9043 inode_inc_iversion(old_inode);
9044 old_dir->i_ctime = old_dir->i_mtime =
9045 new_dir->i_ctime = new_dir->i_mtime =
9046 old_inode->i_ctime = current_time(old_dir);
9048 if (old_dentry->d_parent != new_dentry->d_parent)
9049 btrfs_record_unlink_dir(trans, BTRFS_I(old_dir),
9050 BTRFS_I(old_inode), 1);
9052 if (unlikely(old_ino == BTRFS_FIRST_FREE_OBJECTID)) {
9053 ret = btrfs_unlink_subvol(trans, old_dir, old_dentry);
9055 ret = __btrfs_unlink_inode(trans, root, BTRFS_I(old_dir),
9056 BTRFS_I(d_inode(old_dentry)),
9057 old_dentry->d_name.name,
9058 old_dentry->d_name.len);
9060 ret = btrfs_update_inode(trans, root, old_inode);
9063 btrfs_abort_transaction(trans, ret);
9068 inode_inc_iversion(new_inode);
9069 new_inode->i_ctime = current_time(new_inode);
9070 if (unlikely(btrfs_ino(BTRFS_I(new_inode)) ==
9071 BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)) {
9072 ret = btrfs_unlink_subvol(trans, new_dir, new_dentry);
9073 BUG_ON(new_inode->i_nlink == 0);
9075 ret = btrfs_unlink_inode(trans, dest, BTRFS_I(new_dir),
9076 BTRFS_I(d_inode(new_dentry)),
9077 new_dentry->d_name.name,
9078 new_dentry->d_name.len);
9080 if (!ret && new_inode->i_nlink == 0)
9081 ret = btrfs_orphan_add(trans,
9082 BTRFS_I(d_inode(new_dentry)));
9084 btrfs_abort_transaction(trans, ret);
9089 ret = btrfs_add_link(trans, BTRFS_I(new_dir), BTRFS_I(old_inode),
9090 new_dentry->d_name.name,
9091 new_dentry->d_name.len, 0, index);
9093 btrfs_abort_transaction(trans, ret);
9097 if (old_inode->i_nlink == 1)
9098 BTRFS_I(old_inode)->dir_index = index;
9101 struct dentry *parent = new_dentry->d_parent;
9103 btrfs_init_log_ctx(&ctx, old_inode);
9104 ret = btrfs_log_new_name(trans, BTRFS_I(old_inode),
9105 BTRFS_I(old_dir), parent,
9107 if (ret == BTRFS_NEED_LOG_SYNC)
9109 else if (ret == BTRFS_NEED_TRANS_COMMIT)
9110 commit_transaction = true;
9112 btrfs_end_log_trans(root);
9116 if (flags & RENAME_WHITEOUT) {
9117 ret = btrfs_whiteout_for_rename(trans, root, old_dir,
9121 btrfs_abort_transaction(trans, ret);
9127 * If we have pinned the log and an error happened, we unpin tasks
9128 * trying to sync the log and force them to fallback to a transaction
9129 * commit if the log currently contains any of the inodes involved in
9130 * this rename operation (to ensure we do not persist a log with an
9131 * inconsistent state for any of these inodes or leading to any
9132 * inconsistencies when replayed). If the transaction was aborted, the
9133 * abortion reason is propagated to userspace when attempting to commit
9134 * the transaction. If the log does not contain any of these inodes, we
9135 * allow the tasks to sync it.
9137 if (ret && log_pinned) {
9138 if (btrfs_inode_in_log(BTRFS_I(old_dir), fs_info->generation) ||
9139 btrfs_inode_in_log(BTRFS_I(new_dir), fs_info->generation) ||
9140 btrfs_inode_in_log(BTRFS_I(old_inode), fs_info->generation) ||
9142 btrfs_inode_in_log(BTRFS_I(new_inode), fs_info->generation)))
9143 btrfs_set_log_full_commit(trans);
9145 btrfs_end_log_trans(root);
9148 if (!ret && sync_log) {
9149 ret = btrfs_sync_log(trans, BTRFS_I(old_inode)->root, &ctx);
9151 commit_transaction = true;
9152 } else if (sync_log) {
9153 mutex_lock(&root->log_mutex);
9154 list_del(&ctx.list);
9155 mutex_unlock(&root->log_mutex);
9157 if (commit_transaction) {
9158 ret = btrfs_commit_transaction(trans);
9162 ret2 = btrfs_end_transaction(trans);
9163 ret = ret ? ret : ret2;
9166 if (old_ino == BTRFS_FIRST_FREE_OBJECTID)
9167 up_read(&fs_info->subvol_sem);
9172 static int btrfs_rename2(struct inode *old_dir, struct dentry *old_dentry,
9173 struct inode *new_dir, struct dentry *new_dentry,
9176 if (flags & ~(RENAME_NOREPLACE | RENAME_EXCHANGE | RENAME_WHITEOUT))
9179 if (flags & RENAME_EXCHANGE)
9180 return btrfs_rename_exchange(old_dir, old_dentry, new_dir,
9183 return btrfs_rename(old_dir, old_dentry, new_dir, new_dentry, flags);
9186 struct btrfs_delalloc_work {
9187 struct inode *inode;
9188 struct completion completion;
9189 struct list_head list;
9190 struct btrfs_work work;
9193 static void btrfs_run_delalloc_work(struct btrfs_work *work)
9195 struct btrfs_delalloc_work *delalloc_work;
9196 struct inode *inode;
9198 delalloc_work = container_of(work, struct btrfs_delalloc_work,
9200 inode = delalloc_work->inode;
9201 filemap_flush(inode->i_mapping);
9202 if (test_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
9203 &BTRFS_I(inode)->runtime_flags))
9204 filemap_flush(inode->i_mapping);
9207 complete(&delalloc_work->completion);
9210 static struct btrfs_delalloc_work *btrfs_alloc_delalloc_work(struct inode *inode)
9212 struct btrfs_delalloc_work *work;
9214 work = kmalloc(sizeof(*work), GFP_NOFS);
9218 init_completion(&work->completion);
9219 INIT_LIST_HEAD(&work->list);
9220 work->inode = inode;
9221 btrfs_init_work(&work->work, btrfs_run_delalloc_work, NULL, NULL);
9227 * some fairly slow code that needs optimization. This walks the list
9228 * of all the inodes with pending delalloc and forces them to disk.
9230 static int start_delalloc_inodes(struct btrfs_root *root, int nr, bool snapshot)
9232 struct btrfs_inode *binode;
9233 struct inode *inode;
9234 struct btrfs_delalloc_work *work, *next;
9235 struct list_head works;
9236 struct list_head splice;
9239 INIT_LIST_HEAD(&works);
9240 INIT_LIST_HEAD(&splice);
9242 mutex_lock(&root->delalloc_mutex);
9243 spin_lock(&root->delalloc_lock);
9244 list_splice_init(&root->delalloc_inodes, &splice);
9245 while (!list_empty(&splice)) {
9246 binode = list_entry(splice.next, struct btrfs_inode,
9249 list_move_tail(&binode->delalloc_inodes,
9250 &root->delalloc_inodes);
9251 inode = igrab(&binode->vfs_inode);
9253 cond_resched_lock(&root->delalloc_lock);
9256 spin_unlock(&root->delalloc_lock);
9259 set_bit(BTRFS_INODE_SNAPSHOT_FLUSH,
9260 &binode->runtime_flags);
9261 work = btrfs_alloc_delalloc_work(inode);
9267 list_add_tail(&work->list, &works);
9268 btrfs_queue_work(root->fs_info->flush_workers,
9271 if (nr != -1 && ret >= nr)
9274 spin_lock(&root->delalloc_lock);
9276 spin_unlock(&root->delalloc_lock);
9279 list_for_each_entry_safe(work, next, &works, list) {
9280 list_del_init(&work->list);
9281 wait_for_completion(&work->completion);
9285 if (!list_empty(&splice)) {
9286 spin_lock(&root->delalloc_lock);
9287 list_splice_tail(&splice, &root->delalloc_inodes);
9288 spin_unlock(&root->delalloc_lock);
9290 mutex_unlock(&root->delalloc_mutex);
9294 int btrfs_start_delalloc_snapshot(struct btrfs_root *root)
9296 struct btrfs_fs_info *fs_info = root->fs_info;
9299 if (test_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state))
9302 ret = start_delalloc_inodes(root, -1, true);
9308 int btrfs_start_delalloc_roots(struct btrfs_fs_info *fs_info, int nr)
9310 struct btrfs_root *root;
9311 struct list_head splice;
9314 if (test_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state))
9317 INIT_LIST_HEAD(&splice);
9319 mutex_lock(&fs_info->delalloc_root_mutex);
9320 spin_lock(&fs_info->delalloc_root_lock);
9321 list_splice_init(&fs_info->delalloc_roots, &splice);
9322 while (!list_empty(&splice) && nr) {
9323 root = list_first_entry(&splice, struct btrfs_root,
9325 root = btrfs_grab_root(root);
9327 list_move_tail(&root->delalloc_root,
9328 &fs_info->delalloc_roots);
9329 spin_unlock(&fs_info->delalloc_root_lock);
9331 ret = start_delalloc_inodes(root, nr, false);
9332 btrfs_put_root(root);
9340 spin_lock(&fs_info->delalloc_root_lock);
9342 spin_unlock(&fs_info->delalloc_root_lock);
9346 if (!list_empty(&splice)) {
9347 spin_lock(&fs_info->delalloc_root_lock);
9348 list_splice_tail(&splice, &fs_info->delalloc_roots);
9349 spin_unlock(&fs_info->delalloc_root_lock);
9351 mutex_unlock(&fs_info->delalloc_root_mutex);
9355 static int btrfs_symlink(struct inode *dir, struct dentry *dentry,
9356 const char *symname)
9358 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
9359 struct btrfs_trans_handle *trans;
9360 struct btrfs_root *root = BTRFS_I(dir)->root;
9361 struct btrfs_path *path;
9362 struct btrfs_key key;
9363 struct inode *inode = NULL;
9370 struct btrfs_file_extent_item *ei;
9371 struct extent_buffer *leaf;
9373 name_len = strlen(symname);
9374 if (name_len > BTRFS_MAX_INLINE_DATA_SIZE(fs_info))
9375 return -ENAMETOOLONG;
9378 * 2 items for inode item and ref
9379 * 2 items for dir items
9380 * 1 item for updating parent inode item
9381 * 1 item for the inline extent item
9382 * 1 item for xattr if selinux is on
9384 trans = btrfs_start_transaction(root, 7);
9386 return PTR_ERR(trans);
9388 err = btrfs_find_free_ino(root, &objectid);
9392 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
9393 dentry->d_name.len, btrfs_ino(BTRFS_I(dir)),
9394 objectid, S_IFLNK|S_IRWXUGO, &index);
9395 if (IS_ERR(inode)) {
9396 err = PTR_ERR(inode);
9402 * If the active LSM wants to access the inode during
9403 * d_instantiate it needs these. Smack checks to see
9404 * if the filesystem supports xattrs by looking at the
9407 inode->i_fop = &btrfs_file_operations;
9408 inode->i_op = &btrfs_file_inode_operations;
9409 inode->i_mapping->a_ops = &btrfs_aops;
9410 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
9412 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
9416 path = btrfs_alloc_path();
9421 key.objectid = btrfs_ino(BTRFS_I(inode));
9423 key.type = BTRFS_EXTENT_DATA_KEY;
9424 datasize = btrfs_file_extent_calc_inline_size(name_len);
9425 err = btrfs_insert_empty_item(trans, root, path, &key,
9428 btrfs_free_path(path);
9431 leaf = path->nodes[0];
9432 ei = btrfs_item_ptr(leaf, path->slots[0],
9433 struct btrfs_file_extent_item);
9434 btrfs_set_file_extent_generation(leaf, ei, trans->transid);
9435 btrfs_set_file_extent_type(leaf, ei,
9436 BTRFS_FILE_EXTENT_INLINE);
9437 btrfs_set_file_extent_encryption(leaf, ei, 0);
9438 btrfs_set_file_extent_compression(leaf, ei, 0);
9439 btrfs_set_file_extent_other_encoding(leaf, ei, 0);
9440 btrfs_set_file_extent_ram_bytes(leaf, ei, name_len);
9442 ptr = btrfs_file_extent_inline_start(ei);
9443 write_extent_buffer(leaf, symname, ptr, name_len);
9444 btrfs_mark_buffer_dirty(leaf);
9445 btrfs_free_path(path);
9447 inode->i_op = &btrfs_symlink_inode_operations;
9448 inode_nohighmem(inode);
9449 inode_set_bytes(inode, name_len);
9450 btrfs_i_size_write(BTRFS_I(inode), name_len);
9451 err = btrfs_update_inode(trans, root, inode);
9453 * Last step, add directory indexes for our symlink inode. This is the
9454 * last step to avoid extra cleanup of these indexes if an error happens
9458 err = btrfs_add_nondir(trans, BTRFS_I(dir), dentry,
9459 BTRFS_I(inode), 0, index);
9463 d_instantiate_new(dentry, inode);
9466 btrfs_end_transaction(trans);
9468 inode_dec_link_count(inode);
9469 discard_new_inode(inode);
9471 btrfs_btree_balance_dirty(fs_info);
9475 static int __btrfs_prealloc_file_range(struct inode *inode, int mode,
9476 u64 start, u64 num_bytes, u64 min_size,
9477 loff_t actual_len, u64 *alloc_hint,
9478 struct btrfs_trans_handle *trans)
9480 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
9481 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
9482 struct extent_map *em;
9483 struct btrfs_root *root = BTRFS_I(inode)->root;
9484 struct btrfs_key ins;
9485 u64 cur_offset = start;
9486 u64 clear_offset = start;
9489 u64 last_alloc = (u64)-1;
9491 bool own_trans = true;
9492 u64 end = start + num_bytes - 1;
9496 while (num_bytes > 0) {
9498 trans = btrfs_start_transaction(root, 3);
9499 if (IS_ERR(trans)) {
9500 ret = PTR_ERR(trans);
9505 cur_bytes = min_t(u64, num_bytes, SZ_256M);
9506 cur_bytes = max(cur_bytes, min_size);
9508 * If we are severely fragmented we could end up with really
9509 * small allocations, so if the allocator is returning small
9510 * chunks lets make its job easier by only searching for those
9513 cur_bytes = min(cur_bytes, last_alloc);
9514 ret = btrfs_reserve_extent(root, cur_bytes, cur_bytes,
9515 min_size, 0, *alloc_hint, &ins, 1, 0);
9518 btrfs_end_transaction(trans);
9523 * We've reserved this space, and thus converted it from
9524 * ->bytes_may_use to ->bytes_reserved. Any error that happens
9525 * from here on out we will only need to clear our reservation
9526 * for the remaining unreserved area, so advance our
9527 * clear_offset by our extent size.
9529 clear_offset += ins.offset;
9530 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
9532 last_alloc = ins.offset;
9533 ret = insert_reserved_file_extent(trans, inode,
9534 cur_offset, ins.objectid,
9535 ins.offset, ins.offset,
9536 ins.offset, 0, 0, 0,
9537 BTRFS_FILE_EXTENT_PREALLOC);
9539 btrfs_free_reserved_extent(fs_info, ins.objectid,
9541 btrfs_abort_transaction(trans, ret);
9543 btrfs_end_transaction(trans);
9547 btrfs_drop_extent_cache(BTRFS_I(inode), cur_offset,
9548 cur_offset + ins.offset -1, 0);
9550 em = alloc_extent_map();
9552 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
9553 &BTRFS_I(inode)->runtime_flags);
9557 em->start = cur_offset;
9558 em->orig_start = cur_offset;
9559 em->len = ins.offset;
9560 em->block_start = ins.objectid;
9561 em->block_len = ins.offset;
9562 em->orig_block_len = ins.offset;
9563 em->ram_bytes = ins.offset;
9564 set_bit(EXTENT_FLAG_PREALLOC, &em->flags);
9565 em->generation = trans->transid;
9568 write_lock(&em_tree->lock);
9569 ret = add_extent_mapping(em_tree, em, 1);
9570 write_unlock(&em_tree->lock);
9573 btrfs_drop_extent_cache(BTRFS_I(inode), cur_offset,
9574 cur_offset + ins.offset - 1,
9577 free_extent_map(em);
9579 num_bytes -= ins.offset;
9580 cur_offset += ins.offset;
9581 *alloc_hint = ins.objectid + ins.offset;
9583 inode_inc_iversion(inode);
9584 inode->i_ctime = current_time(inode);
9585 BTRFS_I(inode)->flags |= BTRFS_INODE_PREALLOC;
9586 if (!(mode & FALLOC_FL_KEEP_SIZE) &&
9587 (actual_len > inode->i_size) &&
9588 (cur_offset > inode->i_size)) {
9589 if (cur_offset > actual_len)
9590 i_size = actual_len;
9592 i_size = cur_offset;
9593 i_size_write(inode, i_size);
9594 btrfs_inode_safe_disk_i_size_write(inode, 0);
9597 ret = btrfs_update_inode(trans, root, inode);
9600 btrfs_abort_transaction(trans, ret);
9602 btrfs_end_transaction(trans);
9607 btrfs_end_transaction(trans);
9609 if (clear_offset < end)
9610 btrfs_free_reserved_data_space(inode, NULL, clear_offset,
9611 end - clear_offset + 1);
9615 int btrfs_prealloc_file_range(struct inode *inode, int mode,
9616 u64 start, u64 num_bytes, u64 min_size,
9617 loff_t actual_len, u64 *alloc_hint)
9619 return __btrfs_prealloc_file_range(inode, mode, start, num_bytes,
9620 min_size, actual_len, alloc_hint,
9624 int btrfs_prealloc_file_range_trans(struct inode *inode,
9625 struct btrfs_trans_handle *trans, int mode,
9626 u64 start, u64 num_bytes, u64 min_size,
9627 loff_t actual_len, u64 *alloc_hint)
9629 return __btrfs_prealloc_file_range(inode, mode, start, num_bytes,
9630 min_size, actual_len, alloc_hint, trans);
9633 static int btrfs_set_page_dirty(struct page *page)
9635 return __set_page_dirty_nobuffers(page);
9638 static int btrfs_permission(struct inode *inode, int mask)
9640 struct btrfs_root *root = BTRFS_I(inode)->root;
9641 umode_t mode = inode->i_mode;
9643 if (mask & MAY_WRITE &&
9644 (S_ISREG(mode) || S_ISDIR(mode) || S_ISLNK(mode))) {
9645 if (btrfs_root_readonly(root))
9647 if (BTRFS_I(inode)->flags & BTRFS_INODE_READONLY)
9650 return generic_permission(inode, mask);
9653 static int btrfs_tmpfile(struct inode *dir, struct dentry *dentry, umode_t mode)
9655 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
9656 struct btrfs_trans_handle *trans;
9657 struct btrfs_root *root = BTRFS_I(dir)->root;
9658 struct inode *inode = NULL;
9664 * 5 units required for adding orphan entry
9666 trans = btrfs_start_transaction(root, 5);
9668 return PTR_ERR(trans);
9670 ret = btrfs_find_free_ino(root, &objectid);
9674 inode = btrfs_new_inode(trans, root, dir, NULL, 0,
9675 btrfs_ino(BTRFS_I(dir)), objectid, mode, &index);
9676 if (IS_ERR(inode)) {
9677 ret = PTR_ERR(inode);
9682 inode->i_fop = &btrfs_file_operations;
9683 inode->i_op = &btrfs_file_inode_operations;
9685 inode->i_mapping->a_ops = &btrfs_aops;
9686 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
9688 ret = btrfs_init_inode_security(trans, inode, dir, NULL);
9692 ret = btrfs_update_inode(trans, root, inode);
9695 ret = btrfs_orphan_add(trans, BTRFS_I(inode));
9700 * We set number of links to 0 in btrfs_new_inode(), and here we set
9701 * it to 1 because d_tmpfile() will issue a warning if the count is 0,
9704 * d_tmpfile() -> inode_dec_link_count() -> drop_nlink()
9706 set_nlink(inode, 1);
9707 d_tmpfile(dentry, inode);
9708 unlock_new_inode(inode);
9709 mark_inode_dirty(inode);
9711 btrfs_end_transaction(trans);
9713 discard_new_inode(inode);
9714 btrfs_btree_balance_dirty(fs_info);
9718 void btrfs_set_range_writeback(struct extent_io_tree *tree, u64 start, u64 end)
9720 struct inode *inode = tree->private_data;
9721 unsigned long index = start >> PAGE_SHIFT;
9722 unsigned long end_index = end >> PAGE_SHIFT;
9725 while (index <= end_index) {
9726 page = find_get_page(inode->i_mapping, index);
9727 ASSERT(page); /* Pages should be in the extent_io_tree */
9728 set_page_writeback(page);
9736 * Add an entry indicating a block group or device which is pinned by a
9737 * swapfile. Returns 0 on success, 1 if there is already an entry for it, or a
9738 * negative errno on failure.
9740 static int btrfs_add_swapfile_pin(struct inode *inode, void *ptr,
9741 bool is_block_group)
9743 struct btrfs_fs_info *fs_info = BTRFS_I(inode)->root->fs_info;
9744 struct btrfs_swapfile_pin *sp, *entry;
9746 struct rb_node *parent = NULL;
9748 sp = kmalloc(sizeof(*sp), GFP_NOFS);
9753 sp->is_block_group = is_block_group;
9755 spin_lock(&fs_info->swapfile_pins_lock);
9756 p = &fs_info->swapfile_pins.rb_node;
9759 entry = rb_entry(parent, struct btrfs_swapfile_pin, node);
9760 if (sp->ptr < entry->ptr ||
9761 (sp->ptr == entry->ptr && sp->inode < entry->inode)) {
9763 } else if (sp->ptr > entry->ptr ||
9764 (sp->ptr == entry->ptr && sp->inode > entry->inode)) {
9765 p = &(*p)->rb_right;
9767 spin_unlock(&fs_info->swapfile_pins_lock);
9772 rb_link_node(&sp->node, parent, p);
9773 rb_insert_color(&sp->node, &fs_info->swapfile_pins);
9774 spin_unlock(&fs_info->swapfile_pins_lock);
9778 /* Free all of the entries pinned by this swapfile. */
9779 static void btrfs_free_swapfile_pins(struct inode *inode)
9781 struct btrfs_fs_info *fs_info = BTRFS_I(inode)->root->fs_info;
9782 struct btrfs_swapfile_pin *sp;
9783 struct rb_node *node, *next;
9785 spin_lock(&fs_info->swapfile_pins_lock);
9786 node = rb_first(&fs_info->swapfile_pins);
9788 next = rb_next(node);
9789 sp = rb_entry(node, struct btrfs_swapfile_pin, node);
9790 if (sp->inode == inode) {
9791 rb_erase(&sp->node, &fs_info->swapfile_pins);
9792 if (sp->is_block_group)
9793 btrfs_put_block_group(sp->ptr);
9798 spin_unlock(&fs_info->swapfile_pins_lock);
9801 struct btrfs_swap_info {
9807 unsigned long nr_pages;
9811 static int btrfs_add_swap_extent(struct swap_info_struct *sis,
9812 struct btrfs_swap_info *bsi)
9814 unsigned long nr_pages;
9815 u64 first_ppage, first_ppage_reported, next_ppage;
9818 first_ppage = ALIGN(bsi->block_start, PAGE_SIZE) >> PAGE_SHIFT;
9819 next_ppage = ALIGN_DOWN(bsi->block_start + bsi->block_len,
9820 PAGE_SIZE) >> PAGE_SHIFT;
9822 if (first_ppage >= next_ppage)
9824 nr_pages = next_ppage - first_ppage;
9826 first_ppage_reported = first_ppage;
9827 if (bsi->start == 0)
9828 first_ppage_reported++;
9829 if (bsi->lowest_ppage > first_ppage_reported)
9830 bsi->lowest_ppage = first_ppage_reported;
9831 if (bsi->highest_ppage < (next_ppage - 1))
9832 bsi->highest_ppage = next_ppage - 1;
9834 ret = add_swap_extent(sis, bsi->nr_pages, nr_pages, first_ppage);
9837 bsi->nr_extents += ret;
9838 bsi->nr_pages += nr_pages;
9842 static void btrfs_swap_deactivate(struct file *file)
9844 struct inode *inode = file_inode(file);
9846 btrfs_free_swapfile_pins(inode);
9847 atomic_dec(&BTRFS_I(inode)->root->nr_swapfiles);
9850 static int btrfs_swap_activate(struct swap_info_struct *sis, struct file *file,
9853 struct inode *inode = file_inode(file);
9854 struct btrfs_fs_info *fs_info = BTRFS_I(inode)->root->fs_info;
9855 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
9856 struct extent_state *cached_state = NULL;
9857 struct extent_map *em = NULL;
9858 struct btrfs_device *device = NULL;
9859 struct btrfs_swap_info bsi = {
9860 .lowest_ppage = (sector_t)-1ULL,
9867 * If the swap file was just created, make sure delalloc is done. If the
9868 * file changes again after this, the user is doing something stupid and
9869 * we don't really care.
9871 ret = btrfs_wait_ordered_range(inode, 0, (u64)-1);
9876 * The inode is locked, so these flags won't change after we check them.
9878 if (BTRFS_I(inode)->flags & BTRFS_INODE_COMPRESS) {
9879 btrfs_warn(fs_info, "swapfile must not be compressed");
9882 if (!(BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW)) {
9883 btrfs_warn(fs_info, "swapfile must not be copy-on-write");
9886 if (!(BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)) {
9887 btrfs_warn(fs_info, "swapfile must not be checksummed");
9892 * Balance or device remove/replace/resize can move stuff around from
9893 * under us. The EXCL_OP flag makes sure they aren't running/won't run
9894 * concurrently while we are mapping the swap extents, and
9895 * fs_info->swapfile_pins prevents them from running while the swap file
9896 * is active and moving the extents. Note that this also prevents a
9897 * concurrent device add which isn't actually necessary, but it's not
9898 * really worth the trouble to allow it.
9900 if (test_and_set_bit(BTRFS_FS_EXCL_OP, &fs_info->flags)) {
9902 "cannot activate swapfile while exclusive operation is running");
9906 * Snapshots can create extents which require COW even if NODATACOW is
9907 * set. We use this counter to prevent snapshots. We must increment it
9908 * before walking the extents because we don't want a concurrent
9909 * snapshot to run after we've already checked the extents.
9911 atomic_inc(&BTRFS_I(inode)->root->nr_swapfiles);
9913 isize = ALIGN_DOWN(inode->i_size, fs_info->sectorsize);
9915 lock_extent_bits(io_tree, 0, isize - 1, &cached_state);
9917 while (start < isize) {
9918 u64 logical_block_start, physical_block_start;
9919 struct btrfs_block_group *bg;
9920 u64 len = isize - start;
9922 em = btrfs_get_extent(BTRFS_I(inode), NULL, 0, start, len);
9928 if (em->block_start == EXTENT_MAP_HOLE) {
9929 btrfs_warn(fs_info, "swapfile must not have holes");
9933 if (em->block_start == EXTENT_MAP_INLINE) {
9935 * It's unlikely we'll ever actually find ourselves
9936 * here, as a file small enough to fit inline won't be
9937 * big enough to store more than the swap header, but in
9938 * case something changes in the future, let's catch it
9939 * here rather than later.
9941 btrfs_warn(fs_info, "swapfile must not be inline");
9945 if (test_bit(EXTENT_FLAG_COMPRESSED, &em->flags)) {
9946 btrfs_warn(fs_info, "swapfile must not be compressed");
9951 logical_block_start = em->block_start + (start - em->start);
9952 len = min(len, em->len - (start - em->start));
9953 free_extent_map(em);
9956 ret = can_nocow_extent(inode, start, &len, NULL, NULL, NULL);
9963 "swapfile must not be copy-on-write");
9968 em = btrfs_get_chunk_map(fs_info, logical_block_start, len);
9974 if (em->map_lookup->type & BTRFS_BLOCK_GROUP_PROFILE_MASK) {
9976 "swapfile must have single data profile");
9981 if (device == NULL) {
9982 device = em->map_lookup->stripes[0].dev;
9983 ret = btrfs_add_swapfile_pin(inode, device, false);
9988 } else if (device != em->map_lookup->stripes[0].dev) {
9989 btrfs_warn(fs_info, "swapfile must be on one device");
9994 physical_block_start = (em->map_lookup->stripes[0].physical +
9995 (logical_block_start - em->start));
9996 len = min(len, em->len - (logical_block_start - em->start));
9997 free_extent_map(em);
10000 bg = btrfs_lookup_block_group(fs_info, logical_block_start);
10002 btrfs_warn(fs_info,
10003 "could not find block group containing swapfile");
10008 ret = btrfs_add_swapfile_pin(inode, bg, true);
10010 btrfs_put_block_group(bg);
10017 if (bsi.block_len &&
10018 bsi.block_start + bsi.block_len == physical_block_start) {
10019 bsi.block_len += len;
10021 if (bsi.block_len) {
10022 ret = btrfs_add_swap_extent(sis, &bsi);
10027 bsi.block_start = physical_block_start;
10028 bsi.block_len = len;
10035 ret = btrfs_add_swap_extent(sis, &bsi);
10038 if (!IS_ERR_OR_NULL(em))
10039 free_extent_map(em);
10041 unlock_extent_cached(io_tree, 0, isize - 1, &cached_state);
10044 btrfs_swap_deactivate(file);
10046 clear_bit(BTRFS_FS_EXCL_OP, &fs_info->flags);
10052 sis->bdev = device->bdev;
10053 *span = bsi.highest_ppage - bsi.lowest_ppage + 1;
10054 sis->max = bsi.nr_pages;
10055 sis->pages = bsi.nr_pages - 1;
10056 sis->highest_bit = bsi.nr_pages - 1;
10057 return bsi.nr_extents;
10060 static void btrfs_swap_deactivate(struct file *file)
10064 static int btrfs_swap_activate(struct swap_info_struct *sis, struct file *file,
10067 return -EOPNOTSUPP;
10071 static const struct inode_operations btrfs_dir_inode_operations = {
10072 .getattr = btrfs_getattr,
10073 .lookup = btrfs_lookup,
10074 .create = btrfs_create,
10075 .unlink = btrfs_unlink,
10076 .link = btrfs_link,
10077 .mkdir = btrfs_mkdir,
10078 .rmdir = btrfs_rmdir,
10079 .rename = btrfs_rename2,
10080 .symlink = btrfs_symlink,
10081 .setattr = btrfs_setattr,
10082 .mknod = btrfs_mknod,
10083 .listxattr = btrfs_listxattr,
10084 .permission = btrfs_permission,
10085 .get_acl = btrfs_get_acl,
10086 .set_acl = btrfs_set_acl,
10087 .update_time = btrfs_update_time,
10088 .tmpfile = btrfs_tmpfile,
10091 static const struct file_operations btrfs_dir_file_operations = {
10092 .llseek = generic_file_llseek,
10093 .read = generic_read_dir,
10094 .iterate_shared = btrfs_real_readdir,
10095 .open = btrfs_opendir,
10096 .unlocked_ioctl = btrfs_ioctl,
10097 #ifdef CONFIG_COMPAT
10098 .compat_ioctl = btrfs_compat_ioctl,
10100 .release = btrfs_release_file,
10101 .fsync = btrfs_sync_file,
10104 static const struct extent_io_ops btrfs_extent_io_ops = {
10105 /* mandatory callbacks */
10106 .submit_bio_hook = btrfs_submit_bio_hook,
10107 .readpage_end_io_hook = btrfs_readpage_end_io_hook,
10111 * btrfs doesn't support the bmap operation because swapfiles
10112 * use bmap to make a mapping of extents in the file. They assume
10113 * these extents won't change over the life of the file and they
10114 * use the bmap result to do IO directly to the drive.
10116 * the btrfs bmap call would return logical addresses that aren't
10117 * suitable for IO and they also will change frequently as COW
10118 * operations happen. So, swapfile + btrfs == corruption.
10120 * For now we're avoiding this by dropping bmap.
10122 static const struct address_space_operations btrfs_aops = {
10123 .readpage = btrfs_readpage,
10124 .writepage = btrfs_writepage,
10125 .writepages = btrfs_writepages,
10126 .readahead = btrfs_readahead,
10127 .direct_IO = noop_direct_IO,
10128 .invalidatepage = btrfs_invalidatepage,
10129 .releasepage = btrfs_releasepage,
10130 #ifdef CONFIG_MIGRATION
10131 .migratepage = btrfs_migratepage,
10133 .set_page_dirty = btrfs_set_page_dirty,
10134 .error_remove_page = generic_error_remove_page,
10135 .swap_activate = btrfs_swap_activate,
10136 .swap_deactivate = btrfs_swap_deactivate,
10139 static const struct inode_operations btrfs_file_inode_operations = {
10140 .getattr = btrfs_getattr,
10141 .setattr = btrfs_setattr,
10142 .listxattr = btrfs_listxattr,
10143 .permission = btrfs_permission,
10144 .fiemap = btrfs_fiemap,
10145 .get_acl = btrfs_get_acl,
10146 .set_acl = btrfs_set_acl,
10147 .update_time = btrfs_update_time,
10149 static const struct inode_operations btrfs_special_inode_operations = {
10150 .getattr = btrfs_getattr,
10151 .setattr = btrfs_setattr,
10152 .permission = btrfs_permission,
10153 .listxattr = btrfs_listxattr,
10154 .get_acl = btrfs_get_acl,
10155 .set_acl = btrfs_set_acl,
10156 .update_time = btrfs_update_time,
10158 static const struct inode_operations btrfs_symlink_inode_operations = {
10159 .get_link = page_get_link,
10160 .getattr = btrfs_getattr,
10161 .setattr = btrfs_setattr,
10162 .permission = btrfs_permission,
10163 .listxattr = btrfs_listxattr,
10164 .update_time = btrfs_update_time,
10167 const struct dentry_operations btrfs_dentry_operations = {
10168 .d_delete = btrfs_dentry_delete,