1 // SPDX-License-Identifier: GPL-2.0
3 * Copyright (C) 2007 Oracle. All rights reserved.
6 #include <linux/kernel.h>
8 #include <linux/buffer_head.h>
9 #include <linux/file.h>
11 #include <linux/pagemap.h>
12 #include <linux/highmem.h>
13 #include <linux/time.h>
14 #include <linux/init.h>
15 #include <linux/string.h>
16 #include <linux/backing-dev.h>
17 #include <linux/mpage.h>
18 #include <linux/swap.h>
19 #include <linux/writeback.h>
20 #include <linux/compat.h>
21 #include <linux/bit_spinlock.h>
22 #include <linux/xattr.h>
23 #include <linux/posix_acl.h>
24 #include <linux/falloc.h>
25 #include <linux/slab.h>
26 #include <linux/ratelimit.h>
27 #include <linux/mount.h>
28 #include <linux/btrfs.h>
29 #include <linux/blkdev.h>
30 #include <linux/posix_acl_xattr.h>
31 #include <linux/uio.h>
32 #include <linux/magic.h>
33 #include <linux/iversion.h>
34 #include <asm/unaligned.h>
37 #include "transaction.h"
38 #include "btrfs_inode.h"
39 #include "print-tree.h"
40 #include "ordered-data.h"
44 #include "compression.h"
46 #include "free-space-cache.h"
47 #include "inode-map.h"
53 struct btrfs_iget_args {
54 struct btrfs_key *location;
55 struct btrfs_root *root;
58 struct btrfs_dio_data {
60 u64 unsubmitted_oe_range_start;
61 u64 unsubmitted_oe_range_end;
65 static const struct inode_operations btrfs_dir_inode_operations;
66 static const struct inode_operations btrfs_symlink_inode_operations;
67 static const struct inode_operations btrfs_dir_ro_inode_operations;
68 static const struct inode_operations btrfs_special_inode_operations;
69 static const struct inode_operations btrfs_file_inode_operations;
70 static const struct address_space_operations btrfs_aops;
71 static const struct address_space_operations btrfs_symlink_aops;
72 static const struct file_operations btrfs_dir_file_operations;
73 static const struct extent_io_ops btrfs_extent_io_ops;
75 static struct kmem_cache *btrfs_inode_cachep;
76 struct kmem_cache *btrfs_trans_handle_cachep;
77 struct kmem_cache *btrfs_path_cachep;
78 struct kmem_cache *btrfs_free_space_cachep;
81 static const unsigned char btrfs_type_by_mode[S_IFMT >> S_SHIFT] = {
82 [S_IFREG >> S_SHIFT] = BTRFS_FT_REG_FILE,
83 [S_IFDIR >> S_SHIFT] = BTRFS_FT_DIR,
84 [S_IFCHR >> S_SHIFT] = BTRFS_FT_CHRDEV,
85 [S_IFBLK >> S_SHIFT] = BTRFS_FT_BLKDEV,
86 [S_IFIFO >> S_SHIFT] = BTRFS_FT_FIFO,
87 [S_IFSOCK >> S_SHIFT] = BTRFS_FT_SOCK,
88 [S_IFLNK >> S_SHIFT] = BTRFS_FT_SYMLINK,
91 static int btrfs_setsize(struct inode *inode, struct iattr *attr);
92 static int btrfs_truncate(struct inode *inode, bool skip_writeback);
93 static int btrfs_finish_ordered_io(struct btrfs_ordered_extent *ordered_extent);
94 static noinline int cow_file_range(struct inode *inode,
95 struct page *locked_page,
96 u64 start, u64 end, u64 delalloc_end,
97 int *page_started, unsigned long *nr_written,
98 int unlock, struct btrfs_dedupe_hash *hash);
99 static struct extent_map *create_io_em(struct inode *inode, u64 start, u64 len,
100 u64 orig_start, u64 block_start,
101 u64 block_len, u64 orig_block_len,
102 u64 ram_bytes, int compress_type,
105 static void __endio_write_update_ordered(struct inode *inode,
106 const u64 offset, const u64 bytes,
107 const bool uptodate);
110 * Cleanup all submitted ordered extents in specified range to handle errors
111 * from the fill_dellaloc() callback.
113 * NOTE: caller must ensure that when an error happens, it can not call
114 * extent_clear_unlock_delalloc() to clear both the bits EXTENT_DO_ACCOUNTING
115 * and EXTENT_DELALLOC simultaneously, because that causes the reserved metadata
116 * to be released, which we want to happen only when finishing the ordered
117 * extent (btrfs_finish_ordered_io()). Also note that the caller of the
118 * fill_delalloc() callback already does proper cleanup for the first page of
119 * the range, that is, it invokes the callback writepage_end_io_hook() for the
120 * range of the first page.
122 static inline void btrfs_cleanup_ordered_extents(struct inode *inode,
126 unsigned long index = offset >> PAGE_SHIFT;
127 unsigned long end_index = (offset + bytes - 1) >> PAGE_SHIFT;
130 while (index <= end_index) {
131 page = find_get_page(inode->i_mapping, index);
135 ClearPagePrivate2(page);
138 return __endio_write_update_ordered(inode, offset + PAGE_SIZE,
139 bytes - PAGE_SIZE, false);
142 static int btrfs_dirty_inode(struct inode *inode);
144 #ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
145 void btrfs_test_inode_set_ops(struct inode *inode)
147 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
151 static int btrfs_init_inode_security(struct btrfs_trans_handle *trans,
152 struct inode *inode, struct inode *dir,
153 const struct qstr *qstr)
157 err = btrfs_init_acl(trans, inode, dir);
159 err = btrfs_xattr_security_init(trans, inode, dir, qstr);
164 * this does all the hard work for inserting an inline extent into
165 * the btree. The caller should have done a btrfs_drop_extents so that
166 * no overlapping inline items exist in the btree
168 static int insert_inline_extent(struct btrfs_trans_handle *trans,
169 struct btrfs_path *path, int extent_inserted,
170 struct btrfs_root *root, struct inode *inode,
171 u64 start, size_t size, size_t compressed_size,
173 struct page **compressed_pages)
175 struct extent_buffer *leaf;
176 struct page *page = NULL;
179 struct btrfs_file_extent_item *ei;
181 size_t cur_size = size;
182 unsigned long offset;
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 = start & (PAGE_SIZE - 1);
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're an inline extent, so nobody can
247 * extend the file past i_size without locking
248 * a page we already have locked.
250 * We must do any isize and inode updates
251 * before we unlock the pages. Otherwise we
252 * could end up racing with unlink.
254 BTRFS_I(inode)->disk_i_size = inode->i_size;
255 ret = btrfs_update_inode(trans, root, inode);
263 * conditionally insert an inline extent into the file. This
264 * does the checks required to make sure the data is small enough
265 * to fit as an inline extent.
267 static noinline int cow_file_range_inline(struct inode *inode, u64 start,
268 u64 end, size_t compressed_size,
270 struct page **compressed_pages)
272 struct btrfs_root *root = BTRFS_I(inode)->root;
273 struct btrfs_fs_info *fs_info = root->fs_info;
274 struct btrfs_trans_handle *trans;
275 u64 isize = i_size_read(inode);
276 u64 actual_end = min(end + 1, isize);
277 u64 inline_len = actual_end - start;
278 u64 aligned_end = ALIGN(end, fs_info->sectorsize);
279 u64 data_len = inline_len;
281 struct btrfs_path *path;
282 int extent_inserted = 0;
283 u32 extent_item_size;
286 data_len = compressed_size;
289 actual_end > fs_info->sectorsize ||
290 data_len > BTRFS_MAX_INLINE_DATA_SIZE(fs_info) ||
292 (actual_end & (fs_info->sectorsize - 1)) == 0) ||
294 data_len > fs_info->max_inline) {
298 path = btrfs_alloc_path();
302 trans = btrfs_join_transaction(root);
304 btrfs_free_path(path);
305 return PTR_ERR(trans);
307 trans->block_rsv = &BTRFS_I(inode)->block_rsv;
309 if (compressed_size && compressed_pages)
310 extent_item_size = btrfs_file_extent_calc_inline_size(
313 extent_item_size = btrfs_file_extent_calc_inline_size(
316 ret = __btrfs_drop_extents(trans, root, inode, path,
317 start, aligned_end, NULL,
318 1, 1, extent_item_size, &extent_inserted);
320 btrfs_abort_transaction(trans, ret);
324 if (isize > actual_end)
325 inline_len = min_t(u64, isize, actual_end);
326 ret = insert_inline_extent(trans, path, extent_inserted,
328 inline_len, compressed_size,
329 compress_type, compressed_pages);
330 if (ret && ret != -ENOSPC) {
331 btrfs_abort_transaction(trans, ret);
333 } else if (ret == -ENOSPC) {
338 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &BTRFS_I(inode)->runtime_flags);
339 btrfs_drop_extent_cache(BTRFS_I(inode), start, aligned_end - 1, 0);
342 * Don't forget to free the reserved space, as for inlined extent
343 * it won't count as data extent, free them directly here.
344 * And at reserve time, it's always aligned to page size, so
345 * just free one page here.
347 btrfs_qgroup_free_data(inode, NULL, 0, PAGE_SIZE);
348 btrfs_free_path(path);
349 btrfs_end_transaction(trans);
353 struct async_extent {
358 unsigned long nr_pages;
360 struct list_head list;
365 struct btrfs_root *root;
366 struct page *locked_page;
369 unsigned int write_flags;
370 struct list_head extents;
371 struct btrfs_work work;
374 static noinline int add_async_extent(struct async_cow *cow,
375 u64 start, u64 ram_size,
378 unsigned long nr_pages,
381 struct async_extent *async_extent;
383 async_extent = kmalloc(sizeof(*async_extent), GFP_NOFS);
384 BUG_ON(!async_extent); /* -ENOMEM */
385 async_extent->start = start;
386 async_extent->ram_size = ram_size;
387 async_extent->compressed_size = compressed_size;
388 async_extent->pages = pages;
389 async_extent->nr_pages = nr_pages;
390 async_extent->compress_type = compress_type;
391 list_add_tail(&async_extent->list, &cow->extents);
395 static inline int inode_need_compress(struct inode *inode, u64 start, u64 end)
397 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
400 if (btrfs_test_opt(fs_info, FORCE_COMPRESS))
403 if (BTRFS_I(inode)->defrag_compress)
405 /* bad compression ratios */
406 if (BTRFS_I(inode)->flags & BTRFS_INODE_NOCOMPRESS)
408 if (btrfs_test_opt(fs_info, COMPRESS) ||
409 BTRFS_I(inode)->flags & BTRFS_INODE_COMPRESS ||
410 BTRFS_I(inode)->prop_compress)
411 return btrfs_compress_heuristic(inode, start, end);
415 static inline void inode_should_defrag(struct btrfs_inode *inode,
416 u64 start, u64 end, u64 num_bytes, u64 small_write)
418 /* If this is a small write inside eof, kick off a defrag */
419 if (num_bytes < small_write &&
420 (start > 0 || end + 1 < inode->disk_i_size))
421 btrfs_add_inode_defrag(NULL, inode);
425 * we create compressed extents in two phases. The first
426 * phase compresses a range of pages that have already been
427 * locked (both pages and state bits are locked).
429 * This is done inside an ordered work queue, and the compression
430 * is spread across many cpus. The actual IO submission is step
431 * two, and the ordered work queue takes care of making sure that
432 * happens in the same order things were put onto the queue by
433 * writepages and friends.
435 * If this code finds it can't get good compression, it puts an
436 * entry onto the work queue to write the uncompressed bytes. This
437 * makes sure that both compressed inodes and uncompressed inodes
438 * are written in the same order that the flusher thread sent them
441 static noinline void compress_file_range(struct inode *inode,
442 struct page *locked_page,
444 struct async_cow *async_cow,
447 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
448 u64 blocksize = fs_info->sectorsize;
450 u64 isize = i_size_read(inode);
452 struct page **pages = NULL;
453 unsigned long nr_pages;
454 unsigned long total_compressed = 0;
455 unsigned long total_in = 0;
458 int compress_type = fs_info->compress_type;
461 inode_should_defrag(BTRFS_I(inode), start, end, end - start + 1,
464 actual_end = min_t(u64, isize, end + 1);
467 nr_pages = (end >> PAGE_SHIFT) - (start >> PAGE_SHIFT) + 1;
468 BUILD_BUG_ON((BTRFS_MAX_COMPRESSED % PAGE_SIZE) != 0);
469 nr_pages = min_t(unsigned long, nr_pages,
470 BTRFS_MAX_COMPRESSED / PAGE_SIZE);
473 * we don't want to send crud past the end of i_size through
474 * compression, that's just a waste of CPU time. So, if the
475 * end of the file is before the start of our current
476 * requested range of bytes, we bail out to the uncompressed
477 * cleanup code that can deal with all of this.
479 * It isn't really the fastest way to fix things, but this is a
480 * very uncommon corner.
482 if (actual_end <= start)
483 goto cleanup_and_bail_uncompressed;
485 total_compressed = actual_end - start;
488 * skip compression for a small file range(<=blocksize) that
489 * isn't an inline extent, since it doesn't save disk space at all.
491 if (total_compressed <= blocksize &&
492 (start > 0 || end + 1 < BTRFS_I(inode)->disk_i_size))
493 goto cleanup_and_bail_uncompressed;
495 total_compressed = min_t(unsigned long, total_compressed,
496 BTRFS_MAX_UNCOMPRESSED);
501 * we do compression for mount -o compress and when the
502 * inode has not been flagged as nocompress. This flag can
503 * change at any time if we discover bad compression ratios.
505 if (inode_need_compress(inode, start, end)) {
507 pages = kcalloc(nr_pages, sizeof(struct page *), GFP_NOFS);
509 /* just bail out to the uncompressed code */
513 if (BTRFS_I(inode)->defrag_compress)
514 compress_type = BTRFS_I(inode)->defrag_compress;
515 else if (BTRFS_I(inode)->prop_compress)
516 compress_type = BTRFS_I(inode)->prop_compress;
519 * we need to call clear_page_dirty_for_io on each
520 * page in the range. Otherwise applications with the file
521 * mmap'd can wander in and change the page contents while
522 * we are compressing them.
524 * If the compression fails for any reason, we set the pages
525 * dirty again later on.
527 * Note that the remaining part is redirtied, the start pointer
528 * has moved, the end is the original one.
531 extent_range_clear_dirty_for_io(inode, start, end);
535 /* Compression level is applied here and only here */
536 ret = btrfs_compress_pages(
537 compress_type | (fs_info->compress_level << 4),
538 inode->i_mapping, start,
545 unsigned long offset = total_compressed &
547 struct page *page = pages[nr_pages - 1];
550 /* zero the tail end of the last page, we might be
551 * sending it down to disk
554 kaddr = kmap_atomic(page);
555 memset(kaddr + offset, 0,
557 kunmap_atomic(kaddr);
564 /* lets try to make an inline extent */
565 if (ret || total_in < actual_end) {
566 /* we didn't compress the entire range, try
567 * to make an uncompressed inline extent.
569 ret = cow_file_range_inline(inode, start, end, 0,
570 BTRFS_COMPRESS_NONE, NULL);
572 /* try making a compressed inline extent */
573 ret = cow_file_range_inline(inode, start, end,
575 compress_type, pages);
578 unsigned long clear_flags = EXTENT_DELALLOC |
579 EXTENT_DELALLOC_NEW | EXTENT_DEFRAG |
580 EXTENT_DO_ACCOUNTING;
581 unsigned long page_error_op;
583 page_error_op = ret < 0 ? PAGE_SET_ERROR : 0;
586 * inline extent creation worked or returned error,
587 * we don't need to create any more async work items.
588 * Unlock and free up our temp pages.
590 * We use DO_ACCOUNTING here because we need the
591 * delalloc_release_metadata to be done _after_ we drop
592 * our outstanding extent for clearing delalloc for this
595 extent_clear_unlock_delalloc(inode, start, end, end,
608 * we aren't doing an inline extent round the compressed size
609 * up to a block size boundary so the allocator does sane
612 total_compressed = ALIGN(total_compressed, blocksize);
615 * one last check to make sure the compression is really a
616 * win, compare the page count read with the blocks on disk,
617 * compression must free at least one sector size
619 total_in = ALIGN(total_in, PAGE_SIZE);
620 if (total_compressed + blocksize <= total_in) {
624 * The async work queues will take care of doing actual
625 * allocation on disk for these compressed pages, and
626 * will submit them to the elevator.
628 add_async_extent(async_cow, start, total_in,
629 total_compressed, pages, nr_pages,
632 if (start + total_in < end) {
643 * the compression code ran but failed to make things smaller,
644 * free any pages it allocated and our page pointer array
646 for (i = 0; i < nr_pages; i++) {
647 WARN_ON(pages[i]->mapping);
652 total_compressed = 0;
655 /* flag the file so we don't compress in the future */
656 if (!btrfs_test_opt(fs_info, FORCE_COMPRESS) &&
657 !(BTRFS_I(inode)->prop_compress)) {
658 BTRFS_I(inode)->flags |= BTRFS_INODE_NOCOMPRESS;
661 cleanup_and_bail_uncompressed:
663 * No compression, but we still need to write the pages in the file
664 * we've been given so far. redirty the locked page if it corresponds
665 * to our extent and set things up for the async work queue to run
666 * cow_file_range to do the normal delalloc dance.
668 if (page_offset(locked_page) >= start &&
669 page_offset(locked_page) <= end)
670 __set_page_dirty_nobuffers(locked_page);
671 /* unlocked later on in the async handlers */
674 extent_range_redirty_for_io(inode, start, end);
675 add_async_extent(async_cow, start, end - start + 1, 0, NULL, 0,
676 BTRFS_COMPRESS_NONE);
682 for (i = 0; i < nr_pages; i++) {
683 WARN_ON(pages[i]->mapping);
689 static void free_async_extent_pages(struct async_extent *async_extent)
693 if (!async_extent->pages)
696 for (i = 0; i < async_extent->nr_pages; i++) {
697 WARN_ON(async_extent->pages[i]->mapping);
698 put_page(async_extent->pages[i]);
700 kfree(async_extent->pages);
701 async_extent->nr_pages = 0;
702 async_extent->pages = NULL;
706 * phase two of compressed writeback. This is the ordered portion
707 * of the code, which only gets called in the order the work was
708 * queued. We walk all the async extents created by compress_file_range
709 * and send them down to the disk.
711 static noinline void submit_compressed_extents(struct inode *inode,
712 struct async_cow *async_cow)
714 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
715 struct async_extent *async_extent;
717 struct btrfs_key ins;
718 struct extent_map *em;
719 struct btrfs_root *root = BTRFS_I(inode)->root;
720 struct extent_io_tree *io_tree;
724 while (!list_empty(&async_cow->extents)) {
725 async_extent = list_entry(async_cow->extents.next,
726 struct async_extent, list);
727 list_del(&async_extent->list);
729 io_tree = &BTRFS_I(inode)->io_tree;
732 /* did the compression code fall back to uncompressed IO? */
733 if (!async_extent->pages) {
734 int page_started = 0;
735 unsigned long nr_written = 0;
737 lock_extent(io_tree, async_extent->start,
738 async_extent->start +
739 async_extent->ram_size - 1);
741 /* allocate blocks */
742 ret = cow_file_range(inode, async_cow->locked_page,
744 async_extent->start +
745 async_extent->ram_size - 1,
746 async_extent->start +
747 async_extent->ram_size - 1,
748 &page_started, &nr_written, 0,
754 * if page_started, cow_file_range inserted an
755 * inline extent and took care of all the unlocking
756 * and IO for us. Otherwise, we need to submit
757 * all those pages down to the drive.
759 if (!page_started && !ret)
760 extent_write_locked_range(inode,
762 async_extent->start +
763 async_extent->ram_size - 1,
766 unlock_page(async_cow->locked_page);
772 lock_extent(io_tree, async_extent->start,
773 async_extent->start + async_extent->ram_size - 1);
775 ret = btrfs_reserve_extent(root, async_extent->ram_size,
776 async_extent->compressed_size,
777 async_extent->compressed_size,
778 0, alloc_hint, &ins, 1, 1);
780 free_async_extent_pages(async_extent);
782 if (ret == -ENOSPC) {
783 unlock_extent(io_tree, async_extent->start,
784 async_extent->start +
785 async_extent->ram_size - 1);
788 * we need to redirty the pages if we decide to
789 * fallback to uncompressed IO, otherwise we
790 * will not submit these pages down to lower
793 extent_range_redirty_for_io(inode,
795 async_extent->start +
796 async_extent->ram_size - 1);
803 * here we're doing allocation and writeback of the
806 em = create_io_em(inode, async_extent->start,
807 async_extent->ram_size, /* len */
808 async_extent->start, /* orig_start */
809 ins.objectid, /* block_start */
810 ins.offset, /* block_len */
811 ins.offset, /* orig_block_len */
812 async_extent->ram_size, /* ram_bytes */
813 async_extent->compress_type,
814 BTRFS_ORDERED_COMPRESSED);
816 /* ret value is not necessary due to void function */
817 goto out_free_reserve;
820 ret = btrfs_add_ordered_extent_compress(inode,
823 async_extent->ram_size,
825 BTRFS_ORDERED_COMPRESSED,
826 async_extent->compress_type);
828 btrfs_drop_extent_cache(BTRFS_I(inode),
830 async_extent->start +
831 async_extent->ram_size - 1, 0);
832 goto out_free_reserve;
834 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
837 * clear dirty, set writeback and unlock the pages.
839 extent_clear_unlock_delalloc(inode, async_extent->start,
840 async_extent->start +
841 async_extent->ram_size - 1,
842 async_extent->start +
843 async_extent->ram_size - 1,
844 NULL, EXTENT_LOCKED | EXTENT_DELALLOC,
845 PAGE_UNLOCK | PAGE_CLEAR_DIRTY |
847 if (btrfs_submit_compressed_write(inode,
849 async_extent->ram_size,
851 ins.offset, async_extent->pages,
852 async_extent->nr_pages,
853 async_cow->write_flags)) {
854 struct extent_io_tree *tree = &BTRFS_I(inode)->io_tree;
855 struct page *p = async_extent->pages[0];
856 const u64 start = async_extent->start;
857 const u64 end = start + async_extent->ram_size - 1;
859 p->mapping = inode->i_mapping;
860 tree->ops->writepage_end_io_hook(p, start, end,
863 extent_clear_unlock_delalloc(inode, start, end, end,
867 free_async_extent_pages(async_extent);
869 alloc_hint = ins.objectid + ins.offset;
875 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
876 btrfs_free_reserved_extent(fs_info, ins.objectid, ins.offset, 1);
878 extent_clear_unlock_delalloc(inode, async_extent->start,
879 async_extent->start +
880 async_extent->ram_size - 1,
881 async_extent->start +
882 async_extent->ram_size - 1,
883 NULL, EXTENT_LOCKED | EXTENT_DELALLOC |
884 EXTENT_DELALLOC_NEW |
885 EXTENT_DEFRAG | EXTENT_DO_ACCOUNTING,
886 PAGE_UNLOCK | PAGE_CLEAR_DIRTY |
887 PAGE_SET_WRITEBACK | PAGE_END_WRITEBACK |
889 free_async_extent_pages(async_extent);
894 static u64 get_extent_allocation_hint(struct inode *inode, u64 start,
897 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
898 struct extent_map *em;
901 read_lock(&em_tree->lock);
902 em = search_extent_mapping(em_tree, start, num_bytes);
905 * if block start isn't an actual block number then find the
906 * first block in this inode and use that as a hint. If that
907 * block is also bogus then just don't worry about it.
909 if (em->block_start >= EXTENT_MAP_LAST_BYTE) {
911 em = search_extent_mapping(em_tree, 0, 0);
912 if (em && em->block_start < EXTENT_MAP_LAST_BYTE)
913 alloc_hint = em->block_start;
917 alloc_hint = em->block_start;
921 read_unlock(&em_tree->lock);
927 * when extent_io.c finds a delayed allocation range in the file,
928 * the call backs end up in this code. The basic idea is to
929 * allocate extents on disk for the range, and create ordered data structs
930 * in ram to track those extents.
932 * locked_page is the page that writepage had locked already. We use
933 * it to make sure we don't do extra locks or unlocks.
935 * *page_started is set to one if we unlock locked_page and do everything
936 * required to start IO on it. It may be clean and already done with
939 static noinline int cow_file_range(struct inode *inode,
940 struct page *locked_page,
941 u64 start, u64 end, u64 delalloc_end,
942 int *page_started, unsigned long *nr_written,
943 int unlock, struct btrfs_dedupe_hash *hash)
945 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
946 struct btrfs_root *root = BTRFS_I(inode)->root;
949 unsigned long ram_size;
950 u64 cur_alloc_size = 0;
951 u64 blocksize = fs_info->sectorsize;
952 struct btrfs_key ins;
953 struct extent_map *em;
955 unsigned long page_ops;
956 bool extent_reserved = false;
959 if (btrfs_is_free_space_inode(BTRFS_I(inode))) {
965 num_bytes = ALIGN(end - start + 1, blocksize);
966 num_bytes = max(blocksize, num_bytes);
967 ASSERT(num_bytes <= btrfs_super_total_bytes(fs_info->super_copy));
969 inode_should_defrag(BTRFS_I(inode), start, end, num_bytes, SZ_64K);
972 /* lets try to make an inline extent */
973 ret = cow_file_range_inline(inode, start, end, 0,
974 BTRFS_COMPRESS_NONE, NULL);
977 * We use DO_ACCOUNTING here because we need the
978 * delalloc_release_metadata to be run _after_ we drop
979 * our outstanding extent for clearing delalloc for this
982 extent_clear_unlock_delalloc(inode, start, end,
984 EXTENT_LOCKED | EXTENT_DELALLOC |
985 EXTENT_DELALLOC_NEW | EXTENT_DEFRAG |
986 EXTENT_DO_ACCOUNTING, PAGE_UNLOCK |
987 PAGE_CLEAR_DIRTY | PAGE_SET_WRITEBACK |
989 *nr_written = *nr_written +
990 (end - start + PAGE_SIZE) / PAGE_SIZE;
993 } else if (ret < 0) {
998 alloc_hint = get_extent_allocation_hint(inode, start, num_bytes);
999 btrfs_drop_extent_cache(BTRFS_I(inode), start,
1000 start + num_bytes - 1, 0);
1002 while (num_bytes > 0) {
1003 cur_alloc_size = num_bytes;
1004 ret = btrfs_reserve_extent(root, cur_alloc_size, cur_alloc_size,
1005 fs_info->sectorsize, 0, alloc_hint,
1009 cur_alloc_size = ins.offset;
1010 extent_reserved = true;
1012 ram_size = ins.offset;
1013 em = create_io_em(inode, start, ins.offset, /* len */
1014 start, /* orig_start */
1015 ins.objectid, /* block_start */
1016 ins.offset, /* block_len */
1017 ins.offset, /* orig_block_len */
1018 ram_size, /* ram_bytes */
1019 BTRFS_COMPRESS_NONE, /* compress_type */
1020 BTRFS_ORDERED_REGULAR /* type */);
1023 free_extent_map(em);
1025 ret = btrfs_add_ordered_extent(inode, start, ins.objectid,
1026 ram_size, cur_alloc_size, 0);
1028 goto out_drop_extent_cache;
1030 if (root->root_key.objectid ==
1031 BTRFS_DATA_RELOC_TREE_OBJECTID) {
1032 ret = btrfs_reloc_clone_csums(inode, start,
1035 * Only drop cache here, and process as normal.
1037 * We must not allow extent_clear_unlock_delalloc()
1038 * at out_unlock label to free meta of this ordered
1039 * extent, as its meta should be freed by
1040 * btrfs_finish_ordered_io().
1042 * So we must continue until @start is increased to
1043 * skip current ordered extent.
1046 btrfs_drop_extent_cache(BTRFS_I(inode), start,
1047 start + ram_size - 1, 0);
1050 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
1052 /* we're not doing compressed IO, don't unlock the first
1053 * page (which the caller expects to stay locked), don't
1054 * clear any dirty bits and don't set any writeback bits
1056 * Do set the Private2 bit so we know this page was properly
1057 * setup for writepage
1059 page_ops = unlock ? PAGE_UNLOCK : 0;
1060 page_ops |= PAGE_SET_PRIVATE2;
1062 extent_clear_unlock_delalloc(inode, start,
1063 start + ram_size - 1,
1064 delalloc_end, locked_page,
1065 EXTENT_LOCKED | EXTENT_DELALLOC,
1067 if (num_bytes < cur_alloc_size)
1070 num_bytes -= cur_alloc_size;
1071 alloc_hint = ins.objectid + ins.offset;
1072 start += cur_alloc_size;
1073 extent_reserved = false;
1076 * btrfs_reloc_clone_csums() error, since start is increased
1077 * extent_clear_unlock_delalloc() at out_unlock label won't
1078 * free metadata of current ordered extent, we're OK to exit.
1086 out_drop_extent_cache:
1087 btrfs_drop_extent_cache(BTRFS_I(inode), start, start + ram_size - 1, 0);
1089 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
1090 btrfs_free_reserved_extent(fs_info, ins.objectid, ins.offset, 1);
1092 clear_bits = EXTENT_LOCKED | EXTENT_DELALLOC | EXTENT_DELALLOC_NEW |
1093 EXTENT_DEFRAG | EXTENT_CLEAR_META_RESV;
1094 page_ops = PAGE_UNLOCK | PAGE_CLEAR_DIRTY | PAGE_SET_WRITEBACK |
1097 * If we reserved an extent for our delalloc range (or a subrange) and
1098 * failed to create the respective ordered extent, then it means that
1099 * when we reserved the extent we decremented the extent's size from
1100 * the data space_info's bytes_may_use counter and incremented the
1101 * space_info's bytes_reserved counter by the same amount. We must make
1102 * sure extent_clear_unlock_delalloc() does not try to decrement again
1103 * the data space_info's bytes_may_use counter, therefore we do not pass
1104 * it the flag EXTENT_CLEAR_DATA_RESV.
1106 if (extent_reserved) {
1107 extent_clear_unlock_delalloc(inode, start,
1108 start + cur_alloc_size,
1109 start + cur_alloc_size,
1113 start += cur_alloc_size;
1117 extent_clear_unlock_delalloc(inode, start, end, delalloc_end,
1119 clear_bits | EXTENT_CLEAR_DATA_RESV,
1125 * work queue call back to started compression on a file and pages
1127 static noinline void async_cow_start(struct btrfs_work *work)
1129 struct async_cow *async_cow;
1131 async_cow = container_of(work, struct async_cow, work);
1133 compress_file_range(async_cow->inode, async_cow->locked_page,
1134 async_cow->start, async_cow->end, async_cow,
1136 if (num_added == 0) {
1137 btrfs_add_delayed_iput(async_cow->inode);
1138 async_cow->inode = NULL;
1143 * work queue call back to submit previously compressed pages
1145 static noinline void async_cow_submit(struct btrfs_work *work)
1147 struct btrfs_fs_info *fs_info;
1148 struct async_cow *async_cow;
1149 struct btrfs_root *root;
1150 unsigned long nr_pages;
1152 async_cow = container_of(work, struct async_cow, work);
1154 root = async_cow->root;
1155 fs_info = root->fs_info;
1156 nr_pages = (async_cow->end - async_cow->start + PAGE_SIZE) >>
1160 * atomic_sub_return implies a barrier for waitqueue_active
1162 if (atomic_sub_return(nr_pages, &fs_info->async_delalloc_pages) <
1164 waitqueue_active(&fs_info->async_submit_wait))
1165 wake_up(&fs_info->async_submit_wait);
1167 if (async_cow->inode)
1168 submit_compressed_extents(async_cow->inode, async_cow);
1171 static noinline void async_cow_free(struct btrfs_work *work)
1173 struct async_cow *async_cow;
1174 async_cow = container_of(work, struct async_cow, work);
1175 if (async_cow->inode)
1176 btrfs_add_delayed_iput(async_cow->inode);
1180 static int cow_file_range_async(struct inode *inode, struct page *locked_page,
1181 u64 start, u64 end, int *page_started,
1182 unsigned long *nr_written,
1183 unsigned int write_flags)
1185 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1186 struct async_cow *async_cow;
1187 struct btrfs_root *root = BTRFS_I(inode)->root;
1188 unsigned long nr_pages;
1191 clear_extent_bit(&BTRFS_I(inode)->io_tree, start, end, EXTENT_LOCKED,
1193 while (start < end) {
1194 async_cow = kmalloc(sizeof(*async_cow), GFP_NOFS);
1195 BUG_ON(!async_cow); /* -ENOMEM */
1196 async_cow->inode = igrab(inode);
1197 async_cow->root = root;
1198 async_cow->locked_page = locked_page;
1199 async_cow->start = start;
1200 async_cow->write_flags = write_flags;
1202 if (BTRFS_I(inode)->flags & BTRFS_INODE_NOCOMPRESS &&
1203 !btrfs_test_opt(fs_info, FORCE_COMPRESS))
1206 cur_end = min(end, start + SZ_512K - 1);
1208 async_cow->end = cur_end;
1209 INIT_LIST_HEAD(&async_cow->extents);
1211 btrfs_init_work(&async_cow->work,
1212 btrfs_delalloc_helper,
1213 async_cow_start, async_cow_submit,
1216 nr_pages = (cur_end - start + PAGE_SIZE) >>
1218 atomic_add(nr_pages, &fs_info->async_delalloc_pages);
1220 btrfs_queue_work(fs_info->delalloc_workers, &async_cow->work);
1222 *nr_written += nr_pages;
1223 start = cur_end + 1;
1229 static noinline int csum_exist_in_range(struct btrfs_fs_info *fs_info,
1230 u64 bytenr, u64 num_bytes)
1233 struct btrfs_ordered_sum *sums;
1236 ret = btrfs_lookup_csums_range(fs_info->csum_root, bytenr,
1237 bytenr + num_bytes - 1, &list, 0);
1238 if (ret == 0 && list_empty(&list))
1241 while (!list_empty(&list)) {
1242 sums = list_entry(list.next, struct btrfs_ordered_sum, list);
1243 list_del(&sums->list);
1252 * when nowcow writeback call back. This checks for snapshots or COW copies
1253 * of the extents that exist in the file, and COWs the file as required.
1255 * If no cow copies or snapshots exist, we write directly to the existing
1258 static noinline int run_delalloc_nocow(struct inode *inode,
1259 struct page *locked_page,
1260 u64 start, u64 end, int *page_started, int force,
1261 unsigned long *nr_written)
1263 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1264 struct btrfs_root *root = BTRFS_I(inode)->root;
1265 struct extent_buffer *leaf;
1266 struct btrfs_path *path;
1267 struct btrfs_file_extent_item *fi;
1268 struct btrfs_key found_key;
1269 struct extent_map *em;
1284 u64 ino = btrfs_ino(BTRFS_I(inode));
1286 path = btrfs_alloc_path();
1288 extent_clear_unlock_delalloc(inode, start, end, end,
1290 EXTENT_LOCKED | EXTENT_DELALLOC |
1291 EXTENT_DO_ACCOUNTING |
1292 EXTENT_DEFRAG, PAGE_UNLOCK |
1294 PAGE_SET_WRITEBACK |
1295 PAGE_END_WRITEBACK);
1299 nolock = btrfs_is_free_space_inode(BTRFS_I(inode));
1301 cow_start = (u64)-1;
1304 ret = btrfs_lookup_file_extent(NULL, root, path, ino,
1308 if (ret > 0 && path->slots[0] > 0 && check_prev) {
1309 leaf = path->nodes[0];
1310 btrfs_item_key_to_cpu(leaf, &found_key,
1311 path->slots[0] - 1);
1312 if (found_key.objectid == ino &&
1313 found_key.type == BTRFS_EXTENT_DATA_KEY)
1318 leaf = path->nodes[0];
1319 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
1320 ret = btrfs_next_leaf(root, path);
1322 if (cow_start != (u64)-1)
1323 cur_offset = cow_start;
1328 leaf = path->nodes[0];
1334 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
1336 if (found_key.objectid > ino)
1338 if (WARN_ON_ONCE(found_key.objectid < ino) ||
1339 found_key.type < BTRFS_EXTENT_DATA_KEY) {
1343 if (found_key.type > BTRFS_EXTENT_DATA_KEY ||
1344 found_key.offset > end)
1347 if (found_key.offset > cur_offset) {
1348 extent_end = found_key.offset;
1353 fi = btrfs_item_ptr(leaf, path->slots[0],
1354 struct btrfs_file_extent_item);
1355 extent_type = btrfs_file_extent_type(leaf, fi);
1357 ram_bytes = btrfs_file_extent_ram_bytes(leaf, fi);
1358 if (extent_type == BTRFS_FILE_EXTENT_REG ||
1359 extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
1360 disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
1361 extent_offset = btrfs_file_extent_offset(leaf, fi);
1362 extent_end = found_key.offset +
1363 btrfs_file_extent_num_bytes(leaf, fi);
1365 btrfs_file_extent_disk_num_bytes(leaf, fi);
1366 if (extent_end <= start) {
1370 if (disk_bytenr == 0)
1372 if (btrfs_file_extent_compression(leaf, fi) ||
1373 btrfs_file_extent_encryption(leaf, fi) ||
1374 btrfs_file_extent_other_encoding(leaf, fi))
1376 if (extent_type == BTRFS_FILE_EXTENT_REG && !force)
1378 if (btrfs_extent_readonly(fs_info, disk_bytenr))
1380 ret = btrfs_cross_ref_exist(root, ino,
1382 extent_offset, disk_bytenr);
1385 * ret could be -EIO if the above fails to read
1389 if (cow_start != (u64)-1)
1390 cur_offset = cow_start;
1394 WARN_ON_ONCE(nolock);
1397 disk_bytenr += extent_offset;
1398 disk_bytenr += cur_offset - found_key.offset;
1399 num_bytes = min(end + 1, extent_end) - cur_offset;
1401 * if there are pending snapshots for this root,
1402 * we fall into common COW way.
1405 err = btrfs_start_write_no_snapshotting(root);
1410 * force cow if csum exists in the range.
1411 * this ensure that csum for a given extent are
1412 * either valid or do not exist.
1414 ret = csum_exist_in_range(fs_info, disk_bytenr,
1418 btrfs_end_write_no_snapshotting(root);
1421 * ret could be -EIO if the above fails to read
1425 if (cow_start != (u64)-1)
1426 cur_offset = cow_start;
1429 WARN_ON_ONCE(nolock);
1432 if (!btrfs_inc_nocow_writers(fs_info, disk_bytenr)) {
1434 btrfs_end_write_no_snapshotting(root);
1438 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
1439 extent_end = found_key.offset +
1440 btrfs_file_extent_inline_len(leaf,
1441 path->slots[0], fi);
1442 extent_end = ALIGN(extent_end,
1443 fs_info->sectorsize);
1448 if (extent_end <= start) {
1450 if (!nolock && nocow)
1451 btrfs_end_write_no_snapshotting(root);
1453 btrfs_dec_nocow_writers(fs_info, disk_bytenr);
1457 if (cow_start == (u64)-1)
1458 cow_start = cur_offset;
1459 cur_offset = extent_end;
1460 if (cur_offset > end)
1466 btrfs_release_path(path);
1467 if (cow_start != (u64)-1) {
1468 ret = cow_file_range(inode, locked_page,
1469 cow_start, found_key.offset - 1,
1470 end, page_started, nr_written, 1,
1473 if (!nolock && nocow)
1474 btrfs_end_write_no_snapshotting(root);
1476 btrfs_dec_nocow_writers(fs_info,
1480 cow_start = (u64)-1;
1483 if (extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
1484 u64 orig_start = found_key.offset - extent_offset;
1486 em = create_io_em(inode, cur_offset, num_bytes,
1488 disk_bytenr, /* block_start */
1489 num_bytes, /* block_len */
1490 disk_num_bytes, /* orig_block_len */
1491 ram_bytes, BTRFS_COMPRESS_NONE,
1492 BTRFS_ORDERED_PREALLOC);
1494 if (!nolock && nocow)
1495 btrfs_end_write_no_snapshotting(root);
1497 btrfs_dec_nocow_writers(fs_info,
1502 free_extent_map(em);
1505 if (extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
1506 type = BTRFS_ORDERED_PREALLOC;
1508 type = BTRFS_ORDERED_NOCOW;
1511 ret = btrfs_add_ordered_extent(inode, cur_offset, disk_bytenr,
1512 num_bytes, num_bytes, type);
1514 btrfs_dec_nocow_writers(fs_info, disk_bytenr);
1515 BUG_ON(ret); /* -ENOMEM */
1517 if (root->root_key.objectid ==
1518 BTRFS_DATA_RELOC_TREE_OBJECTID)
1520 * Error handled later, as we must prevent
1521 * extent_clear_unlock_delalloc() in error handler
1522 * from freeing metadata of created ordered extent.
1524 ret = btrfs_reloc_clone_csums(inode, cur_offset,
1527 extent_clear_unlock_delalloc(inode, cur_offset,
1528 cur_offset + num_bytes - 1, end,
1529 locked_page, EXTENT_LOCKED |
1531 EXTENT_CLEAR_DATA_RESV,
1532 PAGE_UNLOCK | PAGE_SET_PRIVATE2);
1534 if (!nolock && nocow)
1535 btrfs_end_write_no_snapshotting(root);
1536 cur_offset = extent_end;
1539 * btrfs_reloc_clone_csums() error, now we're OK to call error
1540 * handler, as metadata for created ordered extent will only
1541 * be freed by btrfs_finish_ordered_io().
1545 if (cur_offset > end)
1548 btrfs_release_path(path);
1550 if (cur_offset <= end && cow_start == (u64)-1) {
1551 cow_start = cur_offset;
1555 if (cow_start != (u64)-1) {
1556 ret = cow_file_range(inode, locked_page, cow_start, end, end,
1557 page_started, nr_written, 1, NULL);
1563 if (ret && cur_offset < end)
1564 extent_clear_unlock_delalloc(inode, cur_offset, end, end,
1565 locked_page, EXTENT_LOCKED |
1566 EXTENT_DELALLOC | EXTENT_DEFRAG |
1567 EXTENT_DO_ACCOUNTING, PAGE_UNLOCK |
1569 PAGE_SET_WRITEBACK |
1570 PAGE_END_WRITEBACK);
1571 btrfs_free_path(path);
1575 static inline int need_force_cow(struct inode *inode, u64 start, u64 end)
1578 if (!(BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW) &&
1579 !(BTRFS_I(inode)->flags & BTRFS_INODE_PREALLOC))
1583 * @defrag_bytes is a hint value, no spinlock held here,
1584 * if is not zero, it means the file is defragging.
1585 * Force cow if given extent needs to be defragged.
1587 if (BTRFS_I(inode)->defrag_bytes &&
1588 test_range_bit(&BTRFS_I(inode)->io_tree, start, end,
1589 EXTENT_DEFRAG, 0, NULL))
1596 * extent_io.c call back to do delayed allocation processing
1598 static int run_delalloc_range(void *private_data, struct page *locked_page,
1599 u64 start, u64 end, int *page_started,
1600 unsigned long *nr_written,
1601 struct writeback_control *wbc)
1603 struct inode *inode = private_data;
1605 int force_cow = need_force_cow(inode, start, end);
1606 unsigned int write_flags = wbc_to_write_flags(wbc);
1608 if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW && !force_cow) {
1609 ret = run_delalloc_nocow(inode, locked_page, start, end,
1610 page_started, 1, nr_written);
1611 } else if (BTRFS_I(inode)->flags & BTRFS_INODE_PREALLOC && !force_cow) {
1612 ret = run_delalloc_nocow(inode, locked_page, start, end,
1613 page_started, 0, nr_written);
1614 } else if (!inode_need_compress(inode, start, end)) {
1615 ret = cow_file_range(inode, locked_page, start, end, end,
1616 page_started, nr_written, 1, NULL);
1618 set_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
1619 &BTRFS_I(inode)->runtime_flags);
1620 ret = cow_file_range_async(inode, locked_page, start, end,
1621 page_started, nr_written,
1625 btrfs_cleanup_ordered_extents(inode, start, end - start + 1);
1629 static void btrfs_split_extent_hook(void *private_data,
1630 struct extent_state *orig, u64 split)
1632 struct inode *inode = private_data;
1635 /* not delalloc, ignore it */
1636 if (!(orig->state & EXTENT_DELALLOC))
1639 size = orig->end - orig->start + 1;
1640 if (size > BTRFS_MAX_EXTENT_SIZE) {
1645 * See the explanation in btrfs_merge_extent_hook, the same
1646 * applies here, just in reverse.
1648 new_size = orig->end - split + 1;
1649 num_extents = count_max_extents(new_size);
1650 new_size = split - orig->start;
1651 num_extents += count_max_extents(new_size);
1652 if (count_max_extents(size) >= num_extents)
1656 spin_lock(&BTRFS_I(inode)->lock);
1657 btrfs_mod_outstanding_extents(BTRFS_I(inode), 1);
1658 spin_unlock(&BTRFS_I(inode)->lock);
1662 * extent_io.c merge_extent_hook, used to track merged delayed allocation
1663 * extents so we can keep track of new extents that are just merged onto old
1664 * extents, such as when we are doing sequential writes, so we can properly
1665 * account for the metadata space we'll need.
1667 static void btrfs_merge_extent_hook(void *private_data,
1668 struct extent_state *new,
1669 struct extent_state *other)
1671 struct inode *inode = private_data;
1672 u64 new_size, old_size;
1675 /* not delalloc, ignore it */
1676 if (!(other->state & EXTENT_DELALLOC))
1679 if (new->start > other->start)
1680 new_size = new->end - other->start + 1;
1682 new_size = other->end - new->start + 1;
1684 /* we're not bigger than the max, unreserve the space and go */
1685 if (new_size <= BTRFS_MAX_EXTENT_SIZE) {
1686 spin_lock(&BTRFS_I(inode)->lock);
1687 btrfs_mod_outstanding_extents(BTRFS_I(inode), -1);
1688 spin_unlock(&BTRFS_I(inode)->lock);
1693 * We have to add up either side to figure out how many extents were
1694 * accounted for before we merged into one big extent. If the number of
1695 * extents we accounted for is <= the amount we need for the new range
1696 * then we can return, otherwise drop. Think of it like this
1700 * So we've grown the extent by a MAX_SIZE extent, this would mean we
1701 * need 2 outstanding extents, on one side we have 1 and the other side
1702 * we have 1 so they are == and we can return. But in this case
1704 * [MAX_SIZE+4k][MAX_SIZE+4k]
1706 * Each range on their own accounts for 2 extents, but merged together
1707 * they are only 3 extents worth of accounting, so we need to drop in
1710 old_size = other->end - other->start + 1;
1711 num_extents = count_max_extents(old_size);
1712 old_size = new->end - new->start + 1;
1713 num_extents += count_max_extents(old_size);
1714 if (count_max_extents(new_size) >= num_extents)
1717 spin_lock(&BTRFS_I(inode)->lock);
1718 btrfs_mod_outstanding_extents(BTRFS_I(inode), -1);
1719 spin_unlock(&BTRFS_I(inode)->lock);
1722 static void btrfs_add_delalloc_inodes(struct btrfs_root *root,
1723 struct inode *inode)
1725 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1727 spin_lock(&root->delalloc_lock);
1728 if (list_empty(&BTRFS_I(inode)->delalloc_inodes)) {
1729 list_add_tail(&BTRFS_I(inode)->delalloc_inodes,
1730 &root->delalloc_inodes);
1731 set_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1732 &BTRFS_I(inode)->runtime_flags);
1733 root->nr_delalloc_inodes++;
1734 if (root->nr_delalloc_inodes == 1) {
1735 spin_lock(&fs_info->delalloc_root_lock);
1736 BUG_ON(!list_empty(&root->delalloc_root));
1737 list_add_tail(&root->delalloc_root,
1738 &fs_info->delalloc_roots);
1739 spin_unlock(&fs_info->delalloc_root_lock);
1742 spin_unlock(&root->delalloc_lock);
1746 void __btrfs_del_delalloc_inode(struct btrfs_root *root,
1747 struct btrfs_inode *inode)
1749 struct btrfs_fs_info *fs_info = btrfs_sb(inode->vfs_inode.i_sb);
1751 if (!list_empty(&inode->delalloc_inodes)) {
1752 list_del_init(&inode->delalloc_inodes);
1753 clear_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1754 &inode->runtime_flags);
1755 root->nr_delalloc_inodes--;
1756 if (!root->nr_delalloc_inodes) {
1757 spin_lock(&fs_info->delalloc_root_lock);
1758 BUG_ON(list_empty(&root->delalloc_root));
1759 list_del_init(&root->delalloc_root);
1760 spin_unlock(&fs_info->delalloc_root_lock);
1765 static void btrfs_del_delalloc_inode(struct btrfs_root *root,
1766 struct btrfs_inode *inode)
1768 spin_lock(&root->delalloc_lock);
1769 __btrfs_del_delalloc_inode(root, inode);
1770 spin_unlock(&root->delalloc_lock);
1774 * extent_io.c set_bit_hook, used to track delayed allocation
1775 * bytes in this file, and to maintain the list of inodes that
1776 * have pending delalloc work to be done.
1778 static void btrfs_set_bit_hook(void *private_data,
1779 struct extent_state *state, unsigned *bits)
1781 struct inode *inode = private_data;
1783 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1785 if ((*bits & EXTENT_DEFRAG) && !(*bits & EXTENT_DELALLOC))
1788 * set_bit and clear bit hooks normally require _irqsave/restore
1789 * but in this case, we are only testing for the DELALLOC
1790 * bit, which is only set or cleared with irqs on
1792 if (!(state->state & EXTENT_DELALLOC) && (*bits & EXTENT_DELALLOC)) {
1793 struct btrfs_root *root = BTRFS_I(inode)->root;
1794 u64 len = state->end + 1 - state->start;
1795 u32 num_extents = count_max_extents(len);
1796 bool do_list = !btrfs_is_free_space_inode(BTRFS_I(inode));
1798 spin_lock(&BTRFS_I(inode)->lock);
1799 btrfs_mod_outstanding_extents(BTRFS_I(inode), num_extents);
1800 spin_unlock(&BTRFS_I(inode)->lock);
1802 /* For sanity tests */
1803 if (btrfs_is_testing(fs_info))
1806 percpu_counter_add_batch(&fs_info->delalloc_bytes, len,
1807 fs_info->delalloc_batch);
1808 spin_lock(&BTRFS_I(inode)->lock);
1809 BTRFS_I(inode)->delalloc_bytes += len;
1810 if (*bits & EXTENT_DEFRAG)
1811 BTRFS_I(inode)->defrag_bytes += len;
1812 if (do_list && !test_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1813 &BTRFS_I(inode)->runtime_flags))
1814 btrfs_add_delalloc_inodes(root, inode);
1815 spin_unlock(&BTRFS_I(inode)->lock);
1818 if (!(state->state & EXTENT_DELALLOC_NEW) &&
1819 (*bits & EXTENT_DELALLOC_NEW)) {
1820 spin_lock(&BTRFS_I(inode)->lock);
1821 BTRFS_I(inode)->new_delalloc_bytes += state->end + 1 -
1823 spin_unlock(&BTRFS_I(inode)->lock);
1828 * extent_io.c clear_bit_hook, see set_bit_hook for why
1830 static void btrfs_clear_bit_hook(void *private_data,
1831 struct extent_state *state,
1834 struct btrfs_inode *inode = BTRFS_I((struct inode *)private_data);
1835 struct btrfs_fs_info *fs_info = btrfs_sb(inode->vfs_inode.i_sb);
1836 u64 len = state->end + 1 - state->start;
1837 u32 num_extents = count_max_extents(len);
1839 if ((state->state & EXTENT_DEFRAG) && (*bits & EXTENT_DEFRAG)) {
1840 spin_lock(&inode->lock);
1841 inode->defrag_bytes -= len;
1842 spin_unlock(&inode->lock);
1846 * set_bit and clear bit hooks normally require _irqsave/restore
1847 * but in this case, we are only testing for the DELALLOC
1848 * bit, which is only set or cleared with irqs on
1850 if ((state->state & EXTENT_DELALLOC) && (*bits & EXTENT_DELALLOC)) {
1851 struct btrfs_root *root = inode->root;
1852 bool do_list = !btrfs_is_free_space_inode(inode);
1854 spin_lock(&inode->lock);
1855 btrfs_mod_outstanding_extents(inode, -num_extents);
1856 spin_unlock(&inode->lock);
1859 * We don't reserve metadata space for space cache inodes so we
1860 * don't need to call dellalloc_release_metadata if there is an
1863 if (*bits & EXTENT_CLEAR_META_RESV &&
1864 root != fs_info->tree_root)
1865 btrfs_delalloc_release_metadata(inode, len, false);
1867 /* For sanity tests. */
1868 if (btrfs_is_testing(fs_info))
1871 if (root->root_key.objectid != BTRFS_DATA_RELOC_TREE_OBJECTID &&
1872 do_list && !(state->state & EXTENT_NORESERVE) &&
1873 (*bits & EXTENT_CLEAR_DATA_RESV))
1874 btrfs_free_reserved_data_space_noquota(
1878 percpu_counter_add_batch(&fs_info->delalloc_bytes, -len,
1879 fs_info->delalloc_batch);
1880 spin_lock(&inode->lock);
1881 inode->delalloc_bytes -= len;
1882 if (do_list && inode->delalloc_bytes == 0 &&
1883 test_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1884 &inode->runtime_flags))
1885 btrfs_del_delalloc_inode(root, inode);
1886 spin_unlock(&inode->lock);
1889 if ((state->state & EXTENT_DELALLOC_NEW) &&
1890 (*bits & EXTENT_DELALLOC_NEW)) {
1891 spin_lock(&inode->lock);
1892 ASSERT(inode->new_delalloc_bytes >= len);
1893 inode->new_delalloc_bytes -= len;
1894 spin_unlock(&inode->lock);
1899 * extent_io.c merge_bio_hook, this must check the chunk tree to make sure
1900 * we don't create bios that span stripes or chunks
1902 * return 1 if page cannot be merged to bio
1903 * return 0 if page can be merged to bio
1904 * return error otherwise
1906 int btrfs_merge_bio_hook(struct page *page, unsigned long offset,
1907 size_t size, struct bio *bio,
1908 unsigned long bio_flags)
1910 struct inode *inode = page->mapping->host;
1911 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1912 u64 logical = (u64)bio->bi_iter.bi_sector << 9;
1917 if (bio_flags & EXTENT_BIO_COMPRESSED)
1920 length = bio->bi_iter.bi_size;
1921 map_length = length;
1922 ret = btrfs_map_block(fs_info, btrfs_op(bio), logical, &map_length,
1926 if (map_length < length + size)
1932 * in order to insert checksums into the metadata in large chunks,
1933 * we wait until bio submission time. All the pages in the bio are
1934 * checksummed and sums are attached onto the ordered extent record.
1936 * At IO completion time the cums attached on the ordered extent record
1937 * are inserted into the btree
1939 static blk_status_t btrfs_submit_bio_start(void *private_data, struct bio *bio,
1942 struct inode *inode = private_data;
1943 blk_status_t ret = 0;
1945 ret = btrfs_csum_one_bio(inode, bio, 0, 0);
1946 BUG_ON(ret); /* -ENOMEM */
1951 * in order to insert checksums into the metadata in large chunks,
1952 * we wait until bio submission time. All the pages in the bio are
1953 * checksummed and sums are attached onto the ordered extent record.
1955 * At IO completion time the cums attached on the ordered extent record
1956 * are inserted into the btree
1958 static blk_status_t btrfs_submit_bio_done(void *private_data, struct bio *bio,
1961 struct inode *inode = private_data;
1962 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1965 ret = btrfs_map_bio(fs_info, bio, mirror_num, 1);
1967 bio->bi_status = ret;
1974 * extent_io.c submission hook. This does the right thing for csum calculation
1975 * on write, or reading the csums from the tree before a read.
1977 * Rules about async/sync submit,
1978 * a) read: sync submit
1980 * b) write without checksum: sync submit
1982 * c) write with checksum:
1983 * c-1) if bio is issued by fsync: sync submit
1984 * (sync_writers != 0)
1986 * c-2) if root is reloc root: sync submit
1987 * (only in case of buffered IO)
1989 * c-3) otherwise: async submit
1991 static blk_status_t btrfs_submit_bio_hook(void *private_data, struct bio *bio,
1992 int mirror_num, unsigned long bio_flags,
1995 struct inode *inode = private_data;
1996 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1997 struct btrfs_root *root = BTRFS_I(inode)->root;
1998 enum btrfs_wq_endio_type metadata = BTRFS_WQ_ENDIO_DATA;
1999 blk_status_t ret = 0;
2001 int async = !atomic_read(&BTRFS_I(inode)->sync_writers);
2003 skip_sum = BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM;
2005 if (btrfs_is_free_space_inode(BTRFS_I(inode)))
2006 metadata = BTRFS_WQ_ENDIO_FREE_SPACE;
2008 if (bio_op(bio) != REQ_OP_WRITE) {
2009 ret = btrfs_bio_wq_end_io(fs_info, bio, metadata);
2013 if (bio_flags & EXTENT_BIO_COMPRESSED) {
2014 ret = btrfs_submit_compressed_read(inode, bio,
2018 } else if (!skip_sum) {
2019 ret = btrfs_lookup_bio_sums(inode, bio, NULL);
2024 } else if (async && !skip_sum) {
2025 /* csum items have already been cloned */
2026 if (root->root_key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID)
2028 /* we're doing a write, do the async checksumming */
2029 ret = btrfs_wq_submit_bio(fs_info, bio, mirror_num, bio_flags,
2031 btrfs_submit_bio_start,
2032 btrfs_submit_bio_done);
2034 } else if (!skip_sum) {
2035 ret = btrfs_csum_one_bio(inode, bio, 0, 0);
2041 ret = btrfs_map_bio(fs_info, bio, mirror_num, 0);
2045 bio->bi_status = ret;
2052 * given a list of ordered sums record them in the inode. This happens
2053 * at IO completion time based on sums calculated at bio submission time.
2055 static noinline int add_pending_csums(struct btrfs_trans_handle *trans,
2056 struct inode *inode, struct list_head *list)
2058 struct btrfs_ordered_sum *sum;
2061 list_for_each_entry(sum, list, list) {
2062 trans->adding_csums = true;
2063 ret = btrfs_csum_file_blocks(trans,
2064 BTRFS_I(inode)->root->fs_info->csum_root, sum);
2065 trans->adding_csums = false;
2072 int btrfs_set_extent_delalloc(struct inode *inode, u64 start, u64 end,
2073 unsigned int extra_bits,
2074 struct extent_state **cached_state, int dedupe)
2076 WARN_ON((end & (PAGE_SIZE - 1)) == 0);
2077 return set_extent_delalloc(&BTRFS_I(inode)->io_tree, start, end,
2078 extra_bits, cached_state);
2081 /* see btrfs_writepage_start_hook for details on why this is required */
2082 struct btrfs_writepage_fixup {
2084 struct btrfs_work work;
2087 static void btrfs_writepage_fixup_worker(struct btrfs_work *work)
2089 struct btrfs_writepage_fixup *fixup;
2090 struct btrfs_ordered_extent *ordered;
2091 struct extent_state *cached_state = NULL;
2092 struct extent_changeset *data_reserved = NULL;
2094 struct inode *inode;
2099 fixup = container_of(work, struct btrfs_writepage_fixup, work);
2103 if (!page->mapping || !PageDirty(page) || !PageChecked(page)) {
2104 ClearPageChecked(page);
2108 inode = page->mapping->host;
2109 page_start = page_offset(page);
2110 page_end = page_offset(page) + PAGE_SIZE - 1;
2112 lock_extent_bits(&BTRFS_I(inode)->io_tree, page_start, page_end,
2115 /* already ordered? We're done */
2116 if (PagePrivate2(page))
2119 ordered = btrfs_lookup_ordered_range(BTRFS_I(inode), page_start,
2122 unlock_extent_cached(&BTRFS_I(inode)->io_tree, page_start,
2123 page_end, &cached_state);
2125 btrfs_start_ordered_extent(inode, ordered, 1);
2126 btrfs_put_ordered_extent(ordered);
2130 ret = btrfs_delalloc_reserve_space(inode, &data_reserved, page_start,
2133 mapping_set_error(page->mapping, ret);
2134 end_extent_writepage(page, ret, page_start, page_end);
2135 ClearPageChecked(page);
2139 ret = btrfs_set_extent_delalloc(inode, page_start, page_end, 0,
2142 mapping_set_error(page->mapping, ret);
2143 end_extent_writepage(page, ret, page_start, page_end);
2144 ClearPageChecked(page);
2148 ClearPageChecked(page);
2149 set_page_dirty(page);
2150 btrfs_delalloc_release_extents(BTRFS_I(inode), PAGE_SIZE, false);
2152 unlock_extent_cached(&BTRFS_I(inode)->io_tree, page_start, page_end,
2158 extent_changeset_free(data_reserved);
2162 * There are a few paths in the higher layers of the kernel that directly
2163 * set the page dirty bit without asking the filesystem if it is a
2164 * good idea. This causes problems because we want to make sure COW
2165 * properly happens and the data=ordered rules are followed.
2167 * In our case any range that doesn't have the ORDERED bit set
2168 * hasn't been properly setup for IO. We kick off an async process
2169 * to fix it up. The async helper will wait for ordered extents, set
2170 * the delalloc bit and make it safe to write the page.
2172 static int btrfs_writepage_start_hook(struct page *page, u64 start, u64 end)
2174 struct inode *inode = page->mapping->host;
2175 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2176 struct btrfs_writepage_fixup *fixup;
2178 /* this page is properly in the ordered list */
2179 if (TestClearPagePrivate2(page))
2182 if (PageChecked(page))
2185 fixup = kzalloc(sizeof(*fixup), GFP_NOFS);
2189 SetPageChecked(page);
2191 btrfs_init_work(&fixup->work, btrfs_fixup_helper,
2192 btrfs_writepage_fixup_worker, NULL, NULL);
2194 btrfs_queue_work(fs_info->fixup_workers, &fixup->work);
2198 static int insert_reserved_file_extent(struct btrfs_trans_handle *trans,
2199 struct inode *inode, u64 file_pos,
2200 u64 disk_bytenr, u64 disk_num_bytes,
2201 u64 num_bytes, u64 ram_bytes,
2202 u8 compression, u8 encryption,
2203 u16 other_encoding, int extent_type)
2205 struct btrfs_root *root = BTRFS_I(inode)->root;
2206 struct btrfs_file_extent_item *fi;
2207 struct btrfs_path *path;
2208 struct extent_buffer *leaf;
2209 struct btrfs_key ins;
2211 int extent_inserted = 0;
2214 path = btrfs_alloc_path();
2219 * we may be replacing one extent in the tree with another.
2220 * The new extent is pinned in the extent map, and we don't want
2221 * to drop it from the cache until it is completely in the btree.
2223 * So, tell btrfs_drop_extents to leave this extent in the cache.
2224 * the caller is expected to unpin it and allow it to be merged
2227 ret = __btrfs_drop_extents(trans, root, inode, path, file_pos,
2228 file_pos + num_bytes, NULL, 0,
2229 1, sizeof(*fi), &extent_inserted);
2233 if (!extent_inserted) {
2234 ins.objectid = btrfs_ino(BTRFS_I(inode));
2235 ins.offset = file_pos;
2236 ins.type = BTRFS_EXTENT_DATA_KEY;
2238 path->leave_spinning = 1;
2239 ret = btrfs_insert_empty_item(trans, root, path, &ins,
2244 leaf = path->nodes[0];
2245 fi = btrfs_item_ptr(leaf, path->slots[0],
2246 struct btrfs_file_extent_item);
2247 btrfs_set_file_extent_generation(leaf, fi, trans->transid);
2248 btrfs_set_file_extent_type(leaf, fi, extent_type);
2249 btrfs_set_file_extent_disk_bytenr(leaf, fi, disk_bytenr);
2250 btrfs_set_file_extent_disk_num_bytes(leaf, fi, disk_num_bytes);
2251 btrfs_set_file_extent_offset(leaf, fi, 0);
2252 btrfs_set_file_extent_num_bytes(leaf, fi, num_bytes);
2253 btrfs_set_file_extent_ram_bytes(leaf, fi, ram_bytes);
2254 btrfs_set_file_extent_compression(leaf, fi, compression);
2255 btrfs_set_file_extent_encryption(leaf, fi, encryption);
2256 btrfs_set_file_extent_other_encoding(leaf, fi, other_encoding);
2258 btrfs_mark_buffer_dirty(leaf);
2259 btrfs_release_path(path);
2261 inode_add_bytes(inode, num_bytes);
2263 ins.objectid = disk_bytenr;
2264 ins.offset = disk_num_bytes;
2265 ins.type = BTRFS_EXTENT_ITEM_KEY;
2268 * Release the reserved range from inode dirty range map, as it is
2269 * already moved into delayed_ref_head
2271 ret = btrfs_qgroup_release_data(inode, file_pos, ram_bytes);
2275 ret = btrfs_alloc_reserved_file_extent(trans, root,
2276 btrfs_ino(BTRFS_I(inode)),
2277 file_pos, qg_released, &ins);
2279 btrfs_free_path(path);
2284 /* snapshot-aware defrag */
2285 struct sa_defrag_extent_backref {
2286 struct rb_node node;
2287 struct old_sa_defrag_extent *old;
2296 struct old_sa_defrag_extent {
2297 struct list_head list;
2298 struct new_sa_defrag_extent *new;
2307 struct new_sa_defrag_extent {
2308 struct rb_root root;
2309 struct list_head head;
2310 struct btrfs_path *path;
2311 struct inode *inode;
2319 static int backref_comp(struct sa_defrag_extent_backref *b1,
2320 struct sa_defrag_extent_backref *b2)
2322 if (b1->root_id < b2->root_id)
2324 else if (b1->root_id > b2->root_id)
2327 if (b1->inum < b2->inum)
2329 else if (b1->inum > b2->inum)
2332 if (b1->file_pos < b2->file_pos)
2334 else if (b1->file_pos > b2->file_pos)
2338 * [------------------------------] ===> (a range of space)
2339 * |<--->| |<---->| =============> (fs/file tree A)
2340 * |<---------------------------->| ===> (fs/file tree B)
2342 * A range of space can refer to two file extents in one tree while
2343 * refer to only one file extent in another tree.
2345 * So we may process a disk offset more than one time(two extents in A)
2346 * and locate at the same extent(one extent in B), then insert two same
2347 * backrefs(both refer to the extent in B).
2352 static void backref_insert(struct rb_root *root,
2353 struct sa_defrag_extent_backref *backref)
2355 struct rb_node **p = &root->rb_node;
2356 struct rb_node *parent = NULL;
2357 struct sa_defrag_extent_backref *entry;
2362 entry = rb_entry(parent, struct sa_defrag_extent_backref, node);
2364 ret = backref_comp(backref, entry);
2368 p = &(*p)->rb_right;
2371 rb_link_node(&backref->node, parent, p);
2372 rb_insert_color(&backref->node, root);
2376 * Note the backref might has changed, and in this case we just return 0.
2378 static noinline int record_one_backref(u64 inum, u64 offset, u64 root_id,
2381 struct btrfs_file_extent_item *extent;
2382 struct old_sa_defrag_extent *old = ctx;
2383 struct new_sa_defrag_extent *new = old->new;
2384 struct btrfs_path *path = new->path;
2385 struct btrfs_key key;
2386 struct btrfs_root *root;
2387 struct sa_defrag_extent_backref *backref;
2388 struct extent_buffer *leaf;
2389 struct inode *inode = new->inode;
2390 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2396 if (BTRFS_I(inode)->root->root_key.objectid == root_id &&
2397 inum == btrfs_ino(BTRFS_I(inode)))
2400 key.objectid = root_id;
2401 key.type = BTRFS_ROOT_ITEM_KEY;
2402 key.offset = (u64)-1;
2404 root = btrfs_read_fs_root_no_name(fs_info, &key);
2406 if (PTR_ERR(root) == -ENOENT)
2409 btrfs_debug(fs_info, "inum=%llu, offset=%llu, root_id=%llu",
2410 inum, offset, root_id);
2411 return PTR_ERR(root);
2414 key.objectid = inum;
2415 key.type = BTRFS_EXTENT_DATA_KEY;
2416 if (offset > (u64)-1 << 32)
2419 key.offset = offset;
2421 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2422 if (WARN_ON(ret < 0))
2429 leaf = path->nodes[0];
2430 slot = path->slots[0];
2432 if (slot >= btrfs_header_nritems(leaf)) {
2433 ret = btrfs_next_leaf(root, path);
2436 } else if (ret > 0) {
2445 btrfs_item_key_to_cpu(leaf, &key, slot);
2447 if (key.objectid > inum)
2450 if (key.objectid < inum || key.type != BTRFS_EXTENT_DATA_KEY)
2453 extent = btrfs_item_ptr(leaf, slot,
2454 struct btrfs_file_extent_item);
2456 if (btrfs_file_extent_disk_bytenr(leaf, extent) != old->bytenr)
2460 * 'offset' refers to the exact key.offset,
2461 * NOT the 'offset' field in btrfs_extent_data_ref, ie.
2462 * (key.offset - extent_offset).
2464 if (key.offset != offset)
2467 extent_offset = btrfs_file_extent_offset(leaf, extent);
2468 num_bytes = btrfs_file_extent_num_bytes(leaf, extent);
2470 if (extent_offset >= old->extent_offset + old->offset +
2471 old->len || extent_offset + num_bytes <=
2472 old->extent_offset + old->offset)
2477 backref = kmalloc(sizeof(*backref), GFP_NOFS);
2483 backref->root_id = root_id;
2484 backref->inum = inum;
2485 backref->file_pos = offset;
2486 backref->num_bytes = num_bytes;
2487 backref->extent_offset = extent_offset;
2488 backref->generation = btrfs_file_extent_generation(leaf, extent);
2490 backref_insert(&new->root, backref);
2493 btrfs_release_path(path);
2498 static noinline bool record_extent_backrefs(struct btrfs_path *path,
2499 struct new_sa_defrag_extent *new)
2501 struct btrfs_fs_info *fs_info = btrfs_sb(new->inode->i_sb);
2502 struct old_sa_defrag_extent *old, *tmp;
2507 list_for_each_entry_safe(old, tmp, &new->head, list) {
2508 ret = iterate_inodes_from_logical(old->bytenr +
2509 old->extent_offset, fs_info,
2510 path, record_one_backref,
2512 if (ret < 0 && ret != -ENOENT)
2515 /* no backref to be processed for this extent */
2517 list_del(&old->list);
2522 if (list_empty(&new->head))
2528 static int relink_is_mergable(struct extent_buffer *leaf,
2529 struct btrfs_file_extent_item *fi,
2530 struct new_sa_defrag_extent *new)
2532 if (btrfs_file_extent_disk_bytenr(leaf, fi) != new->bytenr)
2535 if (btrfs_file_extent_type(leaf, fi) != BTRFS_FILE_EXTENT_REG)
2538 if (btrfs_file_extent_compression(leaf, fi) != new->compress_type)
2541 if (btrfs_file_extent_encryption(leaf, fi) ||
2542 btrfs_file_extent_other_encoding(leaf, fi))
2549 * Note the backref might has changed, and in this case we just return 0.
2551 static noinline int relink_extent_backref(struct btrfs_path *path,
2552 struct sa_defrag_extent_backref *prev,
2553 struct sa_defrag_extent_backref *backref)
2555 struct btrfs_file_extent_item *extent;
2556 struct btrfs_file_extent_item *item;
2557 struct btrfs_ordered_extent *ordered;
2558 struct btrfs_trans_handle *trans;
2559 struct btrfs_root *root;
2560 struct btrfs_key key;
2561 struct extent_buffer *leaf;
2562 struct old_sa_defrag_extent *old = backref->old;
2563 struct new_sa_defrag_extent *new = old->new;
2564 struct btrfs_fs_info *fs_info = btrfs_sb(new->inode->i_sb);
2565 struct inode *inode;
2566 struct extent_state *cached = NULL;
2575 if (prev && prev->root_id == backref->root_id &&
2576 prev->inum == backref->inum &&
2577 prev->file_pos + prev->num_bytes == backref->file_pos)
2580 /* step 1: get root */
2581 key.objectid = backref->root_id;
2582 key.type = BTRFS_ROOT_ITEM_KEY;
2583 key.offset = (u64)-1;
2585 index = srcu_read_lock(&fs_info->subvol_srcu);
2587 root = btrfs_read_fs_root_no_name(fs_info, &key);
2589 srcu_read_unlock(&fs_info->subvol_srcu, index);
2590 if (PTR_ERR(root) == -ENOENT)
2592 return PTR_ERR(root);
2595 if (btrfs_root_readonly(root)) {
2596 srcu_read_unlock(&fs_info->subvol_srcu, index);
2600 /* step 2: get inode */
2601 key.objectid = backref->inum;
2602 key.type = BTRFS_INODE_ITEM_KEY;
2605 inode = btrfs_iget(fs_info->sb, &key, root, NULL);
2606 if (IS_ERR(inode)) {
2607 srcu_read_unlock(&fs_info->subvol_srcu, index);
2611 srcu_read_unlock(&fs_info->subvol_srcu, index);
2613 /* step 3: relink backref */
2614 lock_start = backref->file_pos;
2615 lock_end = backref->file_pos + backref->num_bytes - 1;
2616 lock_extent_bits(&BTRFS_I(inode)->io_tree, lock_start, lock_end,
2619 ordered = btrfs_lookup_first_ordered_extent(inode, lock_end);
2621 btrfs_put_ordered_extent(ordered);
2625 trans = btrfs_join_transaction(root);
2626 if (IS_ERR(trans)) {
2627 ret = PTR_ERR(trans);
2631 key.objectid = backref->inum;
2632 key.type = BTRFS_EXTENT_DATA_KEY;
2633 key.offset = backref->file_pos;
2635 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2638 } else if (ret > 0) {
2643 extent = btrfs_item_ptr(path->nodes[0], path->slots[0],
2644 struct btrfs_file_extent_item);
2646 if (btrfs_file_extent_generation(path->nodes[0], extent) !=
2647 backref->generation)
2650 btrfs_release_path(path);
2652 start = backref->file_pos;
2653 if (backref->extent_offset < old->extent_offset + old->offset)
2654 start += old->extent_offset + old->offset -
2655 backref->extent_offset;
2657 len = min(backref->extent_offset + backref->num_bytes,
2658 old->extent_offset + old->offset + old->len);
2659 len -= max(backref->extent_offset, old->extent_offset + old->offset);
2661 ret = btrfs_drop_extents(trans, root, inode, start,
2666 key.objectid = btrfs_ino(BTRFS_I(inode));
2667 key.type = BTRFS_EXTENT_DATA_KEY;
2670 path->leave_spinning = 1;
2672 struct btrfs_file_extent_item *fi;
2674 struct btrfs_key found_key;
2676 ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
2681 leaf = path->nodes[0];
2682 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
2684 fi = btrfs_item_ptr(leaf, path->slots[0],
2685 struct btrfs_file_extent_item);
2686 extent_len = btrfs_file_extent_num_bytes(leaf, fi);
2688 if (extent_len + found_key.offset == start &&
2689 relink_is_mergable(leaf, fi, new)) {
2690 btrfs_set_file_extent_num_bytes(leaf, fi,
2692 btrfs_mark_buffer_dirty(leaf);
2693 inode_add_bytes(inode, len);
2699 btrfs_release_path(path);
2704 ret = btrfs_insert_empty_item(trans, root, path, &key,
2707 btrfs_abort_transaction(trans, ret);
2711 leaf = path->nodes[0];
2712 item = btrfs_item_ptr(leaf, path->slots[0],
2713 struct btrfs_file_extent_item);
2714 btrfs_set_file_extent_disk_bytenr(leaf, item, new->bytenr);
2715 btrfs_set_file_extent_disk_num_bytes(leaf, item, new->disk_len);
2716 btrfs_set_file_extent_offset(leaf, item, start - new->file_pos);
2717 btrfs_set_file_extent_num_bytes(leaf, item, len);
2718 btrfs_set_file_extent_ram_bytes(leaf, item, new->len);
2719 btrfs_set_file_extent_generation(leaf, item, trans->transid);
2720 btrfs_set_file_extent_type(leaf, item, BTRFS_FILE_EXTENT_REG);
2721 btrfs_set_file_extent_compression(leaf, item, new->compress_type);
2722 btrfs_set_file_extent_encryption(leaf, item, 0);
2723 btrfs_set_file_extent_other_encoding(leaf, item, 0);
2725 btrfs_mark_buffer_dirty(leaf);
2726 inode_add_bytes(inode, len);
2727 btrfs_release_path(path);
2729 ret = btrfs_inc_extent_ref(trans, root, new->bytenr,
2731 backref->root_id, backref->inum,
2732 new->file_pos); /* start - extent_offset */
2734 btrfs_abort_transaction(trans, ret);
2740 btrfs_release_path(path);
2741 path->leave_spinning = 0;
2742 btrfs_end_transaction(trans);
2744 unlock_extent_cached(&BTRFS_I(inode)->io_tree, lock_start, lock_end,
2750 static void free_sa_defrag_extent(struct new_sa_defrag_extent *new)
2752 struct old_sa_defrag_extent *old, *tmp;
2757 list_for_each_entry_safe(old, tmp, &new->head, list) {
2763 static void relink_file_extents(struct new_sa_defrag_extent *new)
2765 struct btrfs_fs_info *fs_info = btrfs_sb(new->inode->i_sb);
2766 struct btrfs_path *path;
2767 struct sa_defrag_extent_backref *backref;
2768 struct sa_defrag_extent_backref *prev = NULL;
2769 struct inode *inode;
2770 struct rb_node *node;
2775 path = btrfs_alloc_path();
2779 if (!record_extent_backrefs(path, new)) {
2780 btrfs_free_path(path);
2783 btrfs_release_path(path);
2786 node = rb_first(&new->root);
2789 rb_erase(node, &new->root);
2791 backref = rb_entry(node, struct sa_defrag_extent_backref, node);
2793 ret = relink_extent_backref(path, prev, backref);
2806 btrfs_free_path(path);
2808 free_sa_defrag_extent(new);
2810 atomic_dec(&fs_info->defrag_running);
2811 wake_up(&fs_info->transaction_wait);
2814 static struct new_sa_defrag_extent *
2815 record_old_file_extents(struct inode *inode,
2816 struct btrfs_ordered_extent *ordered)
2818 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2819 struct btrfs_root *root = BTRFS_I(inode)->root;
2820 struct btrfs_path *path;
2821 struct btrfs_key key;
2822 struct old_sa_defrag_extent *old;
2823 struct new_sa_defrag_extent *new;
2826 new = kmalloc(sizeof(*new), GFP_NOFS);
2831 new->file_pos = ordered->file_offset;
2832 new->len = ordered->len;
2833 new->bytenr = ordered->start;
2834 new->disk_len = ordered->disk_len;
2835 new->compress_type = ordered->compress_type;
2836 new->root = RB_ROOT;
2837 INIT_LIST_HEAD(&new->head);
2839 path = btrfs_alloc_path();
2843 key.objectid = btrfs_ino(BTRFS_I(inode));
2844 key.type = BTRFS_EXTENT_DATA_KEY;
2845 key.offset = new->file_pos;
2847 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2850 if (ret > 0 && path->slots[0] > 0)
2853 /* find out all the old extents for the file range */
2855 struct btrfs_file_extent_item *extent;
2856 struct extent_buffer *l;
2865 slot = path->slots[0];
2867 if (slot >= btrfs_header_nritems(l)) {
2868 ret = btrfs_next_leaf(root, path);
2876 btrfs_item_key_to_cpu(l, &key, slot);
2878 if (key.objectid != btrfs_ino(BTRFS_I(inode)))
2880 if (key.type != BTRFS_EXTENT_DATA_KEY)
2882 if (key.offset >= new->file_pos + new->len)
2885 extent = btrfs_item_ptr(l, slot, struct btrfs_file_extent_item);
2887 num_bytes = btrfs_file_extent_num_bytes(l, extent);
2888 if (key.offset + num_bytes < new->file_pos)
2891 disk_bytenr = btrfs_file_extent_disk_bytenr(l, extent);
2895 extent_offset = btrfs_file_extent_offset(l, extent);
2897 old = kmalloc(sizeof(*old), GFP_NOFS);
2901 offset = max(new->file_pos, key.offset);
2902 end = min(new->file_pos + new->len, key.offset + num_bytes);
2904 old->bytenr = disk_bytenr;
2905 old->extent_offset = extent_offset;
2906 old->offset = offset - key.offset;
2907 old->len = end - offset;
2910 list_add_tail(&old->list, &new->head);
2916 btrfs_free_path(path);
2917 atomic_inc(&fs_info->defrag_running);
2922 btrfs_free_path(path);
2924 free_sa_defrag_extent(new);
2928 static void btrfs_release_delalloc_bytes(struct btrfs_fs_info *fs_info,
2931 struct btrfs_block_group_cache *cache;
2933 cache = btrfs_lookup_block_group(fs_info, start);
2936 spin_lock(&cache->lock);
2937 cache->delalloc_bytes -= len;
2938 spin_unlock(&cache->lock);
2940 btrfs_put_block_group(cache);
2943 /* as ordered data IO finishes, this gets called so we can finish
2944 * an ordered extent if the range of bytes in the file it covers are
2947 static int btrfs_finish_ordered_io(struct btrfs_ordered_extent *ordered_extent)
2949 struct inode *inode = ordered_extent->inode;
2950 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2951 struct btrfs_root *root = BTRFS_I(inode)->root;
2952 struct btrfs_trans_handle *trans = NULL;
2953 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
2954 struct extent_state *cached_state = NULL;
2955 struct new_sa_defrag_extent *new = NULL;
2956 int compress_type = 0;
2958 u64 logical_len = ordered_extent->len;
2960 bool truncated = false;
2961 bool range_locked = false;
2962 bool clear_new_delalloc_bytes = false;
2964 if (!test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags) &&
2965 !test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags) &&
2966 !test_bit(BTRFS_ORDERED_DIRECT, &ordered_extent->flags))
2967 clear_new_delalloc_bytes = true;
2969 nolock = btrfs_is_free_space_inode(BTRFS_I(inode));
2971 if (test_bit(BTRFS_ORDERED_IOERR, &ordered_extent->flags)) {
2976 btrfs_free_io_failure_record(BTRFS_I(inode),
2977 ordered_extent->file_offset,
2978 ordered_extent->file_offset +
2979 ordered_extent->len - 1);
2981 if (test_bit(BTRFS_ORDERED_TRUNCATED, &ordered_extent->flags)) {
2983 logical_len = ordered_extent->truncated_len;
2984 /* Truncated the entire extent, don't bother adding */
2989 if (test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags)) {
2990 BUG_ON(!list_empty(&ordered_extent->list)); /* Logic error */
2993 * For mwrite(mmap + memset to write) case, we still reserve
2994 * space for NOCOW range.
2995 * As NOCOW won't cause a new delayed ref, just free the space
2997 btrfs_qgroup_free_data(inode, NULL, ordered_extent->file_offset,
2998 ordered_extent->len);
2999 btrfs_ordered_update_i_size(inode, 0, ordered_extent);
3001 trans = btrfs_join_transaction_nolock(root);
3003 trans = btrfs_join_transaction(root);
3004 if (IS_ERR(trans)) {
3005 ret = PTR_ERR(trans);
3009 trans->block_rsv = &BTRFS_I(inode)->block_rsv;
3010 ret = btrfs_update_inode_fallback(trans, root, inode);
3011 if (ret) /* -ENOMEM or corruption */
3012 btrfs_abort_transaction(trans, ret);
3016 range_locked = true;
3017 lock_extent_bits(io_tree, ordered_extent->file_offset,
3018 ordered_extent->file_offset + ordered_extent->len - 1,
3021 ret = test_range_bit(io_tree, ordered_extent->file_offset,
3022 ordered_extent->file_offset + ordered_extent->len - 1,
3023 EXTENT_DEFRAG, 0, cached_state);
3025 u64 last_snapshot = btrfs_root_last_snapshot(&root->root_item);
3026 if (0 && last_snapshot >= BTRFS_I(inode)->generation)
3027 /* the inode is shared */
3028 new = record_old_file_extents(inode, ordered_extent);
3030 clear_extent_bit(io_tree, ordered_extent->file_offset,
3031 ordered_extent->file_offset + ordered_extent->len - 1,
3032 EXTENT_DEFRAG, 0, 0, &cached_state);
3036 trans = btrfs_join_transaction_nolock(root);
3038 trans = btrfs_join_transaction(root);
3039 if (IS_ERR(trans)) {
3040 ret = PTR_ERR(trans);
3045 trans->block_rsv = &BTRFS_I(inode)->block_rsv;
3047 if (test_bit(BTRFS_ORDERED_COMPRESSED, &ordered_extent->flags))
3048 compress_type = ordered_extent->compress_type;
3049 if (test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags)) {
3050 BUG_ON(compress_type);
3051 btrfs_qgroup_free_data(inode, NULL, ordered_extent->file_offset,
3052 ordered_extent->len);
3053 ret = btrfs_mark_extent_written(trans, BTRFS_I(inode),
3054 ordered_extent->file_offset,
3055 ordered_extent->file_offset +
3058 BUG_ON(root == fs_info->tree_root);
3059 ret = insert_reserved_file_extent(trans, inode,
3060 ordered_extent->file_offset,
3061 ordered_extent->start,
3062 ordered_extent->disk_len,
3063 logical_len, logical_len,
3064 compress_type, 0, 0,
3065 BTRFS_FILE_EXTENT_REG);
3067 btrfs_release_delalloc_bytes(fs_info,
3068 ordered_extent->start,
3069 ordered_extent->disk_len);
3071 unpin_extent_cache(&BTRFS_I(inode)->extent_tree,
3072 ordered_extent->file_offset, ordered_extent->len,
3075 btrfs_abort_transaction(trans, ret);
3079 ret = add_pending_csums(trans, inode, &ordered_extent->list);
3081 btrfs_abort_transaction(trans, ret);
3085 btrfs_ordered_update_i_size(inode, 0, ordered_extent);
3086 ret = btrfs_update_inode_fallback(trans, root, inode);
3087 if (ret) { /* -ENOMEM or corruption */
3088 btrfs_abort_transaction(trans, ret);
3093 if (range_locked || clear_new_delalloc_bytes) {
3094 unsigned int clear_bits = 0;
3097 clear_bits |= EXTENT_LOCKED;
3098 if (clear_new_delalloc_bytes)
3099 clear_bits |= EXTENT_DELALLOC_NEW;
3100 clear_extent_bit(&BTRFS_I(inode)->io_tree,
3101 ordered_extent->file_offset,
3102 ordered_extent->file_offset +
3103 ordered_extent->len - 1,
3105 (clear_bits & EXTENT_LOCKED) ? 1 : 0,
3110 btrfs_end_transaction(trans);
3112 if (ret || truncated) {
3116 start = ordered_extent->file_offset + logical_len;
3118 start = ordered_extent->file_offset;
3119 end = ordered_extent->file_offset + ordered_extent->len - 1;
3120 clear_extent_uptodate(io_tree, start, end, NULL);
3122 /* Drop the cache for the part of the extent we didn't write. */
3123 btrfs_drop_extent_cache(BTRFS_I(inode), start, end, 0);
3126 * If the ordered extent had an IOERR or something else went
3127 * wrong we need to return the space for this ordered extent
3128 * back to the allocator. We only free the extent in the
3129 * truncated case if we didn't write out the extent at all.
3131 if ((ret || !logical_len) &&
3132 !test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags) &&
3133 !test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags))
3134 btrfs_free_reserved_extent(fs_info,
3135 ordered_extent->start,
3136 ordered_extent->disk_len, 1);
3141 * This needs to be done to make sure anybody waiting knows we are done
3142 * updating everything for this ordered extent.
3144 btrfs_remove_ordered_extent(inode, ordered_extent);
3146 /* for snapshot-aware defrag */
3149 free_sa_defrag_extent(new);
3150 atomic_dec(&fs_info->defrag_running);
3152 relink_file_extents(new);
3157 btrfs_put_ordered_extent(ordered_extent);
3158 /* once for the tree */
3159 btrfs_put_ordered_extent(ordered_extent);
3164 static void finish_ordered_fn(struct btrfs_work *work)
3166 struct btrfs_ordered_extent *ordered_extent;
3167 ordered_extent = container_of(work, struct btrfs_ordered_extent, work);
3168 btrfs_finish_ordered_io(ordered_extent);
3171 static void btrfs_writepage_end_io_hook(struct page *page, u64 start, u64 end,
3172 struct extent_state *state, int uptodate)
3174 struct inode *inode = page->mapping->host;
3175 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
3176 struct btrfs_ordered_extent *ordered_extent = NULL;
3177 struct btrfs_workqueue *wq;
3178 btrfs_work_func_t func;
3180 trace_btrfs_writepage_end_io_hook(page, start, end, uptodate);
3182 ClearPagePrivate2(page);
3183 if (!btrfs_dec_test_ordered_pending(inode, &ordered_extent, start,
3184 end - start + 1, uptodate))
3187 if (btrfs_is_free_space_inode(BTRFS_I(inode))) {
3188 wq = fs_info->endio_freespace_worker;
3189 func = btrfs_freespace_write_helper;
3191 wq = fs_info->endio_write_workers;
3192 func = btrfs_endio_write_helper;
3195 btrfs_init_work(&ordered_extent->work, func, finish_ordered_fn, NULL,
3197 btrfs_queue_work(wq, &ordered_extent->work);
3200 static int __readpage_endio_check(struct inode *inode,
3201 struct btrfs_io_bio *io_bio,
3202 int icsum, struct page *page,
3203 int pgoff, u64 start, size_t len)
3209 csum_expected = *(((u32 *)io_bio->csum) + icsum);
3211 kaddr = kmap_atomic(page);
3212 csum = btrfs_csum_data(kaddr + pgoff, csum, len);
3213 btrfs_csum_final(csum, (u8 *)&csum);
3214 if (csum != csum_expected)
3217 kunmap_atomic(kaddr);
3220 btrfs_print_data_csum_error(BTRFS_I(inode), start, csum, csum_expected,
3221 io_bio->mirror_num);
3222 memset(kaddr + pgoff, 1, len);
3223 flush_dcache_page(page);
3224 kunmap_atomic(kaddr);
3229 * when reads are done, we need to check csums to verify the data is correct
3230 * if there's a match, we allow the bio to finish. If not, the code in
3231 * extent_io.c will try to find good copies for us.
3233 static int btrfs_readpage_end_io_hook(struct btrfs_io_bio *io_bio,
3234 u64 phy_offset, struct page *page,
3235 u64 start, u64 end, int mirror)
3237 size_t offset = start - page_offset(page);
3238 struct inode *inode = page->mapping->host;
3239 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
3240 struct btrfs_root *root = BTRFS_I(inode)->root;
3242 if (PageChecked(page)) {
3243 ClearPageChecked(page);
3247 if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)
3250 if (root->root_key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID &&
3251 test_range_bit(io_tree, start, end, EXTENT_NODATASUM, 1, NULL)) {
3252 clear_extent_bits(io_tree, start, end, EXTENT_NODATASUM);
3256 phy_offset >>= inode->i_sb->s_blocksize_bits;
3257 return __readpage_endio_check(inode, io_bio, phy_offset, page, offset,
3258 start, (size_t)(end - start + 1));
3262 * btrfs_add_delayed_iput - perform a delayed iput on @inode
3264 * @inode: The inode we want to perform iput on
3266 * This function uses the generic vfs_inode::i_count to track whether we should
3267 * just decrement it (in case it's > 1) or if this is the last iput then link
3268 * the inode to the delayed iput machinery. Delayed iputs are processed at
3269 * transaction commit time/superblock commit/cleaner kthread.
3271 void btrfs_add_delayed_iput(struct inode *inode)
3273 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
3274 struct btrfs_inode *binode = BTRFS_I(inode);
3276 if (atomic_add_unless(&inode->i_count, -1, 1))
3279 spin_lock(&fs_info->delayed_iput_lock);
3280 ASSERT(list_empty(&binode->delayed_iput));
3281 list_add_tail(&binode->delayed_iput, &fs_info->delayed_iputs);
3282 spin_unlock(&fs_info->delayed_iput_lock);
3285 void btrfs_run_delayed_iputs(struct btrfs_fs_info *fs_info)
3288 spin_lock(&fs_info->delayed_iput_lock);
3289 while (!list_empty(&fs_info->delayed_iputs)) {
3290 struct btrfs_inode *inode;
3292 inode = list_first_entry(&fs_info->delayed_iputs,
3293 struct btrfs_inode, delayed_iput);
3294 list_del_init(&inode->delayed_iput);
3295 spin_unlock(&fs_info->delayed_iput_lock);
3296 iput(&inode->vfs_inode);
3297 spin_lock(&fs_info->delayed_iput_lock);
3299 spin_unlock(&fs_info->delayed_iput_lock);
3303 * This is called in transaction commit time. If there are no orphan
3304 * files in the subvolume, it removes orphan item and frees block_rsv
3307 void btrfs_orphan_commit_root(struct btrfs_trans_handle *trans,
3308 struct btrfs_root *root)
3310 struct btrfs_fs_info *fs_info = root->fs_info;
3311 struct btrfs_block_rsv *block_rsv;
3314 if (atomic_read(&root->orphan_inodes) ||
3315 root->orphan_cleanup_state != ORPHAN_CLEANUP_DONE)
3318 spin_lock(&root->orphan_lock);
3319 if (atomic_read(&root->orphan_inodes)) {
3320 spin_unlock(&root->orphan_lock);
3324 if (root->orphan_cleanup_state != ORPHAN_CLEANUP_DONE) {
3325 spin_unlock(&root->orphan_lock);
3329 block_rsv = root->orphan_block_rsv;
3330 root->orphan_block_rsv = NULL;
3331 spin_unlock(&root->orphan_lock);
3333 if (test_bit(BTRFS_ROOT_ORPHAN_ITEM_INSERTED, &root->state) &&
3334 btrfs_root_refs(&root->root_item) > 0) {
3335 ret = btrfs_del_orphan_item(trans, fs_info->tree_root,
3336 root->root_key.objectid);
3338 btrfs_abort_transaction(trans, ret);
3340 clear_bit(BTRFS_ROOT_ORPHAN_ITEM_INSERTED,
3345 WARN_ON(block_rsv->size > 0);
3346 btrfs_free_block_rsv(fs_info, block_rsv);
3351 * This creates an orphan entry for the given inode in case something goes
3352 * wrong in the middle of an unlink/truncate.
3354 * NOTE: caller of this function should reserve 5 units of metadata for
3357 int btrfs_orphan_add(struct btrfs_trans_handle *trans,
3358 struct btrfs_inode *inode)
3360 struct btrfs_fs_info *fs_info = btrfs_sb(inode->vfs_inode.i_sb);
3361 struct btrfs_root *root = inode->root;
3362 struct btrfs_block_rsv *block_rsv = NULL;
3364 bool insert = false;
3367 if (!root->orphan_block_rsv) {
3368 block_rsv = btrfs_alloc_block_rsv(fs_info,
3369 BTRFS_BLOCK_RSV_TEMP);
3374 if (!test_and_set_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
3375 &inode->runtime_flags))
3378 if (!test_and_set_bit(BTRFS_INODE_ORPHAN_META_RESERVED,
3379 &inode->runtime_flags))
3382 spin_lock(&root->orphan_lock);
3383 /* If someone has created ->orphan_block_rsv, be happy to use it. */
3384 if (!root->orphan_block_rsv) {
3385 root->orphan_block_rsv = block_rsv;
3386 } else if (block_rsv) {
3387 btrfs_free_block_rsv(fs_info, block_rsv);
3392 atomic_inc(&root->orphan_inodes);
3393 spin_unlock(&root->orphan_lock);
3395 /* grab metadata reservation from transaction handle */
3397 ret = btrfs_orphan_reserve_metadata(trans, inode);
3401 * dec doesn't need spin_lock as ->orphan_block_rsv
3402 * would be released only if ->orphan_inodes is
3405 atomic_dec(&root->orphan_inodes);
3406 clear_bit(BTRFS_INODE_ORPHAN_META_RESERVED,
3407 &inode->runtime_flags);
3409 clear_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
3410 &inode->runtime_flags);
3415 /* insert an orphan item to track this unlinked/truncated file */
3417 ret = btrfs_insert_orphan_item(trans, root, btrfs_ino(inode));
3420 clear_bit(BTRFS_INODE_ORPHAN_META_RESERVED,
3421 &inode->runtime_flags);
3422 btrfs_orphan_release_metadata(inode);
3425 * btrfs_orphan_commit_root may race with us and set
3426 * ->orphan_block_rsv to zero, in order to avoid that,
3427 * decrease ->orphan_inodes after everything is done.
3429 atomic_dec(&root->orphan_inodes);
3430 if (ret != -EEXIST) {
3431 clear_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
3432 &inode->runtime_flags);
3433 btrfs_abort_transaction(trans, ret);
3444 * We have done the truncate/delete so we can go ahead and remove the orphan
3445 * item for this particular inode.
3447 static int btrfs_orphan_del(struct btrfs_trans_handle *trans,
3448 struct btrfs_inode *inode)
3450 struct btrfs_root *root = inode->root;
3451 int delete_item = 0;
3454 if (test_and_clear_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
3455 &inode->runtime_flags))
3458 if (delete_item && trans)
3459 ret = btrfs_del_orphan_item(trans, root, btrfs_ino(inode));
3461 if (test_and_clear_bit(BTRFS_INODE_ORPHAN_META_RESERVED,
3462 &inode->runtime_flags))
3463 btrfs_orphan_release_metadata(inode);
3466 * btrfs_orphan_commit_root may race with us and set ->orphan_block_rsv
3467 * to zero, in order to avoid that, decrease ->orphan_inodes after
3468 * everything is done.
3471 atomic_dec(&root->orphan_inodes);
3477 * this cleans up any orphans that may be left on the list from the last use
3480 int btrfs_orphan_cleanup(struct btrfs_root *root)
3482 struct btrfs_fs_info *fs_info = root->fs_info;
3483 struct btrfs_path *path;
3484 struct extent_buffer *leaf;
3485 struct btrfs_key key, found_key;
3486 struct btrfs_trans_handle *trans;
3487 struct inode *inode;
3488 u64 last_objectid = 0;
3489 int ret = 0, nr_unlink = 0, nr_truncate = 0;
3491 if (cmpxchg(&root->orphan_cleanup_state, 0, ORPHAN_CLEANUP_STARTED))
3494 path = btrfs_alloc_path();
3499 path->reada = READA_BACK;
3501 key.objectid = BTRFS_ORPHAN_OBJECTID;
3502 key.type = BTRFS_ORPHAN_ITEM_KEY;
3503 key.offset = (u64)-1;
3506 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
3511 * if ret == 0 means we found what we were searching for, which
3512 * is weird, but possible, so only screw with path if we didn't
3513 * find the key and see if we have stuff that matches
3517 if (path->slots[0] == 0)
3522 /* pull out the item */
3523 leaf = path->nodes[0];
3524 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
3526 /* make sure the item matches what we want */
3527 if (found_key.objectid != BTRFS_ORPHAN_OBJECTID)
3529 if (found_key.type != BTRFS_ORPHAN_ITEM_KEY)
3532 /* release the path since we're done with it */
3533 btrfs_release_path(path);
3536 * this is where we are basically btrfs_lookup, without the
3537 * crossing root thing. we store the inode number in the
3538 * offset of the orphan item.
3541 if (found_key.offset == last_objectid) {
3543 "Error removing orphan entry, stopping orphan cleanup");
3548 last_objectid = found_key.offset;
3550 found_key.objectid = found_key.offset;
3551 found_key.type = BTRFS_INODE_ITEM_KEY;
3552 found_key.offset = 0;
3553 inode = btrfs_iget(fs_info->sb, &found_key, root, NULL);
3554 ret = PTR_ERR_OR_ZERO(inode);
3555 if (ret && ret != -ENOENT)
3558 if (ret == -ENOENT && root == fs_info->tree_root) {
3559 struct btrfs_root *dead_root;
3560 struct btrfs_fs_info *fs_info = root->fs_info;
3561 int is_dead_root = 0;
3564 * this is an orphan in the tree root. Currently these
3565 * could come from 2 sources:
3566 * a) a snapshot deletion in progress
3567 * b) a free space cache inode
3568 * We need to distinguish those two, as the snapshot
3569 * orphan must not get deleted.
3570 * find_dead_roots already ran before us, so if this
3571 * is a snapshot deletion, we should find the root
3572 * in the dead_roots list
3574 spin_lock(&fs_info->trans_lock);
3575 list_for_each_entry(dead_root, &fs_info->dead_roots,
3577 if (dead_root->root_key.objectid ==
3578 found_key.objectid) {
3583 spin_unlock(&fs_info->trans_lock);
3585 /* prevent this orphan from being found again */
3586 key.offset = found_key.objectid - 1;
3591 * Inode is already gone but the orphan item is still there,
3592 * kill the orphan item.
3594 if (ret == -ENOENT) {
3595 trans = btrfs_start_transaction(root, 1);
3596 if (IS_ERR(trans)) {
3597 ret = PTR_ERR(trans);
3600 btrfs_debug(fs_info, "auto deleting %Lu",
3601 found_key.objectid);
3602 ret = btrfs_del_orphan_item(trans, root,
3603 found_key.objectid);
3604 btrfs_end_transaction(trans);
3611 * add this inode to the orphan list so btrfs_orphan_del does
3612 * the proper thing when we hit it
3614 set_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
3615 &BTRFS_I(inode)->runtime_flags);
3616 atomic_inc(&root->orphan_inodes);
3618 /* if we have links, this was a truncate, lets do that */
3619 if (inode->i_nlink) {
3620 if (WARN_ON(!S_ISREG(inode->i_mode))) {
3626 /* 1 for the orphan item deletion. */
3627 trans = btrfs_start_transaction(root, 1);
3628 if (IS_ERR(trans)) {
3630 ret = PTR_ERR(trans);
3633 ret = btrfs_orphan_add(trans, BTRFS_I(inode));
3634 btrfs_end_transaction(trans);
3640 ret = btrfs_truncate(inode, false);
3642 btrfs_orphan_del(NULL, BTRFS_I(inode));
3647 /* this will do delete_inode and everything for us */
3652 /* release the path since we're done with it */
3653 btrfs_release_path(path);
3655 root->orphan_cleanup_state = ORPHAN_CLEANUP_DONE;
3657 if (root->orphan_block_rsv)
3658 btrfs_block_rsv_release(fs_info, root->orphan_block_rsv,
3661 if (root->orphan_block_rsv ||
3662 test_bit(BTRFS_ROOT_ORPHAN_ITEM_INSERTED, &root->state)) {
3663 trans = btrfs_join_transaction(root);
3665 btrfs_end_transaction(trans);
3669 btrfs_debug(fs_info, "unlinked %d orphans", nr_unlink);
3671 btrfs_debug(fs_info, "truncated %d orphans", nr_truncate);
3675 btrfs_err(fs_info, "could not do orphan cleanup %d", ret);
3676 btrfs_free_path(path);
3681 * very simple check to peek ahead in the leaf looking for xattrs. If we
3682 * don't find any xattrs, we know there can't be any acls.
3684 * slot is the slot the inode is in, objectid is the objectid of the inode
3686 static noinline int acls_after_inode_item(struct extent_buffer *leaf,
3687 int slot, u64 objectid,
3688 int *first_xattr_slot)
3690 u32 nritems = btrfs_header_nritems(leaf);
3691 struct btrfs_key found_key;
3692 static u64 xattr_access = 0;
3693 static u64 xattr_default = 0;
3696 if (!xattr_access) {
3697 xattr_access = btrfs_name_hash(XATTR_NAME_POSIX_ACL_ACCESS,
3698 strlen(XATTR_NAME_POSIX_ACL_ACCESS));
3699 xattr_default = btrfs_name_hash(XATTR_NAME_POSIX_ACL_DEFAULT,
3700 strlen(XATTR_NAME_POSIX_ACL_DEFAULT));
3704 *first_xattr_slot = -1;
3705 while (slot < nritems) {
3706 btrfs_item_key_to_cpu(leaf, &found_key, slot);
3708 /* we found a different objectid, there must not be acls */
3709 if (found_key.objectid != objectid)
3712 /* we found an xattr, assume we've got an acl */
3713 if (found_key.type == BTRFS_XATTR_ITEM_KEY) {
3714 if (*first_xattr_slot == -1)
3715 *first_xattr_slot = slot;
3716 if (found_key.offset == xattr_access ||
3717 found_key.offset == xattr_default)
3722 * we found a key greater than an xattr key, there can't
3723 * be any acls later on
3725 if (found_key.type > BTRFS_XATTR_ITEM_KEY)
3732 * it goes inode, inode backrefs, xattrs, extents,
3733 * so if there are a ton of hard links to an inode there can
3734 * be a lot of backrefs. Don't waste time searching too hard,
3735 * this is just an optimization
3740 /* we hit the end of the leaf before we found an xattr or
3741 * something larger than an xattr. We have to assume the inode
3744 if (*first_xattr_slot == -1)
3745 *first_xattr_slot = slot;
3750 * read an inode from the btree into the in-memory inode
3752 static int btrfs_read_locked_inode(struct inode *inode)
3754 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
3755 struct btrfs_path *path;
3756 struct extent_buffer *leaf;
3757 struct btrfs_inode_item *inode_item;
3758 struct btrfs_root *root = BTRFS_I(inode)->root;
3759 struct btrfs_key location;
3764 bool filled = false;
3765 int first_xattr_slot;
3767 ret = btrfs_fill_inode(inode, &rdev);
3771 path = btrfs_alloc_path();
3777 memcpy(&location, &BTRFS_I(inode)->location, sizeof(location));
3779 ret = btrfs_lookup_inode(NULL, root, path, &location, 0);
3786 leaf = path->nodes[0];
3791 inode_item = btrfs_item_ptr(leaf, path->slots[0],
3792 struct btrfs_inode_item);
3793 inode->i_mode = btrfs_inode_mode(leaf, inode_item);
3794 set_nlink(inode, btrfs_inode_nlink(leaf, inode_item));
3795 i_uid_write(inode, btrfs_inode_uid(leaf, inode_item));
3796 i_gid_write(inode, btrfs_inode_gid(leaf, inode_item));
3797 btrfs_i_size_write(BTRFS_I(inode), btrfs_inode_size(leaf, inode_item));
3799 inode->i_atime.tv_sec = btrfs_timespec_sec(leaf, &inode_item->atime);
3800 inode->i_atime.tv_nsec = btrfs_timespec_nsec(leaf, &inode_item->atime);
3802 inode->i_mtime.tv_sec = btrfs_timespec_sec(leaf, &inode_item->mtime);
3803 inode->i_mtime.tv_nsec = btrfs_timespec_nsec(leaf, &inode_item->mtime);
3805 inode->i_ctime.tv_sec = btrfs_timespec_sec(leaf, &inode_item->ctime);
3806 inode->i_ctime.tv_nsec = btrfs_timespec_nsec(leaf, &inode_item->ctime);
3808 BTRFS_I(inode)->i_otime.tv_sec =
3809 btrfs_timespec_sec(leaf, &inode_item->otime);
3810 BTRFS_I(inode)->i_otime.tv_nsec =
3811 btrfs_timespec_nsec(leaf, &inode_item->otime);
3813 inode_set_bytes(inode, btrfs_inode_nbytes(leaf, inode_item));
3814 BTRFS_I(inode)->generation = btrfs_inode_generation(leaf, inode_item);
3815 BTRFS_I(inode)->last_trans = btrfs_inode_transid(leaf, inode_item);
3817 inode_set_iversion_queried(inode,
3818 btrfs_inode_sequence(leaf, inode_item));
3819 inode->i_generation = BTRFS_I(inode)->generation;
3821 rdev = btrfs_inode_rdev(leaf, inode_item);
3823 BTRFS_I(inode)->index_cnt = (u64)-1;
3824 BTRFS_I(inode)->flags = btrfs_inode_flags(leaf, inode_item);
3828 * If we were modified in the current generation and evicted from memory
3829 * and then re-read we need to do a full sync since we don't have any
3830 * idea about which extents were modified before we were evicted from
3833 * This is required for both inode re-read from disk and delayed inode
3834 * in delayed_nodes_tree.
3836 if (BTRFS_I(inode)->last_trans == fs_info->generation)
3837 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
3838 &BTRFS_I(inode)->runtime_flags);
3841 * We don't persist the id of the transaction where an unlink operation
3842 * against the inode was last made. So here we assume the inode might
3843 * have been evicted, and therefore the exact value of last_unlink_trans
3844 * lost, and set it to last_trans to avoid metadata inconsistencies
3845 * between the inode and its parent if the inode is fsync'ed and the log
3846 * replayed. For example, in the scenario:
3849 * ln mydir/foo mydir/bar
3852 * echo 2 > /proc/sys/vm/drop_caches # evicts inode
3853 * xfs_io -c fsync mydir/foo
3855 * mount fs, triggers fsync log replay
3857 * We must make sure that when we fsync our inode foo we also log its
3858 * parent inode, otherwise after log replay the parent still has the
3859 * dentry with the "bar" name but our inode foo has a link count of 1
3860 * and doesn't have an inode ref with the name "bar" anymore.
3862 * Setting last_unlink_trans to last_trans is a pessimistic approach,
3863 * but it guarantees correctness at the expense of occasional full
3864 * transaction commits on fsync if our inode is a directory, or if our
3865 * inode is not a directory, logging its parent unnecessarily.
3867 BTRFS_I(inode)->last_unlink_trans = BTRFS_I(inode)->last_trans;
3870 if (inode->i_nlink != 1 ||
3871 path->slots[0] >= btrfs_header_nritems(leaf))
3874 btrfs_item_key_to_cpu(leaf, &location, path->slots[0]);
3875 if (location.objectid != btrfs_ino(BTRFS_I(inode)))
3878 ptr = btrfs_item_ptr_offset(leaf, path->slots[0]);
3879 if (location.type == BTRFS_INODE_REF_KEY) {
3880 struct btrfs_inode_ref *ref;
3882 ref = (struct btrfs_inode_ref *)ptr;
3883 BTRFS_I(inode)->dir_index = btrfs_inode_ref_index(leaf, ref);
3884 } else if (location.type == BTRFS_INODE_EXTREF_KEY) {
3885 struct btrfs_inode_extref *extref;
3887 extref = (struct btrfs_inode_extref *)ptr;
3888 BTRFS_I(inode)->dir_index = btrfs_inode_extref_index(leaf,
3893 * try to precache a NULL acl entry for files that don't have
3894 * any xattrs or acls
3896 maybe_acls = acls_after_inode_item(leaf, path->slots[0],
3897 btrfs_ino(BTRFS_I(inode)), &first_xattr_slot);
3898 if (first_xattr_slot != -1) {
3899 path->slots[0] = first_xattr_slot;
3900 ret = btrfs_load_inode_props(inode, path);
3903 "error loading props for ino %llu (root %llu): %d",
3904 btrfs_ino(BTRFS_I(inode)),
3905 root->root_key.objectid, ret);
3907 btrfs_free_path(path);
3910 cache_no_acl(inode);
3912 switch (inode->i_mode & S_IFMT) {
3914 inode->i_mapping->a_ops = &btrfs_aops;
3915 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
3916 inode->i_fop = &btrfs_file_operations;
3917 inode->i_op = &btrfs_file_inode_operations;
3920 inode->i_fop = &btrfs_dir_file_operations;
3921 inode->i_op = &btrfs_dir_inode_operations;
3924 inode->i_op = &btrfs_symlink_inode_operations;
3925 inode_nohighmem(inode);
3926 inode->i_mapping->a_ops = &btrfs_symlink_aops;
3929 inode->i_op = &btrfs_special_inode_operations;
3930 init_special_inode(inode, inode->i_mode, rdev);
3934 btrfs_update_iflags(inode);
3938 btrfs_free_path(path);
3939 make_bad_inode(inode);
3944 * given a leaf and an inode, copy the inode fields into the leaf
3946 static void fill_inode_item(struct btrfs_trans_handle *trans,
3947 struct extent_buffer *leaf,
3948 struct btrfs_inode_item *item,
3949 struct inode *inode)
3951 struct btrfs_map_token token;
3953 btrfs_init_map_token(&token);
3955 btrfs_set_token_inode_uid(leaf, item, i_uid_read(inode), &token);
3956 btrfs_set_token_inode_gid(leaf, item, i_gid_read(inode), &token);
3957 btrfs_set_token_inode_size(leaf, item, BTRFS_I(inode)->disk_i_size,
3959 btrfs_set_token_inode_mode(leaf, item, inode->i_mode, &token);
3960 btrfs_set_token_inode_nlink(leaf, item, inode->i_nlink, &token);
3962 btrfs_set_token_timespec_sec(leaf, &item->atime,
3963 inode->i_atime.tv_sec, &token);
3964 btrfs_set_token_timespec_nsec(leaf, &item->atime,
3965 inode->i_atime.tv_nsec, &token);
3967 btrfs_set_token_timespec_sec(leaf, &item->mtime,
3968 inode->i_mtime.tv_sec, &token);
3969 btrfs_set_token_timespec_nsec(leaf, &item->mtime,
3970 inode->i_mtime.tv_nsec, &token);
3972 btrfs_set_token_timespec_sec(leaf, &item->ctime,
3973 inode->i_ctime.tv_sec, &token);
3974 btrfs_set_token_timespec_nsec(leaf, &item->ctime,
3975 inode->i_ctime.tv_nsec, &token);
3977 btrfs_set_token_timespec_sec(leaf, &item->otime,
3978 BTRFS_I(inode)->i_otime.tv_sec, &token);
3979 btrfs_set_token_timespec_nsec(leaf, &item->otime,
3980 BTRFS_I(inode)->i_otime.tv_nsec, &token);
3982 btrfs_set_token_inode_nbytes(leaf, item, inode_get_bytes(inode),
3984 btrfs_set_token_inode_generation(leaf, item, BTRFS_I(inode)->generation,
3986 btrfs_set_token_inode_sequence(leaf, item, inode_peek_iversion(inode),
3988 btrfs_set_token_inode_transid(leaf, item, trans->transid, &token);
3989 btrfs_set_token_inode_rdev(leaf, item, inode->i_rdev, &token);
3990 btrfs_set_token_inode_flags(leaf, item, BTRFS_I(inode)->flags, &token);
3991 btrfs_set_token_inode_block_group(leaf, item, 0, &token);
3995 * copy everything in the in-memory inode into the btree.
3997 static noinline int btrfs_update_inode_item(struct btrfs_trans_handle *trans,
3998 struct btrfs_root *root, struct inode *inode)
4000 struct btrfs_inode_item *inode_item;
4001 struct btrfs_path *path;
4002 struct extent_buffer *leaf;
4005 path = btrfs_alloc_path();
4009 path->leave_spinning = 1;
4010 ret = btrfs_lookup_inode(trans, root, path, &BTRFS_I(inode)->location,
4018 leaf = path->nodes[0];
4019 inode_item = btrfs_item_ptr(leaf, path->slots[0],
4020 struct btrfs_inode_item);
4022 fill_inode_item(trans, leaf, inode_item, inode);
4023 btrfs_mark_buffer_dirty(leaf);
4024 btrfs_set_inode_last_trans(trans, inode);
4027 btrfs_free_path(path);
4032 * copy everything in the in-memory inode into the btree.
4034 noinline int btrfs_update_inode(struct btrfs_trans_handle *trans,
4035 struct btrfs_root *root, struct inode *inode)
4037 struct btrfs_fs_info *fs_info = root->fs_info;
4041 * If the inode is a free space inode, we can deadlock during commit
4042 * if we put it into the delayed code.
4044 * The data relocation inode should also be directly updated
4047 if (!btrfs_is_free_space_inode(BTRFS_I(inode))
4048 && root->root_key.objectid != BTRFS_DATA_RELOC_TREE_OBJECTID
4049 && !test_bit(BTRFS_FS_LOG_RECOVERING, &fs_info->flags)) {
4050 btrfs_update_root_times(trans, root);
4052 ret = btrfs_delayed_update_inode(trans, root, inode);
4054 btrfs_set_inode_last_trans(trans, inode);
4058 return btrfs_update_inode_item(trans, root, inode);
4061 noinline int btrfs_update_inode_fallback(struct btrfs_trans_handle *trans,
4062 struct btrfs_root *root,
4063 struct inode *inode)
4067 ret = btrfs_update_inode(trans, root, inode);
4069 return btrfs_update_inode_item(trans, root, inode);
4074 * unlink helper that gets used here in inode.c and in the tree logging
4075 * recovery code. It remove a link in a directory with a given name, and
4076 * also drops the back refs in the inode to the directory
4078 static int __btrfs_unlink_inode(struct btrfs_trans_handle *trans,
4079 struct btrfs_root *root,
4080 struct btrfs_inode *dir,
4081 struct btrfs_inode *inode,
4082 const char *name, int name_len)
4084 struct btrfs_fs_info *fs_info = root->fs_info;
4085 struct btrfs_path *path;
4087 struct extent_buffer *leaf;
4088 struct btrfs_dir_item *di;
4089 struct btrfs_key key;
4091 u64 ino = btrfs_ino(inode);
4092 u64 dir_ino = btrfs_ino(dir);
4094 path = btrfs_alloc_path();
4100 path->leave_spinning = 1;
4101 di = btrfs_lookup_dir_item(trans, root, path, dir_ino,
4102 name, name_len, -1);
4111 leaf = path->nodes[0];
4112 btrfs_dir_item_key_to_cpu(leaf, di, &key);
4113 ret = btrfs_delete_one_dir_name(trans, root, path, di);
4116 btrfs_release_path(path);
4119 * If we don't have dir index, we have to get it by looking up
4120 * the inode ref, since we get the inode ref, remove it directly,
4121 * it is unnecessary to do delayed deletion.
4123 * But if we have dir index, needn't search inode ref to get it.
4124 * Since the inode ref is close to the inode item, it is better
4125 * that we delay to delete it, and just do this deletion when
4126 * we update the inode item.
4128 if (inode->dir_index) {
4129 ret = btrfs_delayed_delete_inode_ref(inode);
4131 index = inode->dir_index;
4136 ret = btrfs_del_inode_ref(trans, root, name, name_len, ino,
4140 "failed to delete reference to %.*s, inode %llu parent %llu",
4141 name_len, name, ino, dir_ino);
4142 btrfs_abort_transaction(trans, ret);
4146 ret = btrfs_delete_delayed_dir_index(trans, fs_info, dir, index);
4148 btrfs_abort_transaction(trans, ret);
4152 ret = btrfs_del_inode_ref_in_log(trans, root, name, name_len, inode,
4154 if (ret != 0 && ret != -ENOENT) {
4155 btrfs_abort_transaction(trans, ret);
4159 ret = btrfs_del_dir_entries_in_log(trans, root, name, name_len, dir,
4164 btrfs_abort_transaction(trans, ret);
4166 btrfs_free_path(path);
4170 btrfs_i_size_write(dir, dir->vfs_inode.i_size - name_len * 2);
4171 inode_inc_iversion(&inode->vfs_inode);
4172 inode_inc_iversion(&dir->vfs_inode);
4173 inode->vfs_inode.i_ctime = dir->vfs_inode.i_mtime =
4174 dir->vfs_inode.i_ctime = current_time(&inode->vfs_inode);
4175 ret = btrfs_update_inode(trans, root, &dir->vfs_inode);
4180 int btrfs_unlink_inode(struct btrfs_trans_handle *trans,
4181 struct btrfs_root *root,
4182 struct btrfs_inode *dir, struct btrfs_inode *inode,
4183 const char *name, int name_len)
4186 ret = __btrfs_unlink_inode(trans, root, dir, inode, name, name_len);
4188 drop_nlink(&inode->vfs_inode);
4189 ret = btrfs_update_inode(trans, root, &inode->vfs_inode);
4195 * helper to start transaction for unlink and rmdir.
4197 * unlink and rmdir are special in btrfs, they do not always free space, so
4198 * if we cannot make our reservations the normal way try and see if there is
4199 * plenty of slack room in the global reserve to migrate, otherwise we cannot
4200 * allow the unlink to occur.
4202 static struct btrfs_trans_handle *__unlink_start_trans(struct inode *dir)
4204 struct btrfs_root *root = BTRFS_I(dir)->root;
4207 * 1 for the possible orphan item
4208 * 1 for the dir item
4209 * 1 for the dir index
4210 * 1 for the inode ref
4213 return btrfs_start_transaction_fallback_global_rsv(root, 5, 5);
4216 static int btrfs_unlink(struct inode *dir, struct dentry *dentry)
4218 struct btrfs_root *root = BTRFS_I(dir)->root;
4219 struct btrfs_trans_handle *trans;
4220 struct inode *inode = d_inode(dentry);
4223 trans = __unlink_start_trans(dir);
4225 return PTR_ERR(trans);
4227 btrfs_record_unlink_dir(trans, BTRFS_I(dir), BTRFS_I(d_inode(dentry)),
4230 ret = btrfs_unlink_inode(trans, root, BTRFS_I(dir),
4231 BTRFS_I(d_inode(dentry)), dentry->d_name.name,
4232 dentry->d_name.len);
4236 if (inode->i_nlink == 0) {
4237 ret = btrfs_orphan_add(trans, BTRFS_I(inode));
4243 btrfs_end_transaction(trans);
4244 btrfs_btree_balance_dirty(root->fs_info);
4248 int btrfs_unlink_subvol(struct btrfs_trans_handle *trans,
4249 struct btrfs_root *root,
4250 struct inode *dir, u64 objectid,
4251 const char *name, int name_len)
4253 struct btrfs_fs_info *fs_info = root->fs_info;
4254 struct btrfs_path *path;
4255 struct extent_buffer *leaf;
4256 struct btrfs_dir_item *di;
4257 struct btrfs_key key;
4260 u64 dir_ino = btrfs_ino(BTRFS_I(dir));
4262 path = btrfs_alloc_path();
4266 di = btrfs_lookup_dir_item(trans, root, path, dir_ino,
4267 name, name_len, -1);
4268 if (IS_ERR_OR_NULL(di)) {
4276 leaf = path->nodes[0];
4277 btrfs_dir_item_key_to_cpu(leaf, di, &key);
4278 WARN_ON(key.type != BTRFS_ROOT_ITEM_KEY || key.objectid != objectid);
4279 ret = btrfs_delete_one_dir_name(trans, root, path, di);
4281 btrfs_abort_transaction(trans, ret);
4284 btrfs_release_path(path);
4286 ret = btrfs_del_root_ref(trans, fs_info, objectid,
4287 root->root_key.objectid, dir_ino,
4288 &index, name, name_len);
4290 if (ret != -ENOENT) {
4291 btrfs_abort_transaction(trans, ret);
4294 di = btrfs_search_dir_index_item(root, path, dir_ino,
4296 if (IS_ERR_OR_NULL(di)) {
4301 btrfs_abort_transaction(trans, ret);
4305 leaf = path->nodes[0];
4306 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
4307 btrfs_release_path(path);
4310 btrfs_release_path(path);
4312 ret = btrfs_delete_delayed_dir_index(trans, fs_info, BTRFS_I(dir), index);
4314 btrfs_abort_transaction(trans, ret);
4318 btrfs_i_size_write(BTRFS_I(dir), dir->i_size - name_len * 2);
4319 inode_inc_iversion(dir);
4320 dir->i_mtime = dir->i_ctime = current_time(dir);
4321 ret = btrfs_update_inode_fallback(trans, root, dir);
4323 btrfs_abort_transaction(trans, ret);
4325 btrfs_free_path(path);
4329 static int btrfs_rmdir(struct inode *dir, struct dentry *dentry)
4331 struct inode *inode = d_inode(dentry);
4333 struct btrfs_root *root = BTRFS_I(dir)->root;
4334 struct btrfs_trans_handle *trans;
4335 u64 last_unlink_trans;
4337 if (inode->i_size > BTRFS_EMPTY_DIR_SIZE)
4339 if (btrfs_ino(BTRFS_I(inode)) == BTRFS_FIRST_FREE_OBJECTID)
4342 trans = __unlink_start_trans(dir);
4344 return PTR_ERR(trans);
4346 if (unlikely(btrfs_ino(BTRFS_I(inode)) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)) {
4347 err = btrfs_unlink_subvol(trans, root, dir,
4348 BTRFS_I(inode)->location.objectid,
4349 dentry->d_name.name,
4350 dentry->d_name.len);
4354 err = btrfs_orphan_add(trans, BTRFS_I(inode));
4358 last_unlink_trans = BTRFS_I(inode)->last_unlink_trans;
4360 /* now the directory is empty */
4361 err = btrfs_unlink_inode(trans, root, BTRFS_I(dir),
4362 BTRFS_I(d_inode(dentry)), dentry->d_name.name,
4363 dentry->d_name.len);
4365 btrfs_i_size_write(BTRFS_I(inode), 0);
4367 * Propagate the last_unlink_trans value of the deleted dir to
4368 * its parent directory. This is to prevent an unrecoverable
4369 * log tree in the case we do something like this:
4371 * 2) create snapshot under dir foo
4372 * 3) delete the snapshot
4375 * 6) fsync foo or some file inside foo
4377 if (last_unlink_trans >= trans->transid)
4378 BTRFS_I(dir)->last_unlink_trans = last_unlink_trans;
4381 btrfs_end_transaction(trans);
4382 btrfs_btree_balance_dirty(root->fs_info);
4387 static int truncate_space_check(struct btrfs_trans_handle *trans,
4388 struct btrfs_root *root,
4391 struct btrfs_fs_info *fs_info = root->fs_info;
4395 * This is only used to apply pressure to the enospc system, we don't
4396 * intend to use this reservation at all.
4398 bytes_deleted = btrfs_csum_bytes_to_leaves(fs_info, bytes_deleted);
4399 bytes_deleted *= fs_info->nodesize;
4400 ret = btrfs_block_rsv_add(root, &fs_info->trans_block_rsv,
4401 bytes_deleted, BTRFS_RESERVE_NO_FLUSH);
4403 trace_btrfs_space_reservation(fs_info, "transaction",
4406 trans->bytes_reserved += bytes_deleted;
4413 * Return this if we need to call truncate_block for the last bit of the
4416 #define NEED_TRUNCATE_BLOCK 1
4419 * this can truncate away extent items, csum items and directory items.
4420 * It starts at a high offset and removes keys until it can't find
4421 * any higher than new_size
4423 * csum items that cross the new i_size are truncated to the new size
4426 * min_type is the minimum key type to truncate down to. If set to 0, this
4427 * will kill all the items on this inode, including the INODE_ITEM_KEY.
4429 int btrfs_truncate_inode_items(struct btrfs_trans_handle *trans,
4430 struct btrfs_root *root,
4431 struct inode *inode,
4432 u64 new_size, u32 min_type)
4434 struct btrfs_fs_info *fs_info = root->fs_info;
4435 struct btrfs_path *path;
4436 struct extent_buffer *leaf;
4437 struct btrfs_file_extent_item *fi;
4438 struct btrfs_key key;
4439 struct btrfs_key found_key;
4440 u64 extent_start = 0;
4441 u64 extent_num_bytes = 0;
4442 u64 extent_offset = 0;
4444 u64 last_size = new_size;
4445 u32 found_type = (u8)-1;
4448 int pending_del_nr = 0;
4449 int pending_del_slot = 0;
4450 int extent_type = -1;
4453 u64 ino = btrfs_ino(BTRFS_I(inode));
4454 u64 bytes_deleted = 0;
4455 bool be_nice = false;
4456 bool should_throttle = false;
4457 bool should_end = false;
4459 BUG_ON(new_size > 0 && min_type != BTRFS_EXTENT_DATA_KEY);
4462 * for non-free space inodes and ref cows, we want to back off from
4465 if (!btrfs_is_free_space_inode(BTRFS_I(inode)) &&
4466 test_bit(BTRFS_ROOT_REF_COWS, &root->state))
4469 path = btrfs_alloc_path();
4472 path->reada = READA_BACK;
4475 * We want to drop from the next block forward in case this new size is
4476 * not block aligned since we will be keeping the last block of the
4477 * extent just the way it is.
4479 if (test_bit(BTRFS_ROOT_REF_COWS, &root->state) ||
4480 root == fs_info->tree_root)
4481 btrfs_drop_extent_cache(BTRFS_I(inode), ALIGN(new_size,
4482 fs_info->sectorsize),
4486 * This function is also used to drop the items in the log tree before
4487 * we relog the inode, so if root != BTRFS_I(inode)->root, it means
4488 * it is used to drop the loged items. So we shouldn't kill the delayed
4491 if (min_type == 0 && root == BTRFS_I(inode)->root)
4492 btrfs_kill_delayed_inode_items(BTRFS_I(inode));
4495 key.offset = (u64)-1;
4500 * with a 16K leaf size and 128MB extents, you can actually queue
4501 * up a huge file in a single leaf. Most of the time that
4502 * bytes_deleted is > 0, it will be huge by the time we get here
4504 if (be_nice && bytes_deleted > SZ_32M) {
4505 if (btrfs_should_end_transaction(trans)) {
4512 path->leave_spinning = 1;
4513 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
4520 /* there are no items in the tree for us to truncate, we're
4523 if (path->slots[0] == 0)
4530 leaf = path->nodes[0];
4531 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
4532 found_type = found_key.type;
4534 if (found_key.objectid != ino)
4537 if (found_type < min_type)
4540 item_end = found_key.offset;
4541 if (found_type == BTRFS_EXTENT_DATA_KEY) {
4542 fi = btrfs_item_ptr(leaf, path->slots[0],
4543 struct btrfs_file_extent_item);
4544 extent_type = btrfs_file_extent_type(leaf, fi);
4545 if (extent_type != BTRFS_FILE_EXTENT_INLINE) {
4547 btrfs_file_extent_num_bytes(leaf, fi);
4549 trace_btrfs_truncate_show_fi_regular(
4550 BTRFS_I(inode), leaf, fi,
4552 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
4553 item_end += btrfs_file_extent_inline_len(leaf,
4554 path->slots[0], fi);
4556 trace_btrfs_truncate_show_fi_inline(
4557 BTRFS_I(inode), leaf, fi, path->slots[0],
4562 if (found_type > min_type) {
4565 if (item_end < new_size)
4567 if (found_key.offset >= new_size)
4573 /* FIXME, shrink the extent if the ref count is only 1 */
4574 if (found_type != BTRFS_EXTENT_DATA_KEY)
4577 if (extent_type != BTRFS_FILE_EXTENT_INLINE) {
4579 extent_start = btrfs_file_extent_disk_bytenr(leaf, fi);
4581 u64 orig_num_bytes =
4582 btrfs_file_extent_num_bytes(leaf, fi);
4583 extent_num_bytes = ALIGN(new_size -
4585 fs_info->sectorsize);
4586 btrfs_set_file_extent_num_bytes(leaf, fi,
4588 num_dec = (orig_num_bytes -
4590 if (test_bit(BTRFS_ROOT_REF_COWS,
4593 inode_sub_bytes(inode, num_dec);
4594 btrfs_mark_buffer_dirty(leaf);
4597 btrfs_file_extent_disk_num_bytes(leaf,
4599 extent_offset = found_key.offset -
4600 btrfs_file_extent_offset(leaf, fi);
4602 /* FIXME blocksize != 4096 */
4603 num_dec = btrfs_file_extent_num_bytes(leaf, fi);
4604 if (extent_start != 0) {
4606 if (test_bit(BTRFS_ROOT_REF_COWS,
4608 inode_sub_bytes(inode, num_dec);
4611 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
4613 * we can't truncate inline items that have had
4617 btrfs_file_extent_encryption(leaf, fi) == 0 &&
4618 btrfs_file_extent_other_encoding(leaf, fi) == 0 &&
4619 btrfs_file_extent_compression(leaf, fi) == 0) {
4620 u32 size = (u32)(new_size - found_key.offset);
4622 btrfs_set_file_extent_ram_bytes(leaf, fi, size);
4623 size = btrfs_file_extent_calc_inline_size(size);
4624 btrfs_truncate_item(root->fs_info, path, size, 1);
4625 } else if (!del_item) {
4627 * We have to bail so the last_size is set to
4628 * just before this extent.
4630 err = NEED_TRUNCATE_BLOCK;
4634 if (test_bit(BTRFS_ROOT_REF_COWS, &root->state))
4635 inode_sub_bytes(inode, item_end + 1 - new_size);
4639 last_size = found_key.offset;
4641 last_size = new_size;
4643 if (!pending_del_nr) {
4644 /* no pending yet, add ourselves */
4645 pending_del_slot = path->slots[0];
4647 } else if (pending_del_nr &&
4648 path->slots[0] + 1 == pending_del_slot) {
4649 /* hop on the pending chunk */
4651 pending_del_slot = path->slots[0];
4658 should_throttle = false;
4661 (test_bit(BTRFS_ROOT_REF_COWS, &root->state) ||
4662 root == fs_info->tree_root)) {
4663 btrfs_set_path_blocking(path);
4664 bytes_deleted += extent_num_bytes;
4665 ret = btrfs_free_extent(trans, root, extent_start,
4666 extent_num_bytes, 0,
4667 btrfs_header_owner(leaf),
4668 ino, extent_offset);
4670 if (btrfs_should_throttle_delayed_refs(trans, fs_info))
4671 btrfs_async_run_delayed_refs(fs_info,
4672 trans->delayed_ref_updates * 2,
4675 if (truncate_space_check(trans, root,
4676 extent_num_bytes)) {
4679 if (btrfs_should_throttle_delayed_refs(trans,
4681 should_throttle = true;
4685 if (found_type == BTRFS_INODE_ITEM_KEY)
4688 if (path->slots[0] == 0 ||
4689 path->slots[0] != pending_del_slot ||
4690 should_throttle || should_end) {
4691 if (pending_del_nr) {
4692 ret = btrfs_del_items(trans, root, path,
4696 btrfs_abort_transaction(trans, ret);
4701 btrfs_release_path(path);
4702 if (should_throttle) {
4703 unsigned long updates = trans->delayed_ref_updates;
4705 trans->delayed_ref_updates = 0;
4706 ret = btrfs_run_delayed_refs(trans,
4713 * if we failed to refill our space rsv, bail out
4714 * and let the transaction restart
4726 if (pending_del_nr) {
4727 ret = btrfs_del_items(trans, root, path, pending_del_slot,
4730 btrfs_abort_transaction(trans, ret);
4733 if (root->root_key.objectid != BTRFS_TREE_LOG_OBJECTID) {
4734 ASSERT(last_size >= new_size);
4735 if (!err && last_size > new_size)
4736 last_size = new_size;
4737 btrfs_ordered_update_i_size(inode, last_size, NULL);
4740 btrfs_free_path(path);
4742 if (be_nice && bytes_deleted > SZ_32M) {
4743 unsigned long updates = trans->delayed_ref_updates;
4745 trans->delayed_ref_updates = 0;
4746 ret = btrfs_run_delayed_refs(trans, updates * 2);
4755 * btrfs_truncate_block - read, zero a chunk and write a block
4756 * @inode - inode that we're zeroing
4757 * @from - the offset to start zeroing
4758 * @len - the length to zero, 0 to zero the entire range respective to the
4760 * @front - zero up to the offset instead of from the offset on
4762 * This will find the block for the "from" offset and cow the block and zero the
4763 * part we want to zero. This is used with truncate and hole punching.
4765 int btrfs_truncate_block(struct inode *inode, loff_t from, loff_t len,
4768 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
4769 struct address_space *mapping = inode->i_mapping;
4770 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
4771 struct btrfs_ordered_extent *ordered;
4772 struct extent_state *cached_state = NULL;
4773 struct extent_changeset *data_reserved = NULL;
4775 u32 blocksize = fs_info->sectorsize;
4776 pgoff_t index = from >> PAGE_SHIFT;
4777 unsigned offset = from & (blocksize - 1);
4779 gfp_t mask = btrfs_alloc_write_mask(mapping);
4784 if (IS_ALIGNED(offset, blocksize) &&
4785 (!len || IS_ALIGNED(len, blocksize)))
4788 block_start = round_down(from, blocksize);
4789 block_end = block_start + blocksize - 1;
4791 ret = btrfs_delalloc_reserve_space(inode, &data_reserved,
4792 block_start, blocksize);
4797 page = find_or_create_page(mapping, index, mask);
4799 btrfs_delalloc_release_space(inode, data_reserved,
4800 block_start, blocksize, true);
4801 btrfs_delalloc_release_extents(BTRFS_I(inode), blocksize, true);
4806 if (!PageUptodate(page)) {
4807 ret = btrfs_readpage(NULL, page);
4809 if (page->mapping != mapping) {
4814 if (!PageUptodate(page)) {
4819 wait_on_page_writeback(page);
4821 lock_extent_bits(io_tree, block_start, block_end, &cached_state);
4822 set_page_extent_mapped(page);
4824 ordered = btrfs_lookup_ordered_extent(inode, block_start);
4826 unlock_extent_cached(io_tree, block_start, block_end,
4830 btrfs_start_ordered_extent(inode, ordered, 1);
4831 btrfs_put_ordered_extent(ordered);
4835 clear_extent_bit(&BTRFS_I(inode)->io_tree, block_start, block_end,
4836 EXTENT_DIRTY | EXTENT_DELALLOC |
4837 EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG,
4838 0, 0, &cached_state);
4840 ret = btrfs_set_extent_delalloc(inode, block_start, block_end, 0,
4843 unlock_extent_cached(io_tree, block_start, block_end,
4848 if (offset != blocksize) {
4850 len = blocksize - offset;
4853 memset(kaddr + (block_start - page_offset(page)),
4856 memset(kaddr + (block_start - page_offset(page)) + offset,
4858 flush_dcache_page(page);
4861 ClearPageChecked(page);
4862 set_page_dirty(page);
4863 unlock_extent_cached(io_tree, block_start, block_end, &cached_state);
4867 btrfs_delalloc_release_space(inode, data_reserved, block_start,
4869 btrfs_delalloc_release_extents(BTRFS_I(inode), blocksize, (ret != 0));
4873 extent_changeset_free(data_reserved);
4877 static int maybe_insert_hole(struct btrfs_root *root, struct inode *inode,
4878 u64 offset, u64 len)
4880 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
4881 struct btrfs_trans_handle *trans;
4885 * Still need to make sure the inode looks like it's been updated so
4886 * that any holes get logged if we fsync.
4888 if (btrfs_fs_incompat(fs_info, NO_HOLES)) {
4889 BTRFS_I(inode)->last_trans = fs_info->generation;
4890 BTRFS_I(inode)->last_sub_trans = root->log_transid;
4891 BTRFS_I(inode)->last_log_commit = root->last_log_commit;
4896 * 1 - for the one we're dropping
4897 * 1 - for the one we're adding
4898 * 1 - for updating the inode.
4900 trans = btrfs_start_transaction(root, 3);
4902 return PTR_ERR(trans);
4904 ret = btrfs_drop_extents(trans, root, inode, offset, offset + len, 1);
4906 btrfs_abort_transaction(trans, ret);
4907 btrfs_end_transaction(trans);
4911 ret = btrfs_insert_file_extent(trans, root, btrfs_ino(BTRFS_I(inode)),
4912 offset, 0, 0, len, 0, len, 0, 0, 0);
4914 btrfs_abort_transaction(trans, ret);
4916 btrfs_update_inode(trans, root, inode);
4917 btrfs_end_transaction(trans);
4922 * This function puts in dummy file extents for the area we're creating a hole
4923 * for. So if we are truncating this file to a larger size we need to insert
4924 * these file extents so that btrfs_get_extent will return a EXTENT_MAP_HOLE for
4925 * the range between oldsize and size
4927 int btrfs_cont_expand(struct inode *inode, loff_t oldsize, loff_t size)
4929 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
4930 struct btrfs_root *root = BTRFS_I(inode)->root;
4931 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
4932 struct extent_map *em = NULL;
4933 struct extent_state *cached_state = NULL;
4934 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
4935 u64 hole_start = ALIGN(oldsize, fs_info->sectorsize);
4936 u64 block_end = ALIGN(size, fs_info->sectorsize);
4943 * If our size started in the middle of a block we need to zero out the
4944 * rest of the block before we expand the i_size, otherwise we could
4945 * expose stale data.
4947 err = btrfs_truncate_block(inode, oldsize, 0, 0);
4951 if (size <= hole_start)
4955 struct btrfs_ordered_extent *ordered;
4957 lock_extent_bits(io_tree, hole_start, block_end - 1,
4959 ordered = btrfs_lookup_ordered_range(BTRFS_I(inode), hole_start,
4960 block_end - hole_start);
4963 unlock_extent_cached(io_tree, hole_start, block_end - 1,
4965 btrfs_start_ordered_extent(inode, ordered, 1);
4966 btrfs_put_ordered_extent(ordered);
4969 cur_offset = hole_start;
4971 em = btrfs_get_extent(BTRFS_I(inode), NULL, 0, cur_offset,
4972 block_end - cur_offset, 0);
4978 last_byte = min(extent_map_end(em), block_end);
4979 last_byte = ALIGN(last_byte, fs_info->sectorsize);
4980 if (!test_bit(EXTENT_FLAG_PREALLOC, &em->flags)) {
4981 struct extent_map *hole_em;
4982 hole_size = last_byte - cur_offset;
4984 err = maybe_insert_hole(root, inode, cur_offset,
4988 btrfs_drop_extent_cache(BTRFS_I(inode), cur_offset,
4989 cur_offset + hole_size - 1, 0);
4990 hole_em = alloc_extent_map();
4992 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
4993 &BTRFS_I(inode)->runtime_flags);
4996 hole_em->start = cur_offset;
4997 hole_em->len = hole_size;
4998 hole_em->orig_start = cur_offset;
5000 hole_em->block_start = EXTENT_MAP_HOLE;
5001 hole_em->block_len = 0;
5002 hole_em->orig_block_len = 0;
5003 hole_em->ram_bytes = hole_size;
5004 hole_em->bdev = fs_info->fs_devices->latest_bdev;
5005 hole_em->compress_type = BTRFS_COMPRESS_NONE;
5006 hole_em->generation = fs_info->generation;
5009 write_lock(&em_tree->lock);
5010 err = add_extent_mapping(em_tree, hole_em, 1);
5011 write_unlock(&em_tree->lock);
5014 btrfs_drop_extent_cache(BTRFS_I(inode),
5019 free_extent_map(hole_em);
5022 free_extent_map(em);
5024 cur_offset = last_byte;
5025 if (cur_offset >= block_end)
5028 free_extent_map(em);
5029 unlock_extent_cached(io_tree, hole_start, block_end - 1, &cached_state);
5033 static int btrfs_setsize(struct inode *inode, struct iattr *attr)
5035 struct btrfs_root *root = BTRFS_I(inode)->root;
5036 struct btrfs_trans_handle *trans;
5037 loff_t oldsize = i_size_read(inode);
5038 loff_t newsize = attr->ia_size;
5039 int mask = attr->ia_valid;
5043 * The regular truncate() case without ATTR_CTIME and ATTR_MTIME is a
5044 * special case where we need to update the times despite not having
5045 * these flags set. For all other operations the VFS set these flags
5046 * explicitly if it wants a timestamp update.
5048 if (newsize != oldsize) {
5049 inode_inc_iversion(inode);
5050 if (!(mask & (ATTR_CTIME | ATTR_MTIME)))
5051 inode->i_ctime = inode->i_mtime =
5052 current_time(inode);
5055 if (newsize > oldsize) {
5057 * Don't do an expanding truncate while snapshotting is ongoing.
5058 * This is to ensure the snapshot captures a fully consistent
5059 * state of this file - if the snapshot captures this expanding
5060 * truncation, it must capture all writes that happened before
5063 btrfs_wait_for_snapshot_creation(root);
5064 ret = btrfs_cont_expand(inode, oldsize, newsize);
5066 btrfs_end_write_no_snapshotting(root);
5070 trans = btrfs_start_transaction(root, 1);
5071 if (IS_ERR(trans)) {
5072 btrfs_end_write_no_snapshotting(root);
5073 return PTR_ERR(trans);
5076 i_size_write(inode, newsize);
5077 btrfs_ordered_update_i_size(inode, i_size_read(inode), NULL);
5078 pagecache_isize_extended(inode, oldsize, newsize);
5079 ret = btrfs_update_inode(trans, root, inode);
5080 btrfs_end_write_no_snapshotting(root);
5081 btrfs_end_transaction(trans);
5085 * We're truncating a file that used to have good data down to
5086 * zero. Make sure it gets into the ordered flush list so that
5087 * any new writes get down to disk quickly.
5090 set_bit(BTRFS_INODE_ORDERED_DATA_CLOSE,
5091 &BTRFS_I(inode)->runtime_flags);
5094 * 1 for the orphan item we're going to add
5095 * 1 for the orphan item deletion.
5097 trans = btrfs_start_transaction(root, 2);
5099 return PTR_ERR(trans);
5102 * We need to do this in case we fail at _any_ point during the
5103 * actual truncate. Once we do the truncate_setsize we could
5104 * invalidate pages which forces any outstanding ordered io to
5105 * be instantly completed which will give us extents that need
5106 * to be truncated. If we fail to get an orphan inode down we
5107 * could have left over extents that were never meant to live,
5108 * so we need to guarantee from this point on that everything
5109 * will be consistent.
5111 ret = btrfs_orphan_add(trans, BTRFS_I(inode));
5112 btrfs_end_transaction(trans);
5116 /* we don't support swapfiles, so vmtruncate shouldn't fail */
5117 truncate_setsize(inode, newsize);
5119 /* Disable nonlocked read DIO to avoid the end less truncate */
5120 btrfs_inode_block_unlocked_dio(BTRFS_I(inode));
5121 inode_dio_wait(inode);
5122 btrfs_inode_resume_unlocked_dio(BTRFS_I(inode));
5124 ret = btrfs_truncate(inode, newsize == oldsize);
5125 if (ret && inode->i_nlink) {
5128 /* To get a stable disk_i_size */
5129 err = btrfs_wait_ordered_range(inode, 0, (u64)-1);
5131 btrfs_orphan_del(NULL, BTRFS_I(inode));
5136 * failed to truncate, disk_i_size is only adjusted down
5137 * as we remove extents, so it should represent the true
5138 * size of the inode, so reset the in memory size and
5139 * delete our orphan entry.
5141 trans = btrfs_join_transaction(root);
5142 if (IS_ERR(trans)) {
5143 btrfs_orphan_del(NULL, BTRFS_I(inode));
5146 i_size_write(inode, BTRFS_I(inode)->disk_i_size);
5147 err = btrfs_orphan_del(trans, BTRFS_I(inode));
5149 btrfs_abort_transaction(trans, err);
5150 btrfs_end_transaction(trans);
5157 static int btrfs_setattr(struct dentry *dentry, struct iattr *attr)
5159 struct inode *inode = d_inode(dentry);
5160 struct btrfs_root *root = BTRFS_I(inode)->root;
5163 if (btrfs_root_readonly(root))
5166 err = setattr_prepare(dentry, attr);
5170 if (S_ISREG(inode->i_mode) && (attr->ia_valid & ATTR_SIZE)) {
5171 err = btrfs_setsize(inode, attr);
5176 if (attr->ia_valid) {
5177 setattr_copy(inode, attr);
5178 inode_inc_iversion(inode);
5179 err = btrfs_dirty_inode(inode);
5181 if (!err && attr->ia_valid & ATTR_MODE)
5182 err = posix_acl_chmod(inode, inode->i_mode);
5189 * While truncating the inode pages during eviction, we get the VFS calling
5190 * btrfs_invalidatepage() against each page of the inode. This is slow because
5191 * the calls to btrfs_invalidatepage() result in a huge amount of calls to
5192 * lock_extent_bits() and clear_extent_bit(), which keep merging and splitting
5193 * extent_state structures over and over, wasting lots of time.
5195 * Therefore if the inode is being evicted, let btrfs_invalidatepage() skip all
5196 * those expensive operations on a per page basis and do only the ordered io
5197 * finishing, while we release here the extent_map and extent_state structures,
5198 * without the excessive merging and splitting.
5200 static void evict_inode_truncate_pages(struct inode *inode)
5202 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
5203 struct extent_map_tree *map_tree = &BTRFS_I(inode)->extent_tree;
5204 struct rb_node *node;
5206 ASSERT(inode->i_state & I_FREEING);
5207 truncate_inode_pages_final(&inode->i_data);
5209 write_lock(&map_tree->lock);
5210 while (!RB_EMPTY_ROOT(&map_tree->map)) {
5211 struct extent_map *em;
5213 node = rb_first(&map_tree->map);
5214 em = rb_entry(node, struct extent_map, rb_node);
5215 clear_bit(EXTENT_FLAG_PINNED, &em->flags);
5216 clear_bit(EXTENT_FLAG_LOGGING, &em->flags);
5217 remove_extent_mapping(map_tree, em);
5218 free_extent_map(em);
5219 if (need_resched()) {
5220 write_unlock(&map_tree->lock);
5222 write_lock(&map_tree->lock);
5225 write_unlock(&map_tree->lock);
5228 * Keep looping until we have no more ranges in the io tree.
5229 * We can have ongoing bios started by readpages (called from readahead)
5230 * that have their endio callback (extent_io.c:end_bio_extent_readpage)
5231 * still in progress (unlocked the pages in the bio but did not yet
5232 * unlocked the ranges in the io tree). Therefore this means some
5233 * ranges can still be locked and eviction started because before
5234 * submitting those bios, which are executed by a separate task (work
5235 * queue kthread), inode references (inode->i_count) were not taken
5236 * (which would be dropped in the end io callback of each bio).
5237 * Therefore here we effectively end up waiting for those bios and
5238 * anyone else holding locked ranges without having bumped the inode's
5239 * reference count - if we don't do it, when they access the inode's
5240 * io_tree to unlock a range it may be too late, leading to an
5241 * use-after-free issue.
5243 spin_lock(&io_tree->lock);
5244 while (!RB_EMPTY_ROOT(&io_tree->state)) {
5245 struct extent_state *state;
5246 struct extent_state *cached_state = NULL;
5250 node = rb_first(&io_tree->state);
5251 state = rb_entry(node, struct extent_state, rb_node);
5252 start = state->start;
5254 spin_unlock(&io_tree->lock);
5256 lock_extent_bits(io_tree, start, end, &cached_state);
5259 * If still has DELALLOC flag, the extent didn't reach disk,
5260 * and its reserved space won't be freed by delayed_ref.
5261 * So we need to free its reserved space here.
5262 * (Refer to comment in btrfs_invalidatepage, case 2)
5264 * Note, end is the bytenr of last byte, so we need + 1 here.
5266 if (state->state & EXTENT_DELALLOC)
5267 btrfs_qgroup_free_data(inode, NULL, start, end - start + 1);
5269 clear_extent_bit(io_tree, start, end,
5270 EXTENT_LOCKED | EXTENT_DIRTY |
5271 EXTENT_DELALLOC | EXTENT_DO_ACCOUNTING |
5272 EXTENT_DEFRAG, 1, 1, &cached_state);
5275 spin_lock(&io_tree->lock);
5277 spin_unlock(&io_tree->lock);
5280 void btrfs_evict_inode(struct inode *inode)
5282 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
5283 struct btrfs_trans_handle *trans;
5284 struct btrfs_root *root = BTRFS_I(inode)->root;
5285 struct btrfs_block_rsv *rsv, *global_rsv;
5286 int steal_from_global = 0;
5290 trace_btrfs_inode_evict(inode);
5297 min_size = btrfs_calc_trunc_metadata_size(fs_info, 1);
5299 evict_inode_truncate_pages(inode);
5301 if (inode->i_nlink &&
5302 ((btrfs_root_refs(&root->root_item) != 0 &&
5303 root->root_key.objectid != BTRFS_ROOT_TREE_OBJECTID) ||
5304 btrfs_is_free_space_inode(BTRFS_I(inode))))
5307 if (is_bad_inode(inode)) {
5308 btrfs_orphan_del(NULL, BTRFS_I(inode));
5311 /* do we really want it for ->i_nlink > 0 and zero btrfs_root_refs? */
5312 if (!special_file(inode->i_mode))
5313 btrfs_wait_ordered_range(inode, 0, (u64)-1);
5315 btrfs_free_io_failure_record(BTRFS_I(inode), 0, (u64)-1);
5317 if (test_bit(BTRFS_FS_LOG_RECOVERING, &fs_info->flags)) {
5318 BUG_ON(test_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
5319 &BTRFS_I(inode)->runtime_flags));
5323 if (inode->i_nlink > 0) {
5324 BUG_ON(btrfs_root_refs(&root->root_item) != 0 &&
5325 root->root_key.objectid != BTRFS_ROOT_TREE_OBJECTID);
5329 ret = btrfs_commit_inode_delayed_inode(BTRFS_I(inode));
5331 btrfs_orphan_del(NULL, BTRFS_I(inode));
5335 rsv = btrfs_alloc_block_rsv(fs_info, BTRFS_BLOCK_RSV_TEMP);
5337 btrfs_orphan_del(NULL, BTRFS_I(inode));
5340 rsv->size = min_size;
5342 global_rsv = &fs_info->global_block_rsv;
5344 btrfs_i_size_write(BTRFS_I(inode), 0);
5347 * This is a bit simpler than btrfs_truncate since we've already
5348 * reserved our space for our orphan item in the unlink, so we just
5349 * need to reserve some slack space in case we add bytes and update
5350 * inode item when doing the truncate.
5353 ret = btrfs_block_rsv_refill(root, rsv, min_size,
5354 BTRFS_RESERVE_FLUSH_LIMIT);
5357 * Try and steal from the global reserve since we will
5358 * likely not use this space anyway, we want to try as
5359 * hard as possible to get this to work.
5362 steal_from_global++;
5364 steal_from_global = 0;
5368 * steal_from_global == 0: we reserved stuff, hooray!
5369 * steal_from_global == 1: we didn't reserve stuff, boo!
5370 * steal_from_global == 2: we've committed, still not a lot of
5371 * room but maybe we'll have room in the global reserve this
5373 * steal_from_global == 3: abandon all hope!
5375 if (steal_from_global > 2) {
5377 "Could not get space for a delete, will truncate on mount %d",
5379 btrfs_orphan_del(NULL, BTRFS_I(inode));
5380 btrfs_free_block_rsv(fs_info, rsv);
5384 trans = btrfs_join_transaction(root);
5385 if (IS_ERR(trans)) {
5386 btrfs_orphan_del(NULL, BTRFS_I(inode));
5387 btrfs_free_block_rsv(fs_info, rsv);
5392 * We can't just steal from the global reserve, we need to make
5393 * sure there is room to do it, if not we need to commit and try
5396 if (steal_from_global) {
5397 if (!btrfs_check_space_for_delayed_refs(trans, fs_info))
5398 ret = btrfs_block_rsv_migrate(global_rsv, rsv,
5405 * Couldn't steal from the global reserve, we have too much
5406 * pending stuff built up, commit the transaction and try it
5410 ret = btrfs_commit_transaction(trans);
5412 btrfs_orphan_del(NULL, BTRFS_I(inode));
5413 btrfs_free_block_rsv(fs_info, rsv);
5418 steal_from_global = 0;
5421 trans->block_rsv = rsv;
5423 ret = btrfs_truncate_inode_items(trans, root, inode, 0, 0);
5424 if (ret != -ENOSPC && ret != -EAGAIN)
5427 trans->block_rsv = &fs_info->trans_block_rsv;
5428 btrfs_end_transaction(trans);
5430 btrfs_btree_balance_dirty(fs_info);
5433 btrfs_free_block_rsv(fs_info, rsv);
5436 * Errors here aren't a big deal, it just means we leave orphan items
5437 * in the tree. They will be cleaned up on the next mount.
5440 trans->block_rsv = root->orphan_block_rsv;
5441 btrfs_orphan_del(trans, BTRFS_I(inode));
5443 btrfs_orphan_del(NULL, BTRFS_I(inode));
5446 trans->block_rsv = &fs_info->trans_block_rsv;
5447 if (!(root == fs_info->tree_root ||
5448 root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID))
5449 btrfs_return_ino(root, btrfs_ino(BTRFS_I(inode)));
5451 btrfs_end_transaction(trans);
5452 btrfs_btree_balance_dirty(fs_info);
5454 btrfs_remove_delayed_node(BTRFS_I(inode));
5459 * this returns the key found in the dir entry in the location pointer.
5460 * If no dir entries were found, returns -ENOENT.
5461 * If found a corrupted location in dir entry, returns -EUCLEAN.
5463 static int btrfs_inode_by_name(struct inode *dir, struct dentry *dentry,
5464 struct btrfs_key *location)
5466 const char *name = dentry->d_name.name;
5467 int namelen = dentry->d_name.len;
5468 struct btrfs_dir_item *di;
5469 struct btrfs_path *path;
5470 struct btrfs_root *root = BTRFS_I(dir)->root;
5473 path = btrfs_alloc_path();
5477 di = btrfs_lookup_dir_item(NULL, root, path, btrfs_ino(BTRFS_I(dir)),
5488 btrfs_dir_item_key_to_cpu(path->nodes[0], di, location);
5489 if (location->type != BTRFS_INODE_ITEM_KEY &&
5490 location->type != BTRFS_ROOT_ITEM_KEY) {
5492 btrfs_warn(root->fs_info,
5493 "%s gets something invalid in DIR_ITEM (name %s, directory ino %llu, location(%llu %u %llu))",
5494 __func__, name, btrfs_ino(BTRFS_I(dir)),
5495 location->objectid, location->type, location->offset);
5498 btrfs_free_path(path);
5503 * when we hit a tree root in a directory, the btrfs part of the inode
5504 * needs to be changed to reflect the root directory of the tree root. This
5505 * is kind of like crossing a mount point.
5507 static int fixup_tree_root_location(struct btrfs_fs_info *fs_info,
5509 struct dentry *dentry,
5510 struct btrfs_key *location,
5511 struct btrfs_root **sub_root)
5513 struct btrfs_path *path;
5514 struct btrfs_root *new_root;
5515 struct btrfs_root_ref *ref;
5516 struct extent_buffer *leaf;
5517 struct btrfs_key key;
5521 path = btrfs_alloc_path();
5528 key.objectid = BTRFS_I(dir)->root->root_key.objectid;
5529 key.type = BTRFS_ROOT_REF_KEY;
5530 key.offset = location->objectid;
5532 ret = btrfs_search_slot(NULL, fs_info->tree_root, &key, path, 0, 0);
5539 leaf = path->nodes[0];
5540 ref = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_root_ref);
5541 if (btrfs_root_ref_dirid(leaf, ref) != btrfs_ino(BTRFS_I(dir)) ||
5542 btrfs_root_ref_name_len(leaf, ref) != dentry->d_name.len)
5545 ret = memcmp_extent_buffer(leaf, dentry->d_name.name,
5546 (unsigned long)(ref + 1),
5547 dentry->d_name.len);
5551 btrfs_release_path(path);
5553 new_root = btrfs_read_fs_root_no_name(fs_info, location);
5554 if (IS_ERR(new_root)) {
5555 err = PTR_ERR(new_root);
5559 *sub_root = new_root;
5560 location->objectid = btrfs_root_dirid(&new_root->root_item);
5561 location->type = BTRFS_INODE_ITEM_KEY;
5562 location->offset = 0;
5565 btrfs_free_path(path);
5569 static void inode_tree_add(struct inode *inode)
5571 struct btrfs_root *root = BTRFS_I(inode)->root;
5572 struct btrfs_inode *entry;
5574 struct rb_node *parent;
5575 struct rb_node *new = &BTRFS_I(inode)->rb_node;
5576 u64 ino = btrfs_ino(BTRFS_I(inode));
5578 if (inode_unhashed(inode))
5581 spin_lock(&root->inode_lock);
5582 p = &root->inode_tree.rb_node;
5585 entry = rb_entry(parent, struct btrfs_inode, rb_node);
5587 if (ino < btrfs_ino(BTRFS_I(&entry->vfs_inode)))
5588 p = &parent->rb_left;
5589 else if (ino > btrfs_ino(BTRFS_I(&entry->vfs_inode)))
5590 p = &parent->rb_right;
5592 WARN_ON(!(entry->vfs_inode.i_state &
5593 (I_WILL_FREE | I_FREEING)));
5594 rb_replace_node(parent, new, &root->inode_tree);
5595 RB_CLEAR_NODE(parent);
5596 spin_unlock(&root->inode_lock);
5600 rb_link_node(new, parent, p);
5601 rb_insert_color(new, &root->inode_tree);
5602 spin_unlock(&root->inode_lock);
5605 static void inode_tree_del(struct inode *inode)
5607 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
5608 struct btrfs_root *root = BTRFS_I(inode)->root;
5611 spin_lock(&root->inode_lock);
5612 if (!RB_EMPTY_NODE(&BTRFS_I(inode)->rb_node)) {
5613 rb_erase(&BTRFS_I(inode)->rb_node, &root->inode_tree);
5614 RB_CLEAR_NODE(&BTRFS_I(inode)->rb_node);
5615 empty = RB_EMPTY_ROOT(&root->inode_tree);
5617 spin_unlock(&root->inode_lock);
5619 if (empty && btrfs_root_refs(&root->root_item) == 0) {
5620 synchronize_srcu(&fs_info->subvol_srcu);
5621 spin_lock(&root->inode_lock);
5622 empty = RB_EMPTY_ROOT(&root->inode_tree);
5623 spin_unlock(&root->inode_lock);
5625 btrfs_add_dead_root(root);
5629 void btrfs_invalidate_inodes(struct btrfs_root *root)
5631 struct btrfs_fs_info *fs_info = root->fs_info;
5632 struct rb_node *node;
5633 struct rb_node *prev;
5634 struct btrfs_inode *entry;
5635 struct inode *inode;
5638 if (!test_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state))
5639 WARN_ON(btrfs_root_refs(&root->root_item) != 0);
5641 spin_lock(&root->inode_lock);
5643 node = root->inode_tree.rb_node;
5647 entry = rb_entry(node, struct btrfs_inode, rb_node);
5649 if (objectid < btrfs_ino(BTRFS_I(&entry->vfs_inode)))
5650 node = node->rb_left;
5651 else if (objectid > btrfs_ino(BTRFS_I(&entry->vfs_inode)))
5652 node = node->rb_right;
5658 entry = rb_entry(prev, struct btrfs_inode, rb_node);
5659 if (objectid <= btrfs_ino(BTRFS_I(&entry->vfs_inode))) {
5663 prev = rb_next(prev);
5667 entry = rb_entry(node, struct btrfs_inode, rb_node);
5668 objectid = btrfs_ino(BTRFS_I(&entry->vfs_inode)) + 1;
5669 inode = igrab(&entry->vfs_inode);
5671 spin_unlock(&root->inode_lock);
5672 if (atomic_read(&inode->i_count) > 1)
5673 d_prune_aliases(inode);
5675 * btrfs_drop_inode will have it removed from
5676 * the inode cache when its usage count
5681 spin_lock(&root->inode_lock);
5685 if (cond_resched_lock(&root->inode_lock))
5688 node = rb_next(node);
5690 spin_unlock(&root->inode_lock);
5693 static int btrfs_init_locked_inode(struct inode *inode, void *p)
5695 struct btrfs_iget_args *args = p;
5696 inode->i_ino = args->location->objectid;
5697 memcpy(&BTRFS_I(inode)->location, args->location,
5698 sizeof(*args->location));
5699 BTRFS_I(inode)->root = args->root;
5703 static int btrfs_find_actor(struct inode *inode, void *opaque)
5705 struct btrfs_iget_args *args = opaque;
5706 return args->location->objectid == BTRFS_I(inode)->location.objectid &&
5707 args->root == BTRFS_I(inode)->root;
5710 static struct inode *btrfs_iget_locked(struct super_block *s,
5711 struct btrfs_key *location,
5712 struct btrfs_root *root)
5714 struct inode *inode;
5715 struct btrfs_iget_args args;
5716 unsigned long hashval = btrfs_inode_hash(location->objectid, root);
5718 args.location = location;
5721 inode = iget5_locked(s, hashval, btrfs_find_actor,
5722 btrfs_init_locked_inode,
5727 /* Get an inode object given its location and corresponding root.
5728 * Returns in *is_new if the inode was read from disk
5730 struct inode *btrfs_iget(struct super_block *s, struct btrfs_key *location,
5731 struct btrfs_root *root, int *new)
5733 struct inode *inode;
5735 inode = btrfs_iget_locked(s, location, root);
5737 return ERR_PTR(-ENOMEM);
5739 if (inode->i_state & I_NEW) {
5742 ret = btrfs_read_locked_inode(inode);
5743 if (!is_bad_inode(inode)) {
5744 inode_tree_add(inode);
5745 unlock_new_inode(inode);
5749 unlock_new_inode(inode);
5752 inode = ERR_PTR(ret < 0 ? ret : -ESTALE);
5759 static struct inode *new_simple_dir(struct super_block *s,
5760 struct btrfs_key *key,
5761 struct btrfs_root *root)
5763 struct inode *inode = new_inode(s);
5766 return ERR_PTR(-ENOMEM);
5768 BTRFS_I(inode)->root = root;
5769 memcpy(&BTRFS_I(inode)->location, key, sizeof(*key));
5770 set_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags);
5772 inode->i_ino = BTRFS_EMPTY_SUBVOL_DIR_OBJECTID;
5773 inode->i_op = &btrfs_dir_ro_inode_operations;
5774 inode->i_opflags &= ~IOP_XATTR;
5775 inode->i_fop = &simple_dir_operations;
5776 inode->i_mode = S_IFDIR | S_IRUGO | S_IWUSR | S_IXUGO;
5777 inode->i_mtime = current_time(inode);
5778 inode->i_atime = inode->i_mtime;
5779 inode->i_ctime = inode->i_mtime;
5780 BTRFS_I(inode)->i_otime = inode->i_mtime;
5785 struct inode *btrfs_lookup_dentry(struct inode *dir, struct dentry *dentry)
5787 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
5788 struct inode *inode;
5789 struct btrfs_root *root = BTRFS_I(dir)->root;
5790 struct btrfs_root *sub_root = root;
5791 struct btrfs_key location;
5795 if (dentry->d_name.len > BTRFS_NAME_LEN)
5796 return ERR_PTR(-ENAMETOOLONG);
5798 ret = btrfs_inode_by_name(dir, dentry, &location);
5800 return ERR_PTR(ret);
5802 if (location.type == BTRFS_INODE_ITEM_KEY) {
5803 inode = btrfs_iget(dir->i_sb, &location, root, NULL);
5807 index = srcu_read_lock(&fs_info->subvol_srcu);
5808 ret = fixup_tree_root_location(fs_info, dir, dentry,
5809 &location, &sub_root);
5812 inode = ERR_PTR(ret);
5814 inode = new_simple_dir(dir->i_sb, &location, sub_root);
5816 inode = btrfs_iget(dir->i_sb, &location, sub_root, NULL);
5818 srcu_read_unlock(&fs_info->subvol_srcu, index);
5820 if (!IS_ERR(inode) && root != sub_root) {
5821 down_read(&fs_info->cleanup_work_sem);
5822 if (!sb_rdonly(inode->i_sb))
5823 ret = btrfs_orphan_cleanup(sub_root);
5824 up_read(&fs_info->cleanup_work_sem);
5827 inode = ERR_PTR(ret);
5834 static int btrfs_dentry_delete(const struct dentry *dentry)
5836 struct btrfs_root *root;
5837 struct inode *inode = d_inode(dentry);
5839 if (!inode && !IS_ROOT(dentry))
5840 inode = d_inode(dentry->d_parent);
5843 root = BTRFS_I(inode)->root;
5844 if (btrfs_root_refs(&root->root_item) == 0)
5847 if (btrfs_ino(BTRFS_I(inode)) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)
5853 static void btrfs_dentry_release(struct dentry *dentry)
5855 kfree(dentry->d_fsdata);
5858 static struct dentry *btrfs_lookup(struct inode *dir, struct dentry *dentry,
5861 struct inode *inode;
5863 inode = btrfs_lookup_dentry(dir, dentry);
5864 if (IS_ERR(inode)) {
5865 if (PTR_ERR(inode) == -ENOENT)
5868 return ERR_CAST(inode);
5871 return d_splice_alias(inode, dentry);
5874 unsigned char btrfs_filetype_table[] = {
5875 DT_UNKNOWN, DT_REG, DT_DIR, DT_CHR, DT_BLK, DT_FIFO, DT_SOCK, DT_LNK
5879 * All this infrastructure exists because dir_emit can fault, and we are holding
5880 * the tree lock when doing readdir. For now just allocate a buffer and copy
5881 * our information into that, and then dir_emit from the buffer. This is
5882 * similar to what NFS does, only we don't keep the buffer around in pagecache
5883 * because I'm afraid I'll mess that up. Long term we need to make filldir do
5884 * copy_to_user_inatomic so we don't have to worry about page faulting under the
5887 static int btrfs_opendir(struct inode *inode, struct file *file)
5889 struct btrfs_file_private *private;
5891 private = kzalloc(sizeof(struct btrfs_file_private), GFP_KERNEL);
5894 private->filldir_buf = kzalloc(PAGE_SIZE, GFP_KERNEL);
5895 if (!private->filldir_buf) {
5899 file->private_data = private;
5910 static int btrfs_filldir(void *addr, int entries, struct dir_context *ctx)
5913 struct dir_entry *entry = addr;
5914 char *name = (char *)(entry + 1);
5916 ctx->pos = get_unaligned(&entry->offset);
5917 if (!dir_emit(ctx, name, get_unaligned(&entry->name_len),
5918 get_unaligned(&entry->ino),
5919 get_unaligned(&entry->type)))
5921 addr += sizeof(struct dir_entry) +
5922 get_unaligned(&entry->name_len);
5928 static int btrfs_real_readdir(struct file *file, struct dir_context *ctx)
5930 struct inode *inode = file_inode(file);
5931 struct btrfs_root *root = BTRFS_I(inode)->root;
5932 struct btrfs_file_private *private = file->private_data;
5933 struct btrfs_dir_item *di;
5934 struct btrfs_key key;
5935 struct btrfs_key found_key;
5936 struct btrfs_path *path;
5938 struct list_head ins_list;
5939 struct list_head del_list;
5941 struct extent_buffer *leaf;
5948 struct btrfs_key location;
5950 if (!dir_emit_dots(file, ctx))
5953 path = btrfs_alloc_path();
5957 addr = private->filldir_buf;
5958 path->reada = READA_FORWARD;
5960 INIT_LIST_HEAD(&ins_list);
5961 INIT_LIST_HEAD(&del_list);
5962 put = btrfs_readdir_get_delayed_items(inode, &ins_list, &del_list);
5965 key.type = BTRFS_DIR_INDEX_KEY;
5966 key.offset = ctx->pos;
5967 key.objectid = btrfs_ino(BTRFS_I(inode));
5969 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
5974 struct dir_entry *entry;
5976 leaf = path->nodes[0];
5977 slot = path->slots[0];
5978 if (slot >= btrfs_header_nritems(leaf)) {
5979 ret = btrfs_next_leaf(root, path);
5987 btrfs_item_key_to_cpu(leaf, &found_key, slot);
5989 if (found_key.objectid != key.objectid)
5991 if (found_key.type != BTRFS_DIR_INDEX_KEY)
5993 if (found_key.offset < ctx->pos)
5995 if (btrfs_should_delete_dir_index(&del_list, found_key.offset))
5997 di = btrfs_item_ptr(leaf, slot, struct btrfs_dir_item);
5998 name_len = btrfs_dir_name_len(leaf, di);
5999 if ((total_len + sizeof(struct dir_entry) + name_len) >=
6001 btrfs_release_path(path);
6002 ret = btrfs_filldir(private->filldir_buf, entries, ctx);
6005 addr = private->filldir_buf;
6012 put_unaligned(name_len, &entry->name_len);
6013 name_ptr = (char *)(entry + 1);
6014 read_extent_buffer(leaf, name_ptr, (unsigned long)(di + 1),
6016 put_unaligned(btrfs_filetype_table[btrfs_dir_type(leaf, di)],
6018 btrfs_dir_item_key_to_cpu(leaf, di, &location);
6019 put_unaligned(location.objectid, &entry->ino);
6020 put_unaligned(found_key.offset, &entry->offset);
6022 addr += sizeof(struct dir_entry) + name_len;
6023 total_len += sizeof(struct dir_entry) + name_len;
6027 btrfs_release_path(path);
6029 ret = btrfs_filldir(private->filldir_buf, entries, ctx);
6033 ret = btrfs_readdir_delayed_dir_index(ctx, &ins_list);
6038 * Stop new entries from being returned after we return the last
6041 * New directory entries are assigned a strictly increasing
6042 * offset. This means that new entries created during readdir
6043 * are *guaranteed* to be seen in the future by that readdir.
6044 * This has broken buggy programs which operate on names as
6045 * they're returned by readdir. Until we re-use freed offsets
6046 * we have this hack to stop new entries from being returned
6047 * under the assumption that they'll never reach this huge
6050 * This is being careful not to overflow 32bit loff_t unless the
6051 * last entry requires it because doing so has broken 32bit apps
6054 if (ctx->pos >= INT_MAX)
6055 ctx->pos = LLONG_MAX;
6062 btrfs_readdir_put_delayed_items(inode, &ins_list, &del_list);
6063 btrfs_free_path(path);
6067 int btrfs_write_inode(struct inode *inode, struct writeback_control *wbc)
6069 struct btrfs_root *root = BTRFS_I(inode)->root;
6070 struct btrfs_trans_handle *trans;
6072 bool nolock = false;
6074 if (test_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags))
6077 if (btrfs_fs_closing(root->fs_info) &&
6078 btrfs_is_free_space_inode(BTRFS_I(inode)))
6081 if (wbc->sync_mode == WB_SYNC_ALL) {
6083 trans = btrfs_join_transaction_nolock(root);
6085 trans = btrfs_join_transaction(root);
6087 return PTR_ERR(trans);
6088 ret = btrfs_commit_transaction(trans);
6094 * This is somewhat expensive, updating the tree every time the
6095 * inode changes. But, it is most likely to find the inode in cache.
6096 * FIXME, needs more benchmarking...there are no reasons other than performance
6097 * to keep or drop this code.
6099 static int btrfs_dirty_inode(struct inode *inode)
6101 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
6102 struct btrfs_root *root = BTRFS_I(inode)->root;
6103 struct btrfs_trans_handle *trans;
6106 if (test_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags))
6109 trans = btrfs_join_transaction(root);
6111 return PTR_ERR(trans);
6113 ret = btrfs_update_inode(trans, root, inode);
6114 if (ret && ret == -ENOSPC) {
6115 /* whoops, lets try again with the full transaction */
6116 btrfs_end_transaction(trans);
6117 trans = btrfs_start_transaction(root, 1);
6119 return PTR_ERR(trans);
6121 ret = btrfs_update_inode(trans, root, inode);
6123 btrfs_end_transaction(trans);
6124 if (BTRFS_I(inode)->delayed_node)
6125 btrfs_balance_delayed_items(fs_info);
6131 * This is a copy of file_update_time. We need this so we can return error on
6132 * ENOSPC for updating the inode in the case of file write and mmap writes.
6134 static int btrfs_update_time(struct inode *inode, struct timespec *now,
6137 struct btrfs_root *root = BTRFS_I(inode)->root;
6138 bool dirty = flags & ~S_VERSION;
6140 if (btrfs_root_readonly(root))
6143 if (flags & S_VERSION)
6144 dirty |= inode_maybe_inc_iversion(inode, dirty);
6145 if (flags & S_CTIME)
6146 inode->i_ctime = *now;
6147 if (flags & S_MTIME)
6148 inode->i_mtime = *now;
6149 if (flags & S_ATIME)
6150 inode->i_atime = *now;
6151 return dirty ? btrfs_dirty_inode(inode) : 0;
6155 * find the highest existing sequence number in a directory
6156 * and then set the in-memory index_cnt variable to reflect
6157 * free sequence numbers
6159 static int btrfs_set_inode_index_count(struct btrfs_inode *inode)
6161 struct btrfs_root *root = inode->root;
6162 struct btrfs_key key, found_key;
6163 struct btrfs_path *path;
6164 struct extent_buffer *leaf;
6167 key.objectid = btrfs_ino(inode);
6168 key.type = BTRFS_DIR_INDEX_KEY;
6169 key.offset = (u64)-1;
6171 path = btrfs_alloc_path();
6175 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
6178 /* FIXME: we should be able to handle this */
6184 * MAGIC NUMBER EXPLANATION:
6185 * since we search a directory based on f_pos we have to start at 2
6186 * since '.' and '..' have f_pos of 0 and 1 respectively, so everybody
6187 * else has to start at 2
6189 if (path->slots[0] == 0) {
6190 inode->index_cnt = 2;
6196 leaf = path->nodes[0];
6197 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
6199 if (found_key.objectid != btrfs_ino(inode) ||
6200 found_key.type != BTRFS_DIR_INDEX_KEY) {
6201 inode->index_cnt = 2;
6205 inode->index_cnt = found_key.offset + 1;
6207 btrfs_free_path(path);
6212 * helper to find a free sequence number in a given directory. This current
6213 * code is very simple, later versions will do smarter things in the btree
6215 int btrfs_set_inode_index(struct btrfs_inode *dir, u64 *index)
6219 if (dir->index_cnt == (u64)-1) {
6220 ret = btrfs_inode_delayed_dir_index_count(dir);
6222 ret = btrfs_set_inode_index_count(dir);
6228 *index = dir->index_cnt;
6234 static int btrfs_insert_inode_locked(struct inode *inode)
6236 struct btrfs_iget_args args;
6237 args.location = &BTRFS_I(inode)->location;
6238 args.root = BTRFS_I(inode)->root;
6240 return insert_inode_locked4(inode,
6241 btrfs_inode_hash(inode->i_ino, BTRFS_I(inode)->root),
6242 btrfs_find_actor, &args);
6246 * Inherit flags from the parent inode.
6248 * Currently only the compression flags and the cow flags are inherited.
6250 static void btrfs_inherit_iflags(struct inode *inode, struct inode *dir)
6257 flags = BTRFS_I(dir)->flags;
6259 if (flags & BTRFS_INODE_NOCOMPRESS) {
6260 BTRFS_I(inode)->flags &= ~BTRFS_INODE_COMPRESS;
6261 BTRFS_I(inode)->flags |= BTRFS_INODE_NOCOMPRESS;
6262 } else if (flags & BTRFS_INODE_COMPRESS) {
6263 BTRFS_I(inode)->flags &= ~BTRFS_INODE_NOCOMPRESS;
6264 BTRFS_I(inode)->flags |= BTRFS_INODE_COMPRESS;
6267 if (flags & BTRFS_INODE_NODATACOW) {
6268 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATACOW;
6269 if (S_ISREG(inode->i_mode))
6270 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATASUM;
6273 btrfs_update_iflags(inode);
6276 static struct inode *btrfs_new_inode(struct btrfs_trans_handle *trans,
6277 struct btrfs_root *root,
6279 const char *name, int name_len,
6280 u64 ref_objectid, u64 objectid,
6281 umode_t mode, u64 *index)
6283 struct btrfs_fs_info *fs_info = root->fs_info;
6284 struct inode *inode;
6285 struct btrfs_inode_item *inode_item;
6286 struct btrfs_key *location;
6287 struct btrfs_path *path;
6288 struct btrfs_inode_ref *ref;
6289 struct btrfs_key key[2];
6291 int nitems = name ? 2 : 1;
6295 path = btrfs_alloc_path();
6297 return ERR_PTR(-ENOMEM);
6299 inode = new_inode(fs_info->sb);
6301 btrfs_free_path(path);
6302 return ERR_PTR(-ENOMEM);
6306 * O_TMPFILE, set link count to 0, so that after this point,
6307 * we fill in an inode item with the correct link count.
6310 set_nlink(inode, 0);
6313 * we have to initialize this early, so we can reclaim the inode
6314 * number if we fail afterwards in this function.
6316 inode->i_ino = objectid;
6319 trace_btrfs_inode_request(dir);
6321 ret = btrfs_set_inode_index(BTRFS_I(dir), index);
6323 btrfs_free_path(path);
6325 return ERR_PTR(ret);
6331 * index_cnt is ignored for everything but a dir,
6332 * btrfs_set_inode_index_count has an explanation for the magic
6335 BTRFS_I(inode)->index_cnt = 2;
6336 BTRFS_I(inode)->dir_index = *index;
6337 BTRFS_I(inode)->root = root;
6338 BTRFS_I(inode)->generation = trans->transid;
6339 inode->i_generation = BTRFS_I(inode)->generation;
6342 * We could have gotten an inode number from somebody who was fsynced
6343 * and then removed in this same transaction, so let's just set full
6344 * sync since it will be a full sync anyway and this will blow away the
6345 * old info in the log.
6347 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &BTRFS_I(inode)->runtime_flags);
6349 key[0].objectid = objectid;
6350 key[0].type = BTRFS_INODE_ITEM_KEY;
6353 sizes[0] = sizeof(struct btrfs_inode_item);
6357 * Start new inodes with an inode_ref. This is slightly more
6358 * efficient for small numbers of hard links since they will
6359 * be packed into one item. Extended refs will kick in if we
6360 * add more hard links than can fit in the ref item.
6362 key[1].objectid = objectid;
6363 key[1].type = BTRFS_INODE_REF_KEY;
6364 key[1].offset = ref_objectid;
6366 sizes[1] = name_len + sizeof(*ref);
6369 location = &BTRFS_I(inode)->location;
6370 location->objectid = objectid;
6371 location->offset = 0;
6372 location->type = BTRFS_INODE_ITEM_KEY;
6374 ret = btrfs_insert_inode_locked(inode);
6378 path->leave_spinning = 1;
6379 ret = btrfs_insert_empty_items(trans, root, path, key, sizes, nitems);
6383 inode_init_owner(inode, dir, mode);
6384 inode_set_bytes(inode, 0);
6386 inode->i_mtime = current_time(inode);
6387 inode->i_atime = inode->i_mtime;
6388 inode->i_ctime = inode->i_mtime;
6389 BTRFS_I(inode)->i_otime = inode->i_mtime;
6391 inode_item = btrfs_item_ptr(path->nodes[0], path->slots[0],
6392 struct btrfs_inode_item);
6393 memzero_extent_buffer(path->nodes[0], (unsigned long)inode_item,
6394 sizeof(*inode_item));
6395 fill_inode_item(trans, path->nodes[0], inode_item, inode);
6398 ref = btrfs_item_ptr(path->nodes[0], path->slots[0] + 1,
6399 struct btrfs_inode_ref);
6400 btrfs_set_inode_ref_name_len(path->nodes[0], ref, name_len);
6401 btrfs_set_inode_ref_index(path->nodes[0], ref, *index);
6402 ptr = (unsigned long)(ref + 1);
6403 write_extent_buffer(path->nodes[0], name, ptr, name_len);
6406 btrfs_mark_buffer_dirty(path->nodes[0]);
6407 btrfs_free_path(path);
6409 btrfs_inherit_iflags(inode, dir);
6411 if (S_ISREG(mode)) {
6412 if (btrfs_test_opt(fs_info, NODATASUM))
6413 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATASUM;
6414 if (btrfs_test_opt(fs_info, NODATACOW))
6415 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATACOW |
6416 BTRFS_INODE_NODATASUM;
6419 inode_tree_add(inode);
6421 trace_btrfs_inode_new(inode);
6422 btrfs_set_inode_last_trans(trans, inode);
6424 btrfs_update_root_times(trans, root);
6426 ret = btrfs_inode_inherit_props(trans, inode, dir);
6429 "error inheriting props for ino %llu (root %llu): %d",
6430 btrfs_ino(BTRFS_I(inode)), root->root_key.objectid, ret);
6435 unlock_new_inode(inode);
6438 BTRFS_I(dir)->index_cnt--;
6439 btrfs_free_path(path);
6441 return ERR_PTR(ret);
6444 static inline u8 btrfs_inode_type(struct inode *inode)
6446 return btrfs_type_by_mode[(inode->i_mode & S_IFMT) >> S_SHIFT];
6450 * utility function to add 'inode' into 'parent_inode' with
6451 * a give name and a given sequence number.
6452 * if 'add_backref' is true, also insert a backref from the
6453 * inode to the parent directory.
6455 int btrfs_add_link(struct btrfs_trans_handle *trans,
6456 struct btrfs_inode *parent_inode, struct btrfs_inode *inode,
6457 const char *name, int name_len, int add_backref, u64 index)
6459 struct btrfs_fs_info *fs_info = btrfs_sb(inode->vfs_inode.i_sb);
6461 struct btrfs_key key;
6462 struct btrfs_root *root = parent_inode->root;
6463 u64 ino = btrfs_ino(inode);
6464 u64 parent_ino = btrfs_ino(parent_inode);
6466 if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
6467 memcpy(&key, &inode->root->root_key, sizeof(key));
6470 key.type = BTRFS_INODE_ITEM_KEY;
6474 if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
6475 ret = btrfs_add_root_ref(trans, fs_info, key.objectid,
6476 root->root_key.objectid, parent_ino,
6477 index, name, name_len);
6478 } else if (add_backref) {
6479 ret = btrfs_insert_inode_ref(trans, root, name, name_len, ino,
6483 /* Nothing to clean up yet */
6487 ret = btrfs_insert_dir_item(trans, root, name, name_len,
6489 btrfs_inode_type(&inode->vfs_inode), index);
6490 if (ret == -EEXIST || ret == -EOVERFLOW)
6493 btrfs_abort_transaction(trans, ret);
6497 btrfs_i_size_write(parent_inode, parent_inode->vfs_inode.i_size +
6499 inode_inc_iversion(&parent_inode->vfs_inode);
6500 parent_inode->vfs_inode.i_mtime = parent_inode->vfs_inode.i_ctime =
6501 current_time(&parent_inode->vfs_inode);
6502 ret = btrfs_update_inode(trans, root, &parent_inode->vfs_inode);
6504 btrfs_abort_transaction(trans, ret);
6508 if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
6511 err = btrfs_del_root_ref(trans, fs_info, key.objectid,
6512 root->root_key.objectid, parent_ino,
6513 &local_index, name, name_len);
6515 } else if (add_backref) {
6519 err = btrfs_del_inode_ref(trans, root, name, name_len,
6520 ino, parent_ino, &local_index);
6525 static int btrfs_add_nondir(struct btrfs_trans_handle *trans,
6526 struct btrfs_inode *dir, struct dentry *dentry,
6527 struct btrfs_inode *inode, int backref, u64 index)
6529 int err = btrfs_add_link(trans, dir, inode,
6530 dentry->d_name.name, dentry->d_name.len,
6537 static int btrfs_mknod(struct inode *dir, struct dentry *dentry,
6538 umode_t mode, dev_t rdev)
6540 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
6541 struct btrfs_trans_handle *trans;
6542 struct btrfs_root *root = BTRFS_I(dir)->root;
6543 struct inode *inode = NULL;
6550 * 2 for inode item and ref
6552 * 1 for xattr if selinux is on
6554 trans = btrfs_start_transaction(root, 5);
6556 return PTR_ERR(trans);
6558 err = btrfs_find_free_ino(root, &objectid);
6562 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
6563 dentry->d_name.len, btrfs_ino(BTRFS_I(dir)), objectid,
6565 if (IS_ERR(inode)) {
6566 err = PTR_ERR(inode);
6571 * If the active LSM wants to access the inode during
6572 * d_instantiate it needs these. Smack checks to see
6573 * if the filesystem supports xattrs by looking at the
6576 inode->i_op = &btrfs_special_inode_operations;
6577 init_special_inode(inode, inode->i_mode, rdev);
6579 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
6581 goto out_unlock_inode;
6583 err = btrfs_add_nondir(trans, BTRFS_I(dir), dentry, BTRFS_I(inode),
6586 goto out_unlock_inode;
6588 btrfs_update_inode(trans, root, inode);
6589 unlock_new_inode(inode);
6590 d_instantiate(dentry, inode);
6594 btrfs_end_transaction(trans);
6595 btrfs_btree_balance_dirty(fs_info);
6597 inode_dec_link_count(inode);
6604 unlock_new_inode(inode);
6609 static int btrfs_create(struct inode *dir, struct dentry *dentry,
6610 umode_t mode, bool excl)
6612 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
6613 struct btrfs_trans_handle *trans;
6614 struct btrfs_root *root = BTRFS_I(dir)->root;
6615 struct inode *inode = NULL;
6616 int drop_inode_on_err = 0;
6622 * 2 for inode item and ref
6624 * 1 for xattr if selinux is on
6626 trans = btrfs_start_transaction(root, 5);
6628 return PTR_ERR(trans);
6630 err = btrfs_find_free_ino(root, &objectid);
6634 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
6635 dentry->d_name.len, btrfs_ino(BTRFS_I(dir)), objectid,
6637 if (IS_ERR(inode)) {
6638 err = PTR_ERR(inode);
6641 drop_inode_on_err = 1;
6643 * If the active LSM wants to access the inode during
6644 * d_instantiate it needs these. Smack checks to see
6645 * if the filesystem supports xattrs by looking at the
6648 inode->i_fop = &btrfs_file_operations;
6649 inode->i_op = &btrfs_file_inode_operations;
6650 inode->i_mapping->a_ops = &btrfs_aops;
6652 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
6654 goto out_unlock_inode;
6656 err = btrfs_update_inode(trans, root, inode);
6658 goto out_unlock_inode;
6660 err = btrfs_add_nondir(trans, BTRFS_I(dir), dentry, BTRFS_I(inode),
6663 goto out_unlock_inode;
6665 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
6666 unlock_new_inode(inode);
6667 d_instantiate(dentry, inode);
6670 btrfs_end_transaction(trans);
6671 if (err && drop_inode_on_err) {
6672 inode_dec_link_count(inode);
6675 btrfs_btree_balance_dirty(fs_info);
6679 unlock_new_inode(inode);
6684 static int btrfs_link(struct dentry *old_dentry, struct inode *dir,
6685 struct dentry *dentry)
6687 struct btrfs_trans_handle *trans = NULL;
6688 struct btrfs_root *root = BTRFS_I(dir)->root;
6689 struct inode *inode = d_inode(old_dentry);
6690 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
6695 /* do not allow sys_link's with other subvols of the same device */
6696 if (root->objectid != BTRFS_I(inode)->root->objectid)
6699 if (inode->i_nlink >= BTRFS_LINK_MAX)
6702 err = btrfs_set_inode_index(BTRFS_I(dir), &index);
6707 * 2 items for inode and inode ref
6708 * 2 items for dir items
6709 * 1 item for parent inode
6711 trans = btrfs_start_transaction(root, 5);
6712 if (IS_ERR(trans)) {
6713 err = PTR_ERR(trans);
6718 /* There are several dir indexes for this inode, clear the cache. */
6719 BTRFS_I(inode)->dir_index = 0ULL;
6721 inode_inc_iversion(inode);
6722 inode->i_ctime = current_time(inode);
6724 set_bit(BTRFS_INODE_COPY_EVERYTHING, &BTRFS_I(inode)->runtime_flags);
6726 err = btrfs_add_nondir(trans, BTRFS_I(dir), dentry, BTRFS_I(inode),
6732 struct dentry *parent = dentry->d_parent;
6733 err = btrfs_update_inode(trans, root, inode);
6736 if (inode->i_nlink == 1) {
6738 * If new hard link count is 1, it's a file created
6739 * with open(2) O_TMPFILE flag.
6741 err = btrfs_orphan_del(trans, BTRFS_I(inode));
6745 d_instantiate(dentry, inode);
6746 btrfs_log_new_name(trans, BTRFS_I(inode), NULL, parent);
6751 btrfs_end_transaction(trans);
6753 inode_dec_link_count(inode);
6756 btrfs_btree_balance_dirty(fs_info);
6760 static int btrfs_mkdir(struct inode *dir, struct dentry *dentry, umode_t mode)
6762 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
6763 struct inode *inode = NULL;
6764 struct btrfs_trans_handle *trans;
6765 struct btrfs_root *root = BTRFS_I(dir)->root;
6767 int drop_on_err = 0;
6772 * 2 items for inode and ref
6773 * 2 items for dir items
6774 * 1 for xattr if selinux is on
6776 trans = btrfs_start_transaction(root, 5);
6778 return PTR_ERR(trans);
6780 err = btrfs_find_free_ino(root, &objectid);
6784 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
6785 dentry->d_name.len, btrfs_ino(BTRFS_I(dir)), objectid,
6786 S_IFDIR | mode, &index);
6787 if (IS_ERR(inode)) {
6788 err = PTR_ERR(inode);
6793 /* these must be set before we unlock the inode */
6794 inode->i_op = &btrfs_dir_inode_operations;
6795 inode->i_fop = &btrfs_dir_file_operations;
6797 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
6799 goto out_fail_inode;
6801 btrfs_i_size_write(BTRFS_I(inode), 0);
6802 err = btrfs_update_inode(trans, root, inode);
6804 goto out_fail_inode;
6806 err = btrfs_add_link(trans, BTRFS_I(dir), BTRFS_I(inode),
6807 dentry->d_name.name,
6808 dentry->d_name.len, 0, index);
6810 goto out_fail_inode;
6812 d_instantiate(dentry, inode);
6814 * mkdir is special. We're unlocking after we call d_instantiate
6815 * to avoid a race with nfsd calling d_instantiate.
6817 unlock_new_inode(inode);
6821 btrfs_end_transaction(trans);
6823 inode_dec_link_count(inode);
6826 btrfs_btree_balance_dirty(fs_info);
6830 unlock_new_inode(inode);
6834 static noinline int uncompress_inline(struct btrfs_path *path,
6836 size_t pg_offset, u64 extent_offset,
6837 struct btrfs_file_extent_item *item)
6840 struct extent_buffer *leaf = path->nodes[0];
6843 unsigned long inline_size;
6847 WARN_ON(pg_offset != 0);
6848 compress_type = btrfs_file_extent_compression(leaf, item);
6849 max_size = btrfs_file_extent_ram_bytes(leaf, item);
6850 inline_size = btrfs_file_extent_inline_item_len(leaf,
6851 btrfs_item_nr(path->slots[0]));
6852 tmp = kmalloc(inline_size, GFP_NOFS);
6855 ptr = btrfs_file_extent_inline_start(item);
6857 read_extent_buffer(leaf, tmp, ptr, inline_size);
6859 max_size = min_t(unsigned long, PAGE_SIZE, max_size);
6860 ret = btrfs_decompress(compress_type, tmp, page,
6861 extent_offset, inline_size, max_size);
6864 * decompression code contains a memset to fill in any space between the end
6865 * of the uncompressed data and the end of max_size in case the decompressed
6866 * data ends up shorter than ram_bytes. That doesn't cover the hole between
6867 * the end of an inline extent and the beginning of the next block, so we
6868 * cover that region here.
6871 if (max_size + pg_offset < PAGE_SIZE) {
6872 char *map = kmap(page);
6873 memset(map + pg_offset + max_size, 0, PAGE_SIZE - max_size - pg_offset);
6881 * a bit scary, this does extent mapping from logical file offset to the disk.
6882 * the ugly parts come from merging extents from the disk with the in-ram
6883 * representation. This gets more complex because of the data=ordered code,
6884 * where the in-ram extents might be locked pending data=ordered completion.
6886 * This also copies inline extents directly into the page.
6888 struct extent_map *btrfs_get_extent(struct btrfs_inode *inode,
6890 size_t pg_offset, u64 start, u64 len,
6893 struct btrfs_fs_info *fs_info = btrfs_sb(inode->vfs_inode.i_sb);
6896 u64 extent_start = 0;
6898 u64 objectid = btrfs_ino(inode);
6900 struct btrfs_path *path = NULL;
6901 struct btrfs_root *root = inode->root;
6902 struct btrfs_file_extent_item *item;
6903 struct extent_buffer *leaf;
6904 struct btrfs_key found_key;
6905 struct extent_map *em = NULL;
6906 struct extent_map_tree *em_tree = &inode->extent_tree;
6907 struct extent_io_tree *io_tree = &inode->io_tree;
6908 const bool new_inline = !page || create;
6910 read_lock(&em_tree->lock);
6911 em = lookup_extent_mapping(em_tree, start, len);
6913 em->bdev = fs_info->fs_devices->latest_bdev;
6914 read_unlock(&em_tree->lock);
6917 if (em->start > start || em->start + em->len <= start)
6918 free_extent_map(em);
6919 else if (em->block_start == EXTENT_MAP_INLINE && page)
6920 free_extent_map(em);
6924 em = alloc_extent_map();
6929 em->bdev = fs_info->fs_devices->latest_bdev;
6930 em->start = EXTENT_MAP_HOLE;
6931 em->orig_start = EXTENT_MAP_HOLE;
6933 em->block_len = (u64)-1;
6936 path = btrfs_alloc_path();
6942 * Chances are we'll be called again, so go ahead and do
6945 path->reada = READA_FORWARD;
6948 ret = btrfs_lookup_file_extent(NULL, root, path, objectid, start, 0);
6955 if (path->slots[0] == 0)
6960 leaf = path->nodes[0];
6961 item = btrfs_item_ptr(leaf, path->slots[0],
6962 struct btrfs_file_extent_item);
6963 /* are we inside the extent that was found? */
6964 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
6965 found_type = found_key.type;
6966 if (found_key.objectid != objectid ||
6967 found_type != BTRFS_EXTENT_DATA_KEY) {
6969 * If we backup past the first extent we want to move forward
6970 * and see if there is an extent in front of us, otherwise we'll
6971 * say there is a hole for our whole search range which can
6978 found_type = btrfs_file_extent_type(leaf, item);
6979 extent_start = found_key.offset;
6980 if (found_type == BTRFS_FILE_EXTENT_REG ||
6981 found_type == BTRFS_FILE_EXTENT_PREALLOC) {
6982 extent_end = extent_start +
6983 btrfs_file_extent_num_bytes(leaf, item);
6985 trace_btrfs_get_extent_show_fi_regular(inode, leaf, item,
6987 } else if (found_type == BTRFS_FILE_EXTENT_INLINE) {
6989 size = btrfs_file_extent_inline_len(leaf, path->slots[0], item);
6990 extent_end = ALIGN(extent_start + size,
6991 fs_info->sectorsize);
6993 trace_btrfs_get_extent_show_fi_inline(inode, leaf, item,
6998 if (start >= extent_end) {
7000 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
7001 ret = btrfs_next_leaf(root, path);
7008 leaf = path->nodes[0];
7010 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
7011 if (found_key.objectid != objectid ||
7012 found_key.type != BTRFS_EXTENT_DATA_KEY)
7014 if (start + len <= found_key.offset)
7016 if (start > found_key.offset)
7019 em->orig_start = start;
7020 em->len = found_key.offset - start;
7024 btrfs_extent_item_to_extent_map(inode, path, item,
7027 if (found_type == BTRFS_FILE_EXTENT_REG ||
7028 found_type == BTRFS_FILE_EXTENT_PREALLOC) {
7030 } else if (found_type == BTRFS_FILE_EXTENT_INLINE) {
7034 size_t extent_offset;
7040 size = btrfs_file_extent_inline_len(leaf, path->slots[0], item);
7041 extent_offset = page_offset(page) + pg_offset - extent_start;
7042 copy_size = min_t(u64, PAGE_SIZE - pg_offset,
7043 size - extent_offset);
7044 em->start = extent_start + extent_offset;
7045 em->len = ALIGN(copy_size, fs_info->sectorsize);
7046 em->orig_block_len = em->len;
7047 em->orig_start = em->start;
7048 ptr = btrfs_file_extent_inline_start(item) + extent_offset;
7049 if (!PageUptodate(page)) {
7050 if (btrfs_file_extent_compression(leaf, item) !=
7051 BTRFS_COMPRESS_NONE) {
7052 ret = uncompress_inline(path, page, pg_offset,
7053 extent_offset, item);
7060 read_extent_buffer(leaf, map + pg_offset, ptr,
7062 if (pg_offset + copy_size < PAGE_SIZE) {
7063 memset(map + pg_offset + copy_size, 0,
7064 PAGE_SIZE - pg_offset -
7069 flush_dcache_page(page);
7071 set_extent_uptodate(io_tree, em->start,
7072 extent_map_end(em) - 1, NULL, GFP_NOFS);
7077 em->orig_start = start;
7080 em->block_start = EXTENT_MAP_HOLE;
7082 btrfs_release_path(path);
7083 if (em->start > start || extent_map_end(em) <= start) {
7085 "bad extent! em: [%llu %llu] passed [%llu %llu]",
7086 em->start, em->len, start, len);
7092 write_lock(&em_tree->lock);
7093 err = btrfs_add_extent_mapping(em_tree, &em, start, len);
7094 write_unlock(&em_tree->lock);
7097 trace_btrfs_get_extent(root, inode, em);
7099 btrfs_free_path(path);
7101 free_extent_map(em);
7102 return ERR_PTR(err);
7104 BUG_ON(!em); /* Error is always set */
7108 struct extent_map *btrfs_get_extent_fiemap(struct btrfs_inode *inode,
7110 size_t pg_offset, u64 start, u64 len,
7113 struct extent_map *em;
7114 struct extent_map *hole_em = NULL;
7115 u64 range_start = start;
7121 em = btrfs_get_extent(inode, page, pg_offset, start, len, create);
7125 * If our em maps to:
7127 * - a pre-alloc extent,
7128 * there might actually be delalloc bytes behind it.
7130 if (em->block_start != EXTENT_MAP_HOLE &&
7131 !test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
7136 /* check to see if we've wrapped (len == -1 or similar) */
7145 /* ok, we didn't find anything, lets look for delalloc */
7146 found = count_range_bits(&inode->io_tree, &range_start,
7147 end, len, EXTENT_DELALLOC, 1);
7148 found_end = range_start + found;
7149 if (found_end < range_start)
7150 found_end = (u64)-1;
7153 * we didn't find anything useful, return
7154 * the original results from get_extent()
7156 if (range_start > end || found_end <= start) {
7162 /* adjust the range_start to make sure it doesn't
7163 * go backwards from the start they passed in
7165 range_start = max(start, range_start);
7166 found = found_end - range_start;
7169 u64 hole_start = start;
7172 em = alloc_extent_map();
7178 * when btrfs_get_extent can't find anything it
7179 * returns one huge hole
7181 * make sure what it found really fits our range, and
7182 * adjust to make sure it is based on the start from
7186 u64 calc_end = extent_map_end(hole_em);
7188 if (calc_end <= start || (hole_em->start > end)) {
7189 free_extent_map(hole_em);
7192 hole_start = max(hole_em->start, start);
7193 hole_len = calc_end - hole_start;
7197 if (hole_em && range_start > hole_start) {
7198 /* our hole starts before our delalloc, so we
7199 * have to return just the parts of the hole
7200 * that go until the delalloc starts
7202 em->len = min(hole_len,
7203 range_start - hole_start);
7204 em->start = hole_start;
7205 em->orig_start = hole_start;
7207 * don't adjust block start at all,
7208 * it is fixed at EXTENT_MAP_HOLE
7210 em->block_start = hole_em->block_start;
7211 em->block_len = hole_len;
7212 if (test_bit(EXTENT_FLAG_PREALLOC, &hole_em->flags))
7213 set_bit(EXTENT_FLAG_PREALLOC, &em->flags);
7215 em->start = range_start;
7217 em->orig_start = range_start;
7218 em->block_start = EXTENT_MAP_DELALLOC;
7219 em->block_len = found;
7226 free_extent_map(hole_em);
7228 free_extent_map(em);
7229 return ERR_PTR(err);
7234 static struct extent_map *btrfs_create_dio_extent(struct inode *inode,
7237 const u64 orig_start,
7238 const u64 block_start,
7239 const u64 block_len,
7240 const u64 orig_block_len,
7241 const u64 ram_bytes,
7244 struct extent_map *em = NULL;
7247 if (type != BTRFS_ORDERED_NOCOW) {
7248 em = create_io_em(inode, start, len, orig_start,
7249 block_start, block_len, orig_block_len,
7251 BTRFS_COMPRESS_NONE, /* compress_type */
7256 ret = btrfs_add_ordered_extent_dio(inode, start, block_start,
7257 len, block_len, type);
7260 free_extent_map(em);
7261 btrfs_drop_extent_cache(BTRFS_I(inode), start,
7262 start + len - 1, 0);
7271 static struct extent_map *btrfs_new_extent_direct(struct inode *inode,
7274 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7275 struct btrfs_root *root = BTRFS_I(inode)->root;
7276 struct extent_map *em;
7277 struct btrfs_key ins;
7281 alloc_hint = get_extent_allocation_hint(inode, start, len);
7282 ret = btrfs_reserve_extent(root, len, len, fs_info->sectorsize,
7283 0, alloc_hint, &ins, 1, 1);
7285 return ERR_PTR(ret);
7287 em = btrfs_create_dio_extent(inode, start, ins.offset, start,
7288 ins.objectid, ins.offset, ins.offset,
7289 ins.offset, BTRFS_ORDERED_REGULAR);
7290 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
7292 btrfs_free_reserved_extent(fs_info, ins.objectid,
7299 * returns 1 when the nocow is safe, < 1 on error, 0 if the
7300 * block must be cow'd
7302 noinline int can_nocow_extent(struct inode *inode, u64 offset, u64 *len,
7303 u64 *orig_start, u64 *orig_block_len,
7306 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7307 struct btrfs_path *path;
7309 struct extent_buffer *leaf;
7310 struct btrfs_root *root = BTRFS_I(inode)->root;
7311 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
7312 struct btrfs_file_extent_item *fi;
7313 struct btrfs_key key;
7320 bool nocow = (BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW);
7322 path = btrfs_alloc_path();
7326 ret = btrfs_lookup_file_extent(NULL, root, path,
7327 btrfs_ino(BTRFS_I(inode)), offset, 0);
7331 slot = path->slots[0];
7334 /* can't find the item, must cow */
7341 leaf = path->nodes[0];
7342 btrfs_item_key_to_cpu(leaf, &key, slot);
7343 if (key.objectid != btrfs_ino(BTRFS_I(inode)) ||
7344 key.type != BTRFS_EXTENT_DATA_KEY) {
7345 /* not our file or wrong item type, must cow */
7349 if (key.offset > offset) {
7350 /* Wrong offset, must cow */
7354 fi = btrfs_item_ptr(leaf, slot, struct btrfs_file_extent_item);
7355 found_type = btrfs_file_extent_type(leaf, fi);
7356 if (found_type != BTRFS_FILE_EXTENT_REG &&
7357 found_type != BTRFS_FILE_EXTENT_PREALLOC) {
7358 /* not a regular extent, must cow */
7362 if (!nocow && found_type == BTRFS_FILE_EXTENT_REG)
7365 extent_end = key.offset + btrfs_file_extent_num_bytes(leaf, fi);
7366 if (extent_end <= offset)
7369 disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
7370 if (disk_bytenr == 0)
7373 if (btrfs_file_extent_compression(leaf, fi) ||
7374 btrfs_file_extent_encryption(leaf, fi) ||
7375 btrfs_file_extent_other_encoding(leaf, fi))
7378 backref_offset = btrfs_file_extent_offset(leaf, fi);
7381 *orig_start = key.offset - backref_offset;
7382 *orig_block_len = btrfs_file_extent_disk_num_bytes(leaf, fi);
7383 *ram_bytes = btrfs_file_extent_ram_bytes(leaf, fi);
7386 if (btrfs_extent_readonly(fs_info, disk_bytenr))
7389 num_bytes = min(offset + *len, extent_end) - offset;
7390 if (!nocow && found_type == BTRFS_FILE_EXTENT_PREALLOC) {
7393 range_end = round_up(offset + num_bytes,
7394 root->fs_info->sectorsize) - 1;
7395 ret = test_range_bit(io_tree, offset, range_end,
7396 EXTENT_DELALLOC, 0, NULL);
7403 btrfs_release_path(path);
7406 * look for other files referencing this extent, if we
7407 * find any we must cow
7410 ret = btrfs_cross_ref_exist(root, btrfs_ino(BTRFS_I(inode)),
7411 key.offset - backref_offset, disk_bytenr);
7418 * adjust disk_bytenr and num_bytes to cover just the bytes
7419 * in this extent we are about to write. If there
7420 * are any csums in that range we have to cow in order
7421 * to keep the csums correct
7423 disk_bytenr += backref_offset;
7424 disk_bytenr += offset - key.offset;
7425 if (csum_exist_in_range(fs_info, disk_bytenr, num_bytes))
7428 * all of the above have passed, it is safe to overwrite this extent
7434 btrfs_free_path(path);
7438 static int lock_extent_direct(struct inode *inode, u64 lockstart, u64 lockend,
7439 struct extent_state **cached_state, int writing)
7441 struct btrfs_ordered_extent *ordered;
7445 lock_extent_bits(&BTRFS_I(inode)->io_tree, lockstart, lockend,
7448 * We're concerned with the entire range that we're going to be
7449 * doing DIO to, so we need to make sure there's no ordered
7450 * extents in this range.
7452 ordered = btrfs_lookup_ordered_range(BTRFS_I(inode), lockstart,
7453 lockend - lockstart + 1);
7456 * We need to make sure there are no buffered pages in this
7457 * range either, we could have raced between the invalidate in
7458 * generic_file_direct_write and locking the extent. The
7459 * invalidate needs to happen so that reads after a write do not
7463 (!writing || !filemap_range_has_page(inode->i_mapping,
7464 lockstart, lockend)))
7467 unlock_extent_cached(&BTRFS_I(inode)->io_tree, lockstart, lockend,
7472 * If we are doing a DIO read and the ordered extent we
7473 * found is for a buffered write, we can not wait for it
7474 * to complete and retry, because if we do so we can
7475 * deadlock with concurrent buffered writes on page
7476 * locks. This happens only if our DIO read covers more
7477 * than one extent map, if at this point has already
7478 * created an ordered extent for a previous extent map
7479 * and locked its range in the inode's io tree, and a
7480 * concurrent write against that previous extent map's
7481 * range and this range started (we unlock the ranges
7482 * in the io tree only when the bios complete and
7483 * buffered writes always lock pages before attempting
7484 * to lock range in the io tree).
7487 test_bit(BTRFS_ORDERED_DIRECT, &ordered->flags))
7488 btrfs_start_ordered_extent(inode, ordered, 1);
7491 btrfs_put_ordered_extent(ordered);
7494 * We could trigger writeback for this range (and wait
7495 * for it to complete) and then invalidate the pages for
7496 * this range (through invalidate_inode_pages2_range()),
7497 * but that can lead us to a deadlock with a concurrent
7498 * call to readpages() (a buffered read or a defrag call
7499 * triggered a readahead) on a page lock due to an
7500 * ordered dio extent we created before but did not have
7501 * yet a corresponding bio submitted (whence it can not
7502 * complete), which makes readpages() wait for that
7503 * ordered extent to complete while holding a lock on
7518 /* The callers of this must take lock_extent() */
7519 static struct extent_map *create_io_em(struct inode *inode, u64 start, u64 len,
7520 u64 orig_start, u64 block_start,
7521 u64 block_len, u64 orig_block_len,
7522 u64 ram_bytes, int compress_type,
7525 struct extent_map_tree *em_tree;
7526 struct extent_map *em;
7527 struct btrfs_root *root = BTRFS_I(inode)->root;
7530 ASSERT(type == BTRFS_ORDERED_PREALLOC ||
7531 type == BTRFS_ORDERED_COMPRESSED ||
7532 type == BTRFS_ORDERED_NOCOW ||
7533 type == BTRFS_ORDERED_REGULAR);
7535 em_tree = &BTRFS_I(inode)->extent_tree;
7536 em = alloc_extent_map();
7538 return ERR_PTR(-ENOMEM);
7541 em->orig_start = orig_start;
7543 em->block_len = block_len;
7544 em->block_start = block_start;
7545 em->bdev = root->fs_info->fs_devices->latest_bdev;
7546 em->orig_block_len = orig_block_len;
7547 em->ram_bytes = ram_bytes;
7548 em->generation = -1;
7549 set_bit(EXTENT_FLAG_PINNED, &em->flags);
7550 if (type == BTRFS_ORDERED_PREALLOC) {
7551 set_bit(EXTENT_FLAG_FILLING, &em->flags);
7552 } else if (type == BTRFS_ORDERED_COMPRESSED) {
7553 set_bit(EXTENT_FLAG_COMPRESSED, &em->flags);
7554 em->compress_type = compress_type;
7558 btrfs_drop_extent_cache(BTRFS_I(inode), em->start,
7559 em->start + em->len - 1, 0);
7560 write_lock(&em_tree->lock);
7561 ret = add_extent_mapping(em_tree, em, 1);
7562 write_unlock(&em_tree->lock);
7564 * The caller has taken lock_extent(), who could race with us
7567 } while (ret == -EEXIST);
7570 free_extent_map(em);
7571 return ERR_PTR(ret);
7574 /* em got 2 refs now, callers needs to do free_extent_map once. */
7578 static int btrfs_get_blocks_direct(struct inode *inode, sector_t iblock,
7579 struct buffer_head *bh_result, int create)
7581 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7582 struct extent_map *em;
7583 struct extent_state *cached_state = NULL;
7584 struct btrfs_dio_data *dio_data = NULL;
7585 u64 start = iblock << inode->i_blkbits;
7586 u64 lockstart, lockend;
7587 u64 len = bh_result->b_size;
7588 int unlock_bits = EXTENT_LOCKED;
7592 unlock_bits |= EXTENT_DIRTY;
7594 len = min_t(u64, len, fs_info->sectorsize);
7597 lockend = start + len - 1;
7599 if (current->journal_info) {
7601 * Need to pull our outstanding extents and set journal_info to NULL so
7602 * that anything that needs to check if there's a transaction doesn't get
7605 dio_data = current->journal_info;
7606 current->journal_info = NULL;
7610 * If this errors out it's because we couldn't invalidate pagecache for
7611 * this range and we need to fallback to buffered.
7613 if (lock_extent_direct(inode, lockstart, lockend, &cached_state,
7619 em = btrfs_get_extent(BTRFS_I(inode), NULL, 0, start, len, 0);
7626 * Ok for INLINE and COMPRESSED extents we need to fallback on buffered
7627 * io. INLINE is special, and we could probably kludge it in here, but
7628 * it's still buffered so for safety lets just fall back to the generic
7631 * For COMPRESSED we _have_ to read the entire extent in so we can
7632 * decompress it, so there will be buffering required no matter what we
7633 * do, so go ahead and fallback to buffered.
7635 * We return -ENOTBLK because that's what makes DIO go ahead and go back
7636 * to buffered IO. Don't blame me, this is the price we pay for using
7639 if (test_bit(EXTENT_FLAG_COMPRESSED, &em->flags) ||
7640 em->block_start == EXTENT_MAP_INLINE) {
7641 free_extent_map(em);
7646 /* Just a good old fashioned hole, return */
7647 if (!create && (em->block_start == EXTENT_MAP_HOLE ||
7648 test_bit(EXTENT_FLAG_PREALLOC, &em->flags))) {
7649 free_extent_map(em);
7654 * We don't allocate a new extent in the following cases
7656 * 1) The inode is marked as NODATACOW. In this case we'll just use the
7658 * 2) The extent is marked as PREALLOC. We're good to go here and can
7659 * just use the extent.
7663 len = min(len, em->len - (start - em->start));
7664 lockstart = start + len;
7668 if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags) ||
7669 ((BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW) &&
7670 em->block_start != EXTENT_MAP_HOLE)) {
7672 u64 block_start, orig_start, orig_block_len, ram_bytes;
7674 if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
7675 type = BTRFS_ORDERED_PREALLOC;
7677 type = BTRFS_ORDERED_NOCOW;
7678 len = min(len, em->len - (start - em->start));
7679 block_start = em->block_start + (start - em->start);
7681 if (can_nocow_extent(inode, start, &len, &orig_start,
7682 &orig_block_len, &ram_bytes) == 1 &&
7683 btrfs_inc_nocow_writers(fs_info, block_start)) {
7684 struct extent_map *em2;
7686 em2 = btrfs_create_dio_extent(inode, start, len,
7687 orig_start, block_start,
7688 len, orig_block_len,
7690 btrfs_dec_nocow_writers(fs_info, block_start);
7691 if (type == BTRFS_ORDERED_PREALLOC) {
7692 free_extent_map(em);
7695 if (em2 && IS_ERR(em2)) {
7700 * For inode marked NODATACOW or extent marked PREALLOC,
7701 * use the existing or preallocated extent, so does not
7702 * need to adjust btrfs_space_info's bytes_may_use.
7704 btrfs_free_reserved_data_space_noquota(inode,
7711 * this will cow the extent, reset the len in case we changed
7714 len = bh_result->b_size;
7715 free_extent_map(em);
7716 em = btrfs_new_extent_direct(inode, start, len);
7721 len = min(len, em->len - (start - em->start));
7723 bh_result->b_blocknr = (em->block_start + (start - em->start)) >>
7725 bh_result->b_size = len;
7726 bh_result->b_bdev = em->bdev;
7727 set_buffer_mapped(bh_result);
7729 if (!test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
7730 set_buffer_new(bh_result);
7733 * Need to update the i_size under the extent lock so buffered
7734 * readers will get the updated i_size when we unlock.
7736 if (!dio_data->overwrite && start + len > i_size_read(inode))
7737 i_size_write(inode, start + len);
7739 WARN_ON(dio_data->reserve < len);
7740 dio_data->reserve -= len;
7741 dio_data->unsubmitted_oe_range_end = start + len;
7742 current->journal_info = dio_data;
7746 * In the case of write we need to clear and unlock the entire range,
7747 * in the case of read we need to unlock only the end area that we
7748 * aren't using if there is any left over space.
7750 if (lockstart < lockend) {
7751 clear_extent_bit(&BTRFS_I(inode)->io_tree, lockstart,
7752 lockend, unlock_bits, 1, 0,
7755 free_extent_state(cached_state);
7758 free_extent_map(em);
7763 clear_extent_bit(&BTRFS_I(inode)->io_tree, lockstart, lockend,
7764 unlock_bits, 1, 0, &cached_state);
7767 current->journal_info = dio_data;
7771 static inline blk_status_t submit_dio_repair_bio(struct inode *inode,
7775 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7778 BUG_ON(bio_op(bio) == REQ_OP_WRITE);
7780 ret = btrfs_bio_wq_end_io(fs_info, bio, BTRFS_WQ_ENDIO_DIO_REPAIR);
7784 ret = btrfs_map_bio(fs_info, bio, mirror_num, 0);
7789 static int btrfs_check_dio_repairable(struct inode *inode,
7790 struct bio *failed_bio,
7791 struct io_failure_record *failrec,
7794 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7797 num_copies = btrfs_num_copies(fs_info, failrec->logical, failrec->len);
7798 if (num_copies == 1) {
7800 * we only have a single copy of the data, so don't bother with
7801 * all the retry and error correction code that follows. no
7802 * matter what the error is, it is very likely to persist.
7804 btrfs_debug(fs_info,
7805 "Check DIO Repairable: cannot repair, num_copies=%d, next_mirror %d, failed_mirror %d",
7806 num_copies, failrec->this_mirror, failed_mirror);
7810 failrec->failed_mirror = failed_mirror;
7811 failrec->this_mirror++;
7812 if (failrec->this_mirror == failed_mirror)
7813 failrec->this_mirror++;
7815 if (failrec->this_mirror > num_copies) {
7816 btrfs_debug(fs_info,
7817 "Check DIO Repairable: (fail) num_copies=%d, next_mirror %d, failed_mirror %d",
7818 num_copies, failrec->this_mirror, failed_mirror);
7825 static blk_status_t dio_read_error(struct inode *inode, struct bio *failed_bio,
7826 struct page *page, unsigned int pgoff,
7827 u64 start, u64 end, int failed_mirror,
7828 bio_end_io_t *repair_endio, void *repair_arg)
7830 struct io_failure_record *failrec;
7831 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
7832 struct extent_io_tree *failure_tree = &BTRFS_I(inode)->io_failure_tree;
7835 unsigned int read_mode = 0;
7838 blk_status_t status;
7839 struct bio_vec bvec;
7841 BUG_ON(bio_op(failed_bio) == REQ_OP_WRITE);
7843 ret = btrfs_get_io_failure_record(inode, start, end, &failrec);
7845 return errno_to_blk_status(ret);
7847 ret = btrfs_check_dio_repairable(inode, failed_bio, failrec,
7850 free_io_failure(failure_tree, io_tree, failrec);
7851 return BLK_STS_IOERR;
7854 segs = bio_segments(failed_bio);
7855 bio_get_first_bvec(failed_bio, &bvec);
7857 (bvec.bv_len > btrfs_inode_sectorsize(inode)))
7858 read_mode |= REQ_FAILFAST_DEV;
7860 isector = start - btrfs_io_bio(failed_bio)->logical;
7861 isector >>= inode->i_sb->s_blocksize_bits;
7862 bio = btrfs_create_repair_bio(inode, failed_bio, failrec, page,
7863 pgoff, isector, repair_endio, repair_arg);
7864 bio_set_op_attrs(bio, REQ_OP_READ, read_mode);
7866 btrfs_debug(BTRFS_I(inode)->root->fs_info,
7867 "repair DIO read error: submitting new dio read[%#x] to this_mirror=%d, in_validation=%d",
7868 read_mode, failrec->this_mirror, failrec->in_validation);
7870 status = submit_dio_repair_bio(inode, bio, failrec->this_mirror);
7872 free_io_failure(failure_tree, io_tree, failrec);
7879 struct btrfs_retry_complete {
7880 struct completion done;
7881 struct inode *inode;
7886 static void btrfs_retry_endio_nocsum(struct bio *bio)
7888 struct btrfs_retry_complete *done = bio->bi_private;
7889 struct inode *inode = done->inode;
7890 struct bio_vec *bvec;
7891 struct extent_io_tree *io_tree, *failure_tree;
7897 ASSERT(bio->bi_vcnt == 1);
7898 io_tree = &BTRFS_I(inode)->io_tree;
7899 failure_tree = &BTRFS_I(inode)->io_failure_tree;
7900 ASSERT(bio_first_bvec_all(bio)->bv_len == btrfs_inode_sectorsize(inode));
7903 ASSERT(!bio_flagged(bio, BIO_CLONED));
7904 bio_for_each_segment_all(bvec, bio, i)
7905 clean_io_failure(BTRFS_I(inode)->root->fs_info, failure_tree,
7906 io_tree, done->start, bvec->bv_page,
7907 btrfs_ino(BTRFS_I(inode)), 0);
7909 complete(&done->done);
7913 static blk_status_t __btrfs_correct_data_nocsum(struct inode *inode,
7914 struct btrfs_io_bio *io_bio)
7916 struct btrfs_fs_info *fs_info;
7917 struct bio_vec bvec;
7918 struct bvec_iter iter;
7919 struct btrfs_retry_complete done;
7925 blk_status_t err = BLK_STS_OK;
7927 fs_info = BTRFS_I(inode)->root->fs_info;
7928 sectorsize = fs_info->sectorsize;
7930 start = io_bio->logical;
7932 io_bio->bio.bi_iter = io_bio->iter;
7934 bio_for_each_segment(bvec, &io_bio->bio, iter) {
7935 nr_sectors = BTRFS_BYTES_TO_BLKS(fs_info, bvec.bv_len);
7936 pgoff = bvec.bv_offset;
7938 next_block_or_try_again:
7941 init_completion(&done.done);
7943 ret = dio_read_error(inode, &io_bio->bio, bvec.bv_page,
7944 pgoff, start, start + sectorsize - 1,
7946 btrfs_retry_endio_nocsum, &done);
7952 wait_for_completion_io(&done.done);
7954 if (!done.uptodate) {
7955 /* We might have another mirror, so try again */
7956 goto next_block_or_try_again;
7960 start += sectorsize;
7964 pgoff += sectorsize;
7965 ASSERT(pgoff < PAGE_SIZE);
7966 goto next_block_or_try_again;
7973 static void btrfs_retry_endio(struct bio *bio)
7975 struct btrfs_retry_complete *done = bio->bi_private;
7976 struct btrfs_io_bio *io_bio = btrfs_io_bio(bio);
7977 struct extent_io_tree *io_tree, *failure_tree;
7978 struct inode *inode = done->inode;
7979 struct bio_vec *bvec;
7989 ASSERT(bio->bi_vcnt == 1);
7990 ASSERT(bio_first_bvec_all(bio)->bv_len == btrfs_inode_sectorsize(done->inode));
7992 io_tree = &BTRFS_I(inode)->io_tree;
7993 failure_tree = &BTRFS_I(inode)->io_failure_tree;
7995 ASSERT(!bio_flagged(bio, BIO_CLONED));
7996 bio_for_each_segment_all(bvec, bio, i) {
7997 ret = __readpage_endio_check(inode, io_bio, i, bvec->bv_page,
7998 bvec->bv_offset, done->start,
8001 clean_io_failure(BTRFS_I(inode)->root->fs_info,
8002 failure_tree, io_tree, done->start,
8004 btrfs_ino(BTRFS_I(inode)),
8010 done->uptodate = uptodate;
8012 complete(&done->done);
8016 static blk_status_t __btrfs_subio_endio_read(struct inode *inode,
8017 struct btrfs_io_bio *io_bio, blk_status_t err)
8019 struct btrfs_fs_info *fs_info;
8020 struct bio_vec bvec;
8021 struct bvec_iter iter;
8022 struct btrfs_retry_complete done;
8029 bool uptodate = (err == 0);
8031 blk_status_t status;
8033 fs_info = BTRFS_I(inode)->root->fs_info;
8034 sectorsize = fs_info->sectorsize;
8037 start = io_bio->logical;
8039 io_bio->bio.bi_iter = io_bio->iter;
8041 bio_for_each_segment(bvec, &io_bio->bio, iter) {
8042 nr_sectors = BTRFS_BYTES_TO_BLKS(fs_info, bvec.bv_len);
8044 pgoff = bvec.bv_offset;
8047 csum_pos = BTRFS_BYTES_TO_BLKS(fs_info, offset);
8048 ret = __readpage_endio_check(inode, io_bio, csum_pos,
8049 bvec.bv_page, pgoff, start, sectorsize);
8056 init_completion(&done.done);
8058 status = dio_read_error(inode, &io_bio->bio, bvec.bv_page,
8059 pgoff, start, start + sectorsize - 1,
8060 io_bio->mirror_num, btrfs_retry_endio,
8067 wait_for_completion_io(&done.done);
8069 if (!done.uptodate) {
8070 /* We might have another mirror, so try again */
8074 offset += sectorsize;
8075 start += sectorsize;
8081 pgoff += sectorsize;
8082 ASSERT(pgoff < PAGE_SIZE);
8090 static blk_status_t btrfs_subio_endio_read(struct inode *inode,
8091 struct btrfs_io_bio *io_bio, blk_status_t err)
8093 bool skip_csum = BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM;
8097 return __btrfs_correct_data_nocsum(inode, io_bio);
8101 return __btrfs_subio_endio_read(inode, io_bio, err);
8105 static void btrfs_endio_direct_read(struct bio *bio)
8107 struct btrfs_dio_private *dip = bio->bi_private;
8108 struct inode *inode = dip->inode;
8109 struct bio *dio_bio;
8110 struct btrfs_io_bio *io_bio = btrfs_io_bio(bio);
8111 blk_status_t err = bio->bi_status;
8113 if (dip->flags & BTRFS_DIO_ORIG_BIO_SUBMITTED)
8114 err = btrfs_subio_endio_read(inode, io_bio, err);
8116 unlock_extent(&BTRFS_I(inode)->io_tree, dip->logical_offset,
8117 dip->logical_offset + dip->bytes - 1);
8118 dio_bio = dip->dio_bio;
8122 dio_bio->bi_status = err;
8123 dio_end_io(dio_bio);
8126 io_bio->end_io(io_bio, blk_status_to_errno(err));
8130 static void __endio_write_update_ordered(struct inode *inode,
8131 const u64 offset, const u64 bytes,
8132 const bool uptodate)
8134 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
8135 struct btrfs_ordered_extent *ordered = NULL;
8136 struct btrfs_workqueue *wq;
8137 btrfs_work_func_t func;
8138 u64 ordered_offset = offset;
8139 u64 ordered_bytes = bytes;
8143 if (btrfs_is_free_space_inode(BTRFS_I(inode))) {
8144 wq = fs_info->endio_freespace_worker;
8145 func = btrfs_freespace_write_helper;
8147 wq = fs_info->endio_write_workers;
8148 func = btrfs_endio_write_helper;
8152 last_offset = ordered_offset;
8153 ret = btrfs_dec_test_first_ordered_pending(inode, &ordered,
8160 btrfs_init_work(&ordered->work, func, finish_ordered_fn, NULL, NULL);
8161 btrfs_queue_work(wq, &ordered->work);
8164 * If btrfs_dec_test_ordered_pending does not find any ordered extent
8165 * in the range, we can exit.
8167 if (ordered_offset == last_offset)
8170 * our bio might span multiple ordered extents. If we haven't
8171 * completed the accounting for the whole dio, go back and try again
8173 if (ordered_offset < offset + bytes) {
8174 ordered_bytes = offset + bytes - ordered_offset;
8180 static void btrfs_endio_direct_write(struct bio *bio)
8182 struct btrfs_dio_private *dip = bio->bi_private;
8183 struct bio *dio_bio = dip->dio_bio;
8185 __endio_write_update_ordered(dip->inode, dip->logical_offset,
8186 dip->bytes, !bio->bi_status);
8190 dio_bio->bi_status = bio->bi_status;
8191 dio_end_io(dio_bio);
8195 static blk_status_t btrfs_submit_bio_start_direct_io(void *private_data,
8196 struct bio *bio, u64 offset)
8198 struct inode *inode = private_data;
8200 ret = btrfs_csum_one_bio(inode, bio, offset, 1);
8201 BUG_ON(ret); /* -ENOMEM */
8205 static void btrfs_end_dio_bio(struct bio *bio)
8207 struct btrfs_dio_private *dip = bio->bi_private;
8208 blk_status_t err = bio->bi_status;
8211 btrfs_warn(BTRFS_I(dip->inode)->root->fs_info,
8212 "direct IO failed ino %llu rw %d,%u sector %#Lx len %u err no %d",
8213 btrfs_ino(BTRFS_I(dip->inode)), bio_op(bio),
8215 (unsigned long long)bio->bi_iter.bi_sector,
8216 bio->bi_iter.bi_size, err);
8218 if (dip->subio_endio)
8219 err = dip->subio_endio(dip->inode, btrfs_io_bio(bio), err);
8223 * We want to perceive the errors flag being set before
8224 * decrementing the reference count. We don't need a barrier
8225 * since atomic operations with a return value are fully
8226 * ordered as per atomic_t.txt
8231 /* if there are more bios still pending for this dio, just exit */
8232 if (!atomic_dec_and_test(&dip->pending_bios))
8236 bio_io_error(dip->orig_bio);
8238 dip->dio_bio->bi_status = BLK_STS_OK;
8239 bio_endio(dip->orig_bio);
8245 static inline blk_status_t btrfs_lookup_and_bind_dio_csum(struct inode *inode,
8246 struct btrfs_dio_private *dip,
8250 struct btrfs_io_bio *io_bio = btrfs_io_bio(bio);
8251 struct btrfs_io_bio *orig_io_bio = btrfs_io_bio(dip->orig_bio);
8255 * We load all the csum data we need when we submit
8256 * the first bio to reduce the csum tree search and
8259 if (dip->logical_offset == file_offset) {
8260 ret = btrfs_lookup_bio_sums_dio(inode, dip->orig_bio,
8266 if (bio == dip->orig_bio)
8269 file_offset -= dip->logical_offset;
8270 file_offset >>= inode->i_sb->s_blocksize_bits;
8271 io_bio->csum = (u8 *)(((u32 *)orig_io_bio->csum) + file_offset);
8276 static inline blk_status_t btrfs_submit_dio_bio(struct bio *bio,
8277 struct inode *inode, u64 file_offset, int async_submit)
8279 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
8280 struct btrfs_dio_private *dip = bio->bi_private;
8281 bool write = bio_op(bio) == REQ_OP_WRITE;
8284 /* Check btrfs_submit_bio_hook() for rules about async submit. */
8286 async_submit = !atomic_read(&BTRFS_I(inode)->sync_writers);
8289 ret = btrfs_bio_wq_end_io(fs_info, bio, BTRFS_WQ_ENDIO_DATA);
8294 if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)
8297 if (write && async_submit) {
8298 ret = btrfs_wq_submit_bio(fs_info, bio, 0, 0,
8300 btrfs_submit_bio_start_direct_io,
8301 btrfs_submit_bio_done);
8305 * If we aren't doing async submit, calculate the csum of the
8308 ret = btrfs_csum_one_bio(inode, bio, file_offset, 1);
8312 ret = btrfs_lookup_and_bind_dio_csum(inode, dip, bio,
8318 ret = btrfs_map_bio(fs_info, bio, 0, 0);
8323 static int btrfs_submit_direct_hook(struct btrfs_dio_private *dip)
8325 struct inode *inode = dip->inode;
8326 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
8328 struct bio *orig_bio = dip->orig_bio;
8329 u64 start_sector = orig_bio->bi_iter.bi_sector;
8330 u64 file_offset = dip->logical_offset;
8332 int async_submit = 0;
8334 int clone_offset = 0;
8337 blk_status_t status;
8339 map_length = orig_bio->bi_iter.bi_size;
8340 submit_len = map_length;
8341 ret = btrfs_map_block(fs_info, btrfs_op(orig_bio), start_sector << 9,
8342 &map_length, NULL, 0);
8346 if (map_length >= submit_len) {
8348 dip->flags |= BTRFS_DIO_ORIG_BIO_SUBMITTED;
8352 /* async crcs make it difficult to collect full stripe writes. */
8353 if (btrfs_data_alloc_profile(fs_info) & BTRFS_BLOCK_GROUP_RAID56_MASK)
8359 ASSERT(map_length <= INT_MAX);
8360 atomic_inc(&dip->pending_bios);
8362 clone_len = min_t(int, submit_len, map_length);
8365 * This will never fail as it's passing GPF_NOFS and
8366 * the allocation is backed by btrfs_bioset.
8368 bio = btrfs_bio_clone_partial(orig_bio, clone_offset,
8370 bio->bi_private = dip;
8371 bio->bi_end_io = btrfs_end_dio_bio;
8372 btrfs_io_bio(bio)->logical = file_offset;
8374 ASSERT(submit_len >= clone_len);
8375 submit_len -= clone_len;
8376 if (submit_len == 0)
8380 * Increase the count before we submit the bio so we know
8381 * the end IO handler won't happen before we increase the
8382 * count. Otherwise, the dip might get freed before we're
8383 * done setting it up.
8385 atomic_inc(&dip->pending_bios);
8387 status = btrfs_submit_dio_bio(bio, inode, file_offset,
8391 atomic_dec(&dip->pending_bios);
8395 clone_offset += clone_len;
8396 start_sector += clone_len >> 9;
8397 file_offset += clone_len;
8399 map_length = submit_len;
8400 ret = btrfs_map_block(fs_info, btrfs_op(orig_bio),
8401 start_sector << 9, &map_length, NULL, 0);
8404 } while (submit_len > 0);
8407 status = btrfs_submit_dio_bio(bio, inode, file_offset, async_submit);
8415 * Before atomic variable goto zero, we must make sure dip->errors is
8416 * perceived to be set. This ordering is ensured by the fact that an
8417 * atomic operations with a return value are fully ordered as per
8420 if (atomic_dec_and_test(&dip->pending_bios))
8421 bio_io_error(dip->orig_bio);
8423 /* bio_end_io() will handle error, so we needn't return it */
8427 static void btrfs_submit_direct(struct bio *dio_bio, struct inode *inode,
8430 struct btrfs_dio_private *dip = NULL;
8431 struct bio *bio = NULL;
8432 struct btrfs_io_bio *io_bio;
8433 bool write = (bio_op(dio_bio) == REQ_OP_WRITE);
8436 bio = btrfs_bio_clone(dio_bio);
8438 dip = kzalloc(sizeof(*dip), GFP_NOFS);
8444 dip->private = dio_bio->bi_private;
8446 dip->logical_offset = file_offset;
8447 dip->bytes = dio_bio->bi_iter.bi_size;
8448 dip->disk_bytenr = (u64)dio_bio->bi_iter.bi_sector << 9;
8449 bio->bi_private = dip;
8450 dip->orig_bio = bio;
8451 dip->dio_bio = dio_bio;
8452 atomic_set(&dip->pending_bios, 0);
8453 io_bio = btrfs_io_bio(bio);
8454 io_bio->logical = file_offset;
8457 bio->bi_end_io = btrfs_endio_direct_write;
8459 bio->bi_end_io = btrfs_endio_direct_read;
8460 dip->subio_endio = btrfs_subio_endio_read;
8464 * Reset the range for unsubmitted ordered extents (to a 0 length range)
8465 * even if we fail to submit a bio, because in such case we do the
8466 * corresponding error handling below and it must not be done a second
8467 * time by btrfs_direct_IO().
8470 struct btrfs_dio_data *dio_data = current->journal_info;
8472 dio_data->unsubmitted_oe_range_end = dip->logical_offset +
8474 dio_data->unsubmitted_oe_range_start =
8475 dio_data->unsubmitted_oe_range_end;
8478 ret = btrfs_submit_direct_hook(dip);
8483 io_bio->end_io(io_bio, ret);
8487 * If we arrived here it means either we failed to submit the dip
8488 * or we either failed to clone the dio_bio or failed to allocate the
8489 * dip. If we cloned the dio_bio and allocated the dip, we can just
8490 * call bio_endio against our io_bio so that we get proper resource
8491 * cleanup if we fail to submit the dip, otherwise, we must do the
8492 * same as btrfs_endio_direct_[write|read] because we can't call these
8493 * callbacks - they require an allocated dip and a clone of dio_bio.
8498 * The end io callbacks free our dip, do the final put on bio
8499 * and all the cleanup and final put for dio_bio (through
8506 __endio_write_update_ordered(inode,
8508 dio_bio->bi_iter.bi_size,
8511 unlock_extent(&BTRFS_I(inode)->io_tree, file_offset,
8512 file_offset + dio_bio->bi_iter.bi_size - 1);
8514 dio_bio->bi_status = BLK_STS_IOERR;
8516 * Releases and cleans up our dio_bio, no need to bio_put()
8517 * nor bio_endio()/bio_io_error() against dio_bio.
8519 dio_end_io(dio_bio);
8526 static ssize_t check_direct_IO(struct btrfs_fs_info *fs_info,
8527 const struct iov_iter *iter, loff_t offset)
8531 unsigned int blocksize_mask = fs_info->sectorsize - 1;
8532 ssize_t retval = -EINVAL;
8534 if (offset & blocksize_mask)
8537 if (iov_iter_alignment(iter) & blocksize_mask)
8540 /* If this is a write we don't need to check anymore */
8541 if (iov_iter_rw(iter) != READ || !iter_is_iovec(iter))
8544 * Check to make sure we don't have duplicate iov_base's in this
8545 * iovec, if so return EINVAL, otherwise we'll get csum errors
8546 * when reading back.
8548 for (seg = 0; seg < iter->nr_segs; seg++) {
8549 for (i = seg + 1; i < iter->nr_segs; i++) {
8550 if (iter->iov[seg].iov_base == iter->iov[i].iov_base)
8559 static ssize_t btrfs_direct_IO(struct kiocb *iocb, struct iov_iter *iter)
8561 struct file *file = iocb->ki_filp;
8562 struct inode *inode = file->f_mapping->host;
8563 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
8564 struct btrfs_dio_data dio_data = { 0 };
8565 struct extent_changeset *data_reserved = NULL;
8566 loff_t offset = iocb->ki_pos;
8570 bool relock = false;
8573 if (check_direct_IO(fs_info, iter, offset))
8576 inode_dio_begin(inode);
8579 * The generic stuff only does filemap_write_and_wait_range, which
8580 * isn't enough if we've written compressed pages to this area, so
8581 * we need to flush the dirty pages again to make absolutely sure
8582 * that any outstanding dirty pages are on disk.
8584 count = iov_iter_count(iter);
8585 if (test_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
8586 &BTRFS_I(inode)->runtime_flags))
8587 filemap_fdatawrite_range(inode->i_mapping, offset,
8588 offset + count - 1);
8590 if (iov_iter_rw(iter) == WRITE) {
8592 * If the write DIO is beyond the EOF, we need update
8593 * the isize, but it is protected by i_mutex. So we can
8594 * not unlock the i_mutex at this case.
8596 if (offset + count <= inode->i_size) {
8597 dio_data.overwrite = 1;
8598 inode_unlock(inode);
8600 } else if (iocb->ki_flags & IOCB_NOWAIT) {
8604 ret = btrfs_delalloc_reserve_space(inode, &data_reserved,
8610 * We need to know how many extents we reserved so that we can
8611 * do the accounting properly if we go over the number we
8612 * originally calculated. Abuse current->journal_info for this.
8614 dio_data.reserve = round_up(count,
8615 fs_info->sectorsize);
8616 dio_data.unsubmitted_oe_range_start = (u64)offset;
8617 dio_data.unsubmitted_oe_range_end = (u64)offset;
8618 current->journal_info = &dio_data;
8619 down_read(&BTRFS_I(inode)->dio_sem);
8620 } else if (test_bit(BTRFS_INODE_READDIO_NEED_LOCK,
8621 &BTRFS_I(inode)->runtime_flags)) {
8622 inode_dio_end(inode);
8623 flags = DIO_LOCKING | DIO_SKIP_HOLES;
8627 ret = __blockdev_direct_IO(iocb, inode,
8628 fs_info->fs_devices->latest_bdev,
8629 iter, btrfs_get_blocks_direct, NULL,
8630 btrfs_submit_direct, flags);
8631 if (iov_iter_rw(iter) == WRITE) {
8632 up_read(&BTRFS_I(inode)->dio_sem);
8633 current->journal_info = NULL;
8634 if (ret < 0 && ret != -EIOCBQUEUED) {
8635 if (dio_data.reserve)
8636 btrfs_delalloc_release_space(inode, data_reserved,
8637 offset, dio_data.reserve, true);
8639 * On error we might have left some ordered extents
8640 * without submitting corresponding bios for them, so
8641 * cleanup them up to avoid other tasks getting them
8642 * and waiting for them to complete forever.
8644 if (dio_data.unsubmitted_oe_range_start <
8645 dio_data.unsubmitted_oe_range_end)
8646 __endio_write_update_ordered(inode,
8647 dio_data.unsubmitted_oe_range_start,
8648 dio_data.unsubmitted_oe_range_end -
8649 dio_data.unsubmitted_oe_range_start,
8651 } else if (ret >= 0 && (size_t)ret < count)
8652 btrfs_delalloc_release_space(inode, data_reserved,
8653 offset, count - (size_t)ret, true);
8654 btrfs_delalloc_release_extents(BTRFS_I(inode), count, false);
8658 inode_dio_end(inode);
8662 extent_changeset_free(data_reserved);
8666 #define BTRFS_FIEMAP_FLAGS (FIEMAP_FLAG_SYNC)
8668 static int btrfs_fiemap(struct inode *inode, struct fiemap_extent_info *fieinfo,
8669 __u64 start, __u64 len)
8673 ret = fiemap_check_flags(fieinfo, BTRFS_FIEMAP_FLAGS);
8677 return extent_fiemap(inode, fieinfo, start, len);
8680 int btrfs_readpage(struct file *file, struct page *page)
8682 struct extent_io_tree *tree;
8683 tree = &BTRFS_I(page->mapping->host)->io_tree;
8684 return extent_read_full_page(tree, page, btrfs_get_extent, 0);
8687 static int btrfs_writepage(struct page *page, struct writeback_control *wbc)
8689 struct inode *inode = page->mapping->host;
8692 if (current->flags & PF_MEMALLOC) {
8693 redirty_page_for_writepage(wbc, page);
8699 * If we are under memory pressure we will call this directly from the
8700 * VM, we need to make sure we have the inode referenced for the ordered
8701 * extent. If not just return like we didn't do anything.
8703 if (!igrab(inode)) {
8704 redirty_page_for_writepage(wbc, page);
8705 return AOP_WRITEPAGE_ACTIVATE;
8707 ret = extent_write_full_page(page, wbc);
8708 btrfs_add_delayed_iput(inode);
8712 static int btrfs_writepages(struct address_space *mapping,
8713 struct writeback_control *wbc)
8715 struct extent_io_tree *tree;
8717 tree = &BTRFS_I(mapping->host)->io_tree;
8718 return extent_writepages(tree, mapping, wbc);
8722 btrfs_readpages(struct file *file, struct address_space *mapping,
8723 struct list_head *pages, unsigned nr_pages)
8725 struct extent_io_tree *tree;
8726 tree = &BTRFS_I(mapping->host)->io_tree;
8727 return extent_readpages(tree, mapping, pages, nr_pages);
8729 static int __btrfs_releasepage(struct page *page, gfp_t gfp_flags)
8731 struct extent_io_tree *tree;
8732 struct extent_map_tree *map;
8735 tree = &BTRFS_I(page->mapping->host)->io_tree;
8736 map = &BTRFS_I(page->mapping->host)->extent_tree;
8737 ret = try_release_extent_mapping(map, tree, page, gfp_flags);
8739 ClearPagePrivate(page);
8740 set_page_private(page, 0);
8746 static int btrfs_releasepage(struct page *page, gfp_t gfp_flags)
8748 if (PageWriteback(page) || PageDirty(page))
8750 return __btrfs_releasepage(page, gfp_flags);
8753 static void btrfs_invalidatepage(struct page *page, unsigned int offset,
8754 unsigned int length)
8756 struct inode *inode = page->mapping->host;
8757 struct extent_io_tree *tree;
8758 struct btrfs_ordered_extent *ordered;
8759 struct extent_state *cached_state = NULL;
8760 u64 page_start = page_offset(page);
8761 u64 page_end = page_start + PAGE_SIZE - 1;
8764 int inode_evicting = inode->i_state & I_FREEING;
8767 * we have the page locked, so new writeback can't start,
8768 * and the dirty bit won't be cleared while we are here.
8770 * Wait for IO on this page so that we can safely clear
8771 * the PagePrivate2 bit and do ordered accounting
8773 wait_on_page_writeback(page);
8775 tree = &BTRFS_I(inode)->io_tree;
8777 btrfs_releasepage(page, GFP_NOFS);
8781 if (!inode_evicting)
8782 lock_extent_bits(tree, page_start, page_end, &cached_state);
8785 ordered = btrfs_lookup_ordered_range(BTRFS_I(inode), start,
8786 page_end - start + 1);
8788 end = min(page_end, ordered->file_offset + ordered->len - 1);
8790 * IO on this page will never be started, so we need
8791 * to account for any ordered extents now
8793 if (!inode_evicting)
8794 clear_extent_bit(tree, start, end,
8795 EXTENT_DIRTY | EXTENT_DELALLOC |
8796 EXTENT_DELALLOC_NEW |
8797 EXTENT_LOCKED | EXTENT_DO_ACCOUNTING |
8798 EXTENT_DEFRAG, 1, 0, &cached_state);
8800 * whoever cleared the private bit is responsible
8801 * for the finish_ordered_io
8803 if (TestClearPagePrivate2(page)) {
8804 struct btrfs_ordered_inode_tree *tree;
8807 tree = &BTRFS_I(inode)->ordered_tree;
8809 spin_lock_irq(&tree->lock);
8810 set_bit(BTRFS_ORDERED_TRUNCATED, &ordered->flags);
8811 new_len = start - ordered->file_offset;
8812 if (new_len < ordered->truncated_len)
8813 ordered->truncated_len = new_len;
8814 spin_unlock_irq(&tree->lock);
8816 if (btrfs_dec_test_ordered_pending(inode, &ordered,
8818 end - start + 1, 1))
8819 btrfs_finish_ordered_io(ordered);
8821 btrfs_put_ordered_extent(ordered);
8822 if (!inode_evicting) {
8823 cached_state = NULL;
8824 lock_extent_bits(tree, start, end,
8829 if (start < page_end)
8834 * Qgroup reserved space handler
8835 * Page here will be either
8836 * 1) Already written to disk
8837 * In this case, its reserved space is released from data rsv map
8838 * and will be freed by delayed_ref handler finally.
8839 * So even we call qgroup_free_data(), it won't decrease reserved
8841 * 2) Not written to disk
8842 * This means the reserved space should be freed here. However,
8843 * if a truncate invalidates the page (by clearing PageDirty)
8844 * and the page is accounted for while allocating extent
8845 * in btrfs_check_data_free_space() we let delayed_ref to
8846 * free the entire extent.
8848 if (PageDirty(page))
8849 btrfs_qgroup_free_data(inode, NULL, page_start, PAGE_SIZE);
8850 if (!inode_evicting) {
8851 clear_extent_bit(tree, page_start, page_end,
8852 EXTENT_LOCKED | EXTENT_DIRTY |
8853 EXTENT_DELALLOC | EXTENT_DELALLOC_NEW |
8854 EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG, 1, 1,
8857 __btrfs_releasepage(page, GFP_NOFS);
8860 ClearPageChecked(page);
8861 if (PagePrivate(page)) {
8862 ClearPagePrivate(page);
8863 set_page_private(page, 0);
8869 * btrfs_page_mkwrite() is not allowed to change the file size as it gets
8870 * called from a page fault handler when a page is first dirtied. Hence we must
8871 * be careful to check for EOF conditions here. We set the page up correctly
8872 * for a written page which means we get ENOSPC checking when writing into
8873 * holes and correct delalloc and unwritten extent mapping on filesystems that
8874 * support these features.
8876 * We are not allowed to take the i_mutex here so we have to play games to
8877 * protect against truncate races as the page could now be beyond EOF. Because
8878 * vmtruncate() writes the inode size before removing pages, once we have the
8879 * page lock we can determine safely if the page is beyond EOF. If it is not
8880 * beyond EOF, then the page is guaranteed safe against truncation until we
8883 int btrfs_page_mkwrite(struct vm_fault *vmf)
8885 struct page *page = vmf->page;
8886 struct inode *inode = file_inode(vmf->vma->vm_file);
8887 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
8888 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
8889 struct btrfs_ordered_extent *ordered;
8890 struct extent_state *cached_state = NULL;
8891 struct extent_changeset *data_reserved = NULL;
8893 unsigned long zero_start;
8902 reserved_space = PAGE_SIZE;
8904 sb_start_pagefault(inode->i_sb);
8905 page_start = page_offset(page);
8906 page_end = page_start + PAGE_SIZE - 1;
8910 * Reserving delalloc space after obtaining the page lock can lead to
8911 * deadlock. For example, if a dirty page is locked by this function
8912 * and the call to btrfs_delalloc_reserve_space() ends up triggering
8913 * dirty page write out, then the btrfs_writepage() function could
8914 * end up waiting indefinitely to get a lock on the page currently
8915 * being processed by btrfs_page_mkwrite() function.
8917 ret = btrfs_delalloc_reserve_space(inode, &data_reserved, page_start,
8920 ret = file_update_time(vmf->vma->vm_file);
8926 else /* -ENOSPC, -EIO, etc */
8927 ret = VM_FAULT_SIGBUS;
8933 ret = VM_FAULT_NOPAGE; /* make the VM retry the fault */
8936 size = i_size_read(inode);
8938 if ((page->mapping != inode->i_mapping) ||
8939 (page_start >= size)) {
8940 /* page got truncated out from underneath us */
8943 wait_on_page_writeback(page);
8945 lock_extent_bits(io_tree, page_start, page_end, &cached_state);
8946 set_page_extent_mapped(page);
8949 * we can't set the delalloc bits if there are pending ordered
8950 * extents. Drop our locks and wait for them to finish
8952 ordered = btrfs_lookup_ordered_range(BTRFS_I(inode), page_start,
8955 unlock_extent_cached(io_tree, page_start, page_end,
8958 btrfs_start_ordered_extent(inode, ordered, 1);
8959 btrfs_put_ordered_extent(ordered);
8963 if (page->index == ((size - 1) >> PAGE_SHIFT)) {
8964 reserved_space = round_up(size - page_start,
8965 fs_info->sectorsize);
8966 if (reserved_space < PAGE_SIZE) {
8967 end = page_start + reserved_space - 1;
8968 btrfs_delalloc_release_space(inode, data_reserved,
8969 page_start, PAGE_SIZE - reserved_space,
8975 * page_mkwrite gets called when the page is firstly dirtied after it's
8976 * faulted in, but write(2) could also dirty a page and set delalloc
8977 * bits, thus in this case for space account reason, we still need to
8978 * clear any delalloc bits within this page range since we have to
8979 * reserve data&meta space before lock_page() (see above comments).
8981 clear_extent_bit(&BTRFS_I(inode)->io_tree, page_start, end,
8982 EXTENT_DIRTY | EXTENT_DELALLOC |
8983 EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG,
8984 0, 0, &cached_state);
8986 ret = btrfs_set_extent_delalloc(inode, page_start, end, 0,
8989 unlock_extent_cached(io_tree, page_start, page_end,
8991 ret = VM_FAULT_SIGBUS;
8996 /* page is wholly or partially inside EOF */
8997 if (page_start + PAGE_SIZE > size)
8998 zero_start = size & ~PAGE_MASK;
9000 zero_start = PAGE_SIZE;
9002 if (zero_start != PAGE_SIZE) {
9004 memset(kaddr + zero_start, 0, PAGE_SIZE - zero_start);
9005 flush_dcache_page(page);
9008 ClearPageChecked(page);
9009 set_page_dirty(page);
9010 SetPageUptodate(page);
9012 BTRFS_I(inode)->last_trans = fs_info->generation;
9013 BTRFS_I(inode)->last_sub_trans = BTRFS_I(inode)->root->log_transid;
9014 BTRFS_I(inode)->last_log_commit = BTRFS_I(inode)->root->last_log_commit;
9016 unlock_extent_cached(io_tree, page_start, page_end, &cached_state);
9020 btrfs_delalloc_release_extents(BTRFS_I(inode), PAGE_SIZE, true);
9021 sb_end_pagefault(inode->i_sb);
9022 extent_changeset_free(data_reserved);
9023 return VM_FAULT_LOCKED;
9027 btrfs_delalloc_release_extents(BTRFS_I(inode), PAGE_SIZE, (ret != 0));
9028 btrfs_delalloc_release_space(inode, data_reserved, page_start,
9029 reserved_space, (ret != 0));
9031 sb_end_pagefault(inode->i_sb);
9032 extent_changeset_free(data_reserved);
9036 static int btrfs_truncate(struct inode *inode, bool skip_writeback)
9038 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
9039 struct btrfs_root *root = BTRFS_I(inode)->root;
9040 struct btrfs_block_rsv *rsv;
9043 struct btrfs_trans_handle *trans;
9044 u64 mask = fs_info->sectorsize - 1;
9045 u64 min_size = btrfs_calc_trunc_metadata_size(fs_info, 1);
9047 if (!skip_writeback) {
9048 ret = btrfs_wait_ordered_range(inode, inode->i_size & (~mask),
9055 * Yes ladies and gentlemen, this is indeed ugly. The fact is we have
9056 * 3 things going on here
9058 * 1) We need to reserve space for our orphan item and the space to
9059 * delete our orphan item. Lord knows we don't want to have a dangling
9060 * orphan item because we didn't reserve space to remove it.
9062 * 2) We need to reserve space to update our inode.
9064 * 3) We need to have something to cache all the space that is going to
9065 * be free'd up by the truncate operation, but also have some slack
9066 * space reserved in case it uses space during the truncate (thank you
9067 * very much snapshotting).
9069 * And we need these to all be separate. The fact is we can use a lot of
9070 * space doing the truncate, and we have no earthly idea how much space
9071 * we will use, so we need the truncate reservation to be separate so it
9072 * doesn't end up using space reserved for updating the inode or
9073 * removing the orphan item. We also need to be able to stop the
9074 * transaction and start a new one, which means we need to be able to
9075 * update the inode several times, and we have no idea of knowing how
9076 * many times that will be, so we can't just reserve 1 item for the
9077 * entirety of the operation, so that has to be done separately as well.
9078 * Then there is the orphan item, which does indeed need to be held on
9079 * to for the whole operation, and we need nobody to touch this reserved
9080 * space except the orphan code.
9082 * So that leaves us with
9084 * 1) root->orphan_block_rsv - for the orphan deletion.
9085 * 2) rsv - for the truncate reservation, which we will steal from the
9086 * transaction reservation.
9087 * 3) fs_info->trans_block_rsv - this will have 1 items worth left for
9088 * updating the inode.
9090 rsv = btrfs_alloc_block_rsv(fs_info, BTRFS_BLOCK_RSV_TEMP);
9093 rsv->size = min_size;
9097 * 1 for the truncate slack space
9098 * 1 for updating the inode.
9100 trans = btrfs_start_transaction(root, 2);
9101 if (IS_ERR(trans)) {
9102 err = PTR_ERR(trans);
9106 /* Migrate the slack space for the truncate to our reserve */
9107 ret = btrfs_block_rsv_migrate(&fs_info->trans_block_rsv, rsv,
9112 * So if we truncate and then write and fsync we normally would just
9113 * write the extents that changed, which is a problem if we need to
9114 * first truncate that entire inode. So set this flag so we write out
9115 * all of the extents in the inode to the sync log so we're completely
9118 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &BTRFS_I(inode)->runtime_flags);
9119 trans->block_rsv = rsv;
9122 ret = btrfs_truncate_inode_items(trans, root, inode,
9124 BTRFS_EXTENT_DATA_KEY);
9125 trans->block_rsv = &fs_info->trans_block_rsv;
9126 if (ret != -ENOSPC && ret != -EAGAIN) {
9131 ret = btrfs_update_inode(trans, root, inode);
9137 btrfs_end_transaction(trans);
9138 btrfs_btree_balance_dirty(fs_info);
9140 trans = btrfs_start_transaction(root, 2);
9141 if (IS_ERR(trans)) {
9142 ret = err = PTR_ERR(trans);
9147 btrfs_block_rsv_release(fs_info, rsv, -1);
9148 ret = btrfs_block_rsv_migrate(&fs_info->trans_block_rsv,
9150 BUG_ON(ret); /* shouldn't happen */
9151 trans->block_rsv = rsv;
9155 * We can't call btrfs_truncate_block inside a trans handle as we could
9156 * deadlock with freeze, if we got NEED_TRUNCATE_BLOCK then we know
9157 * we've truncated everything except the last little bit, and can do
9158 * btrfs_truncate_block and then update the disk_i_size.
9160 if (ret == NEED_TRUNCATE_BLOCK) {
9161 btrfs_end_transaction(trans);
9162 btrfs_btree_balance_dirty(fs_info);
9164 ret = btrfs_truncate_block(inode, inode->i_size, 0, 0);
9167 trans = btrfs_start_transaction(root, 1);
9168 if (IS_ERR(trans)) {
9169 ret = PTR_ERR(trans);
9172 btrfs_ordered_update_i_size(inode, inode->i_size, NULL);
9175 if (ret == 0 && inode->i_nlink > 0) {
9176 trans->block_rsv = root->orphan_block_rsv;
9177 ret = btrfs_orphan_del(trans, BTRFS_I(inode));
9183 trans->block_rsv = &fs_info->trans_block_rsv;
9184 ret = btrfs_update_inode(trans, root, inode);
9188 ret = btrfs_end_transaction(trans);
9189 btrfs_btree_balance_dirty(fs_info);
9192 btrfs_free_block_rsv(fs_info, rsv);
9201 * create a new subvolume directory/inode (helper for the ioctl).
9203 int btrfs_create_subvol_root(struct btrfs_trans_handle *trans,
9204 struct btrfs_root *new_root,
9205 struct btrfs_root *parent_root,
9208 struct inode *inode;
9212 inode = btrfs_new_inode(trans, new_root, NULL, "..", 2,
9213 new_dirid, new_dirid,
9214 S_IFDIR | (~current_umask() & S_IRWXUGO),
9217 return PTR_ERR(inode);
9218 inode->i_op = &btrfs_dir_inode_operations;
9219 inode->i_fop = &btrfs_dir_file_operations;
9221 set_nlink(inode, 1);
9222 btrfs_i_size_write(BTRFS_I(inode), 0);
9223 unlock_new_inode(inode);
9225 err = btrfs_subvol_inherit_props(trans, new_root, parent_root);
9227 btrfs_err(new_root->fs_info,
9228 "error inheriting subvolume %llu properties: %d",
9229 new_root->root_key.objectid, err);
9231 err = btrfs_update_inode(trans, new_root, inode);
9237 struct inode *btrfs_alloc_inode(struct super_block *sb)
9239 struct btrfs_fs_info *fs_info = btrfs_sb(sb);
9240 struct btrfs_inode *ei;
9241 struct inode *inode;
9243 ei = kmem_cache_alloc(btrfs_inode_cachep, GFP_KERNEL);
9250 ei->last_sub_trans = 0;
9251 ei->logged_trans = 0;
9252 ei->delalloc_bytes = 0;
9253 ei->new_delalloc_bytes = 0;
9254 ei->defrag_bytes = 0;
9255 ei->disk_i_size = 0;
9258 ei->index_cnt = (u64)-1;
9260 ei->last_unlink_trans = 0;
9261 ei->last_log_commit = 0;
9263 spin_lock_init(&ei->lock);
9264 ei->outstanding_extents = 0;
9265 if (sb->s_magic != BTRFS_TEST_MAGIC)
9266 btrfs_init_metadata_block_rsv(fs_info, &ei->block_rsv,
9267 BTRFS_BLOCK_RSV_DELALLOC);
9268 ei->runtime_flags = 0;
9269 ei->prop_compress = BTRFS_COMPRESS_NONE;
9270 ei->defrag_compress = BTRFS_COMPRESS_NONE;
9272 ei->delayed_node = NULL;
9274 ei->i_otime.tv_sec = 0;
9275 ei->i_otime.tv_nsec = 0;
9277 inode = &ei->vfs_inode;
9278 extent_map_tree_init(&ei->extent_tree);
9279 extent_io_tree_init(&ei->io_tree, inode);
9280 extent_io_tree_init(&ei->io_failure_tree, inode);
9281 ei->io_tree.track_uptodate = 1;
9282 ei->io_failure_tree.track_uptodate = 1;
9283 atomic_set(&ei->sync_writers, 0);
9284 mutex_init(&ei->log_mutex);
9285 mutex_init(&ei->delalloc_mutex);
9286 btrfs_ordered_inode_tree_init(&ei->ordered_tree);
9287 INIT_LIST_HEAD(&ei->delalloc_inodes);
9288 INIT_LIST_HEAD(&ei->delayed_iput);
9289 RB_CLEAR_NODE(&ei->rb_node);
9290 init_rwsem(&ei->dio_sem);
9295 #ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
9296 void btrfs_test_destroy_inode(struct inode *inode)
9298 btrfs_drop_extent_cache(BTRFS_I(inode), 0, (u64)-1, 0);
9299 kmem_cache_free(btrfs_inode_cachep, BTRFS_I(inode));
9303 static void btrfs_i_callback(struct rcu_head *head)
9305 struct inode *inode = container_of(head, struct inode, i_rcu);
9306 kmem_cache_free(btrfs_inode_cachep, BTRFS_I(inode));
9309 void btrfs_destroy_inode(struct inode *inode)
9311 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
9312 struct btrfs_ordered_extent *ordered;
9313 struct btrfs_root *root = BTRFS_I(inode)->root;
9315 WARN_ON(!hlist_empty(&inode->i_dentry));
9316 WARN_ON(inode->i_data.nrpages);
9317 WARN_ON(BTRFS_I(inode)->block_rsv.reserved);
9318 WARN_ON(BTRFS_I(inode)->block_rsv.size);
9319 WARN_ON(BTRFS_I(inode)->outstanding_extents);
9320 WARN_ON(BTRFS_I(inode)->delalloc_bytes);
9321 WARN_ON(BTRFS_I(inode)->new_delalloc_bytes);
9322 WARN_ON(BTRFS_I(inode)->csum_bytes);
9323 WARN_ON(BTRFS_I(inode)->defrag_bytes);
9326 * This can happen where we create an inode, but somebody else also
9327 * created the same inode and we need to destroy the one we already
9333 if (test_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
9334 &BTRFS_I(inode)->runtime_flags)) {
9335 btrfs_info(fs_info, "inode %llu still on the orphan list",
9336 btrfs_ino(BTRFS_I(inode)));
9337 atomic_dec(&root->orphan_inodes);
9341 ordered = btrfs_lookup_first_ordered_extent(inode, (u64)-1);
9346 "found ordered extent %llu %llu on inode cleanup",
9347 ordered->file_offset, ordered->len);
9348 btrfs_remove_ordered_extent(inode, ordered);
9349 btrfs_put_ordered_extent(ordered);
9350 btrfs_put_ordered_extent(ordered);
9353 btrfs_qgroup_check_reserved_leak(inode);
9354 inode_tree_del(inode);
9355 btrfs_drop_extent_cache(BTRFS_I(inode), 0, (u64)-1, 0);
9357 call_rcu(&inode->i_rcu, btrfs_i_callback);
9360 int btrfs_drop_inode(struct inode *inode)
9362 struct btrfs_root *root = BTRFS_I(inode)->root;
9367 /* the snap/subvol tree is on deleting */
9368 if (btrfs_root_refs(&root->root_item) == 0)
9371 return generic_drop_inode(inode);
9374 static void init_once(void *foo)
9376 struct btrfs_inode *ei = (struct btrfs_inode *) foo;
9378 inode_init_once(&ei->vfs_inode);
9381 void __cold btrfs_destroy_cachep(void)
9384 * Make sure all delayed rcu free inodes are flushed before we
9388 kmem_cache_destroy(btrfs_inode_cachep);
9389 kmem_cache_destroy(btrfs_trans_handle_cachep);
9390 kmem_cache_destroy(btrfs_path_cachep);
9391 kmem_cache_destroy(btrfs_free_space_cachep);
9394 int __init btrfs_init_cachep(void)
9396 btrfs_inode_cachep = kmem_cache_create("btrfs_inode",
9397 sizeof(struct btrfs_inode), 0,
9398 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD | SLAB_ACCOUNT,
9400 if (!btrfs_inode_cachep)
9403 btrfs_trans_handle_cachep = kmem_cache_create("btrfs_trans_handle",
9404 sizeof(struct btrfs_trans_handle), 0,
9405 SLAB_TEMPORARY | SLAB_MEM_SPREAD, NULL);
9406 if (!btrfs_trans_handle_cachep)
9409 btrfs_path_cachep = kmem_cache_create("btrfs_path",
9410 sizeof(struct btrfs_path), 0,
9411 SLAB_MEM_SPREAD, NULL);
9412 if (!btrfs_path_cachep)
9415 btrfs_free_space_cachep = kmem_cache_create("btrfs_free_space",
9416 sizeof(struct btrfs_free_space), 0,
9417 SLAB_MEM_SPREAD, NULL);
9418 if (!btrfs_free_space_cachep)
9423 btrfs_destroy_cachep();
9427 static int btrfs_getattr(const struct path *path, struct kstat *stat,
9428 u32 request_mask, unsigned int flags)
9431 struct inode *inode = d_inode(path->dentry);
9432 u32 blocksize = inode->i_sb->s_blocksize;
9433 u32 bi_flags = BTRFS_I(inode)->flags;
9435 stat->result_mask |= STATX_BTIME;
9436 stat->btime.tv_sec = BTRFS_I(inode)->i_otime.tv_sec;
9437 stat->btime.tv_nsec = BTRFS_I(inode)->i_otime.tv_nsec;
9438 if (bi_flags & BTRFS_INODE_APPEND)
9439 stat->attributes |= STATX_ATTR_APPEND;
9440 if (bi_flags & BTRFS_INODE_COMPRESS)
9441 stat->attributes |= STATX_ATTR_COMPRESSED;
9442 if (bi_flags & BTRFS_INODE_IMMUTABLE)
9443 stat->attributes |= STATX_ATTR_IMMUTABLE;
9444 if (bi_flags & BTRFS_INODE_NODUMP)
9445 stat->attributes |= STATX_ATTR_NODUMP;
9447 stat->attributes_mask |= (STATX_ATTR_APPEND |
9448 STATX_ATTR_COMPRESSED |
9449 STATX_ATTR_IMMUTABLE |
9452 generic_fillattr(inode, stat);
9453 stat->dev = BTRFS_I(inode)->root->anon_dev;
9455 spin_lock(&BTRFS_I(inode)->lock);
9456 delalloc_bytes = BTRFS_I(inode)->new_delalloc_bytes;
9457 spin_unlock(&BTRFS_I(inode)->lock);
9458 stat->blocks = (ALIGN(inode_get_bytes(inode), blocksize) +
9459 ALIGN(delalloc_bytes, blocksize)) >> 9;
9463 static int btrfs_rename_exchange(struct inode *old_dir,
9464 struct dentry *old_dentry,
9465 struct inode *new_dir,
9466 struct dentry *new_dentry)
9468 struct btrfs_fs_info *fs_info = btrfs_sb(old_dir->i_sb);
9469 struct btrfs_trans_handle *trans;
9470 struct btrfs_root *root = BTRFS_I(old_dir)->root;
9471 struct btrfs_root *dest = BTRFS_I(new_dir)->root;
9472 struct inode *new_inode = new_dentry->d_inode;
9473 struct inode *old_inode = old_dentry->d_inode;
9474 struct timespec ctime = current_time(old_inode);
9475 struct dentry *parent;
9476 u64 old_ino = btrfs_ino(BTRFS_I(old_inode));
9477 u64 new_ino = btrfs_ino(BTRFS_I(new_inode));
9482 bool root_log_pinned = false;
9483 bool dest_log_pinned = false;
9485 /* we only allow rename subvolume link between subvolumes */
9486 if (old_ino != BTRFS_FIRST_FREE_OBJECTID && root != dest)
9489 /* close the race window with snapshot create/destroy ioctl */
9490 if (old_ino == BTRFS_FIRST_FREE_OBJECTID)
9491 down_read(&fs_info->subvol_sem);
9492 if (new_ino == BTRFS_FIRST_FREE_OBJECTID)
9493 down_read(&fs_info->subvol_sem);
9496 * We want to reserve the absolute worst case amount of items. So if
9497 * both inodes are subvols and we need to unlink them then that would
9498 * require 4 item modifications, but if they are both normal inodes it
9499 * would require 5 item modifications, so we'll assume their normal
9500 * inodes. So 5 * 2 is 10, plus 2 for the new links, so 12 total items
9501 * should cover the worst case number of items we'll modify.
9503 trans = btrfs_start_transaction(root, 12);
9504 if (IS_ERR(trans)) {
9505 ret = PTR_ERR(trans);
9510 * We need to find a free sequence number both in the source and
9511 * in the destination directory for the exchange.
9513 ret = btrfs_set_inode_index(BTRFS_I(new_dir), &old_idx);
9516 ret = btrfs_set_inode_index(BTRFS_I(old_dir), &new_idx);
9520 BTRFS_I(old_inode)->dir_index = 0ULL;
9521 BTRFS_I(new_inode)->dir_index = 0ULL;
9523 /* Reference for the source. */
9524 if (old_ino == BTRFS_FIRST_FREE_OBJECTID) {
9525 /* force full log commit if subvolume involved. */
9526 btrfs_set_log_full_commit(fs_info, trans);
9528 btrfs_pin_log_trans(root);
9529 root_log_pinned = true;
9530 ret = btrfs_insert_inode_ref(trans, dest,
9531 new_dentry->d_name.name,
9532 new_dentry->d_name.len,
9534 btrfs_ino(BTRFS_I(new_dir)),
9540 /* And now for the dest. */
9541 if (new_ino == BTRFS_FIRST_FREE_OBJECTID) {
9542 /* force full log commit if subvolume involved. */
9543 btrfs_set_log_full_commit(fs_info, trans);
9545 btrfs_pin_log_trans(dest);
9546 dest_log_pinned = true;
9547 ret = btrfs_insert_inode_ref(trans, root,
9548 old_dentry->d_name.name,
9549 old_dentry->d_name.len,
9551 btrfs_ino(BTRFS_I(old_dir)),
9557 /* Update inode version and ctime/mtime. */
9558 inode_inc_iversion(old_dir);
9559 inode_inc_iversion(new_dir);
9560 inode_inc_iversion(old_inode);
9561 inode_inc_iversion(new_inode);
9562 old_dir->i_ctime = old_dir->i_mtime = ctime;
9563 new_dir->i_ctime = new_dir->i_mtime = ctime;
9564 old_inode->i_ctime = ctime;
9565 new_inode->i_ctime = ctime;
9567 if (old_dentry->d_parent != new_dentry->d_parent) {
9568 btrfs_record_unlink_dir(trans, BTRFS_I(old_dir),
9569 BTRFS_I(old_inode), 1);
9570 btrfs_record_unlink_dir(trans, BTRFS_I(new_dir),
9571 BTRFS_I(new_inode), 1);
9574 /* src is a subvolume */
9575 if (old_ino == BTRFS_FIRST_FREE_OBJECTID) {
9576 root_objectid = BTRFS_I(old_inode)->root->root_key.objectid;
9577 ret = btrfs_unlink_subvol(trans, root, old_dir,
9579 old_dentry->d_name.name,
9580 old_dentry->d_name.len);
9581 } else { /* src is an inode */
9582 ret = __btrfs_unlink_inode(trans, root, BTRFS_I(old_dir),
9583 BTRFS_I(old_dentry->d_inode),
9584 old_dentry->d_name.name,
9585 old_dentry->d_name.len);
9587 ret = btrfs_update_inode(trans, root, old_inode);
9590 btrfs_abort_transaction(trans, ret);
9594 /* dest is a subvolume */
9595 if (new_ino == BTRFS_FIRST_FREE_OBJECTID) {
9596 root_objectid = BTRFS_I(new_inode)->root->root_key.objectid;
9597 ret = btrfs_unlink_subvol(trans, dest, new_dir,
9599 new_dentry->d_name.name,
9600 new_dentry->d_name.len);
9601 } else { /* dest is an inode */
9602 ret = __btrfs_unlink_inode(trans, dest, BTRFS_I(new_dir),
9603 BTRFS_I(new_dentry->d_inode),
9604 new_dentry->d_name.name,
9605 new_dentry->d_name.len);
9607 ret = btrfs_update_inode(trans, dest, new_inode);
9610 btrfs_abort_transaction(trans, ret);
9614 ret = btrfs_add_link(trans, BTRFS_I(new_dir), BTRFS_I(old_inode),
9615 new_dentry->d_name.name,
9616 new_dentry->d_name.len, 0, old_idx);
9618 btrfs_abort_transaction(trans, ret);
9622 ret = btrfs_add_link(trans, BTRFS_I(old_dir), BTRFS_I(new_inode),
9623 old_dentry->d_name.name,
9624 old_dentry->d_name.len, 0, new_idx);
9626 btrfs_abort_transaction(trans, ret);
9630 if (old_inode->i_nlink == 1)
9631 BTRFS_I(old_inode)->dir_index = old_idx;
9632 if (new_inode->i_nlink == 1)
9633 BTRFS_I(new_inode)->dir_index = new_idx;
9635 if (root_log_pinned) {
9636 parent = new_dentry->d_parent;
9637 btrfs_log_new_name(trans, BTRFS_I(old_inode), BTRFS_I(old_dir),
9639 btrfs_end_log_trans(root);
9640 root_log_pinned = false;
9642 if (dest_log_pinned) {
9643 parent = old_dentry->d_parent;
9644 btrfs_log_new_name(trans, BTRFS_I(new_inode), BTRFS_I(new_dir),
9646 btrfs_end_log_trans(dest);
9647 dest_log_pinned = false;
9651 * If we have pinned a log and an error happened, we unpin tasks
9652 * trying to sync the log and force them to fallback to a transaction
9653 * commit if the log currently contains any of the inodes involved in
9654 * this rename operation (to ensure we do not persist a log with an
9655 * inconsistent state for any of these inodes or leading to any
9656 * inconsistencies when replayed). If the transaction was aborted, the
9657 * abortion reason is propagated to userspace when attempting to commit
9658 * the transaction. If the log does not contain any of these inodes, we
9659 * allow the tasks to sync it.
9661 if (ret && (root_log_pinned || dest_log_pinned)) {
9662 if (btrfs_inode_in_log(BTRFS_I(old_dir), fs_info->generation) ||
9663 btrfs_inode_in_log(BTRFS_I(new_dir), fs_info->generation) ||
9664 btrfs_inode_in_log(BTRFS_I(old_inode), fs_info->generation) ||
9666 btrfs_inode_in_log(BTRFS_I(new_inode), fs_info->generation)))
9667 btrfs_set_log_full_commit(fs_info, trans);
9669 if (root_log_pinned) {
9670 btrfs_end_log_trans(root);
9671 root_log_pinned = false;
9673 if (dest_log_pinned) {
9674 btrfs_end_log_trans(dest);
9675 dest_log_pinned = false;
9678 ret = btrfs_end_transaction(trans);
9680 if (new_ino == BTRFS_FIRST_FREE_OBJECTID)
9681 up_read(&fs_info->subvol_sem);
9682 if (old_ino == BTRFS_FIRST_FREE_OBJECTID)
9683 up_read(&fs_info->subvol_sem);
9688 static int btrfs_whiteout_for_rename(struct btrfs_trans_handle *trans,
9689 struct btrfs_root *root,
9691 struct dentry *dentry)
9694 struct inode *inode;
9698 ret = btrfs_find_free_ino(root, &objectid);
9702 inode = btrfs_new_inode(trans, root, dir,
9703 dentry->d_name.name,
9705 btrfs_ino(BTRFS_I(dir)),
9707 S_IFCHR | WHITEOUT_MODE,
9710 if (IS_ERR(inode)) {
9711 ret = PTR_ERR(inode);
9715 inode->i_op = &btrfs_special_inode_operations;
9716 init_special_inode(inode, inode->i_mode,
9719 ret = btrfs_init_inode_security(trans, inode, dir,
9724 ret = btrfs_add_nondir(trans, BTRFS_I(dir), dentry,
9725 BTRFS_I(inode), 0, index);
9729 ret = btrfs_update_inode(trans, root, inode);
9731 unlock_new_inode(inode);
9733 inode_dec_link_count(inode);
9739 static int btrfs_rename(struct inode *old_dir, struct dentry *old_dentry,
9740 struct inode *new_dir, struct dentry *new_dentry,
9743 struct btrfs_fs_info *fs_info = btrfs_sb(old_dir->i_sb);
9744 struct btrfs_trans_handle *trans;
9745 unsigned int trans_num_items;
9746 struct btrfs_root *root = BTRFS_I(old_dir)->root;
9747 struct btrfs_root *dest = BTRFS_I(new_dir)->root;
9748 struct inode *new_inode = d_inode(new_dentry);
9749 struct inode *old_inode = d_inode(old_dentry);
9753 u64 old_ino = btrfs_ino(BTRFS_I(old_inode));
9754 bool log_pinned = false;
9756 if (btrfs_ino(BTRFS_I(new_dir)) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)
9759 /* we only allow rename subvolume link between subvolumes */
9760 if (old_ino != BTRFS_FIRST_FREE_OBJECTID && root != dest)
9763 if (old_ino == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID ||
9764 (new_inode && btrfs_ino(BTRFS_I(new_inode)) == BTRFS_FIRST_FREE_OBJECTID))
9767 if (S_ISDIR(old_inode->i_mode) && new_inode &&
9768 new_inode->i_size > BTRFS_EMPTY_DIR_SIZE)
9772 /* check for collisions, even if the name isn't there */
9773 ret = btrfs_check_dir_item_collision(dest, new_dir->i_ino,
9774 new_dentry->d_name.name,
9775 new_dentry->d_name.len);
9778 if (ret == -EEXIST) {
9780 * eexist without a new_inode */
9781 if (WARN_ON(!new_inode)) {
9785 /* maybe -EOVERFLOW */
9792 * we're using rename to replace one file with another. Start IO on it
9793 * now so we don't add too much work to the end of the transaction
9795 if (new_inode && S_ISREG(old_inode->i_mode) && new_inode->i_size)
9796 filemap_flush(old_inode->i_mapping);
9798 /* close the racy window with snapshot create/destroy ioctl */
9799 if (old_ino == BTRFS_FIRST_FREE_OBJECTID)
9800 down_read(&fs_info->subvol_sem);
9802 * We want to reserve the absolute worst case amount of items. So if
9803 * both inodes are subvols and we need to unlink them then that would
9804 * require 4 item modifications, but if they are both normal inodes it
9805 * would require 5 item modifications, so we'll assume they are normal
9806 * inodes. So 5 * 2 is 10, plus 1 for the new link, so 11 total items
9807 * should cover the worst case number of items we'll modify.
9808 * If our rename has the whiteout flag, we need more 5 units for the
9809 * new inode (1 inode item, 1 inode ref, 2 dir items and 1 xattr item
9810 * when selinux is enabled).
9812 trans_num_items = 11;
9813 if (flags & RENAME_WHITEOUT)
9814 trans_num_items += 5;
9815 trans = btrfs_start_transaction(root, trans_num_items);
9816 if (IS_ERR(trans)) {
9817 ret = PTR_ERR(trans);
9822 btrfs_record_root_in_trans(trans, dest);
9824 ret = btrfs_set_inode_index(BTRFS_I(new_dir), &index);
9828 BTRFS_I(old_inode)->dir_index = 0ULL;
9829 if (unlikely(old_ino == BTRFS_FIRST_FREE_OBJECTID)) {
9830 /* force full log commit if subvolume involved. */
9831 btrfs_set_log_full_commit(fs_info, trans);
9833 btrfs_pin_log_trans(root);
9835 ret = btrfs_insert_inode_ref(trans, dest,
9836 new_dentry->d_name.name,
9837 new_dentry->d_name.len,
9839 btrfs_ino(BTRFS_I(new_dir)), index);
9844 inode_inc_iversion(old_dir);
9845 inode_inc_iversion(new_dir);
9846 inode_inc_iversion(old_inode);
9847 old_dir->i_ctime = old_dir->i_mtime =
9848 new_dir->i_ctime = new_dir->i_mtime =
9849 old_inode->i_ctime = current_time(old_dir);
9851 if (old_dentry->d_parent != new_dentry->d_parent)
9852 btrfs_record_unlink_dir(trans, BTRFS_I(old_dir),
9853 BTRFS_I(old_inode), 1);
9855 if (unlikely(old_ino == BTRFS_FIRST_FREE_OBJECTID)) {
9856 root_objectid = BTRFS_I(old_inode)->root->root_key.objectid;
9857 ret = btrfs_unlink_subvol(trans, root, old_dir, root_objectid,
9858 old_dentry->d_name.name,
9859 old_dentry->d_name.len);
9861 ret = __btrfs_unlink_inode(trans, root, BTRFS_I(old_dir),
9862 BTRFS_I(d_inode(old_dentry)),
9863 old_dentry->d_name.name,
9864 old_dentry->d_name.len);
9866 ret = btrfs_update_inode(trans, root, old_inode);
9869 btrfs_abort_transaction(trans, ret);
9874 inode_inc_iversion(new_inode);
9875 new_inode->i_ctime = current_time(new_inode);
9876 if (unlikely(btrfs_ino(BTRFS_I(new_inode)) ==
9877 BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)) {
9878 root_objectid = BTRFS_I(new_inode)->location.objectid;
9879 ret = btrfs_unlink_subvol(trans, dest, new_dir,
9881 new_dentry->d_name.name,
9882 new_dentry->d_name.len);
9883 BUG_ON(new_inode->i_nlink == 0);
9885 ret = btrfs_unlink_inode(trans, dest, BTRFS_I(new_dir),
9886 BTRFS_I(d_inode(new_dentry)),
9887 new_dentry->d_name.name,
9888 new_dentry->d_name.len);
9890 if (!ret && new_inode->i_nlink == 0)
9891 ret = btrfs_orphan_add(trans,
9892 BTRFS_I(d_inode(new_dentry)));
9894 btrfs_abort_transaction(trans, ret);
9899 ret = btrfs_add_link(trans, BTRFS_I(new_dir), BTRFS_I(old_inode),
9900 new_dentry->d_name.name,
9901 new_dentry->d_name.len, 0, index);
9903 btrfs_abort_transaction(trans, ret);
9907 if (old_inode->i_nlink == 1)
9908 BTRFS_I(old_inode)->dir_index = index;
9911 struct dentry *parent = new_dentry->d_parent;
9913 btrfs_log_new_name(trans, BTRFS_I(old_inode), BTRFS_I(old_dir),
9915 btrfs_end_log_trans(root);
9919 if (flags & RENAME_WHITEOUT) {
9920 ret = btrfs_whiteout_for_rename(trans, root, old_dir,
9924 btrfs_abort_transaction(trans, ret);
9930 * If we have pinned the log and an error happened, we unpin tasks
9931 * trying to sync the log and force them to fallback to a transaction
9932 * commit if the log currently contains any of the inodes involved in
9933 * this rename operation (to ensure we do not persist a log with an
9934 * inconsistent state for any of these inodes or leading to any
9935 * inconsistencies when replayed). If the transaction was aborted, the
9936 * abortion reason is propagated to userspace when attempting to commit
9937 * the transaction. If the log does not contain any of these inodes, we
9938 * allow the tasks to sync it.
9940 if (ret && log_pinned) {
9941 if (btrfs_inode_in_log(BTRFS_I(old_dir), fs_info->generation) ||
9942 btrfs_inode_in_log(BTRFS_I(new_dir), fs_info->generation) ||
9943 btrfs_inode_in_log(BTRFS_I(old_inode), fs_info->generation) ||
9945 btrfs_inode_in_log(BTRFS_I(new_inode), fs_info->generation)))
9946 btrfs_set_log_full_commit(fs_info, trans);
9948 btrfs_end_log_trans(root);
9951 btrfs_end_transaction(trans);
9953 if (old_ino == BTRFS_FIRST_FREE_OBJECTID)
9954 up_read(&fs_info->subvol_sem);
9959 static int btrfs_rename2(struct inode *old_dir, struct dentry *old_dentry,
9960 struct inode *new_dir, struct dentry *new_dentry,
9963 if (flags & ~(RENAME_NOREPLACE | RENAME_EXCHANGE | RENAME_WHITEOUT))
9966 if (flags & RENAME_EXCHANGE)
9967 return btrfs_rename_exchange(old_dir, old_dentry, new_dir,
9970 return btrfs_rename(old_dir, old_dentry, new_dir, new_dentry, flags);
9973 static void btrfs_run_delalloc_work(struct btrfs_work *work)
9975 struct btrfs_delalloc_work *delalloc_work;
9976 struct inode *inode;
9978 delalloc_work = container_of(work, struct btrfs_delalloc_work,
9980 inode = delalloc_work->inode;
9981 filemap_flush(inode->i_mapping);
9982 if (test_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
9983 &BTRFS_I(inode)->runtime_flags))
9984 filemap_flush(inode->i_mapping);
9986 if (delalloc_work->delay_iput)
9987 btrfs_add_delayed_iput(inode);
9990 complete(&delalloc_work->completion);
9993 struct btrfs_delalloc_work *btrfs_alloc_delalloc_work(struct inode *inode,
9996 struct btrfs_delalloc_work *work;
9998 work = kmalloc(sizeof(*work), GFP_NOFS);
10002 init_completion(&work->completion);
10003 INIT_LIST_HEAD(&work->list);
10004 work->inode = inode;
10005 work->delay_iput = delay_iput;
10006 WARN_ON_ONCE(!inode);
10007 btrfs_init_work(&work->work, btrfs_flush_delalloc_helper,
10008 btrfs_run_delalloc_work, NULL, NULL);
10013 void btrfs_wait_and_free_delalloc_work(struct btrfs_delalloc_work *work)
10015 wait_for_completion(&work->completion);
10020 * some fairly slow code that needs optimization. This walks the list
10021 * of all the inodes with pending delalloc and forces them to disk.
10023 static int __start_delalloc_inodes(struct btrfs_root *root, int delay_iput,
10026 struct btrfs_inode *binode;
10027 struct inode *inode;
10028 struct btrfs_delalloc_work *work, *next;
10029 struct list_head works;
10030 struct list_head splice;
10033 INIT_LIST_HEAD(&works);
10034 INIT_LIST_HEAD(&splice);
10036 mutex_lock(&root->delalloc_mutex);
10037 spin_lock(&root->delalloc_lock);
10038 list_splice_init(&root->delalloc_inodes, &splice);
10039 while (!list_empty(&splice)) {
10040 binode = list_entry(splice.next, struct btrfs_inode,
10043 list_move_tail(&binode->delalloc_inodes,
10044 &root->delalloc_inodes);
10045 inode = igrab(&binode->vfs_inode);
10047 cond_resched_lock(&root->delalloc_lock);
10050 spin_unlock(&root->delalloc_lock);
10052 work = btrfs_alloc_delalloc_work(inode, delay_iput);
10055 btrfs_add_delayed_iput(inode);
10061 list_add_tail(&work->list, &works);
10062 btrfs_queue_work(root->fs_info->flush_workers,
10065 if (nr != -1 && ret >= nr)
10068 spin_lock(&root->delalloc_lock);
10070 spin_unlock(&root->delalloc_lock);
10073 list_for_each_entry_safe(work, next, &works, list) {
10074 list_del_init(&work->list);
10075 btrfs_wait_and_free_delalloc_work(work);
10078 if (!list_empty_careful(&splice)) {
10079 spin_lock(&root->delalloc_lock);
10080 list_splice_tail(&splice, &root->delalloc_inodes);
10081 spin_unlock(&root->delalloc_lock);
10083 mutex_unlock(&root->delalloc_mutex);
10087 int btrfs_start_delalloc_inodes(struct btrfs_root *root, int delay_iput)
10089 struct btrfs_fs_info *fs_info = root->fs_info;
10092 if (test_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state))
10095 ret = __start_delalloc_inodes(root, delay_iput, -1);
10101 int btrfs_start_delalloc_roots(struct btrfs_fs_info *fs_info, int delay_iput,
10104 struct btrfs_root *root;
10105 struct list_head splice;
10108 if (test_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state))
10111 INIT_LIST_HEAD(&splice);
10113 mutex_lock(&fs_info->delalloc_root_mutex);
10114 spin_lock(&fs_info->delalloc_root_lock);
10115 list_splice_init(&fs_info->delalloc_roots, &splice);
10116 while (!list_empty(&splice) && nr) {
10117 root = list_first_entry(&splice, struct btrfs_root,
10119 root = btrfs_grab_fs_root(root);
10121 list_move_tail(&root->delalloc_root,
10122 &fs_info->delalloc_roots);
10123 spin_unlock(&fs_info->delalloc_root_lock);
10125 ret = __start_delalloc_inodes(root, delay_iput, nr);
10126 btrfs_put_fs_root(root);
10134 spin_lock(&fs_info->delalloc_root_lock);
10136 spin_unlock(&fs_info->delalloc_root_lock);
10140 if (!list_empty_careful(&splice)) {
10141 spin_lock(&fs_info->delalloc_root_lock);
10142 list_splice_tail(&splice, &fs_info->delalloc_roots);
10143 spin_unlock(&fs_info->delalloc_root_lock);
10145 mutex_unlock(&fs_info->delalloc_root_mutex);
10149 static int btrfs_symlink(struct inode *dir, struct dentry *dentry,
10150 const char *symname)
10152 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
10153 struct btrfs_trans_handle *trans;
10154 struct btrfs_root *root = BTRFS_I(dir)->root;
10155 struct btrfs_path *path;
10156 struct btrfs_key key;
10157 struct inode *inode = NULL;
10159 int drop_inode = 0;
10165 struct btrfs_file_extent_item *ei;
10166 struct extent_buffer *leaf;
10168 name_len = strlen(symname);
10169 if (name_len > BTRFS_MAX_INLINE_DATA_SIZE(fs_info))
10170 return -ENAMETOOLONG;
10173 * 2 items for inode item and ref
10174 * 2 items for dir items
10175 * 1 item for updating parent inode item
10176 * 1 item for the inline extent item
10177 * 1 item for xattr if selinux is on
10179 trans = btrfs_start_transaction(root, 7);
10181 return PTR_ERR(trans);
10183 err = btrfs_find_free_ino(root, &objectid);
10187 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
10188 dentry->d_name.len, btrfs_ino(BTRFS_I(dir)),
10189 objectid, S_IFLNK|S_IRWXUGO, &index);
10190 if (IS_ERR(inode)) {
10191 err = PTR_ERR(inode);
10196 * If the active LSM wants to access the inode during
10197 * d_instantiate it needs these. Smack checks to see
10198 * if the filesystem supports xattrs by looking at the
10201 inode->i_fop = &btrfs_file_operations;
10202 inode->i_op = &btrfs_file_inode_operations;
10203 inode->i_mapping->a_ops = &btrfs_aops;
10204 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
10206 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
10208 goto out_unlock_inode;
10210 path = btrfs_alloc_path();
10213 goto out_unlock_inode;
10215 key.objectid = btrfs_ino(BTRFS_I(inode));
10217 key.type = BTRFS_EXTENT_DATA_KEY;
10218 datasize = btrfs_file_extent_calc_inline_size(name_len);
10219 err = btrfs_insert_empty_item(trans, root, path, &key,
10222 btrfs_free_path(path);
10223 goto out_unlock_inode;
10225 leaf = path->nodes[0];
10226 ei = btrfs_item_ptr(leaf, path->slots[0],
10227 struct btrfs_file_extent_item);
10228 btrfs_set_file_extent_generation(leaf, ei, trans->transid);
10229 btrfs_set_file_extent_type(leaf, ei,
10230 BTRFS_FILE_EXTENT_INLINE);
10231 btrfs_set_file_extent_encryption(leaf, ei, 0);
10232 btrfs_set_file_extent_compression(leaf, ei, 0);
10233 btrfs_set_file_extent_other_encoding(leaf, ei, 0);
10234 btrfs_set_file_extent_ram_bytes(leaf, ei, name_len);
10236 ptr = btrfs_file_extent_inline_start(ei);
10237 write_extent_buffer(leaf, symname, ptr, name_len);
10238 btrfs_mark_buffer_dirty(leaf);
10239 btrfs_free_path(path);
10241 inode->i_op = &btrfs_symlink_inode_operations;
10242 inode_nohighmem(inode);
10243 inode->i_mapping->a_ops = &btrfs_symlink_aops;
10244 inode_set_bytes(inode, name_len);
10245 btrfs_i_size_write(BTRFS_I(inode), name_len);
10246 err = btrfs_update_inode(trans, root, inode);
10248 * Last step, add directory indexes for our symlink inode. This is the
10249 * last step to avoid extra cleanup of these indexes if an error happens
10253 err = btrfs_add_nondir(trans, BTRFS_I(dir), dentry,
10254 BTRFS_I(inode), 0, index);
10257 goto out_unlock_inode;
10260 unlock_new_inode(inode);
10261 d_instantiate(dentry, inode);
10264 btrfs_end_transaction(trans);
10266 inode_dec_link_count(inode);
10269 btrfs_btree_balance_dirty(fs_info);
10274 unlock_new_inode(inode);
10278 static int __btrfs_prealloc_file_range(struct inode *inode, int mode,
10279 u64 start, u64 num_bytes, u64 min_size,
10280 loff_t actual_len, u64 *alloc_hint,
10281 struct btrfs_trans_handle *trans)
10283 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
10284 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
10285 struct extent_map *em;
10286 struct btrfs_root *root = BTRFS_I(inode)->root;
10287 struct btrfs_key ins;
10288 u64 cur_offset = start;
10291 u64 last_alloc = (u64)-1;
10293 bool own_trans = true;
10294 u64 end = start + num_bytes - 1;
10298 while (num_bytes > 0) {
10300 trans = btrfs_start_transaction(root, 3);
10301 if (IS_ERR(trans)) {
10302 ret = PTR_ERR(trans);
10307 cur_bytes = min_t(u64, num_bytes, SZ_256M);
10308 cur_bytes = max(cur_bytes, min_size);
10310 * If we are severely fragmented we could end up with really
10311 * small allocations, so if the allocator is returning small
10312 * chunks lets make its job easier by only searching for those
10315 cur_bytes = min(cur_bytes, last_alloc);
10316 ret = btrfs_reserve_extent(root, cur_bytes, cur_bytes,
10317 min_size, 0, *alloc_hint, &ins, 1, 0);
10320 btrfs_end_transaction(trans);
10323 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
10325 last_alloc = ins.offset;
10326 ret = insert_reserved_file_extent(trans, inode,
10327 cur_offset, ins.objectid,
10328 ins.offset, ins.offset,
10329 ins.offset, 0, 0, 0,
10330 BTRFS_FILE_EXTENT_PREALLOC);
10332 btrfs_free_reserved_extent(fs_info, ins.objectid,
10334 btrfs_abort_transaction(trans, ret);
10336 btrfs_end_transaction(trans);
10340 btrfs_drop_extent_cache(BTRFS_I(inode), cur_offset,
10341 cur_offset + ins.offset -1, 0);
10343 em = alloc_extent_map();
10345 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
10346 &BTRFS_I(inode)->runtime_flags);
10350 em->start = cur_offset;
10351 em->orig_start = cur_offset;
10352 em->len = ins.offset;
10353 em->block_start = ins.objectid;
10354 em->block_len = ins.offset;
10355 em->orig_block_len = ins.offset;
10356 em->ram_bytes = ins.offset;
10357 em->bdev = fs_info->fs_devices->latest_bdev;
10358 set_bit(EXTENT_FLAG_PREALLOC, &em->flags);
10359 em->generation = trans->transid;
10362 write_lock(&em_tree->lock);
10363 ret = add_extent_mapping(em_tree, em, 1);
10364 write_unlock(&em_tree->lock);
10365 if (ret != -EEXIST)
10367 btrfs_drop_extent_cache(BTRFS_I(inode), cur_offset,
10368 cur_offset + ins.offset - 1,
10371 free_extent_map(em);
10373 num_bytes -= ins.offset;
10374 cur_offset += ins.offset;
10375 *alloc_hint = ins.objectid + ins.offset;
10377 inode_inc_iversion(inode);
10378 inode->i_ctime = current_time(inode);
10379 BTRFS_I(inode)->flags |= BTRFS_INODE_PREALLOC;
10380 if (!(mode & FALLOC_FL_KEEP_SIZE) &&
10381 (actual_len > inode->i_size) &&
10382 (cur_offset > inode->i_size)) {
10383 if (cur_offset > actual_len)
10384 i_size = actual_len;
10386 i_size = cur_offset;
10387 i_size_write(inode, i_size);
10388 btrfs_ordered_update_i_size(inode, i_size, NULL);
10391 ret = btrfs_update_inode(trans, root, inode);
10394 btrfs_abort_transaction(trans, ret);
10396 btrfs_end_transaction(trans);
10401 btrfs_end_transaction(trans);
10403 if (cur_offset < end)
10404 btrfs_free_reserved_data_space(inode, NULL, cur_offset,
10405 end - cur_offset + 1);
10409 int btrfs_prealloc_file_range(struct inode *inode, int mode,
10410 u64 start, u64 num_bytes, u64 min_size,
10411 loff_t actual_len, u64 *alloc_hint)
10413 return __btrfs_prealloc_file_range(inode, mode, start, num_bytes,
10414 min_size, actual_len, alloc_hint,
10418 int btrfs_prealloc_file_range_trans(struct inode *inode,
10419 struct btrfs_trans_handle *trans, int mode,
10420 u64 start, u64 num_bytes, u64 min_size,
10421 loff_t actual_len, u64 *alloc_hint)
10423 return __btrfs_prealloc_file_range(inode, mode, start, num_bytes,
10424 min_size, actual_len, alloc_hint, trans);
10427 static int btrfs_set_page_dirty(struct page *page)
10429 return __set_page_dirty_nobuffers(page);
10432 static int btrfs_permission(struct inode *inode, int mask)
10434 struct btrfs_root *root = BTRFS_I(inode)->root;
10435 umode_t mode = inode->i_mode;
10437 if (mask & MAY_WRITE &&
10438 (S_ISREG(mode) || S_ISDIR(mode) || S_ISLNK(mode))) {
10439 if (btrfs_root_readonly(root))
10441 if (BTRFS_I(inode)->flags & BTRFS_INODE_READONLY)
10444 return generic_permission(inode, mask);
10447 static int btrfs_tmpfile(struct inode *dir, struct dentry *dentry, umode_t mode)
10449 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
10450 struct btrfs_trans_handle *trans;
10451 struct btrfs_root *root = BTRFS_I(dir)->root;
10452 struct inode *inode = NULL;
10458 * 5 units required for adding orphan entry
10460 trans = btrfs_start_transaction(root, 5);
10462 return PTR_ERR(trans);
10464 ret = btrfs_find_free_ino(root, &objectid);
10468 inode = btrfs_new_inode(trans, root, dir, NULL, 0,
10469 btrfs_ino(BTRFS_I(dir)), objectid, mode, &index);
10470 if (IS_ERR(inode)) {
10471 ret = PTR_ERR(inode);
10476 inode->i_fop = &btrfs_file_operations;
10477 inode->i_op = &btrfs_file_inode_operations;
10479 inode->i_mapping->a_ops = &btrfs_aops;
10480 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
10482 ret = btrfs_init_inode_security(trans, inode, dir, NULL);
10486 ret = btrfs_update_inode(trans, root, inode);
10489 ret = btrfs_orphan_add(trans, BTRFS_I(inode));
10494 * We set number of links to 0 in btrfs_new_inode(), and here we set
10495 * it to 1 because d_tmpfile() will issue a warning if the count is 0,
10498 * d_tmpfile() -> inode_dec_link_count() -> drop_nlink()
10500 set_nlink(inode, 1);
10501 unlock_new_inode(inode);
10502 d_tmpfile(dentry, inode);
10503 mark_inode_dirty(inode);
10506 btrfs_end_transaction(trans);
10509 btrfs_btree_balance_dirty(fs_info);
10513 unlock_new_inode(inode);
10518 __attribute__((const))
10519 static int btrfs_readpage_io_failed_hook(struct page *page, int failed_mirror)
10524 static struct btrfs_fs_info *iotree_fs_info(void *private_data)
10526 struct inode *inode = private_data;
10527 return btrfs_sb(inode->i_sb);
10530 static void btrfs_check_extent_io_range(void *private_data, const char *caller,
10531 u64 start, u64 end)
10533 struct inode *inode = private_data;
10536 isize = i_size_read(inode);
10537 if (end >= PAGE_SIZE && (end % 2) == 0 && end != isize - 1) {
10538 btrfs_debug_rl(BTRFS_I(inode)->root->fs_info,
10539 "%s: ino %llu isize %llu odd range [%llu,%llu]",
10540 caller, btrfs_ino(BTRFS_I(inode)), isize, start, end);
10544 void btrfs_set_range_writeback(void *private_data, u64 start, u64 end)
10546 struct inode *inode = private_data;
10547 unsigned long index = start >> PAGE_SHIFT;
10548 unsigned long end_index = end >> PAGE_SHIFT;
10551 while (index <= end_index) {
10552 page = find_get_page(inode->i_mapping, index);
10553 ASSERT(page); /* Pages should be in the extent_io_tree */
10554 set_page_writeback(page);
10560 static const struct inode_operations btrfs_dir_inode_operations = {
10561 .getattr = btrfs_getattr,
10562 .lookup = btrfs_lookup,
10563 .create = btrfs_create,
10564 .unlink = btrfs_unlink,
10565 .link = btrfs_link,
10566 .mkdir = btrfs_mkdir,
10567 .rmdir = btrfs_rmdir,
10568 .rename = btrfs_rename2,
10569 .symlink = btrfs_symlink,
10570 .setattr = btrfs_setattr,
10571 .mknod = btrfs_mknod,
10572 .listxattr = btrfs_listxattr,
10573 .permission = btrfs_permission,
10574 .get_acl = btrfs_get_acl,
10575 .set_acl = btrfs_set_acl,
10576 .update_time = btrfs_update_time,
10577 .tmpfile = btrfs_tmpfile,
10579 static const struct inode_operations btrfs_dir_ro_inode_operations = {
10580 .lookup = btrfs_lookup,
10581 .permission = btrfs_permission,
10582 .update_time = btrfs_update_time,
10585 static const struct file_operations btrfs_dir_file_operations = {
10586 .llseek = generic_file_llseek,
10587 .read = generic_read_dir,
10588 .iterate_shared = btrfs_real_readdir,
10589 .open = btrfs_opendir,
10590 .unlocked_ioctl = btrfs_ioctl,
10591 #ifdef CONFIG_COMPAT
10592 .compat_ioctl = btrfs_compat_ioctl,
10594 .release = btrfs_release_file,
10595 .fsync = btrfs_sync_file,
10598 static const struct extent_io_ops btrfs_extent_io_ops = {
10599 /* mandatory callbacks */
10600 .submit_bio_hook = btrfs_submit_bio_hook,
10601 .readpage_end_io_hook = btrfs_readpage_end_io_hook,
10602 .merge_bio_hook = btrfs_merge_bio_hook,
10603 .readpage_io_failed_hook = btrfs_readpage_io_failed_hook,
10604 .tree_fs_info = iotree_fs_info,
10605 .set_range_writeback = btrfs_set_range_writeback,
10607 /* optional callbacks */
10608 .fill_delalloc = run_delalloc_range,
10609 .writepage_end_io_hook = btrfs_writepage_end_io_hook,
10610 .writepage_start_hook = btrfs_writepage_start_hook,
10611 .set_bit_hook = btrfs_set_bit_hook,
10612 .clear_bit_hook = btrfs_clear_bit_hook,
10613 .merge_extent_hook = btrfs_merge_extent_hook,
10614 .split_extent_hook = btrfs_split_extent_hook,
10615 .check_extent_io_range = btrfs_check_extent_io_range,
10619 * btrfs doesn't support the bmap operation because swapfiles
10620 * use bmap to make a mapping of extents in the file. They assume
10621 * these extents won't change over the life of the file and they
10622 * use the bmap result to do IO directly to the drive.
10624 * the btrfs bmap call would return logical addresses that aren't
10625 * suitable for IO and they also will change frequently as COW
10626 * operations happen. So, swapfile + btrfs == corruption.
10628 * For now we're avoiding this by dropping bmap.
10630 static const struct address_space_operations btrfs_aops = {
10631 .readpage = btrfs_readpage,
10632 .writepage = btrfs_writepage,
10633 .writepages = btrfs_writepages,
10634 .readpages = btrfs_readpages,
10635 .direct_IO = btrfs_direct_IO,
10636 .invalidatepage = btrfs_invalidatepage,
10637 .releasepage = btrfs_releasepage,
10638 .set_page_dirty = btrfs_set_page_dirty,
10639 .error_remove_page = generic_error_remove_page,
10642 static const struct address_space_operations btrfs_symlink_aops = {
10643 .readpage = btrfs_readpage,
10644 .writepage = btrfs_writepage,
10645 .invalidatepage = btrfs_invalidatepage,
10646 .releasepage = btrfs_releasepage,
10649 static const struct inode_operations btrfs_file_inode_operations = {
10650 .getattr = btrfs_getattr,
10651 .setattr = btrfs_setattr,
10652 .listxattr = btrfs_listxattr,
10653 .permission = btrfs_permission,
10654 .fiemap = btrfs_fiemap,
10655 .get_acl = btrfs_get_acl,
10656 .set_acl = btrfs_set_acl,
10657 .update_time = btrfs_update_time,
10659 static const struct inode_operations btrfs_special_inode_operations = {
10660 .getattr = btrfs_getattr,
10661 .setattr = btrfs_setattr,
10662 .permission = btrfs_permission,
10663 .listxattr = btrfs_listxattr,
10664 .get_acl = btrfs_get_acl,
10665 .set_acl = btrfs_set_acl,
10666 .update_time = btrfs_update_time,
10668 static const struct inode_operations btrfs_symlink_inode_operations = {
10669 .get_link = page_get_link,
10670 .getattr = btrfs_getattr,
10671 .setattr = btrfs_setattr,
10672 .permission = btrfs_permission,
10673 .listxattr = btrfs_listxattr,
10674 .update_time = btrfs_update_time,
10677 const struct dentry_operations btrfs_dentry_operations = {
10678 .d_delete = btrfs_dentry_delete,
10679 .d_release = btrfs_dentry_release,