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) >>
1159 /* atomic_sub_return implies a barrier */
1160 if (atomic_sub_return(nr_pages, &fs_info->async_delalloc_pages) <
1162 cond_wake_up_nomb(&fs_info->async_submit_wait);
1164 if (async_cow->inode)
1165 submit_compressed_extents(async_cow->inode, async_cow);
1168 static noinline void async_cow_free(struct btrfs_work *work)
1170 struct async_cow *async_cow;
1171 async_cow = container_of(work, struct async_cow, work);
1172 if (async_cow->inode)
1173 btrfs_add_delayed_iput(async_cow->inode);
1177 static int cow_file_range_async(struct inode *inode, struct page *locked_page,
1178 u64 start, u64 end, int *page_started,
1179 unsigned long *nr_written,
1180 unsigned int write_flags)
1182 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1183 struct async_cow *async_cow;
1184 struct btrfs_root *root = BTRFS_I(inode)->root;
1185 unsigned long nr_pages;
1188 clear_extent_bit(&BTRFS_I(inode)->io_tree, start, end, EXTENT_LOCKED,
1190 while (start < end) {
1191 async_cow = kmalloc(sizeof(*async_cow), GFP_NOFS);
1192 BUG_ON(!async_cow); /* -ENOMEM */
1193 async_cow->inode = igrab(inode);
1194 async_cow->root = root;
1195 async_cow->locked_page = locked_page;
1196 async_cow->start = start;
1197 async_cow->write_flags = write_flags;
1199 if (BTRFS_I(inode)->flags & BTRFS_INODE_NOCOMPRESS &&
1200 !btrfs_test_opt(fs_info, FORCE_COMPRESS))
1203 cur_end = min(end, start + SZ_512K - 1);
1205 async_cow->end = cur_end;
1206 INIT_LIST_HEAD(&async_cow->extents);
1208 btrfs_init_work(&async_cow->work,
1209 btrfs_delalloc_helper,
1210 async_cow_start, async_cow_submit,
1213 nr_pages = (cur_end - start + PAGE_SIZE) >>
1215 atomic_add(nr_pages, &fs_info->async_delalloc_pages);
1217 btrfs_queue_work(fs_info->delalloc_workers, &async_cow->work);
1219 *nr_written += nr_pages;
1220 start = cur_end + 1;
1226 static noinline int csum_exist_in_range(struct btrfs_fs_info *fs_info,
1227 u64 bytenr, u64 num_bytes)
1230 struct btrfs_ordered_sum *sums;
1233 ret = btrfs_lookup_csums_range(fs_info->csum_root, bytenr,
1234 bytenr + num_bytes - 1, &list, 0);
1235 if (ret == 0 && list_empty(&list))
1238 while (!list_empty(&list)) {
1239 sums = list_entry(list.next, struct btrfs_ordered_sum, list);
1240 list_del(&sums->list);
1249 * when nowcow writeback call back. This checks for snapshots or COW copies
1250 * of the extents that exist in the file, and COWs the file as required.
1252 * If no cow copies or snapshots exist, we write directly to the existing
1255 static noinline int run_delalloc_nocow(struct inode *inode,
1256 struct page *locked_page,
1257 u64 start, u64 end, int *page_started, int force,
1258 unsigned long *nr_written)
1260 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1261 struct btrfs_root *root = BTRFS_I(inode)->root;
1262 struct extent_buffer *leaf;
1263 struct btrfs_path *path;
1264 struct btrfs_file_extent_item *fi;
1265 struct btrfs_key found_key;
1266 struct extent_map *em;
1281 u64 ino = btrfs_ino(BTRFS_I(inode));
1283 path = btrfs_alloc_path();
1285 extent_clear_unlock_delalloc(inode, start, end, end,
1287 EXTENT_LOCKED | EXTENT_DELALLOC |
1288 EXTENT_DO_ACCOUNTING |
1289 EXTENT_DEFRAG, PAGE_UNLOCK |
1291 PAGE_SET_WRITEBACK |
1292 PAGE_END_WRITEBACK);
1296 nolock = btrfs_is_free_space_inode(BTRFS_I(inode));
1298 cow_start = (u64)-1;
1301 ret = btrfs_lookup_file_extent(NULL, root, path, ino,
1305 if (ret > 0 && path->slots[0] > 0 && check_prev) {
1306 leaf = path->nodes[0];
1307 btrfs_item_key_to_cpu(leaf, &found_key,
1308 path->slots[0] - 1);
1309 if (found_key.objectid == ino &&
1310 found_key.type == BTRFS_EXTENT_DATA_KEY)
1315 leaf = path->nodes[0];
1316 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
1317 ret = btrfs_next_leaf(root, path);
1319 if (cow_start != (u64)-1)
1320 cur_offset = cow_start;
1325 leaf = path->nodes[0];
1331 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
1333 if (found_key.objectid > ino)
1335 if (WARN_ON_ONCE(found_key.objectid < ino) ||
1336 found_key.type < BTRFS_EXTENT_DATA_KEY) {
1340 if (found_key.type > BTRFS_EXTENT_DATA_KEY ||
1341 found_key.offset > end)
1344 if (found_key.offset > cur_offset) {
1345 extent_end = found_key.offset;
1350 fi = btrfs_item_ptr(leaf, path->slots[0],
1351 struct btrfs_file_extent_item);
1352 extent_type = btrfs_file_extent_type(leaf, fi);
1354 ram_bytes = btrfs_file_extent_ram_bytes(leaf, fi);
1355 if (extent_type == BTRFS_FILE_EXTENT_REG ||
1356 extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
1357 disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
1358 extent_offset = btrfs_file_extent_offset(leaf, fi);
1359 extent_end = found_key.offset +
1360 btrfs_file_extent_num_bytes(leaf, fi);
1362 btrfs_file_extent_disk_num_bytes(leaf, fi);
1363 if (extent_end <= start) {
1367 if (disk_bytenr == 0)
1369 if (btrfs_file_extent_compression(leaf, fi) ||
1370 btrfs_file_extent_encryption(leaf, fi) ||
1371 btrfs_file_extent_other_encoding(leaf, fi))
1373 if (extent_type == BTRFS_FILE_EXTENT_REG && !force)
1375 if (btrfs_extent_readonly(fs_info, disk_bytenr))
1377 ret = btrfs_cross_ref_exist(root, ino,
1379 extent_offset, disk_bytenr);
1382 * ret could be -EIO if the above fails to read
1386 if (cow_start != (u64)-1)
1387 cur_offset = cow_start;
1391 WARN_ON_ONCE(nolock);
1394 disk_bytenr += extent_offset;
1395 disk_bytenr += cur_offset - found_key.offset;
1396 num_bytes = min(end + 1, extent_end) - cur_offset;
1398 * if there are pending snapshots for this root,
1399 * we fall into common COW way.
1402 err = btrfs_start_write_no_snapshotting(root);
1407 * force cow if csum exists in the range.
1408 * this ensure that csum for a given extent are
1409 * either valid or do not exist.
1411 ret = csum_exist_in_range(fs_info, disk_bytenr,
1415 btrfs_end_write_no_snapshotting(root);
1418 * ret could be -EIO if the above fails to read
1422 if (cow_start != (u64)-1)
1423 cur_offset = cow_start;
1426 WARN_ON_ONCE(nolock);
1429 if (!btrfs_inc_nocow_writers(fs_info, disk_bytenr)) {
1431 btrfs_end_write_no_snapshotting(root);
1435 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
1436 extent_end = found_key.offset +
1437 btrfs_file_extent_inline_len(leaf,
1438 path->slots[0], fi);
1439 extent_end = ALIGN(extent_end,
1440 fs_info->sectorsize);
1445 if (extent_end <= start) {
1447 if (!nolock && nocow)
1448 btrfs_end_write_no_snapshotting(root);
1450 btrfs_dec_nocow_writers(fs_info, disk_bytenr);
1454 if (cow_start == (u64)-1)
1455 cow_start = cur_offset;
1456 cur_offset = extent_end;
1457 if (cur_offset > end)
1463 btrfs_release_path(path);
1464 if (cow_start != (u64)-1) {
1465 ret = cow_file_range(inode, locked_page,
1466 cow_start, found_key.offset - 1,
1467 end, page_started, nr_written, 1,
1470 if (!nolock && nocow)
1471 btrfs_end_write_no_snapshotting(root);
1473 btrfs_dec_nocow_writers(fs_info,
1477 cow_start = (u64)-1;
1480 if (extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
1481 u64 orig_start = found_key.offset - extent_offset;
1483 em = create_io_em(inode, cur_offset, num_bytes,
1485 disk_bytenr, /* block_start */
1486 num_bytes, /* block_len */
1487 disk_num_bytes, /* orig_block_len */
1488 ram_bytes, BTRFS_COMPRESS_NONE,
1489 BTRFS_ORDERED_PREALLOC);
1491 if (!nolock && nocow)
1492 btrfs_end_write_no_snapshotting(root);
1494 btrfs_dec_nocow_writers(fs_info,
1499 free_extent_map(em);
1502 if (extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
1503 type = BTRFS_ORDERED_PREALLOC;
1505 type = BTRFS_ORDERED_NOCOW;
1508 ret = btrfs_add_ordered_extent(inode, cur_offset, disk_bytenr,
1509 num_bytes, num_bytes, type);
1511 btrfs_dec_nocow_writers(fs_info, disk_bytenr);
1512 BUG_ON(ret); /* -ENOMEM */
1514 if (root->root_key.objectid ==
1515 BTRFS_DATA_RELOC_TREE_OBJECTID)
1517 * Error handled later, as we must prevent
1518 * extent_clear_unlock_delalloc() in error handler
1519 * from freeing metadata of created ordered extent.
1521 ret = btrfs_reloc_clone_csums(inode, cur_offset,
1524 extent_clear_unlock_delalloc(inode, cur_offset,
1525 cur_offset + num_bytes - 1, end,
1526 locked_page, EXTENT_LOCKED |
1528 EXTENT_CLEAR_DATA_RESV,
1529 PAGE_UNLOCK | PAGE_SET_PRIVATE2);
1531 if (!nolock && nocow)
1532 btrfs_end_write_no_snapshotting(root);
1533 cur_offset = extent_end;
1536 * btrfs_reloc_clone_csums() error, now we're OK to call error
1537 * handler, as metadata for created ordered extent will only
1538 * be freed by btrfs_finish_ordered_io().
1542 if (cur_offset > end)
1545 btrfs_release_path(path);
1547 if (cur_offset <= end && cow_start == (u64)-1) {
1548 cow_start = cur_offset;
1552 if (cow_start != (u64)-1) {
1553 ret = cow_file_range(inode, locked_page, cow_start, end, end,
1554 page_started, nr_written, 1, NULL);
1560 if (ret && cur_offset < end)
1561 extent_clear_unlock_delalloc(inode, cur_offset, end, end,
1562 locked_page, EXTENT_LOCKED |
1563 EXTENT_DELALLOC | EXTENT_DEFRAG |
1564 EXTENT_DO_ACCOUNTING, PAGE_UNLOCK |
1566 PAGE_SET_WRITEBACK |
1567 PAGE_END_WRITEBACK);
1568 btrfs_free_path(path);
1572 static inline int need_force_cow(struct inode *inode, u64 start, u64 end)
1575 if (!(BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW) &&
1576 !(BTRFS_I(inode)->flags & BTRFS_INODE_PREALLOC))
1580 * @defrag_bytes is a hint value, no spinlock held here,
1581 * if is not zero, it means the file is defragging.
1582 * Force cow if given extent needs to be defragged.
1584 if (BTRFS_I(inode)->defrag_bytes &&
1585 test_range_bit(&BTRFS_I(inode)->io_tree, start, end,
1586 EXTENT_DEFRAG, 0, NULL))
1593 * extent_io.c call back to do delayed allocation processing
1595 static int run_delalloc_range(void *private_data, struct page *locked_page,
1596 u64 start, u64 end, int *page_started,
1597 unsigned long *nr_written,
1598 struct writeback_control *wbc)
1600 struct inode *inode = private_data;
1602 int force_cow = need_force_cow(inode, start, end);
1603 unsigned int write_flags = wbc_to_write_flags(wbc);
1605 if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW && !force_cow) {
1606 ret = run_delalloc_nocow(inode, locked_page, start, end,
1607 page_started, 1, nr_written);
1608 } else if (BTRFS_I(inode)->flags & BTRFS_INODE_PREALLOC && !force_cow) {
1609 ret = run_delalloc_nocow(inode, locked_page, start, end,
1610 page_started, 0, nr_written);
1611 } else if (!inode_need_compress(inode, start, end)) {
1612 ret = cow_file_range(inode, locked_page, start, end, end,
1613 page_started, nr_written, 1, NULL);
1615 set_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
1616 &BTRFS_I(inode)->runtime_flags);
1617 ret = cow_file_range_async(inode, locked_page, start, end,
1618 page_started, nr_written,
1622 btrfs_cleanup_ordered_extents(inode, start, end - start + 1);
1626 static void btrfs_split_extent_hook(void *private_data,
1627 struct extent_state *orig, u64 split)
1629 struct inode *inode = private_data;
1632 /* not delalloc, ignore it */
1633 if (!(orig->state & EXTENT_DELALLOC))
1636 size = orig->end - orig->start + 1;
1637 if (size > BTRFS_MAX_EXTENT_SIZE) {
1642 * See the explanation in btrfs_merge_extent_hook, the same
1643 * applies here, just in reverse.
1645 new_size = orig->end - split + 1;
1646 num_extents = count_max_extents(new_size);
1647 new_size = split - orig->start;
1648 num_extents += count_max_extents(new_size);
1649 if (count_max_extents(size) >= num_extents)
1653 spin_lock(&BTRFS_I(inode)->lock);
1654 btrfs_mod_outstanding_extents(BTRFS_I(inode), 1);
1655 spin_unlock(&BTRFS_I(inode)->lock);
1659 * extent_io.c merge_extent_hook, used to track merged delayed allocation
1660 * extents so we can keep track of new extents that are just merged onto old
1661 * extents, such as when we are doing sequential writes, so we can properly
1662 * account for the metadata space we'll need.
1664 static void btrfs_merge_extent_hook(void *private_data,
1665 struct extent_state *new,
1666 struct extent_state *other)
1668 struct inode *inode = private_data;
1669 u64 new_size, old_size;
1672 /* not delalloc, ignore it */
1673 if (!(other->state & EXTENT_DELALLOC))
1676 if (new->start > other->start)
1677 new_size = new->end - other->start + 1;
1679 new_size = other->end - new->start + 1;
1681 /* we're not bigger than the max, unreserve the space and go */
1682 if (new_size <= BTRFS_MAX_EXTENT_SIZE) {
1683 spin_lock(&BTRFS_I(inode)->lock);
1684 btrfs_mod_outstanding_extents(BTRFS_I(inode), -1);
1685 spin_unlock(&BTRFS_I(inode)->lock);
1690 * We have to add up either side to figure out how many extents were
1691 * accounted for before we merged into one big extent. If the number of
1692 * extents we accounted for is <= the amount we need for the new range
1693 * then we can return, otherwise drop. Think of it like this
1697 * So we've grown the extent by a MAX_SIZE extent, this would mean we
1698 * need 2 outstanding extents, on one side we have 1 and the other side
1699 * we have 1 so they are == and we can return. But in this case
1701 * [MAX_SIZE+4k][MAX_SIZE+4k]
1703 * Each range on their own accounts for 2 extents, but merged together
1704 * they are only 3 extents worth of accounting, so we need to drop in
1707 old_size = other->end - other->start + 1;
1708 num_extents = count_max_extents(old_size);
1709 old_size = new->end - new->start + 1;
1710 num_extents += count_max_extents(old_size);
1711 if (count_max_extents(new_size) >= num_extents)
1714 spin_lock(&BTRFS_I(inode)->lock);
1715 btrfs_mod_outstanding_extents(BTRFS_I(inode), -1);
1716 spin_unlock(&BTRFS_I(inode)->lock);
1719 static void btrfs_add_delalloc_inodes(struct btrfs_root *root,
1720 struct inode *inode)
1722 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1724 spin_lock(&root->delalloc_lock);
1725 if (list_empty(&BTRFS_I(inode)->delalloc_inodes)) {
1726 list_add_tail(&BTRFS_I(inode)->delalloc_inodes,
1727 &root->delalloc_inodes);
1728 set_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1729 &BTRFS_I(inode)->runtime_flags);
1730 root->nr_delalloc_inodes++;
1731 if (root->nr_delalloc_inodes == 1) {
1732 spin_lock(&fs_info->delalloc_root_lock);
1733 BUG_ON(!list_empty(&root->delalloc_root));
1734 list_add_tail(&root->delalloc_root,
1735 &fs_info->delalloc_roots);
1736 spin_unlock(&fs_info->delalloc_root_lock);
1739 spin_unlock(&root->delalloc_lock);
1743 void __btrfs_del_delalloc_inode(struct btrfs_root *root,
1744 struct btrfs_inode *inode)
1746 struct btrfs_fs_info *fs_info = btrfs_sb(inode->vfs_inode.i_sb);
1748 if (!list_empty(&inode->delalloc_inodes)) {
1749 list_del_init(&inode->delalloc_inodes);
1750 clear_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1751 &inode->runtime_flags);
1752 root->nr_delalloc_inodes--;
1753 if (!root->nr_delalloc_inodes) {
1754 ASSERT(list_empty(&root->delalloc_inodes));
1755 spin_lock(&fs_info->delalloc_root_lock);
1756 BUG_ON(list_empty(&root->delalloc_root));
1757 list_del_init(&root->delalloc_root);
1758 spin_unlock(&fs_info->delalloc_root_lock);
1763 static void btrfs_del_delalloc_inode(struct btrfs_root *root,
1764 struct btrfs_inode *inode)
1766 spin_lock(&root->delalloc_lock);
1767 __btrfs_del_delalloc_inode(root, inode);
1768 spin_unlock(&root->delalloc_lock);
1772 * extent_io.c set_bit_hook, used to track delayed allocation
1773 * bytes in this file, and to maintain the list of inodes that
1774 * have pending delalloc work to be done.
1776 static void btrfs_set_bit_hook(void *private_data,
1777 struct extent_state *state, unsigned *bits)
1779 struct inode *inode = private_data;
1781 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1783 if ((*bits & EXTENT_DEFRAG) && !(*bits & EXTENT_DELALLOC))
1786 * set_bit and clear bit hooks normally require _irqsave/restore
1787 * but in this case, we are only testing for the DELALLOC
1788 * bit, which is only set or cleared with irqs on
1790 if (!(state->state & EXTENT_DELALLOC) && (*bits & EXTENT_DELALLOC)) {
1791 struct btrfs_root *root = BTRFS_I(inode)->root;
1792 u64 len = state->end + 1 - state->start;
1793 u32 num_extents = count_max_extents(len);
1794 bool do_list = !btrfs_is_free_space_inode(BTRFS_I(inode));
1796 spin_lock(&BTRFS_I(inode)->lock);
1797 btrfs_mod_outstanding_extents(BTRFS_I(inode), num_extents);
1798 spin_unlock(&BTRFS_I(inode)->lock);
1800 /* For sanity tests */
1801 if (btrfs_is_testing(fs_info))
1804 percpu_counter_add_batch(&fs_info->delalloc_bytes, len,
1805 fs_info->delalloc_batch);
1806 spin_lock(&BTRFS_I(inode)->lock);
1807 BTRFS_I(inode)->delalloc_bytes += len;
1808 if (*bits & EXTENT_DEFRAG)
1809 BTRFS_I(inode)->defrag_bytes += len;
1810 if (do_list && !test_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1811 &BTRFS_I(inode)->runtime_flags))
1812 btrfs_add_delalloc_inodes(root, inode);
1813 spin_unlock(&BTRFS_I(inode)->lock);
1816 if (!(state->state & EXTENT_DELALLOC_NEW) &&
1817 (*bits & EXTENT_DELALLOC_NEW)) {
1818 spin_lock(&BTRFS_I(inode)->lock);
1819 BTRFS_I(inode)->new_delalloc_bytes += state->end + 1 -
1821 spin_unlock(&BTRFS_I(inode)->lock);
1826 * extent_io.c clear_bit_hook, see set_bit_hook for why
1828 static void btrfs_clear_bit_hook(void *private_data,
1829 struct extent_state *state,
1832 struct btrfs_inode *inode = BTRFS_I((struct inode *)private_data);
1833 struct btrfs_fs_info *fs_info = btrfs_sb(inode->vfs_inode.i_sb);
1834 u64 len = state->end + 1 - state->start;
1835 u32 num_extents = count_max_extents(len);
1837 if ((state->state & EXTENT_DEFRAG) && (*bits & EXTENT_DEFRAG)) {
1838 spin_lock(&inode->lock);
1839 inode->defrag_bytes -= len;
1840 spin_unlock(&inode->lock);
1844 * set_bit and clear bit hooks normally require _irqsave/restore
1845 * but in this case, we are only testing for the DELALLOC
1846 * bit, which is only set or cleared with irqs on
1848 if ((state->state & EXTENT_DELALLOC) && (*bits & EXTENT_DELALLOC)) {
1849 struct btrfs_root *root = inode->root;
1850 bool do_list = !btrfs_is_free_space_inode(inode);
1852 spin_lock(&inode->lock);
1853 btrfs_mod_outstanding_extents(inode, -num_extents);
1854 spin_unlock(&inode->lock);
1857 * We don't reserve metadata space for space cache inodes so we
1858 * don't need to call dellalloc_release_metadata if there is an
1861 if (*bits & EXTENT_CLEAR_META_RESV &&
1862 root != fs_info->tree_root)
1863 btrfs_delalloc_release_metadata(inode, len, false);
1865 /* For sanity tests. */
1866 if (btrfs_is_testing(fs_info))
1869 if (root->root_key.objectid != BTRFS_DATA_RELOC_TREE_OBJECTID &&
1870 do_list && !(state->state & EXTENT_NORESERVE) &&
1871 (*bits & EXTENT_CLEAR_DATA_RESV))
1872 btrfs_free_reserved_data_space_noquota(
1876 percpu_counter_add_batch(&fs_info->delalloc_bytes, -len,
1877 fs_info->delalloc_batch);
1878 spin_lock(&inode->lock);
1879 inode->delalloc_bytes -= len;
1880 if (do_list && inode->delalloc_bytes == 0 &&
1881 test_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1882 &inode->runtime_flags))
1883 btrfs_del_delalloc_inode(root, inode);
1884 spin_unlock(&inode->lock);
1887 if ((state->state & EXTENT_DELALLOC_NEW) &&
1888 (*bits & EXTENT_DELALLOC_NEW)) {
1889 spin_lock(&inode->lock);
1890 ASSERT(inode->new_delalloc_bytes >= len);
1891 inode->new_delalloc_bytes -= len;
1892 spin_unlock(&inode->lock);
1897 * extent_io.c merge_bio_hook, this must check the chunk tree to make sure
1898 * we don't create bios that span stripes or chunks
1900 * return 1 if page cannot be merged to bio
1901 * return 0 if page can be merged to bio
1902 * return error otherwise
1904 int btrfs_merge_bio_hook(struct page *page, unsigned long offset,
1905 size_t size, struct bio *bio,
1906 unsigned long bio_flags)
1908 struct inode *inode = page->mapping->host;
1909 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1910 u64 logical = (u64)bio->bi_iter.bi_sector << 9;
1915 if (bio_flags & EXTENT_BIO_COMPRESSED)
1918 length = bio->bi_iter.bi_size;
1919 map_length = length;
1920 ret = btrfs_map_block(fs_info, btrfs_op(bio), logical, &map_length,
1924 if (map_length < length + size)
1930 * in order to insert checksums into the metadata in large chunks,
1931 * we wait until bio submission time. All the pages in the bio are
1932 * checksummed and sums are attached onto the ordered extent record.
1934 * At IO completion time the cums attached on the ordered extent record
1935 * are inserted into the btree
1937 static blk_status_t btrfs_submit_bio_start(void *private_data, struct bio *bio,
1940 struct inode *inode = private_data;
1941 blk_status_t ret = 0;
1943 ret = btrfs_csum_one_bio(inode, bio, 0, 0);
1944 BUG_ON(ret); /* -ENOMEM */
1949 * in order to insert checksums into the metadata in large chunks,
1950 * we wait until bio submission time. All the pages in the bio are
1951 * checksummed and sums are attached onto the ordered extent record.
1953 * At IO completion time the cums attached on the ordered extent record
1954 * are inserted into the btree
1956 static blk_status_t btrfs_submit_bio_done(void *private_data, struct bio *bio,
1959 struct inode *inode = private_data;
1960 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1963 ret = btrfs_map_bio(fs_info, bio, mirror_num, 1);
1965 bio->bi_status = ret;
1972 * extent_io.c submission hook. This does the right thing for csum calculation
1973 * on write, or reading the csums from the tree before a read.
1975 * Rules about async/sync submit,
1976 * a) read: sync submit
1978 * b) write without checksum: sync submit
1980 * c) write with checksum:
1981 * c-1) if bio is issued by fsync: sync submit
1982 * (sync_writers != 0)
1984 * c-2) if root is reloc root: sync submit
1985 * (only in case of buffered IO)
1987 * c-3) otherwise: async submit
1989 static blk_status_t btrfs_submit_bio_hook(void *private_data, struct bio *bio,
1990 int mirror_num, unsigned long bio_flags,
1993 struct inode *inode = private_data;
1994 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1995 struct btrfs_root *root = BTRFS_I(inode)->root;
1996 enum btrfs_wq_endio_type metadata = BTRFS_WQ_ENDIO_DATA;
1997 blk_status_t ret = 0;
1999 int async = !atomic_read(&BTRFS_I(inode)->sync_writers);
2001 skip_sum = BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM;
2003 if (btrfs_is_free_space_inode(BTRFS_I(inode)))
2004 metadata = BTRFS_WQ_ENDIO_FREE_SPACE;
2006 if (bio_op(bio) != REQ_OP_WRITE) {
2007 ret = btrfs_bio_wq_end_io(fs_info, bio, metadata);
2011 if (bio_flags & EXTENT_BIO_COMPRESSED) {
2012 ret = btrfs_submit_compressed_read(inode, bio,
2016 } else if (!skip_sum) {
2017 ret = btrfs_lookup_bio_sums(inode, bio, NULL);
2022 } else if (async && !skip_sum) {
2023 /* csum items have already been cloned */
2024 if (root->root_key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID)
2026 /* we're doing a write, do the async checksumming */
2027 ret = btrfs_wq_submit_bio(fs_info, bio, mirror_num, bio_flags,
2029 btrfs_submit_bio_start,
2030 btrfs_submit_bio_done);
2032 } else if (!skip_sum) {
2033 ret = btrfs_csum_one_bio(inode, bio, 0, 0);
2039 ret = btrfs_map_bio(fs_info, bio, mirror_num, 0);
2043 bio->bi_status = ret;
2050 * given a list of ordered sums record them in the inode. This happens
2051 * at IO completion time based on sums calculated at bio submission time.
2053 static noinline int add_pending_csums(struct btrfs_trans_handle *trans,
2054 struct inode *inode, struct list_head *list)
2056 struct btrfs_ordered_sum *sum;
2059 list_for_each_entry(sum, list, list) {
2060 trans->adding_csums = true;
2061 ret = btrfs_csum_file_blocks(trans,
2062 BTRFS_I(inode)->root->fs_info->csum_root, sum);
2063 trans->adding_csums = false;
2070 int btrfs_set_extent_delalloc(struct inode *inode, u64 start, u64 end,
2071 unsigned int extra_bits,
2072 struct extent_state **cached_state, int dedupe)
2074 WARN_ON((end & (PAGE_SIZE - 1)) == 0);
2075 return set_extent_delalloc(&BTRFS_I(inode)->io_tree, start, end,
2076 extra_bits, cached_state);
2079 /* see btrfs_writepage_start_hook for details on why this is required */
2080 struct btrfs_writepage_fixup {
2082 struct btrfs_work work;
2085 static void btrfs_writepage_fixup_worker(struct btrfs_work *work)
2087 struct btrfs_writepage_fixup *fixup;
2088 struct btrfs_ordered_extent *ordered;
2089 struct extent_state *cached_state = NULL;
2090 struct extent_changeset *data_reserved = NULL;
2092 struct inode *inode;
2097 fixup = container_of(work, struct btrfs_writepage_fixup, work);
2101 if (!page->mapping || !PageDirty(page) || !PageChecked(page)) {
2102 ClearPageChecked(page);
2106 inode = page->mapping->host;
2107 page_start = page_offset(page);
2108 page_end = page_offset(page) + PAGE_SIZE - 1;
2110 lock_extent_bits(&BTRFS_I(inode)->io_tree, page_start, page_end,
2113 /* already ordered? We're done */
2114 if (PagePrivate2(page))
2117 ordered = btrfs_lookup_ordered_range(BTRFS_I(inode), page_start,
2120 unlock_extent_cached(&BTRFS_I(inode)->io_tree, page_start,
2121 page_end, &cached_state);
2123 btrfs_start_ordered_extent(inode, ordered, 1);
2124 btrfs_put_ordered_extent(ordered);
2128 ret = btrfs_delalloc_reserve_space(inode, &data_reserved, page_start,
2131 mapping_set_error(page->mapping, ret);
2132 end_extent_writepage(page, ret, page_start, page_end);
2133 ClearPageChecked(page);
2137 ret = btrfs_set_extent_delalloc(inode, page_start, page_end, 0,
2140 mapping_set_error(page->mapping, ret);
2141 end_extent_writepage(page, ret, page_start, page_end);
2142 ClearPageChecked(page);
2146 ClearPageChecked(page);
2147 set_page_dirty(page);
2148 btrfs_delalloc_release_extents(BTRFS_I(inode), PAGE_SIZE, false);
2150 unlock_extent_cached(&BTRFS_I(inode)->io_tree, page_start, page_end,
2156 extent_changeset_free(data_reserved);
2160 * There are a few paths in the higher layers of the kernel that directly
2161 * set the page dirty bit without asking the filesystem if it is a
2162 * good idea. This causes problems because we want to make sure COW
2163 * properly happens and the data=ordered rules are followed.
2165 * In our case any range that doesn't have the ORDERED bit set
2166 * hasn't been properly setup for IO. We kick off an async process
2167 * to fix it up. The async helper will wait for ordered extents, set
2168 * the delalloc bit and make it safe to write the page.
2170 static int btrfs_writepage_start_hook(struct page *page, u64 start, u64 end)
2172 struct inode *inode = page->mapping->host;
2173 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2174 struct btrfs_writepage_fixup *fixup;
2176 /* this page is properly in the ordered list */
2177 if (TestClearPagePrivate2(page))
2180 if (PageChecked(page))
2183 fixup = kzalloc(sizeof(*fixup), GFP_NOFS);
2187 SetPageChecked(page);
2189 btrfs_init_work(&fixup->work, btrfs_fixup_helper,
2190 btrfs_writepage_fixup_worker, NULL, NULL);
2192 btrfs_queue_work(fs_info->fixup_workers, &fixup->work);
2196 static int insert_reserved_file_extent(struct btrfs_trans_handle *trans,
2197 struct inode *inode, u64 file_pos,
2198 u64 disk_bytenr, u64 disk_num_bytes,
2199 u64 num_bytes, u64 ram_bytes,
2200 u8 compression, u8 encryption,
2201 u16 other_encoding, int extent_type)
2203 struct btrfs_root *root = BTRFS_I(inode)->root;
2204 struct btrfs_file_extent_item *fi;
2205 struct btrfs_path *path;
2206 struct extent_buffer *leaf;
2207 struct btrfs_key ins;
2209 int extent_inserted = 0;
2212 path = btrfs_alloc_path();
2217 * we may be replacing one extent in the tree with another.
2218 * The new extent is pinned in the extent map, and we don't want
2219 * to drop it from the cache until it is completely in the btree.
2221 * So, tell btrfs_drop_extents to leave this extent in the cache.
2222 * the caller is expected to unpin it and allow it to be merged
2225 ret = __btrfs_drop_extents(trans, root, inode, path, file_pos,
2226 file_pos + num_bytes, NULL, 0,
2227 1, sizeof(*fi), &extent_inserted);
2231 if (!extent_inserted) {
2232 ins.objectid = btrfs_ino(BTRFS_I(inode));
2233 ins.offset = file_pos;
2234 ins.type = BTRFS_EXTENT_DATA_KEY;
2236 path->leave_spinning = 1;
2237 ret = btrfs_insert_empty_item(trans, root, path, &ins,
2242 leaf = path->nodes[0];
2243 fi = btrfs_item_ptr(leaf, path->slots[0],
2244 struct btrfs_file_extent_item);
2245 btrfs_set_file_extent_generation(leaf, fi, trans->transid);
2246 btrfs_set_file_extent_type(leaf, fi, extent_type);
2247 btrfs_set_file_extent_disk_bytenr(leaf, fi, disk_bytenr);
2248 btrfs_set_file_extent_disk_num_bytes(leaf, fi, disk_num_bytes);
2249 btrfs_set_file_extent_offset(leaf, fi, 0);
2250 btrfs_set_file_extent_num_bytes(leaf, fi, num_bytes);
2251 btrfs_set_file_extent_ram_bytes(leaf, fi, ram_bytes);
2252 btrfs_set_file_extent_compression(leaf, fi, compression);
2253 btrfs_set_file_extent_encryption(leaf, fi, encryption);
2254 btrfs_set_file_extent_other_encoding(leaf, fi, other_encoding);
2256 btrfs_mark_buffer_dirty(leaf);
2257 btrfs_release_path(path);
2259 inode_add_bytes(inode, num_bytes);
2261 ins.objectid = disk_bytenr;
2262 ins.offset = disk_num_bytes;
2263 ins.type = BTRFS_EXTENT_ITEM_KEY;
2266 * Release the reserved range from inode dirty range map, as it is
2267 * already moved into delayed_ref_head
2269 ret = btrfs_qgroup_release_data(inode, file_pos, ram_bytes);
2273 ret = btrfs_alloc_reserved_file_extent(trans, root,
2274 btrfs_ino(BTRFS_I(inode)),
2275 file_pos, qg_released, &ins);
2277 btrfs_free_path(path);
2282 /* snapshot-aware defrag */
2283 struct sa_defrag_extent_backref {
2284 struct rb_node node;
2285 struct old_sa_defrag_extent *old;
2294 struct old_sa_defrag_extent {
2295 struct list_head list;
2296 struct new_sa_defrag_extent *new;
2305 struct new_sa_defrag_extent {
2306 struct rb_root root;
2307 struct list_head head;
2308 struct btrfs_path *path;
2309 struct inode *inode;
2317 static int backref_comp(struct sa_defrag_extent_backref *b1,
2318 struct sa_defrag_extent_backref *b2)
2320 if (b1->root_id < b2->root_id)
2322 else if (b1->root_id > b2->root_id)
2325 if (b1->inum < b2->inum)
2327 else if (b1->inum > b2->inum)
2330 if (b1->file_pos < b2->file_pos)
2332 else if (b1->file_pos > b2->file_pos)
2336 * [------------------------------] ===> (a range of space)
2337 * |<--->| |<---->| =============> (fs/file tree A)
2338 * |<---------------------------->| ===> (fs/file tree B)
2340 * A range of space can refer to two file extents in one tree while
2341 * refer to only one file extent in another tree.
2343 * So we may process a disk offset more than one time(two extents in A)
2344 * and locate at the same extent(one extent in B), then insert two same
2345 * backrefs(both refer to the extent in B).
2350 static void backref_insert(struct rb_root *root,
2351 struct sa_defrag_extent_backref *backref)
2353 struct rb_node **p = &root->rb_node;
2354 struct rb_node *parent = NULL;
2355 struct sa_defrag_extent_backref *entry;
2360 entry = rb_entry(parent, struct sa_defrag_extent_backref, node);
2362 ret = backref_comp(backref, entry);
2366 p = &(*p)->rb_right;
2369 rb_link_node(&backref->node, parent, p);
2370 rb_insert_color(&backref->node, root);
2374 * Note the backref might has changed, and in this case we just return 0.
2376 static noinline int record_one_backref(u64 inum, u64 offset, u64 root_id,
2379 struct btrfs_file_extent_item *extent;
2380 struct old_sa_defrag_extent *old = ctx;
2381 struct new_sa_defrag_extent *new = old->new;
2382 struct btrfs_path *path = new->path;
2383 struct btrfs_key key;
2384 struct btrfs_root *root;
2385 struct sa_defrag_extent_backref *backref;
2386 struct extent_buffer *leaf;
2387 struct inode *inode = new->inode;
2388 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2394 if (BTRFS_I(inode)->root->root_key.objectid == root_id &&
2395 inum == btrfs_ino(BTRFS_I(inode)))
2398 key.objectid = root_id;
2399 key.type = BTRFS_ROOT_ITEM_KEY;
2400 key.offset = (u64)-1;
2402 root = btrfs_read_fs_root_no_name(fs_info, &key);
2404 if (PTR_ERR(root) == -ENOENT)
2407 btrfs_debug(fs_info, "inum=%llu, offset=%llu, root_id=%llu",
2408 inum, offset, root_id);
2409 return PTR_ERR(root);
2412 key.objectid = inum;
2413 key.type = BTRFS_EXTENT_DATA_KEY;
2414 if (offset > (u64)-1 << 32)
2417 key.offset = offset;
2419 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2420 if (WARN_ON(ret < 0))
2427 leaf = path->nodes[0];
2428 slot = path->slots[0];
2430 if (slot >= btrfs_header_nritems(leaf)) {
2431 ret = btrfs_next_leaf(root, path);
2434 } else if (ret > 0) {
2443 btrfs_item_key_to_cpu(leaf, &key, slot);
2445 if (key.objectid > inum)
2448 if (key.objectid < inum || key.type != BTRFS_EXTENT_DATA_KEY)
2451 extent = btrfs_item_ptr(leaf, slot,
2452 struct btrfs_file_extent_item);
2454 if (btrfs_file_extent_disk_bytenr(leaf, extent) != old->bytenr)
2458 * 'offset' refers to the exact key.offset,
2459 * NOT the 'offset' field in btrfs_extent_data_ref, ie.
2460 * (key.offset - extent_offset).
2462 if (key.offset != offset)
2465 extent_offset = btrfs_file_extent_offset(leaf, extent);
2466 num_bytes = btrfs_file_extent_num_bytes(leaf, extent);
2468 if (extent_offset >= old->extent_offset + old->offset +
2469 old->len || extent_offset + num_bytes <=
2470 old->extent_offset + old->offset)
2475 backref = kmalloc(sizeof(*backref), GFP_NOFS);
2481 backref->root_id = root_id;
2482 backref->inum = inum;
2483 backref->file_pos = offset;
2484 backref->num_bytes = num_bytes;
2485 backref->extent_offset = extent_offset;
2486 backref->generation = btrfs_file_extent_generation(leaf, extent);
2488 backref_insert(&new->root, backref);
2491 btrfs_release_path(path);
2496 static noinline bool record_extent_backrefs(struct btrfs_path *path,
2497 struct new_sa_defrag_extent *new)
2499 struct btrfs_fs_info *fs_info = btrfs_sb(new->inode->i_sb);
2500 struct old_sa_defrag_extent *old, *tmp;
2505 list_for_each_entry_safe(old, tmp, &new->head, list) {
2506 ret = iterate_inodes_from_logical(old->bytenr +
2507 old->extent_offset, fs_info,
2508 path, record_one_backref,
2510 if (ret < 0 && ret != -ENOENT)
2513 /* no backref to be processed for this extent */
2515 list_del(&old->list);
2520 if (list_empty(&new->head))
2526 static int relink_is_mergable(struct extent_buffer *leaf,
2527 struct btrfs_file_extent_item *fi,
2528 struct new_sa_defrag_extent *new)
2530 if (btrfs_file_extent_disk_bytenr(leaf, fi) != new->bytenr)
2533 if (btrfs_file_extent_type(leaf, fi) != BTRFS_FILE_EXTENT_REG)
2536 if (btrfs_file_extent_compression(leaf, fi) != new->compress_type)
2539 if (btrfs_file_extent_encryption(leaf, fi) ||
2540 btrfs_file_extent_other_encoding(leaf, fi))
2547 * Note the backref might has changed, and in this case we just return 0.
2549 static noinline int relink_extent_backref(struct btrfs_path *path,
2550 struct sa_defrag_extent_backref *prev,
2551 struct sa_defrag_extent_backref *backref)
2553 struct btrfs_file_extent_item *extent;
2554 struct btrfs_file_extent_item *item;
2555 struct btrfs_ordered_extent *ordered;
2556 struct btrfs_trans_handle *trans;
2557 struct btrfs_root *root;
2558 struct btrfs_key key;
2559 struct extent_buffer *leaf;
2560 struct old_sa_defrag_extent *old = backref->old;
2561 struct new_sa_defrag_extent *new = old->new;
2562 struct btrfs_fs_info *fs_info = btrfs_sb(new->inode->i_sb);
2563 struct inode *inode;
2564 struct extent_state *cached = NULL;
2573 if (prev && prev->root_id == backref->root_id &&
2574 prev->inum == backref->inum &&
2575 prev->file_pos + prev->num_bytes == backref->file_pos)
2578 /* step 1: get root */
2579 key.objectid = backref->root_id;
2580 key.type = BTRFS_ROOT_ITEM_KEY;
2581 key.offset = (u64)-1;
2583 index = srcu_read_lock(&fs_info->subvol_srcu);
2585 root = btrfs_read_fs_root_no_name(fs_info, &key);
2587 srcu_read_unlock(&fs_info->subvol_srcu, index);
2588 if (PTR_ERR(root) == -ENOENT)
2590 return PTR_ERR(root);
2593 if (btrfs_root_readonly(root)) {
2594 srcu_read_unlock(&fs_info->subvol_srcu, index);
2598 /* step 2: get inode */
2599 key.objectid = backref->inum;
2600 key.type = BTRFS_INODE_ITEM_KEY;
2603 inode = btrfs_iget(fs_info->sb, &key, root, NULL);
2604 if (IS_ERR(inode)) {
2605 srcu_read_unlock(&fs_info->subvol_srcu, index);
2609 srcu_read_unlock(&fs_info->subvol_srcu, index);
2611 /* step 3: relink backref */
2612 lock_start = backref->file_pos;
2613 lock_end = backref->file_pos + backref->num_bytes - 1;
2614 lock_extent_bits(&BTRFS_I(inode)->io_tree, lock_start, lock_end,
2617 ordered = btrfs_lookup_first_ordered_extent(inode, lock_end);
2619 btrfs_put_ordered_extent(ordered);
2623 trans = btrfs_join_transaction(root);
2624 if (IS_ERR(trans)) {
2625 ret = PTR_ERR(trans);
2629 key.objectid = backref->inum;
2630 key.type = BTRFS_EXTENT_DATA_KEY;
2631 key.offset = backref->file_pos;
2633 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2636 } else if (ret > 0) {
2641 extent = btrfs_item_ptr(path->nodes[0], path->slots[0],
2642 struct btrfs_file_extent_item);
2644 if (btrfs_file_extent_generation(path->nodes[0], extent) !=
2645 backref->generation)
2648 btrfs_release_path(path);
2650 start = backref->file_pos;
2651 if (backref->extent_offset < old->extent_offset + old->offset)
2652 start += old->extent_offset + old->offset -
2653 backref->extent_offset;
2655 len = min(backref->extent_offset + backref->num_bytes,
2656 old->extent_offset + old->offset + old->len);
2657 len -= max(backref->extent_offset, old->extent_offset + old->offset);
2659 ret = btrfs_drop_extents(trans, root, inode, start,
2664 key.objectid = btrfs_ino(BTRFS_I(inode));
2665 key.type = BTRFS_EXTENT_DATA_KEY;
2668 path->leave_spinning = 1;
2670 struct btrfs_file_extent_item *fi;
2672 struct btrfs_key found_key;
2674 ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
2679 leaf = path->nodes[0];
2680 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
2682 fi = btrfs_item_ptr(leaf, path->slots[0],
2683 struct btrfs_file_extent_item);
2684 extent_len = btrfs_file_extent_num_bytes(leaf, fi);
2686 if (extent_len + found_key.offset == start &&
2687 relink_is_mergable(leaf, fi, new)) {
2688 btrfs_set_file_extent_num_bytes(leaf, fi,
2690 btrfs_mark_buffer_dirty(leaf);
2691 inode_add_bytes(inode, len);
2697 btrfs_release_path(path);
2702 ret = btrfs_insert_empty_item(trans, root, path, &key,
2705 btrfs_abort_transaction(trans, ret);
2709 leaf = path->nodes[0];
2710 item = btrfs_item_ptr(leaf, path->slots[0],
2711 struct btrfs_file_extent_item);
2712 btrfs_set_file_extent_disk_bytenr(leaf, item, new->bytenr);
2713 btrfs_set_file_extent_disk_num_bytes(leaf, item, new->disk_len);
2714 btrfs_set_file_extent_offset(leaf, item, start - new->file_pos);
2715 btrfs_set_file_extent_num_bytes(leaf, item, len);
2716 btrfs_set_file_extent_ram_bytes(leaf, item, new->len);
2717 btrfs_set_file_extent_generation(leaf, item, trans->transid);
2718 btrfs_set_file_extent_type(leaf, item, BTRFS_FILE_EXTENT_REG);
2719 btrfs_set_file_extent_compression(leaf, item, new->compress_type);
2720 btrfs_set_file_extent_encryption(leaf, item, 0);
2721 btrfs_set_file_extent_other_encoding(leaf, item, 0);
2723 btrfs_mark_buffer_dirty(leaf);
2724 inode_add_bytes(inode, len);
2725 btrfs_release_path(path);
2727 ret = btrfs_inc_extent_ref(trans, root, new->bytenr,
2729 backref->root_id, backref->inum,
2730 new->file_pos); /* start - extent_offset */
2732 btrfs_abort_transaction(trans, ret);
2738 btrfs_release_path(path);
2739 path->leave_spinning = 0;
2740 btrfs_end_transaction(trans);
2742 unlock_extent_cached(&BTRFS_I(inode)->io_tree, lock_start, lock_end,
2748 static void free_sa_defrag_extent(struct new_sa_defrag_extent *new)
2750 struct old_sa_defrag_extent *old, *tmp;
2755 list_for_each_entry_safe(old, tmp, &new->head, list) {
2761 static void relink_file_extents(struct new_sa_defrag_extent *new)
2763 struct btrfs_fs_info *fs_info = btrfs_sb(new->inode->i_sb);
2764 struct btrfs_path *path;
2765 struct sa_defrag_extent_backref *backref;
2766 struct sa_defrag_extent_backref *prev = NULL;
2767 struct inode *inode;
2768 struct rb_node *node;
2773 path = btrfs_alloc_path();
2777 if (!record_extent_backrefs(path, new)) {
2778 btrfs_free_path(path);
2781 btrfs_release_path(path);
2784 node = rb_first(&new->root);
2787 rb_erase(node, &new->root);
2789 backref = rb_entry(node, struct sa_defrag_extent_backref, node);
2791 ret = relink_extent_backref(path, prev, backref);
2804 btrfs_free_path(path);
2806 free_sa_defrag_extent(new);
2808 atomic_dec(&fs_info->defrag_running);
2809 wake_up(&fs_info->transaction_wait);
2812 static struct new_sa_defrag_extent *
2813 record_old_file_extents(struct inode *inode,
2814 struct btrfs_ordered_extent *ordered)
2816 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2817 struct btrfs_root *root = BTRFS_I(inode)->root;
2818 struct btrfs_path *path;
2819 struct btrfs_key key;
2820 struct old_sa_defrag_extent *old;
2821 struct new_sa_defrag_extent *new;
2824 new = kmalloc(sizeof(*new), GFP_NOFS);
2829 new->file_pos = ordered->file_offset;
2830 new->len = ordered->len;
2831 new->bytenr = ordered->start;
2832 new->disk_len = ordered->disk_len;
2833 new->compress_type = ordered->compress_type;
2834 new->root = RB_ROOT;
2835 INIT_LIST_HEAD(&new->head);
2837 path = btrfs_alloc_path();
2841 key.objectid = btrfs_ino(BTRFS_I(inode));
2842 key.type = BTRFS_EXTENT_DATA_KEY;
2843 key.offset = new->file_pos;
2845 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2848 if (ret > 0 && path->slots[0] > 0)
2851 /* find out all the old extents for the file range */
2853 struct btrfs_file_extent_item *extent;
2854 struct extent_buffer *l;
2863 slot = path->slots[0];
2865 if (slot >= btrfs_header_nritems(l)) {
2866 ret = btrfs_next_leaf(root, path);
2874 btrfs_item_key_to_cpu(l, &key, slot);
2876 if (key.objectid != btrfs_ino(BTRFS_I(inode)))
2878 if (key.type != BTRFS_EXTENT_DATA_KEY)
2880 if (key.offset >= new->file_pos + new->len)
2883 extent = btrfs_item_ptr(l, slot, struct btrfs_file_extent_item);
2885 num_bytes = btrfs_file_extent_num_bytes(l, extent);
2886 if (key.offset + num_bytes < new->file_pos)
2889 disk_bytenr = btrfs_file_extent_disk_bytenr(l, extent);
2893 extent_offset = btrfs_file_extent_offset(l, extent);
2895 old = kmalloc(sizeof(*old), GFP_NOFS);
2899 offset = max(new->file_pos, key.offset);
2900 end = min(new->file_pos + new->len, key.offset + num_bytes);
2902 old->bytenr = disk_bytenr;
2903 old->extent_offset = extent_offset;
2904 old->offset = offset - key.offset;
2905 old->len = end - offset;
2908 list_add_tail(&old->list, &new->head);
2914 btrfs_free_path(path);
2915 atomic_inc(&fs_info->defrag_running);
2920 btrfs_free_path(path);
2922 free_sa_defrag_extent(new);
2926 static void btrfs_release_delalloc_bytes(struct btrfs_fs_info *fs_info,
2929 struct btrfs_block_group_cache *cache;
2931 cache = btrfs_lookup_block_group(fs_info, start);
2934 spin_lock(&cache->lock);
2935 cache->delalloc_bytes -= len;
2936 spin_unlock(&cache->lock);
2938 btrfs_put_block_group(cache);
2941 /* as ordered data IO finishes, this gets called so we can finish
2942 * an ordered extent if the range of bytes in the file it covers are
2945 static int btrfs_finish_ordered_io(struct btrfs_ordered_extent *ordered_extent)
2947 struct inode *inode = ordered_extent->inode;
2948 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2949 struct btrfs_root *root = BTRFS_I(inode)->root;
2950 struct btrfs_trans_handle *trans = NULL;
2951 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
2952 struct extent_state *cached_state = NULL;
2953 struct new_sa_defrag_extent *new = NULL;
2954 int compress_type = 0;
2956 u64 logical_len = ordered_extent->len;
2958 bool truncated = false;
2959 bool range_locked = false;
2960 bool clear_new_delalloc_bytes = false;
2962 if (!test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags) &&
2963 !test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags) &&
2964 !test_bit(BTRFS_ORDERED_DIRECT, &ordered_extent->flags))
2965 clear_new_delalloc_bytes = true;
2967 nolock = btrfs_is_free_space_inode(BTRFS_I(inode));
2969 if (test_bit(BTRFS_ORDERED_IOERR, &ordered_extent->flags)) {
2974 btrfs_free_io_failure_record(BTRFS_I(inode),
2975 ordered_extent->file_offset,
2976 ordered_extent->file_offset +
2977 ordered_extent->len - 1);
2979 if (test_bit(BTRFS_ORDERED_TRUNCATED, &ordered_extent->flags)) {
2981 logical_len = ordered_extent->truncated_len;
2982 /* Truncated the entire extent, don't bother adding */
2987 if (test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags)) {
2988 BUG_ON(!list_empty(&ordered_extent->list)); /* Logic error */
2991 * For mwrite(mmap + memset to write) case, we still reserve
2992 * space for NOCOW range.
2993 * As NOCOW won't cause a new delayed ref, just free the space
2995 btrfs_qgroup_free_data(inode, NULL, ordered_extent->file_offset,
2996 ordered_extent->len);
2997 btrfs_ordered_update_i_size(inode, 0, ordered_extent);
2999 trans = btrfs_join_transaction_nolock(root);
3001 trans = btrfs_join_transaction(root);
3002 if (IS_ERR(trans)) {
3003 ret = PTR_ERR(trans);
3007 trans->block_rsv = &BTRFS_I(inode)->block_rsv;
3008 ret = btrfs_update_inode_fallback(trans, root, inode);
3009 if (ret) /* -ENOMEM or corruption */
3010 btrfs_abort_transaction(trans, ret);
3014 range_locked = true;
3015 lock_extent_bits(io_tree, ordered_extent->file_offset,
3016 ordered_extent->file_offset + ordered_extent->len - 1,
3019 ret = test_range_bit(io_tree, ordered_extent->file_offset,
3020 ordered_extent->file_offset + ordered_extent->len - 1,
3021 EXTENT_DEFRAG, 0, cached_state);
3023 u64 last_snapshot = btrfs_root_last_snapshot(&root->root_item);
3024 if (0 && last_snapshot >= BTRFS_I(inode)->generation)
3025 /* the inode is shared */
3026 new = record_old_file_extents(inode, ordered_extent);
3028 clear_extent_bit(io_tree, ordered_extent->file_offset,
3029 ordered_extent->file_offset + ordered_extent->len - 1,
3030 EXTENT_DEFRAG, 0, 0, &cached_state);
3034 trans = btrfs_join_transaction_nolock(root);
3036 trans = btrfs_join_transaction(root);
3037 if (IS_ERR(trans)) {
3038 ret = PTR_ERR(trans);
3043 trans->block_rsv = &BTRFS_I(inode)->block_rsv;
3045 if (test_bit(BTRFS_ORDERED_COMPRESSED, &ordered_extent->flags))
3046 compress_type = ordered_extent->compress_type;
3047 if (test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags)) {
3048 BUG_ON(compress_type);
3049 btrfs_qgroup_free_data(inode, NULL, ordered_extent->file_offset,
3050 ordered_extent->len);
3051 ret = btrfs_mark_extent_written(trans, BTRFS_I(inode),
3052 ordered_extent->file_offset,
3053 ordered_extent->file_offset +
3056 BUG_ON(root == fs_info->tree_root);
3057 ret = insert_reserved_file_extent(trans, inode,
3058 ordered_extent->file_offset,
3059 ordered_extent->start,
3060 ordered_extent->disk_len,
3061 logical_len, logical_len,
3062 compress_type, 0, 0,
3063 BTRFS_FILE_EXTENT_REG);
3065 btrfs_release_delalloc_bytes(fs_info,
3066 ordered_extent->start,
3067 ordered_extent->disk_len);
3069 unpin_extent_cache(&BTRFS_I(inode)->extent_tree,
3070 ordered_extent->file_offset, ordered_extent->len,
3073 btrfs_abort_transaction(trans, ret);
3077 ret = add_pending_csums(trans, inode, &ordered_extent->list);
3079 btrfs_abort_transaction(trans, ret);
3083 btrfs_ordered_update_i_size(inode, 0, ordered_extent);
3084 ret = btrfs_update_inode_fallback(trans, root, inode);
3085 if (ret) { /* -ENOMEM or corruption */
3086 btrfs_abort_transaction(trans, ret);
3091 if (range_locked || clear_new_delalloc_bytes) {
3092 unsigned int clear_bits = 0;
3095 clear_bits |= EXTENT_LOCKED;
3096 if (clear_new_delalloc_bytes)
3097 clear_bits |= EXTENT_DELALLOC_NEW;
3098 clear_extent_bit(&BTRFS_I(inode)->io_tree,
3099 ordered_extent->file_offset,
3100 ordered_extent->file_offset +
3101 ordered_extent->len - 1,
3103 (clear_bits & EXTENT_LOCKED) ? 1 : 0,
3108 btrfs_end_transaction(trans);
3110 if (ret || truncated) {
3114 start = ordered_extent->file_offset + logical_len;
3116 start = ordered_extent->file_offset;
3117 end = ordered_extent->file_offset + ordered_extent->len - 1;
3118 clear_extent_uptodate(io_tree, start, end, NULL);
3120 /* Drop the cache for the part of the extent we didn't write. */
3121 btrfs_drop_extent_cache(BTRFS_I(inode), start, end, 0);
3124 * If the ordered extent had an IOERR or something else went
3125 * wrong we need to return the space for this ordered extent
3126 * back to the allocator. We only free the extent in the
3127 * truncated case if we didn't write out the extent at all.
3129 if ((ret || !logical_len) &&
3130 !test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags) &&
3131 !test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags))
3132 btrfs_free_reserved_extent(fs_info,
3133 ordered_extent->start,
3134 ordered_extent->disk_len, 1);
3139 * This needs to be done to make sure anybody waiting knows we are done
3140 * updating everything for this ordered extent.
3142 btrfs_remove_ordered_extent(inode, ordered_extent);
3144 /* for snapshot-aware defrag */
3147 free_sa_defrag_extent(new);
3148 atomic_dec(&fs_info->defrag_running);
3150 relink_file_extents(new);
3155 btrfs_put_ordered_extent(ordered_extent);
3156 /* once for the tree */
3157 btrfs_put_ordered_extent(ordered_extent);
3162 static void finish_ordered_fn(struct btrfs_work *work)
3164 struct btrfs_ordered_extent *ordered_extent;
3165 ordered_extent = container_of(work, struct btrfs_ordered_extent, work);
3166 btrfs_finish_ordered_io(ordered_extent);
3169 static void btrfs_writepage_end_io_hook(struct page *page, u64 start, u64 end,
3170 struct extent_state *state, int uptodate)
3172 struct inode *inode = page->mapping->host;
3173 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
3174 struct btrfs_ordered_extent *ordered_extent = NULL;
3175 struct btrfs_workqueue *wq;
3176 btrfs_work_func_t func;
3178 trace_btrfs_writepage_end_io_hook(page, start, end, uptodate);
3180 ClearPagePrivate2(page);
3181 if (!btrfs_dec_test_ordered_pending(inode, &ordered_extent, start,
3182 end - start + 1, uptodate))
3185 if (btrfs_is_free_space_inode(BTRFS_I(inode))) {
3186 wq = fs_info->endio_freespace_worker;
3187 func = btrfs_freespace_write_helper;
3189 wq = fs_info->endio_write_workers;
3190 func = btrfs_endio_write_helper;
3193 btrfs_init_work(&ordered_extent->work, func, finish_ordered_fn, NULL,
3195 btrfs_queue_work(wq, &ordered_extent->work);
3198 static int __readpage_endio_check(struct inode *inode,
3199 struct btrfs_io_bio *io_bio,
3200 int icsum, struct page *page,
3201 int pgoff, u64 start, size_t len)
3207 csum_expected = *(((u32 *)io_bio->csum) + icsum);
3209 kaddr = kmap_atomic(page);
3210 csum = btrfs_csum_data(kaddr + pgoff, csum, len);
3211 btrfs_csum_final(csum, (u8 *)&csum);
3212 if (csum != csum_expected)
3215 kunmap_atomic(kaddr);
3218 btrfs_print_data_csum_error(BTRFS_I(inode), start, csum, csum_expected,
3219 io_bio->mirror_num);
3220 memset(kaddr + pgoff, 1, len);
3221 flush_dcache_page(page);
3222 kunmap_atomic(kaddr);
3227 * when reads are done, we need to check csums to verify the data is correct
3228 * if there's a match, we allow the bio to finish. If not, the code in
3229 * extent_io.c will try to find good copies for us.
3231 static int btrfs_readpage_end_io_hook(struct btrfs_io_bio *io_bio,
3232 u64 phy_offset, struct page *page,
3233 u64 start, u64 end, int mirror)
3235 size_t offset = start - page_offset(page);
3236 struct inode *inode = page->mapping->host;
3237 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
3238 struct btrfs_root *root = BTRFS_I(inode)->root;
3240 if (PageChecked(page)) {
3241 ClearPageChecked(page);
3245 if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)
3248 if (root->root_key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID &&
3249 test_range_bit(io_tree, start, end, EXTENT_NODATASUM, 1, NULL)) {
3250 clear_extent_bits(io_tree, start, end, EXTENT_NODATASUM);
3254 phy_offset >>= inode->i_sb->s_blocksize_bits;
3255 return __readpage_endio_check(inode, io_bio, phy_offset, page, offset,
3256 start, (size_t)(end - start + 1));
3260 * btrfs_add_delayed_iput - perform a delayed iput on @inode
3262 * @inode: The inode we want to perform iput on
3264 * This function uses the generic vfs_inode::i_count to track whether we should
3265 * just decrement it (in case it's > 1) or if this is the last iput then link
3266 * the inode to the delayed iput machinery. Delayed iputs are processed at
3267 * transaction commit time/superblock commit/cleaner kthread.
3269 void btrfs_add_delayed_iput(struct inode *inode)
3271 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
3272 struct btrfs_inode *binode = BTRFS_I(inode);
3274 if (atomic_add_unless(&inode->i_count, -1, 1))
3277 spin_lock(&fs_info->delayed_iput_lock);
3278 ASSERT(list_empty(&binode->delayed_iput));
3279 list_add_tail(&binode->delayed_iput, &fs_info->delayed_iputs);
3280 spin_unlock(&fs_info->delayed_iput_lock);
3283 void btrfs_run_delayed_iputs(struct btrfs_fs_info *fs_info)
3286 spin_lock(&fs_info->delayed_iput_lock);
3287 while (!list_empty(&fs_info->delayed_iputs)) {
3288 struct btrfs_inode *inode;
3290 inode = list_first_entry(&fs_info->delayed_iputs,
3291 struct btrfs_inode, delayed_iput);
3292 list_del_init(&inode->delayed_iput);
3293 spin_unlock(&fs_info->delayed_iput_lock);
3294 iput(&inode->vfs_inode);
3295 spin_lock(&fs_info->delayed_iput_lock);
3297 spin_unlock(&fs_info->delayed_iput_lock);
3301 * This creates an orphan entry for the given inode in case something goes wrong
3302 * in the middle of an unlink.
3304 int btrfs_orphan_add(struct btrfs_trans_handle *trans,
3305 struct btrfs_inode *inode)
3309 ret = btrfs_insert_orphan_item(trans, inode->root, btrfs_ino(inode));
3310 if (ret && ret != -EEXIST) {
3311 btrfs_abort_transaction(trans, ret);
3319 * We have done the delete so we can go ahead and remove the orphan item for
3320 * this particular inode.
3322 static int btrfs_orphan_del(struct btrfs_trans_handle *trans,
3323 struct btrfs_inode *inode)
3325 return btrfs_del_orphan_item(trans, inode->root, btrfs_ino(inode));
3329 * this cleans up any orphans that may be left on the list from the last use
3332 int btrfs_orphan_cleanup(struct btrfs_root *root)
3334 struct btrfs_fs_info *fs_info = root->fs_info;
3335 struct btrfs_path *path;
3336 struct extent_buffer *leaf;
3337 struct btrfs_key key, found_key;
3338 struct btrfs_trans_handle *trans;
3339 struct inode *inode;
3340 u64 last_objectid = 0;
3341 int ret = 0, nr_unlink = 0;
3343 if (cmpxchg(&root->orphan_cleanup_state, 0, ORPHAN_CLEANUP_STARTED))
3346 path = btrfs_alloc_path();
3351 path->reada = READA_BACK;
3353 key.objectid = BTRFS_ORPHAN_OBJECTID;
3354 key.type = BTRFS_ORPHAN_ITEM_KEY;
3355 key.offset = (u64)-1;
3358 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
3363 * if ret == 0 means we found what we were searching for, which
3364 * is weird, but possible, so only screw with path if we didn't
3365 * find the key and see if we have stuff that matches
3369 if (path->slots[0] == 0)
3374 /* pull out the item */
3375 leaf = path->nodes[0];
3376 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
3378 /* make sure the item matches what we want */
3379 if (found_key.objectid != BTRFS_ORPHAN_OBJECTID)
3381 if (found_key.type != BTRFS_ORPHAN_ITEM_KEY)
3384 /* release the path since we're done with it */
3385 btrfs_release_path(path);
3388 * this is where we are basically btrfs_lookup, without the
3389 * crossing root thing. we store the inode number in the
3390 * offset of the orphan item.
3393 if (found_key.offset == last_objectid) {
3395 "Error removing orphan entry, stopping orphan cleanup");
3400 last_objectid = found_key.offset;
3402 found_key.objectid = found_key.offset;
3403 found_key.type = BTRFS_INODE_ITEM_KEY;
3404 found_key.offset = 0;
3405 inode = btrfs_iget(fs_info->sb, &found_key, root, NULL);
3406 ret = PTR_ERR_OR_ZERO(inode);
3407 if (ret && ret != -ENOENT)
3410 if (ret == -ENOENT && root == fs_info->tree_root) {
3411 struct btrfs_root *dead_root;
3412 struct btrfs_fs_info *fs_info = root->fs_info;
3413 int is_dead_root = 0;
3416 * this is an orphan in the tree root. Currently these
3417 * could come from 2 sources:
3418 * a) a snapshot deletion in progress
3419 * b) a free space cache inode
3420 * We need to distinguish those two, as the snapshot
3421 * orphan must not get deleted.
3422 * find_dead_roots already ran before us, so if this
3423 * is a snapshot deletion, we should find the root
3424 * in the dead_roots list
3426 spin_lock(&fs_info->trans_lock);
3427 list_for_each_entry(dead_root, &fs_info->dead_roots,
3429 if (dead_root->root_key.objectid ==
3430 found_key.objectid) {
3435 spin_unlock(&fs_info->trans_lock);
3437 /* prevent this orphan from being found again */
3438 key.offset = found_key.objectid - 1;
3445 * If we have an inode with links, there are a couple of
3446 * possibilities. Old kernels (before v3.12) used to create an
3447 * orphan item for truncate indicating that there were possibly
3448 * extent items past i_size that needed to be deleted. In v3.12,
3449 * truncate was changed to update i_size in sync with the extent
3450 * items, but the (useless) orphan item was still created. Since
3451 * v4.18, we don't create the orphan item for truncate at all.
3453 * So, this item could mean that we need to do a truncate, but
3454 * only if this filesystem was last used on a pre-v3.12 kernel
3455 * and was not cleanly unmounted. The odds of that are quite
3456 * slim, and it's a pain to do the truncate now, so just delete
3459 * It's also possible that this orphan item was supposed to be
3460 * deleted but wasn't. The inode number may have been reused,
3461 * but either way, we can delete the orphan item.
3463 if (ret == -ENOENT || inode->i_nlink) {
3466 trans = btrfs_start_transaction(root, 1);
3467 if (IS_ERR(trans)) {
3468 ret = PTR_ERR(trans);
3471 btrfs_debug(fs_info, "auto deleting %Lu",
3472 found_key.objectid);
3473 ret = btrfs_del_orphan_item(trans, root,
3474 found_key.objectid);
3475 btrfs_end_transaction(trans);
3483 /* this will do delete_inode and everything for us */
3488 /* release the path since we're done with it */
3489 btrfs_release_path(path);
3491 root->orphan_cleanup_state = ORPHAN_CLEANUP_DONE;
3493 if (test_bit(BTRFS_ROOT_ORPHAN_ITEM_INSERTED, &root->state)) {
3494 trans = btrfs_join_transaction(root);
3496 btrfs_end_transaction(trans);
3500 btrfs_debug(fs_info, "unlinked %d orphans", nr_unlink);
3504 btrfs_err(fs_info, "could not do orphan cleanup %d", ret);
3505 btrfs_free_path(path);
3510 * very simple check to peek ahead in the leaf looking for xattrs. If we
3511 * don't find any xattrs, we know there can't be any acls.
3513 * slot is the slot the inode is in, objectid is the objectid of the inode
3515 static noinline int acls_after_inode_item(struct extent_buffer *leaf,
3516 int slot, u64 objectid,
3517 int *first_xattr_slot)
3519 u32 nritems = btrfs_header_nritems(leaf);
3520 struct btrfs_key found_key;
3521 static u64 xattr_access = 0;
3522 static u64 xattr_default = 0;
3525 if (!xattr_access) {
3526 xattr_access = btrfs_name_hash(XATTR_NAME_POSIX_ACL_ACCESS,
3527 strlen(XATTR_NAME_POSIX_ACL_ACCESS));
3528 xattr_default = btrfs_name_hash(XATTR_NAME_POSIX_ACL_DEFAULT,
3529 strlen(XATTR_NAME_POSIX_ACL_DEFAULT));
3533 *first_xattr_slot = -1;
3534 while (slot < nritems) {
3535 btrfs_item_key_to_cpu(leaf, &found_key, slot);
3537 /* we found a different objectid, there must not be acls */
3538 if (found_key.objectid != objectid)
3541 /* we found an xattr, assume we've got an acl */
3542 if (found_key.type == BTRFS_XATTR_ITEM_KEY) {
3543 if (*first_xattr_slot == -1)
3544 *first_xattr_slot = slot;
3545 if (found_key.offset == xattr_access ||
3546 found_key.offset == xattr_default)
3551 * we found a key greater than an xattr key, there can't
3552 * be any acls later on
3554 if (found_key.type > BTRFS_XATTR_ITEM_KEY)
3561 * it goes inode, inode backrefs, xattrs, extents,
3562 * so if there are a ton of hard links to an inode there can
3563 * be a lot of backrefs. Don't waste time searching too hard,
3564 * this is just an optimization
3569 /* we hit the end of the leaf before we found an xattr or
3570 * something larger than an xattr. We have to assume the inode
3573 if (*first_xattr_slot == -1)
3574 *first_xattr_slot = slot;
3579 * read an inode from the btree into the in-memory inode
3581 static int btrfs_read_locked_inode(struct inode *inode)
3583 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
3584 struct btrfs_path *path;
3585 struct extent_buffer *leaf;
3586 struct btrfs_inode_item *inode_item;
3587 struct btrfs_root *root = BTRFS_I(inode)->root;
3588 struct btrfs_key location;
3593 bool filled = false;
3594 int first_xattr_slot;
3596 ret = btrfs_fill_inode(inode, &rdev);
3600 path = btrfs_alloc_path();
3606 memcpy(&location, &BTRFS_I(inode)->location, sizeof(location));
3608 ret = btrfs_lookup_inode(NULL, root, path, &location, 0);
3615 leaf = path->nodes[0];
3620 inode_item = btrfs_item_ptr(leaf, path->slots[0],
3621 struct btrfs_inode_item);
3622 inode->i_mode = btrfs_inode_mode(leaf, inode_item);
3623 set_nlink(inode, btrfs_inode_nlink(leaf, inode_item));
3624 i_uid_write(inode, btrfs_inode_uid(leaf, inode_item));
3625 i_gid_write(inode, btrfs_inode_gid(leaf, inode_item));
3626 btrfs_i_size_write(BTRFS_I(inode), btrfs_inode_size(leaf, inode_item));
3628 inode->i_atime.tv_sec = btrfs_timespec_sec(leaf, &inode_item->atime);
3629 inode->i_atime.tv_nsec = btrfs_timespec_nsec(leaf, &inode_item->atime);
3631 inode->i_mtime.tv_sec = btrfs_timespec_sec(leaf, &inode_item->mtime);
3632 inode->i_mtime.tv_nsec = btrfs_timespec_nsec(leaf, &inode_item->mtime);
3634 inode->i_ctime.tv_sec = btrfs_timespec_sec(leaf, &inode_item->ctime);
3635 inode->i_ctime.tv_nsec = btrfs_timespec_nsec(leaf, &inode_item->ctime);
3637 BTRFS_I(inode)->i_otime.tv_sec =
3638 btrfs_timespec_sec(leaf, &inode_item->otime);
3639 BTRFS_I(inode)->i_otime.tv_nsec =
3640 btrfs_timespec_nsec(leaf, &inode_item->otime);
3642 inode_set_bytes(inode, btrfs_inode_nbytes(leaf, inode_item));
3643 BTRFS_I(inode)->generation = btrfs_inode_generation(leaf, inode_item);
3644 BTRFS_I(inode)->last_trans = btrfs_inode_transid(leaf, inode_item);
3646 inode_set_iversion_queried(inode,
3647 btrfs_inode_sequence(leaf, inode_item));
3648 inode->i_generation = BTRFS_I(inode)->generation;
3650 rdev = btrfs_inode_rdev(leaf, inode_item);
3652 BTRFS_I(inode)->index_cnt = (u64)-1;
3653 BTRFS_I(inode)->flags = btrfs_inode_flags(leaf, inode_item);
3657 * If we were modified in the current generation and evicted from memory
3658 * and then re-read we need to do a full sync since we don't have any
3659 * idea about which extents were modified before we were evicted from
3662 * This is required for both inode re-read from disk and delayed inode
3663 * in delayed_nodes_tree.
3665 if (BTRFS_I(inode)->last_trans == fs_info->generation)
3666 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
3667 &BTRFS_I(inode)->runtime_flags);
3670 * We don't persist the id of the transaction where an unlink operation
3671 * against the inode was last made. So here we assume the inode might
3672 * have been evicted, and therefore the exact value of last_unlink_trans
3673 * lost, and set it to last_trans to avoid metadata inconsistencies
3674 * between the inode and its parent if the inode is fsync'ed and the log
3675 * replayed. For example, in the scenario:
3678 * ln mydir/foo mydir/bar
3681 * echo 2 > /proc/sys/vm/drop_caches # evicts inode
3682 * xfs_io -c fsync mydir/foo
3684 * mount fs, triggers fsync log replay
3686 * We must make sure that when we fsync our inode foo we also log its
3687 * parent inode, otherwise after log replay the parent still has the
3688 * dentry with the "bar" name but our inode foo has a link count of 1
3689 * and doesn't have an inode ref with the name "bar" anymore.
3691 * Setting last_unlink_trans to last_trans is a pessimistic approach,
3692 * but it guarantees correctness at the expense of occasional full
3693 * transaction commits on fsync if our inode is a directory, or if our
3694 * inode is not a directory, logging its parent unnecessarily.
3696 BTRFS_I(inode)->last_unlink_trans = BTRFS_I(inode)->last_trans;
3699 if (inode->i_nlink != 1 ||
3700 path->slots[0] >= btrfs_header_nritems(leaf))
3703 btrfs_item_key_to_cpu(leaf, &location, path->slots[0]);
3704 if (location.objectid != btrfs_ino(BTRFS_I(inode)))
3707 ptr = btrfs_item_ptr_offset(leaf, path->slots[0]);
3708 if (location.type == BTRFS_INODE_REF_KEY) {
3709 struct btrfs_inode_ref *ref;
3711 ref = (struct btrfs_inode_ref *)ptr;
3712 BTRFS_I(inode)->dir_index = btrfs_inode_ref_index(leaf, ref);
3713 } else if (location.type == BTRFS_INODE_EXTREF_KEY) {
3714 struct btrfs_inode_extref *extref;
3716 extref = (struct btrfs_inode_extref *)ptr;
3717 BTRFS_I(inode)->dir_index = btrfs_inode_extref_index(leaf,
3722 * try to precache a NULL acl entry for files that don't have
3723 * any xattrs or acls
3725 maybe_acls = acls_after_inode_item(leaf, path->slots[0],
3726 btrfs_ino(BTRFS_I(inode)), &first_xattr_slot);
3727 if (first_xattr_slot != -1) {
3728 path->slots[0] = first_xattr_slot;
3729 ret = btrfs_load_inode_props(inode, path);
3732 "error loading props for ino %llu (root %llu): %d",
3733 btrfs_ino(BTRFS_I(inode)),
3734 root->root_key.objectid, ret);
3736 btrfs_free_path(path);
3739 cache_no_acl(inode);
3741 switch (inode->i_mode & S_IFMT) {
3743 inode->i_mapping->a_ops = &btrfs_aops;
3744 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
3745 inode->i_fop = &btrfs_file_operations;
3746 inode->i_op = &btrfs_file_inode_operations;
3749 inode->i_fop = &btrfs_dir_file_operations;
3750 inode->i_op = &btrfs_dir_inode_operations;
3753 inode->i_op = &btrfs_symlink_inode_operations;
3754 inode_nohighmem(inode);
3755 inode->i_mapping->a_ops = &btrfs_symlink_aops;
3758 inode->i_op = &btrfs_special_inode_operations;
3759 init_special_inode(inode, inode->i_mode, rdev);
3763 btrfs_sync_inode_flags_to_i_flags(inode);
3767 btrfs_free_path(path);
3768 make_bad_inode(inode);
3773 * given a leaf and an inode, copy the inode fields into the leaf
3775 static void fill_inode_item(struct btrfs_trans_handle *trans,
3776 struct extent_buffer *leaf,
3777 struct btrfs_inode_item *item,
3778 struct inode *inode)
3780 struct btrfs_map_token token;
3782 btrfs_init_map_token(&token);
3784 btrfs_set_token_inode_uid(leaf, item, i_uid_read(inode), &token);
3785 btrfs_set_token_inode_gid(leaf, item, i_gid_read(inode), &token);
3786 btrfs_set_token_inode_size(leaf, item, BTRFS_I(inode)->disk_i_size,
3788 btrfs_set_token_inode_mode(leaf, item, inode->i_mode, &token);
3789 btrfs_set_token_inode_nlink(leaf, item, inode->i_nlink, &token);
3791 btrfs_set_token_timespec_sec(leaf, &item->atime,
3792 inode->i_atime.tv_sec, &token);
3793 btrfs_set_token_timespec_nsec(leaf, &item->atime,
3794 inode->i_atime.tv_nsec, &token);
3796 btrfs_set_token_timespec_sec(leaf, &item->mtime,
3797 inode->i_mtime.tv_sec, &token);
3798 btrfs_set_token_timespec_nsec(leaf, &item->mtime,
3799 inode->i_mtime.tv_nsec, &token);
3801 btrfs_set_token_timespec_sec(leaf, &item->ctime,
3802 inode->i_ctime.tv_sec, &token);
3803 btrfs_set_token_timespec_nsec(leaf, &item->ctime,
3804 inode->i_ctime.tv_nsec, &token);
3806 btrfs_set_token_timespec_sec(leaf, &item->otime,
3807 BTRFS_I(inode)->i_otime.tv_sec, &token);
3808 btrfs_set_token_timespec_nsec(leaf, &item->otime,
3809 BTRFS_I(inode)->i_otime.tv_nsec, &token);
3811 btrfs_set_token_inode_nbytes(leaf, item, inode_get_bytes(inode),
3813 btrfs_set_token_inode_generation(leaf, item, BTRFS_I(inode)->generation,
3815 btrfs_set_token_inode_sequence(leaf, item, inode_peek_iversion(inode),
3817 btrfs_set_token_inode_transid(leaf, item, trans->transid, &token);
3818 btrfs_set_token_inode_rdev(leaf, item, inode->i_rdev, &token);
3819 btrfs_set_token_inode_flags(leaf, item, BTRFS_I(inode)->flags, &token);
3820 btrfs_set_token_inode_block_group(leaf, item, 0, &token);
3824 * copy everything in the in-memory inode into the btree.
3826 static noinline int btrfs_update_inode_item(struct btrfs_trans_handle *trans,
3827 struct btrfs_root *root, struct inode *inode)
3829 struct btrfs_inode_item *inode_item;
3830 struct btrfs_path *path;
3831 struct extent_buffer *leaf;
3834 path = btrfs_alloc_path();
3838 path->leave_spinning = 1;
3839 ret = btrfs_lookup_inode(trans, root, path, &BTRFS_I(inode)->location,
3847 leaf = path->nodes[0];
3848 inode_item = btrfs_item_ptr(leaf, path->slots[0],
3849 struct btrfs_inode_item);
3851 fill_inode_item(trans, leaf, inode_item, inode);
3852 btrfs_mark_buffer_dirty(leaf);
3853 btrfs_set_inode_last_trans(trans, inode);
3856 btrfs_free_path(path);
3861 * copy everything in the in-memory inode into the btree.
3863 noinline int btrfs_update_inode(struct btrfs_trans_handle *trans,
3864 struct btrfs_root *root, struct inode *inode)
3866 struct btrfs_fs_info *fs_info = root->fs_info;
3870 * If the inode is a free space inode, we can deadlock during commit
3871 * if we put it into the delayed code.
3873 * The data relocation inode should also be directly updated
3876 if (!btrfs_is_free_space_inode(BTRFS_I(inode))
3877 && root->root_key.objectid != BTRFS_DATA_RELOC_TREE_OBJECTID
3878 && !test_bit(BTRFS_FS_LOG_RECOVERING, &fs_info->flags)) {
3879 btrfs_update_root_times(trans, root);
3881 ret = btrfs_delayed_update_inode(trans, root, inode);
3883 btrfs_set_inode_last_trans(trans, inode);
3887 return btrfs_update_inode_item(trans, root, inode);
3890 noinline int btrfs_update_inode_fallback(struct btrfs_trans_handle *trans,
3891 struct btrfs_root *root,
3892 struct inode *inode)
3896 ret = btrfs_update_inode(trans, root, inode);
3898 return btrfs_update_inode_item(trans, root, inode);
3903 * unlink helper that gets used here in inode.c and in the tree logging
3904 * recovery code. It remove a link in a directory with a given name, and
3905 * also drops the back refs in the inode to the directory
3907 static int __btrfs_unlink_inode(struct btrfs_trans_handle *trans,
3908 struct btrfs_root *root,
3909 struct btrfs_inode *dir,
3910 struct btrfs_inode *inode,
3911 const char *name, int name_len)
3913 struct btrfs_fs_info *fs_info = root->fs_info;
3914 struct btrfs_path *path;
3916 struct extent_buffer *leaf;
3917 struct btrfs_dir_item *di;
3918 struct btrfs_key key;
3920 u64 ino = btrfs_ino(inode);
3921 u64 dir_ino = btrfs_ino(dir);
3923 path = btrfs_alloc_path();
3929 path->leave_spinning = 1;
3930 di = btrfs_lookup_dir_item(trans, root, path, dir_ino,
3931 name, name_len, -1);
3940 leaf = path->nodes[0];
3941 btrfs_dir_item_key_to_cpu(leaf, di, &key);
3942 ret = btrfs_delete_one_dir_name(trans, root, path, di);
3945 btrfs_release_path(path);
3948 * If we don't have dir index, we have to get it by looking up
3949 * the inode ref, since we get the inode ref, remove it directly,
3950 * it is unnecessary to do delayed deletion.
3952 * But if we have dir index, needn't search inode ref to get it.
3953 * Since the inode ref is close to the inode item, it is better
3954 * that we delay to delete it, and just do this deletion when
3955 * we update the inode item.
3957 if (inode->dir_index) {
3958 ret = btrfs_delayed_delete_inode_ref(inode);
3960 index = inode->dir_index;
3965 ret = btrfs_del_inode_ref(trans, root, name, name_len, ino,
3969 "failed to delete reference to %.*s, inode %llu parent %llu",
3970 name_len, name, ino, dir_ino);
3971 btrfs_abort_transaction(trans, ret);
3975 ret = btrfs_delete_delayed_dir_index(trans, fs_info, dir, index);
3977 btrfs_abort_transaction(trans, ret);
3981 ret = btrfs_del_inode_ref_in_log(trans, root, name, name_len, inode,
3983 if (ret != 0 && ret != -ENOENT) {
3984 btrfs_abort_transaction(trans, ret);
3988 ret = btrfs_del_dir_entries_in_log(trans, root, name, name_len, dir,
3993 btrfs_abort_transaction(trans, ret);
3995 btrfs_free_path(path);
3999 btrfs_i_size_write(dir, dir->vfs_inode.i_size - name_len * 2);
4000 inode_inc_iversion(&inode->vfs_inode);
4001 inode_inc_iversion(&dir->vfs_inode);
4002 inode->vfs_inode.i_ctime = dir->vfs_inode.i_mtime =
4003 dir->vfs_inode.i_ctime = current_time(&inode->vfs_inode);
4004 ret = btrfs_update_inode(trans, root, &dir->vfs_inode);
4009 int btrfs_unlink_inode(struct btrfs_trans_handle *trans,
4010 struct btrfs_root *root,
4011 struct btrfs_inode *dir, struct btrfs_inode *inode,
4012 const char *name, int name_len)
4015 ret = __btrfs_unlink_inode(trans, root, dir, inode, name, name_len);
4017 drop_nlink(&inode->vfs_inode);
4018 ret = btrfs_update_inode(trans, root, &inode->vfs_inode);
4024 * helper to start transaction for unlink and rmdir.
4026 * unlink and rmdir are special in btrfs, they do not always free space, so
4027 * if we cannot make our reservations the normal way try and see if there is
4028 * plenty of slack room in the global reserve to migrate, otherwise we cannot
4029 * allow the unlink to occur.
4031 static struct btrfs_trans_handle *__unlink_start_trans(struct inode *dir)
4033 struct btrfs_root *root = BTRFS_I(dir)->root;
4036 * 1 for the possible orphan item
4037 * 1 for the dir item
4038 * 1 for the dir index
4039 * 1 for the inode ref
4042 return btrfs_start_transaction_fallback_global_rsv(root, 5, 5);
4045 static int btrfs_unlink(struct inode *dir, struct dentry *dentry)
4047 struct btrfs_root *root = BTRFS_I(dir)->root;
4048 struct btrfs_trans_handle *trans;
4049 struct inode *inode = d_inode(dentry);
4052 trans = __unlink_start_trans(dir);
4054 return PTR_ERR(trans);
4056 btrfs_record_unlink_dir(trans, BTRFS_I(dir), BTRFS_I(d_inode(dentry)),
4059 ret = btrfs_unlink_inode(trans, root, BTRFS_I(dir),
4060 BTRFS_I(d_inode(dentry)), dentry->d_name.name,
4061 dentry->d_name.len);
4065 if (inode->i_nlink == 0) {
4066 ret = btrfs_orphan_add(trans, BTRFS_I(inode));
4072 btrfs_end_transaction(trans);
4073 btrfs_btree_balance_dirty(root->fs_info);
4077 static int btrfs_unlink_subvol(struct btrfs_trans_handle *trans,
4078 struct btrfs_root *root,
4079 struct inode *dir, u64 objectid,
4080 const char *name, int name_len)
4082 struct btrfs_fs_info *fs_info = root->fs_info;
4083 struct btrfs_path *path;
4084 struct extent_buffer *leaf;
4085 struct btrfs_dir_item *di;
4086 struct btrfs_key key;
4089 u64 dir_ino = btrfs_ino(BTRFS_I(dir));
4091 path = btrfs_alloc_path();
4095 di = btrfs_lookup_dir_item(trans, root, path, dir_ino,
4096 name, name_len, -1);
4097 if (IS_ERR_OR_NULL(di)) {
4105 leaf = path->nodes[0];
4106 btrfs_dir_item_key_to_cpu(leaf, di, &key);
4107 WARN_ON(key.type != BTRFS_ROOT_ITEM_KEY || key.objectid != objectid);
4108 ret = btrfs_delete_one_dir_name(trans, root, path, di);
4110 btrfs_abort_transaction(trans, ret);
4113 btrfs_release_path(path);
4115 ret = btrfs_del_root_ref(trans, fs_info, objectid,
4116 root->root_key.objectid, dir_ino,
4117 &index, name, name_len);
4119 if (ret != -ENOENT) {
4120 btrfs_abort_transaction(trans, ret);
4123 di = btrfs_search_dir_index_item(root, path, dir_ino,
4125 if (IS_ERR_OR_NULL(di)) {
4130 btrfs_abort_transaction(trans, ret);
4134 leaf = path->nodes[0];
4135 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
4136 btrfs_release_path(path);
4139 btrfs_release_path(path);
4141 ret = btrfs_delete_delayed_dir_index(trans, fs_info, BTRFS_I(dir), index);
4143 btrfs_abort_transaction(trans, ret);
4147 btrfs_i_size_write(BTRFS_I(dir), dir->i_size - name_len * 2);
4148 inode_inc_iversion(dir);
4149 dir->i_mtime = dir->i_ctime = current_time(dir);
4150 ret = btrfs_update_inode_fallback(trans, root, dir);
4152 btrfs_abort_transaction(trans, ret);
4154 btrfs_free_path(path);
4159 * Helper to check if the subvolume references other subvolumes or if it's
4162 static noinline int may_destroy_subvol(struct btrfs_root *root)
4164 struct btrfs_fs_info *fs_info = root->fs_info;
4165 struct btrfs_path *path;
4166 struct btrfs_dir_item *di;
4167 struct btrfs_key key;
4171 path = btrfs_alloc_path();
4175 /* Make sure this root isn't set as the default subvol */
4176 dir_id = btrfs_super_root_dir(fs_info->super_copy);
4177 di = btrfs_lookup_dir_item(NULL, fs_info->tree_root, path,
4178 dir_id, "default", 7, 0);
4179 if (di && !IS_ERR(di)) {
4180 btrfs_dir_item_key_to_cpu(path->nodes[0], di, &key);
4181 if (key.objectid == root->root_key.objectid) {
4184 "deleting default subvolume %llu is not allowed",
4188 btrfs_release_path(path);
4191 key.objectid = root->root_key.objectid;
4192 key.type = BTRFS_ROOT_REF_KEY;
4193 key.offset = (u64)-1;
4195 ret = btrfs_search_slot(NULL, fs_info->tree_root, &key, path, 0, 0);
4201 if (path->slots[0] > 0) {
4203 btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
4204 if (key.objectid == root->root_key.objectid &&
4205 key.type == BTRFS_ROOT_REF_KEY)
4209 btrfs_free_path(path);
4213 /* Delete all dentries for inodes belonging to the root */
4214 static void btrfs_prune_dentries(struct btrfs_root *root)
4216 struct btrfs_fs_info *fs_info = root->fs_info;
4217 struct rb_node *node;
4218 struct rb_node *prev;
4219 struct btrfs_inode *entry;
4220 struct inode *inode;
4223 if (!test_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state))
4224 WARN_ON(btrfs_root_refs(&root->root_item) != 0);
4226 spin_lock(&root->inode_lock);
4228 node = root->inode_tree.rb_node;
4232 entry = rb_entry(node, struct btrfs_inode, rb_node);
4234 if (objectid < btrfs_ino(BTRFS_I(&entry->vfs_inode)))
4235 node = node->rb_left;
4236 else if (objectid > btrfs_ino(BTRFS_I(&entry->vfs_inode)))
4237 node = node->rb_right;
4243 entry = rb_entry(prev, struct btrfs_inode, rb_node);
4244 if (objectid <= btrfs_ino(BTRFS_I(&entry->vfs_inode))) {
4248 prev = rb_next(prev);
4252 entry = rb_entry(node, struct btrfs_inode, rb_node);
4253 objectid = btrfs_ino(BTRFS_I(&entry->vfs_inode)) + 1;
4254 inode = igrab(&entry->vfs_inode);
4256 spin_unlock(&root->inode_lock);
4257 if (atomic_read(&inode->i_count) > 1)
4258 d_prune_aliases(inode);
4260 * btrfs_drop_inode will have it removed from the inode
4261 * cache when its usage count hits zero.
4265 spin_lock(&root->inode_lock);
4269 if (cond_resched_lock(&root->inode_lock))
4272 node = rb_next(node);
4274 spin_unlock(&root->inode_lock);
4277 int btrfs_delete_subvolume(struct inode *dir, struct dentry *dentry)
4279 struct btrfs_fs_info *fs_info = btrfs_sb(dentry->d_sb);
4280 struct btrfs_root *root = BTRFS_I(dir)->root;
4281 struct inode *inode = d_inode(dentry);
4282 struct btrfs_root *dest = BTRFS_I(inode)->root;
4283 struct btrfs_trans_handle *trans;
4284 struct btrfs_block_rsv block_rsv;
4286 u64 qgroup_reserved;
4291 * Don't allow to delete a subvolume with send in progress. This is
4292 * inside the inode lock so the error handling that has to drop the bit
4293 * again is not run concurrently.
4295 spin_lock(&dest->root_item_lock);
4296 root_flags = btrfs_root_flags(&dest->root_item);
4297 if (dest->send_in_progress == 0) {
4298 btrfs_set_root_flags(&dest->root_item,
4299 root_flags | BTRFS_ROOT_SUBVOL_DEAD);
4300 spin_unlock(&dest->root_item_lock);
4302 spin_unlock(&dest->root_item_lock);
4304 "attempt to delete subvolume %llu during send",
4305 dest->root_key.objectid);
4309 down_write(&fs_info->subvol_sem);
4311 err = may_destroy_subvol(dest);
4315 btrfs_init_block_rsv(&block_rsv, BTRFS_BLOCK_RSV_TEMP);
4317 * One for dir inode,
4318 * two for dir entries,
4319 * two for root ref/backref.
4321 err = btrfs_subvolume_reserve_metadata(root, &block_rsv,
4322 5, &qgroup_reserved, true);
4326 trans = btrfs_start_transaction(root, 0);
4327 if (IS_ERR(trans)) {
4328 err = PTR_ERR(trans);
4331 trans->block_rsv = &block_rsv;
4332 trans->bytes_reserved = block_rsv.size;
4334 btrfs_record_snapshot_destroy(trans, BTRFS_I(dir));
4336 ret = btrfs_unlink_subvol(trans, root, dir,
4337 dest->root_key.objectid,
4338 dentry->d_name.name,
4339 dentry->d_name.len);
4342 btrfs_abort_transaction(trans, ret);
4346 btrfs_record_root_in_trans(trans, dest);
4348 memset(&dest->root_item.drop_progress, 0,
4349 sizeof(dest->root_item.drop_progress));
4350 dest->root_item.drop_level = 0;
4351 btrfs_set_root_refs(&dest->root_item, 0);
4353 if (!test_and_set_bit(BTRFS_ROOT_ORPHAN_ITEM_INSERTED, &dest->state)) {
4354 ret = btrfs_insert_orphan_item(trans,
4356 dest->root_key.objectid);
4358 btrfs_abort_transaction(trans, ret);
4364 ret = btrfs_uuid_tree_remove(trans, dest->root_item.uuid,
4365 BTRFS_UUID_KEY_SUBVOL,
4366 dest->root_key.objectid);
4367 if (ret && ret != -ENOENT) {
4368 btrfs_abort_transaction(trans, ret);
4372 if (!btrfs_is_empty_uuid(dest->root_item.received_uuid)) {
4373 ret = btrfs_uuid_tree_remove(trans,
4374 dest->root_item.received_uuid,
4375 BTRFS_UUID_KEY_RECEIVED_SUBVOL,
4376 dest->root_key.objectid);
4377 if (ret && ret != -ENOENT) {
4378 btrfs_abort_transaction(trans, ret);
4385 trans->block_rsv = NULL;
4386 trans->bytes_reserved = 0;
4387 ret = btrfs_end_transaction(trans);
4390 inode->i_flags |= S_DEAD;
4392 btrfs_subvolume_release_metadata(fs_info, &block_rsv);
4394 up_write(&fs_info->subvol_sem);
4396 spin_lock(&dest->root_item_lock);
4397 root_flags = btrfs_root_flags(&dest->root_item);
4398 btrfs_set_root_flags(&dest->root_item,
4399 root_flags & ~BTRFS_ROOT_SUBVOL_DEAD);
4400 spin_unlock(&dest->root_item_lock);
4402 d_invalidate(dentry);
4403 btrfs_prune_dentries(dest);
4404 ASSERT(dest->send_in_progress == 0);
4407 if (dest->ino_cache_inode) {
4408 iput(dest->ino_cache_inode);
4409 dest->ino_cache_inode = NULL;
4416 static int btrfs_rmdir(struct inode *dir, struct dentry *dentry)
4418 struct inode *inode = d_inode(dentry);
4420 struct btrfs_root *root = BTRFS_I(dir)->root;
4421 struct btrfs_trans_handle *trans;
4422 u64 last_unlink_trans;
4424 if (inode->i_size > BTRFS_EMPTY_DIR_SIZE)
4426 if (btrfs_ino(BTRFS_I(inode)) == BTRFS_FIRST_FREE_OBJECTID)
4427 return btrfs_delete_subvolume(dir, dentry);
4429 trans = __unlink_start_trans(dir);
4431 return PTR_ERR(trans);
4433 if (unlikely(btrfs_ino(BTRFS_I(inode)) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)) {
4434 err = btrfs_unlink_subvol(trans, root, dir,
4435 BTRFS_I(inode)->location.objectid,
4436 dentry->d_name.name,
4437 dentry->d_name.len);
4441 err = btrfs_orphan_add(trans, BTRFS_I(inode));
4445 last_unlink_trans = BTRFS_I(inode)->last_unlink_trans;
4447 /* now the directory is empty */
4448 err = btrfs_unlink_inode(trans, root, BTRFS_I(dir),
4449 BTRFS_I(d_inode(dentry)), dentry->d_name.name,
4450 dentry->d_name.len);
4452 btrfs_i_size_write(BTRFS_I(inode), 0);
4454 * Propagate the last_unlink_trans value of the deleted dir to
4455 * its parent directory. This is to prevent an unrecoverable
4456 * log tree in the case we do something like this:
4458 * 2) create snapshot under dir foo
4459 * 3) delete the snapshot
4462 * 6) fsync foo or some file inside foo
4464 if (last_unlink_trans >= trans->transid)
4465 BTRFS_I(dir)->last_unlink_trans = last_unlink_trans;
4468 btrfs_end_transaction(trans);
4469 btrfs_btree_balance_dirty(root->fs_info);
4474 static int truncate_space_check(struct btrfs_trans_handle *trans,
4475 struct btrfs_root *root,
4478 struct btrfs_fs_info *fs_info = root->fs_info;
4482 * This is only used to apply pressure to the enospc system, we don't
4483 * intend to use this reservation at all.
4485 bytes_deleted = btrfs_csum_bytes_to_leaves(fs_info, bytes_deleted);
4486 bytes_deleted *= fs_info->nodesize;
4487 ret = btrfs_block_rsv_add(root, &fs_info->trans_block_rsv,
4488 bytes_deleted, BTRFS_RESERVE_NO_FLUSH);
4490 trace_btrfs_space_reservation(fs_info, "transaction",
4493 trans->bytes_reserved += bytes_deleted;
4500 * Return this if we need to call truncate_block for the last bit of the
4503 #define NEED_TRUNCATE_BLOCK 1
4506 * this can truncate away extent items, csum items and directory items.
4507 * It starts at a high offset and removes keys until it can't find
4508 * any higher than new_size
4510 * csum items that cross the new i_size are truncated to the new size
4513 * min_type is the minimum key type to truncate down to. If set to 0, this
4514 * will kill all the items on this inode, including the INODE_ITEM_KEY.
4516 int btrfs_truncate_inode_items(struct btrfs_trans_handle *trans,
4517 struct btrfs_root *root,
4518 struct inode *inode,
4519 u64 new_size, u32 min_type)
4521 struct btrfs_fs_info *fs_info = root->fs_info;
4522 struct btrfs_path *path;
4523 struct extent_buffer *leaf;
4524 struct btrfs_file_extent_item *fi;
4525 struct btrfs_key key;
4526 struct btrfs_key found_key;
4527 u64 extent_start = 0;
4528 u64 extent_num_bytes = 0;
4529 u64 extent_offset = 0;
4531 u64 last_size = new_size;
4532 u32 found_type = (u8)-1;
4535 int pending_del_nr = 0;
4536 int pending_del_slot = 0;
4537 int extent_type = -1;
4539 u64 ino = btrfs_ino(BTRFS_I(inode));
4540 u64 bytes_deleted = 0;
4541 bool be_nice = false;
4542 bool should_throttle = false;
4543 bool should_end = false;
4545 BUG_ON(new_size > 0 && min_type != BTRFS_EXTENT_DATA_KEY);
4548 * for non-free space inodes and ref cows, we want to back off from
4551 if (!btrfs_is_free_space_inode(BTRFS_I(inode)) &&
4552 test_bit(BTRFS_ROOT_REF_COWS, &root->state))
4555 path = btrfs_alloc_path();
4558 path->reada = READA_BACK;
4561 * We want to drop from the next block forward in case this new size is
4562 * not block aligned since we will be keeping the last block of the
4563 * extent just the way it is.
4565 if (test_bit(BTRFS_ROOT_REF_COWS, &root->state) ||
4566 root == fs_info->tree_root)
4567 btrfs_drop_extent_cache(BTRFS_I(inode), ALIGN(new_size,
4568 fs_info->sectorsize),
4572 * This function is also used to drop the items in the log tree before
4573 * we relog the inode, so if root != BTRFS_I(inode)->root, it means
4574 * it is used to drop the loged items. So we shouldn't kill the delayed
4577 if (min_type == 0 && root == BTRFS_I(inode)->root)
4578 btrfs_kill_delayed_inode_items(BTRFS_I(inode));
4581 key.offset = (u64)-1;
4586 * with a 16K leaf size and 128MB extents, you can actually queue
4587 * up a huge file in a single leaf. Most of the time that
4588 * bytes_deleted is > 0, it will be huge by the time we get here
4590 if (be_nice && bytes_deleted > SZ_32M &&
4591 btrfs_should_end_transaction(trans)) {
4596 path->leave_spinning = 1;
4597 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
4603 /* there are no items in the tree for us to truncate, we're
4606 if (path->slots[0] == 0)
4613 leaf = path->nodes[0];
4614 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
4615 found_type = found_key.type;
4617 if (found_key.objectid != ino)
4620 if (found_type < min_type)
4623 item_end = found_key.offset;
4624 if (found_type == BTRFS_EXTENT_DATA_KEY) {
4625 fi = btrfs_item_ptr(leaf, path->slots[0],
4626 struct btrfs_file_extent_item);
4627 extent_type = btrfs_file_extent_type(leaf, fi);
4628 if (extent_type != BTRFS_FILE_EXTENT_INLINE) {
4630 btrfs_file_extent_num_bytes(leaf, fi);
4632 trace_btrfs_truncate_show_fi_regular(
4633 BTRFS_I(inode), leaf, fi,
4635 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
4636 item_end += btrfs_file_extent_inline_len(leaf,
4637 path->slots[0], fi);
4639 trace_btrfs_truncate_show_fi_inline(
4640 BTRFS_I(inode), leaf, fi, path->slots[0],
4645 if (found_type > min_type) {
4648 if (item_end < new_size)
4650 if (found_key.offset >= new_size)
4656 /* FIXME, shrink the extent if the ref count is only 1 */
4657 if (found_type != BTRFS_EXTENT_DATA_KEY)
4660 if (extent_type != BTRFS_FILE_EXTENT_INLINE) {
4662 extent_start = btrfs_file_extent_disk_bytenr(leaf, fi);
4664 u64 orig_num_bytes =
4665 btrfs_file_extent_num_bytes(leaf, fi);
4666 extent_num_bytes = ALIGN(new_size -
4668 fs_info->sectorsize);
4669 btrfs_set_file_extent_num_bytes(leaf, fi,
4671 num_dec = (orig_num_bytes -
4673 if (test_bit(BTRFS_ROOT_REF_COWS,
4676 inode_sub_bytes(inode, num_dec);
4677 btrfs_mark_buffer_dirty(leaf);
4680 btrfs_file_extent_disk_num_bytes(leaf,
4682 extent_offset = found_key.offset -
4683 btrfs_file_extent_offset(leaf, fi);
4685 /* FIXME blocksize != 4096 */
4686 num_dec = btrfs_file_extent_num_bytes(leaf, fi);
4687 if (extent_start != 0) {
4689 if (test_bit(BTRFS_ROOT_REF_COWS,
4691 inode_sub_bytes(inode, num_dec);
4694 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
4696 * we can't truncate inline items that have had
4700 btrfs_file_extent_encryption(leaf, fi) == 0 &&
4701 btrfs_file_extent_other_encoding(leaf, fi) == 0 &&
4702 btrfs_file_extent_compression(leaf, fi) == 0) {
4703 u32 size = (u32)(new_size - found_key.offset);
4705 btrfs_set_file_extent_ram_bytes(leaf, fi, size);
4706 size = btrfs_file_extent_calc_inline_size(size);
4707 btrfs_truncate_item(root->fs_info, path, size, 1);
4708 } else if (!del_item) {
4710 * We have to bail so the last_size is set to
4711 * just before this extent.
4713 ret = NEED_TRUNCATE_BLOCK;
4717 if (test_bit(BTRFS_ROOT_REF_COWS, &root->state))
4718 inode_sub_bytes(inode, item_end + 1 - new_size);
4722 last_size = found_key.offset;
4724 last_size = new_size;
4726 if (!pending_del_nr) {
4727 /* no pending yet, add ourselves */
4728 pending_del_slot = path->slots[0];
4730 } else if (pending_del_nr &&
4731 path->slots[0] + 1 == pending_del_slot) {
4732 /* hop on the pending chunk */
4734 pending_del_slot = path->slots[0];
4741 should_throttle = false;
4744 (test_bit(BTRFS_ROOT_REF_COWS, &root->state) ||
4745 root == fs_info->tree_root)) {
4746 btrfs_set_path_blocking(path);
4747 bytes_deleted += extent_num_bytes;
4748 ret = btrfs_free_extent(trans, root, extent_start,
4749 extent_num_bytes, 0,
4750 btrfs_header_owner(leaf),
4751 ino, extent_offset);
4753 btrfs_abort_transaction(trans, ret);
4756 if (btrfs_should_throttle_delayed_refs(trans, fs_info))
4757 btrfs_async_run_delayed_refs(fs_info,
4758 trans->delayed_ref_updates * 2,
4761 if (truncate_space_check(trans, root,
4762 extent_num_bytes)) {
4765 if (btrfs_should_throttle_delayed_refs(trans,
4767 should_throttle = true;
4771 if (found_type == BTRFS_INODE_ITEM_KEY)
4774 if (path->slots[0] == 0 ||
4775 path->slots[0] != pending_del_slot ||
4776 should_throttle || should_end) {
4777 if (pending_del_nr) {
4778 ret = btrfs_del_items(trans, root, path,
4782 btrfs_abort_transaction(trans, ret);
4787 btrfs_release_path(path);
4788 if (should_throttle) {
4789 unsigned long updates = trans->delayed_ref_updates;
4791 trans->delayed_ref_updates = 0;
4792 ret = btrfs_run_delayed_refs(trans,
4799 * if we failed to refill our space rsv, bail out
4800 * and let the transaction restart
4812 if (ret >= 0 && pending_del_nr) {
4815 err = btrfs_del_items(trans, root, path, pending_del_slot,
4818 btrfs_abort_transaction(trans, err);
4822 if (root->root_key.objectid != BTRFS_TREE_LOG_OBJECTID) {
4823 ASSERT(last_size >= new_size);
4824 if (!ret && last_size > new_size)
4825 last_size = new_size;
4826 btrfs_ordered_update_i_size(inode, last_size, NULL);
4829 btrfs_free_path(path);
4831 if (be_nice && bytes_deleted > SZ_32M && (ret >= 0 || ret == -EAGAIN)) {
4832 unsigned long updates = trans->delayed_ref_updates;
4836 trans->delayed_ref_updates = 0;
4837 err = btrfs_run_delayed_refs(trans, updates * 2);
4846 * btrfs_truncate_block - read, zero a chunk and write a block
4847 * @inode - inode that we're zeroing
4848 * @from - the offset to start zeroing
4849 * @len - the length to zero, 0 to zero the entire range respective to the
4851 * @front - zero up to the offset instead of from the offset on
4853 * This will find the block for the "from" offset and cow the block and zero the
4854 * part we want to zero. This is used with truncate and hole punching.
4856 int btrfs_truncate_block(struct inode *inode, loff_t from, loff_t len,
4859 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
4860 struct address_space *mapping = inode->i_mapping;
4861 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
4862 struct btrfs_ordered_extent *ordered;
4863 struct extent_state *cached_state = NULL;
4864 struct extent_changeset *data_reserved = NULL;
4866 u32 blocksize = fs_info->sectorsize;
4867 pgoff_t index = from >> PAGE_SHIFT;
4868 unsigned offset = from & (blocksize - 1);
4870 gfp_t mask = btrfs_alloc_write_mask(mapping);
4875 if (IS_ALIGNED(offset, blocksize) &&
4876 (!len || IS_ALIGNED(len, blocksize)))
4879 block_start = round_down(from, blocksize);
4880 block_end = block_start + blocksize - 1;
4882 ret = btrfs_delalloc_reserve_space(inode, &data_reserved,
4883 block_start, blocksize);
4888 page = find_or_create_page(mapping, index, mask);
4890 btrfs_delalloc_release_space(inode, data_reserved,
4891 block_start, blocksize, true);
4892 btrfs_delalloc_release_extents(BTRFS_I(inode), blocksize, true);
4897 if (!PageUptodate(page)) {
4898 ret = btrfs_readpage(NULL, page);
4900 if (page->mapping != mapping) {
4905 if (!PageUptodate(page)) {
4910 wait_on_page_writeback(page);
4912 lock_extent_bits(io_tree, block_start, block_end, &cached_state);
4913 set_page_extent_mapped(page);
4915 ordered = btrfs_lookup_ordered_extent(inode, block_start);
4917 unlock_extent_cached(io_tree, block_start, block_end,
4921 btrfs_start_ordered_extent(inode, ordered, 1);
4922 btrfs_put_ordered_extent(ordered);
4926 clear_extent_bit(&BTRFS_I(inode)->io_tree, block_start, block_end,
4927 EXTENT_DIRTY | EXTENT_DELALLOC |
4928 EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG,
4929 0, 0, &cached_state);
4931 ret = btrfs_set_extent_delalloc(inode, block_start, block_end, 0,
4934 unlock_extent_cached(io_tree, block_start, block_end,
4939 if (offset != blocksize) {
4941 len = blocksize - offset;
4944 memset(kaddr + (block_start - page_offset(page)),
4947 memset(kaddr + (block_start - page_offset(page)) + offset,
4949 flush_dcache_page(page);
4952 ClearPageChecked(page);
4953 set_page_dirty(page);
4954 unlock_extent_cached(io_tree, block_start, block_end, &cached_state);
4958 btrfs_delalloc_release_space(inode, data_reserved, block_start,
4960 btrfs_delalloc_release_extents(BTRFS_I(inode), blocksize, (ret != 0));
4964 extent_changeset_free(data_reserved);
4968 static int maybe_insert_hole(struct btrfs_root *root, struct inode *inode,
4969 u64 offset, u64 len)
4971 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
4972 struct btrfs_trans_handle *trans;
4976 * Still need to make sure the inode looks like it's been updated so
4977 * that any holes get logged if we fsync.
4979 if (btrfs_fs_incompat(fs_info, NO_HOLES)) {
4980 BTRFS_I(inode)->last_trans = fs_info->generation;
4981 BTRFS_I(inode)->last_sub_trans = root->log_transid;
4982 BTRFS_I(inode)->last_log_commit = root->last_log_commit;
4987 * 1 - for the one we're dropping
4988 * 1 - for the one we're adding
4989 * 1 - for updating the inode.
4991 trans = btrfs_start_transaction(root, 3);
4993 return PTR_ERR(trans);
4995 ret = btrfs_drop_extents(trans, root, inode, offset, offset + len, 1);
4997 btrfs_abort_transaction(trans, ret);
4998 btrfs_end_transaction(trans);
5002 ret = btrfs_insert_file_extent(trans, root, btrfs_ino(BTRFS_I(inode)),
5003 offset, 0, 0, len, 0, len, 0, 0, 0);
5005 btrfs_abort_transaction(trans, ret);
5007 btrfs_update_inode(trans, root, inode);
5008 btrfs_end_transaction(trans);
5013 * This function puts in dummy file extents for the area we're creating a hole
5014 * for. So if we are truncating this file to a larger size we need to insert
5015 * these file extents so that btrfs_get_extent will return a EXTENT_MAP_HOLE for
5016 * the range between oldsize and size
5018 int btrfs_cont_expand(struct inode *inode, loff_t oldsize, loff_t size)
5020 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
5021 struct btrfs_root *root = BTRFS_I(inode)->root;
5022 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
5023 struct extent_map *em = NULL;
5024 struct extent_state *cached_state = NULL;
5025 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
5026 u64 hole_start = ALIGN(oldsize, fs_info->sectorsize);
5027 u64 block_end = ALIGN(size, fs_info->sectorsize);
5034 * If our size started in the middle of a block we need to zero out the
5035 * rest of the block before we expand the i_size, otherwise we could
5036 * expose stale data.
5038 err = btrfs_truncate_block(inode, oldsize, 0, 0);
5042 if (size <= hole_start)
5046 struct btrfs_ordered_extent *ordered;
5048 lock_extent_bits(io_tree, hole_start, block_end - 1,
5050 ordered = btrfs_lookup_ordered_range(BTRFS_I(inode), hole_start,
5051 block_end - hole_start);
5054 unlock_extent_cached(io_tree, hole_start, block_end - 1,
5056 btrfs_start_ordered_extent(inode, ordered, 1);
5057 btrfs_put_ordered_extent(ordered);
5060 cur_offset = hole_start;
5062 em = btrfs_get_extent(BTRFS_I(inode), NULL, 0, cur_offset,
5063 block_end - cur_offset, 0);
5069 last_byte = min(extent_map_end(em), block_end);
5070 last_byte = ALIGN(last_byte, fs_info->sectorsize);
5071 if (!test_bit(EXTENT_FLAG_PREALLOC, &em->flags)) {
5072 struct extent_map *hole_em;
5073 hole_size = last_byte - cur_offset;
5075 err = maybe_insert_hole(root, inode, cur_offset,
5079 btrfs_drop_extent_cache(BTRFS_I(inode), cur_offset,
5080 cur_offset + hole_size - 1, 0);
5081 hole_em = alloc_extent_map();
5083 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
5084 &BTRFS_I(inode)->runtime_flags);
5087 hole_em->start = cur_offset;
5088 hole_em->len = hole_size;
5089 hole_em->orig_start = cur_offset;
5091 hole_em->block_start = EXTENT_MAP_HOLE;
5092 hole_em->block_len = 0;
5093 hole_em->orig_block_len = 0;
5094 hole_em->ram_bytes = hole_size;
5095 hole_em->bdev = fs_info->fs_devices->latest_bdev;
5096 hole_em->compress_type = BTRFS_COMPRESS_NONE;
5097 hole_em->generation = fs_info->generation;
5100 write_lock(&em_tree->lock);
5101 err = add_extent_mapping(em_tree, hole_em, 1);
5102 write_unlock(&em_tree->lock);
5105 btrfs_drop_extent_cache(BTRFS_I(inode),
5110 free_extent_map(hole_em);
5113 free_extent_map(em);
5115 cur_offset = last_byte;
5116 if (cur_offset >= block_end)
5119 free_extent_map(em);
5120 unlock_extent_cached(io_tree, hole_start, block_end - 1, &cached_state);
5124 static int btrfs_setsize(struct inode *inode, struct iattr *attr)
5126 struct btrfs_root *root = BTRFS_I(inode)->root;
5127 struct btrfs_trans_handle *trans;
5128 loff_t oldsize = i_size_read(inode);
5129 loff_t newsize = attr->ia_size;
5130 int mask = attr->ia_valid;
5134 * The regular truncate() case without ATTR_CTIME and ATTR_MTIME is a
5135 * special case where we need to update the times despite not having
5136 * these flags set. For all other operations the VFS set these flags
5137 * explicitly if it wants a timestamp update.
5139 if (newsize != oldsize) {
5140 inode_inc_iversion(inode);
5141 if (!(mask & (ATTR_CTIME | ATTR_MTIME)))
5142 inode->i_ctime = inode->i_mtime =
5143 current_time(inode);
5146 if (newsize > oldsize) {
5148 * Don't do an expanding truncate while snapshotting is ongoing.
5149 * This is to ensure the snapshot captures a fully consistent
5150 * state of this file - if the snapshot captures this expanding
5151 * truncation, it must capture all writes that happened before
5154 btrfs_wait_for_snapshot_creation(root);
5155 ret = btrfs_cont_expand(inode, oldsize, newsize);
5157 btrfs_end_write_no_snapshotting(root);
5161 trans = btrfs_start_transaction(root, 1);
5162 if (IS_ERR(trans)) {
5163 btrfs_end_write_no_snapshotting(root);
5164 return PTR_ERR(trans);
5167 i_size_write(inode, newsize);
5168 btrfs_ordered_update_i_size(inode, i_size_read(inode), NULL);
5169 pagecache_isize_extended(inode, oldsize, newsize);
5170 ret = btrfs_update_inode(trans, root, inode);
5171 btrfs_end_write_no_snapshotting(root);
5172 btrfs_end_transaction(trans);
5176 * We're truncating a file that used to have good data down to
5177 * zero. Make sure it gets into the ordered flush list so that
5178 * any new writes get down to disk quickly.
5181 set_bit(BTRFS_INODE_ORDERED_DATA_CLOSE,
5182 &BTRFS_I(inode)->runtime_flags);
5184 truncate_setsize(inode, newsize);
5186 /* Disable nonlocked read DIO to avoid the end less truncate */
5187 btrfs_inode_block_unlocked_dio(BTRFS_I(inode));
5188 inode_dio_wait(inode);
5189 btrfs_inode_resume_unlocked_dio(BTRFS_I(inode));
5191 ret = btrfs_truncate(inode, newsize == oldsize);
5192 if (ret && inode->i_nlink) {
5196 * Truncate failed, so fix up the in-memory size. We
5197 * adjusted disk_i_size down as we removed extents, so
5198 * wait for disk_i_size to be stable and then update the
5199 * in-memory size to match.
5201 err = btrfs_wait_ordered_range(inode, 0, (u64)-1);
5204 i_size_write(inode, BTRFS_I(inode)->disk_i_size);
5211 static int btrfs_setattr(struct dentry *dentry, struct iattr *attr)
5213 struct inode *inode = d_inode(dentry);
5214 struct btrfs_root *root = BTRFS_I(inode)->root;
5217 if (btrfs_root_readonly(root))
5220 err = setattr_prepare(dentry, attr);
5224 if (S_ISREG(inode->i_mode) && (attr->ia_valid & ATTR_SIZE)) {
5225 err = btrfs_setsize(inode, attr);
5230 if (attr->ia_valid) {
5231 setattr_copy(inode, attr);
5232 inode_inc_iversion(inode);
5233 err = btrfs_dirty_inode(inode);
5235 if (!err && attr->ia_valid & ATTR_MODE)
5236 err = posix_acl_chmod(inode, inode->i_mode);
5243 * While truncating the inode pages during eviction, we get the VFS calling
5244 * btrfs_invalidatepage() against each page of the inode. This is slow because
5245 * the calls to btrfs_invalidatepage() result in a huge amount of calls to
5246 * lock_extent_bits() and clear_extent_bit(), which keep merging and splitting
5247 * extent_state structures over and over, wasting lots of time.
5249 * Therefore if the inode is being evicted, let btrfs_invalidatepage() skip all
5250 * those expensive operations on a per page basis and do only the ordered io
5251 * finishing, while we release here the extent_map and extent_state structures,
5252 * without the excessive merging and splitting.
5254 static void evict_inode_truncate_pages(struct inode *inode)
5256 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
5257 struct extent_map_tree *map_tree = &BTRFS_I(inode)->extent_tree;
5258 struct rb_node *node;
5260 ASSERT(inode->i_state & I_FREEING);
5261 truncate_inode_pages_final(&inode->i_data);
5263 write_lock(&map_tree->lock);
5264 while (!RB_EMPTY_ROOT(&map_tree->map)) {
5265 struct extent_map *em;
5267 node = rb_first(&map_tree->map);
5268 em = rb_entry(node, struct extent_map, rb_node);
5269 clear_bit(EXTENT_FLAG_PINNED, &em->flags);
5270 clear_bit(EXTENT_FLAG_LOGGING, &em->flags);
5271 remove_extent_mapping(map_tree, em);
5272 free_extent_map(em);
5273 if (need_resched()) {
5274 write_unlock(&map_tree->lock);
5276 write_lock(&map_tree->lock);
5279 write_unlock(&map_tree->lock);
5282 * Keep looping until we have no more ranges in the io tree.
5283 * We can have ongoing bios started by readpages (called from readahead)
5284 * that have their endio callback (extent_io.c:end_bio_extent_readpage)
5285 * still in progress (unlocked the pages in the bio but did not yet
5286 * unlocked the ranges in the io tree). Therefore this means some
5287 * ranges can still be locked and eviction started because before
5288 * submitting those bios, which are executed by a separate task (work
5289 * queue kthread), inode references (inode->i_count) were not taken
5290 * (which would be dropped in the end io callback of each bio).
5291 * Therefore here we effectively end up waiting for those bios and
5292 * anyone else holding locked ranges without having bumped the inode's
5293 * reference count - if we don't do it, when they access the inode's
5294 * io_tree to unlock a range it may be too late, leading to an
5295 * use-after-free issue.
5297 spin_lock(&io_tree->lock);
5298 while (!RB_EMPTY_ROOT(&io_tree->state)) {
5299 struct extent_state *state;
5300 struct extent_state *cached_state = NULL;
5304 node = rb_first(&io_tree->state);
5305 state = rb_entry(node, struct extent_state, rb_node);
5306 start = state->start;
5308 spin_unlock(&io_tree->lock);
5310 lock_extent_bits(io_tree, start, end, &cached_state);
5313 * If still has DELALLOC flag, the extent didn't reach disk,
5314 * and its reserved space won't be freed by delayed_ref.
5315 * So we need to free its reserved space here.
5316 * (Refer to comment in btrfs_invalidatepage, case 2)
5318 * Note, end is the bytenr of last byte, so we need + 1 here.
5320 if (state->state & EXTENT_DELALLOC)
5321 btrfs_qgroup_free_data(inode, NULL, start, end - start + 1);
5323 clear_extent_bit(io_tree, start, end,
5324 EXTENT_LOCKED | EXTENT_DIRTY |
5325 EXTENT_DELALLOC | EXTENT_DO_ACCOUNTING |
5326 EXTENT_DEFRAG, 1, 1, &cached_state);
5329 spin_lock(&io_tree->lock);
5331 spin_unlock(&io_tree->lock);
5334 static struct btrfs_trans_handle *evict_refill_and_join(struct btrfs_root *root,
5335 struct btrfs_block_rsv *rsv,
5338 struct btrfs_fs_info *fs_info = root->fs_info;
5339 struct btrfs_block_rsv *global_rsv = &fs_info->global_block_rsv;
5343 struct btrfs_trans_handle *trans;
5346 ret = btrfs_block_rsv_refill(root, rsv, min_size,
5347 BTRFS_RESERVE_FLUSH_LIMIT);
5349 if (ret && ++failures > 2) {
5351 "could not allocate space for a delete; will truncate on mount");
5352 return ERR_PTR(-ENOSPC);
5355 trans = btrfs_join_transaction(root);
5356 if (IS_ERR(trans) || !ret)
5360 * Try to steal from the global reserve if there is space for
5363 if (!btrfs_check_space_for_delayed_refs(trans, fs_info) &&
5364 !btrfs_block_rsv_migrate(global_rsv, rsv, min_size, 0))
5367 /* If not, commit and try again. */
5368 ret = btrfs_commit_transaction(trans);
5370 return ERR_PTR(ret);
5374 void btrfs_evict_inode(struct inode *inode)
5376 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
5377 struct btrfs_trans_handle *trans;
5378 struct btrfs_root *root = BTRFS_I(inode)->root;
5379 struct btrfs_block_rsv *rsv;
5383 trace_btrfs_inode_evict(inode);
5390 min_size = btrfs_calc_trunc_metadata_size(fs_info, 1);
5392 evict_inode_truncate_pages(inode);
5394 if (inode->i_nlink &&
5395 ((btrfs_root_refs(&root->root_item) != 0 &&
5396 root->root_key.objectid != BTRFS_ROOT_TREE_OBJECTID) ||
5397 btrfs_is_free_space_inode(BTRFS_I(inode))))
5400 if (is_bad_inode(inode))
5402 /* do we really want it for ->i_nlink > 0 and zero btrfs_root_refs? */
5403 if (!special_file(inode->i_mode))
5404 btrfs_wait_ordered_range(inode, 0, (u64)-1);
5406 btrfs_free_io_failure_record(BTRFS_I(inode), 0, (u64)-1);
5408 if (test_bit(BTRFS_FS_LOG_RECOVERING, &fs_info->flags))
5411 if (inode->i_nlink > 0) {
5412 BUG_ON(btrfs_root_refs(&root->root_item) != 0 &&
5413 root->root_key.objectid != BTRFS_ROOT_TREE_OBJECTID);
5417 ret = btrfs_commit_inode_delayed_inode(BTRFS_I(inode));
5421 rsv = btrfs_alloc_block_rsv(fs_info, BTRFS_BLOCK_RSV_TEMP);
5424 rsv->size = min_size;
5427 btrfs_i_size_write(BTRFS_I(inode), 0);
5430 trans = evict_refill_and_join(root, rsv, min_size);
5434 trans->block_rsv = rsv;
5436 ret = btrfs_truncate_inode_items(trans, root, inode, 0, 0);
5437 trans->block_rsv = &fs_info->trans_block_rsv;
5438 btrfs_end_transaction(trans);
5439 btrfs_btree_balance_dirty(fs_info);
5440 if (ret && ret != -ENOSPC && ret != -EAGAIN)
5447 * Errors here aren't a big deal, it just means we leave orphan items in
5448 * the tree. They will be cleaned up on the next mount. If the inode
5449 * number gets reused, cleanup deletes the orphan item without doing
5450 * anything, and unlink reuses the existing orphan item.
5452 * If it turns out that we are dropping too many of these, we might want
5453 * to add a mechanism for retrying these after a commit.
5455 trans = evict_refill_and_join(root, rsv, min_size);
5456 if (!IS_ERR(trans)) {
5457 trans->block_rsv = rsv;
5458 btrfs_orphan_del(trans, BTRFS_I(inode));
5459 trans->block_rsv = &fs_info->trans_block_rsv;
5460 btrfs_end_transaction(trans);
5463 if (!(root == fs_info->tree_root ||
5464 root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID))
5465 btrfs_return_ino(root, btrfs_ino(BTRFS_I(inode)));
5468 btrfs_free_block_rsv(fs_info, rsv);
5471 * If we didn't successfully delete, the orphan item will still be in
5472 * the tree and we'll retry on the next mount. Again, we might also want
5473 * to retry these periodically in the future.
5475 btrfs_remove_delayed_node(BTRFS_I(inode));
5480 * this returns the key found in the dir entry in the location pointer.
5481 * If no dir entries were found, returns -ENOENT.
5482 * If found a corrupted location in dir entry, returns -EUCLEAN.
5484 static int btrfs_inode_by_name(struct inode *dir, struct dentry *dentry,
5485 struct btrfs_key *location)
5487 const char *name = dentry->d_name.name;
5488 int namelen = dentry->d_name.len;
5489 struct btrfs_dir_item *di;
5490 struct btrfs_path *path;
5491 struct btrfs_root *root = BTRFS_I(dir)->root;
5494 path = btrfs_alloc_path();
5498 di = btrfs_lookup_dir_item(NULL, root, path, btrfs_ino(BTRFS_I(dir)),
5509 btrfs_dir_item_key_to_cpu(path->nodes[0], di, location);
5510 if (location->type != BTRFS_INODE_ITEM_KEY &&
5511 location->type != BTRFS_ROOT_ITEM_KEY) {
5513 btrfs_warn(root->fs_info,
5514 "%s gets something invalid in DIR_ITEM (name %s, directory ino %llu, location(%llu %u %llu))",
5515 __func__, name, btrfs_ino(BTRFS_I(dir)),
5516 location->objectid, location->type, location->offset);
5519 btrfs_free_path(path);
5524 * when we hit a tree root in a directory, the btrfs part of the inode
5525 * needs to be changed to reflect the root directory of the tree root. This
5526 * is kind of like crossing a mount point.
5528 static int fixup_tree_root_location(struct btrfs_fs_info *fs_info,
5530 struct dentry *dentry,
5531 struct btrfs_key *location,
5532 struct btrfs_root **sub_root)
5534 struct btrfs_path *path;
5535 struct btrfs_root *new_root;
5536 struct btrfs_root_ref *ref;
5537 struct extent_buffer *leaf;
5538 struct btrfs_key key;
5542 path = btrfs_alloc_path();
5549 key.objectid = BTRFS_I(dir)->root->root_key.objectid;
5550 key.type = BTRFS_ROOT_REF_KEY;
5551 key.offset = location->objectid;
5553 ret = btrfs_search_slot(NULL, fs_info->tree_root, &key, path, 0, 0);
5560 leaf = path->nodes[0];
5561 ref = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_root_ref);
5562 if (btrfs_root_ref_dirid(leaf, ref) != btrfs_ino(BTRFS_I(dir)) ||
5563 btrfs_root_ref_name_len(leaf, ref) != dentry->d_name.len)
5566 ret = memcmp_extent_buffer(leaf, dentry->d_name.name,
5567 (unsigned long)(ref + 1),
5568 dentry->d_name.len);
5572 btrfs_release_path(path);
5574 new_root = btrfs_read_fs_root_no_name(fs_info, location);
5575 if (IS_ERR(new_root)) {
5576 err = PTR_ERR(new_root);
5580 *sub_root = new_root;
5581 location->objectid = btrfs_root_dirid(&new_root->root_item);
5582 location->type = BTRFS_INODE_ITEM_KEY;
5583 location->offset = 0;
5586 btrfs_free_path(path);
5590 static void inode_tree_add(struct inode *inode)
5592 struct btrfs_root *root = BTRFS_I(inode)->root;
5593 struct btrfs_inode *entry;
5595 struct rb_node *parent;
5596 struct rb_node *new = &BTRFS_I(inode)->rb_node;
5597 u64 ino = btrfs_ino(BTRFS_I(inode));
5599 if (inode_unhashed(inode))
5602 spin_lock(&root->inode_lock);
5603 p = &root->inode_tree.rb_node;
5606 entry = rb_entry(parent, struct btrfs_inode, rb_node);
5608 if (ino < btrfs_ino(BTRFS_I(&entry->vfs_inode)))
5609 p = &parent->rb_left;
5610 else if (ino > btrfs_ino(BTRFS_I(&entry->vfs_inode)))
5611 p = &parent->rb_right;
5613 WARN_ON(!(entry->vfs_inode.i_state &
5614 (I_WILL_FREE | I_FREEING)));
5615 rb_replace_node(parent, new, &root->inode_tree);
5616 RB_CLEAR_NODE(parent);
5617 spin_unlock(&root->inode_lock);
5621 rb_link_node(new, parent, p);
5622 rb_insert_color(new, &root->inode_tree);
5623 spin_unlock(&root->inode_lock);
5626 static void inode_tree_del(struct inode *inode)
5628 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
5629 struct btrfs_root *root = BTRFS_I(inode)->root;
5632 spin_lock(&root->inode_lock);
5633 if (!RB_EMPTY_NODE(&BTRFS_I(inode)->rb_node)) {
5634 rb_erase(&BTRFS_I(inode)->rb_node, &root->inode_tree);
5635 RB_CLEAR_NODE(&BTRFS_I(inode)->rb_node);
5636 empty = RB_EMPTY_ROOT(&root->inode_tree);
5638 spin_unlock(&root->inode_lock);
5640 if (empty && btrfs_root_refs(&root->root_item) == 0) {
5641 synchronize_srcu(&fs_info->subvol_srcu);
5642 spin_lock(&root->inode_lock);
5643 empty = RB_EMPTY_ROOT(&root->inode_tree);
5644 spin_unlock(&root->inode_lock);
5646 btrfs_add_dead_root(root);
5651 static int btrfs_init_locked_inode(struct inode *inode, void *p)
5653 struct btrfs_iget_args *args = p;
5654 inode->i_ino = args->location->objectid;
5655 memcpy(&BTRFS_I(inode)->location, args->location,
5656 sizeof(*args->location));
5657 BTRFS_I(inode)->root = args->root;
5661 static int btrfs_find_actor(struct inode *inode, void *opaque)
5663 struct btrfs_iget_args *args = opaque;
5664 return args->location->objectid == BTRFS_I(inode)->location.objectid &&
5665 args->root == BTRFS_I(inode)->root;
5668 static struct inode *btrfs_iget_locked(struct super_block *s,
5669 struct btrfs_key *location,
5670 struct btrfs_root *root)
5672 struct inode *inode;
5673 struct btrfs_iget_args args;
5674 unsigned long hashval = btrfs_inode_hash(location->objectid, root);
5676 args.location = location;
5679 inode = iget5_locked(s, hashval, btrfs_find_actor,
5680 btrfs_init_locked_inode,
5685 /* Get an inode object given its location and corresponding root.
5686 * Returns in *is_new if the inode was read from disk
5688 struct inode *btrfs_iget(struct super_block *s, struct btrfs_key *location,
5689 struct btrfs_root *root, int *new)
5691 struct inode *inode;
5693 inode = btrfs_iget_locked(s, location, root);
5695 return ERR_PTR(-ENOMEM);
5697 if (inode->i_state & I_NEW) {
5700 ret = btrfs_read_locked_inode(inode);
5701 if (!is_bad_inode(inode)) {
5702 inode_tree_add(inode);
5703 unlock_new_inode(inode);
5707 unlock_new_inode(inode);
5710 inode = ERR_PTR(ret < 0 ? ret : -ESTALE);
5717 static struct inode *new_simple_dir(struct super_block *s,
5718 struct btrfs_key *key,
5719 struct btrfs_root *root)
5721 struct inode *inode = new_inode(s);
5724 return ERR_PTR(-ENOMEM);
5726 BTRFS_I(inode)->root = root;
5727 memcpy(&BTRFS_I(inode)->location, key, sizeof(*key));
5728 set_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags);
5730 inode->i_ino = BTRFS_EMPTY_SUBVOL_DIR_OBJECTID;
5731 inode->i_op = &btrfs_dir_ro_inode_operations;
5732 inode->i_opflags &= ~IOP_XATTR;
5733 inode->i_fop = &simple_dir_operations;
5734 inode->i_mode = S_IFDIR | S_IRUGO | S_IWUSR | S_IXUGO;
5735 inode->i_mtime = current_time(inode);
5736 inode->i_atime = inode->i_mtime;
5737 inode->i_ctime = inode->i_mtime;
5738 BTRFS_I(inode)->i_otime = inode->i_mtime;
5743 struct inode *btrfs_lookup_dentry(struct inode *dir, struct dentry *dentry)
5745 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
5746 struct inode *inode;
5747 struct btrfs_root *root = BTRFS_I(dir)->root;
5748 struct btrfs_root *sub_root = root;
5749 struct btrfs_key location;
5753 if (dentry->d_name.len > BTRFS_NAME_LEN)
5754 return ERR_PTR(-ENAMETOOLONG);
5756 ret = btrfs_inode_by_name(dir, dentry, &location);
5758 return ERR_PTR(ret);
5760 if (location.type == BTRFS_INODE_ITEM_KEY) {
5761 inode = btrfs_iget(dir->i_sb, &location, root, NULL);
5765 index = srcu_read_lock(&fs_info->subvol_srcu);
5766 ret = fixup_tree_root_location(fs_info, dir, dentry,
5767 &location, &sub_root);
5770 inode = ERR_PTR(ret);
5772 inode = new_simple_dir(dir->i_sb, &location, sub_root);
5774 inode = btrfs_iget(dir->i_sb, &location, sub_root, NULL);
5776 srcu_read_unlock(&fs_info->subvol_srcu, index);
5778 if (!IS_ERR(inode) && root != sub_root) {
5779 down_read(&fs_info->cleanup_work_sem);
5780 if (!sb_rdonly(inode->i_sb))
5781 ret = btrfs_orphan_cleanup(sub_root);
5782 up_read(&fs_info->cleanup_work_sem);
5785 inode = ERR_PTR(ret);
5792 static int btrfs_dentry_delete(const struct dentry *dentry)
5794 struct btrfs_root *root;
5795 struct inode *inode = d_inode(dentry);
5797 if (!inode && !IS_ROOT(dentry))
5798 inode = d_inode(dentry->d_parent);
5801 root = BTRFS_I(inode)->root;
5802 if (btrfs_root_refs(&root->root_item) == 0)
5805 if (btrfs_ino(BTRFS_I(inode)) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)
5811 static struct dentry *btrfs_lookup(struct inode *dir, struct dentry *dentry,
5814 struct inode *inode;
5816 inode = btrfs_lookup_dentry(dir, dentry);
5817 if (IS_ERR(inode)) {
5818 if (PTR_ERR(inode) == -ENOENT)
5821 return ERR_CAST(inode);
5824 return d_splice_alias(inode, dentry);
5827 unsigned char btrfs_filetype_table[] = {
5828 DT_UNKNOWN, DT_REG, DT_DIR, DT_CHR, DT_BLK, DT_FIFO, DT_SOCK, DT_LNK
5832 * All this infrastructure exists because dir_emit can fault, and we are holding
5833 * the tree lock when doing readdir. For now just allocate a buffer and copy
5834 * our information into that, and then dir_emit from the buffer. This is
5835 * similar to what NFS does, only we don't keep the buffer around in pagecache
5836 * because I'm afraid I'll mess that up. Long term we need to make filldir do
5837 * copy_to_user_inatomic so we don't have to worry about page faulting under the
5840 static int btrfs_opendir(struct inode *inode, struct file *file)
5842 struct btrfs_file_private *private;
5844 private = kzalloc(sizeof(struct btrfs_file_private), GFP_KERNEL);
5847 private->filldir_buf = kzalloc(PAGE_SIZE, GFP_KERNEL);
5848 if (!private->filldir_buf) {
5852 file->private_data = private;
5863 static int btrfs_filldir(void *addr, int entries, struct dir_context *ctx)
5866 struct dir_entry *entry = addr;
5867 char *name = (char *)(entry + 1);
5869 ctx->pos = get_unaligned(&entry->offset);
5870 if (!dir_emit(ctx, name, get_unaligned(&entry->name_len),
5871 get_unaligned(&entry->ino),
5872 get_unaligned(&entry->type)))
5874 addr += sizeof(struct dir_entry) +
5875 get_unaligned(&entry->name_len);
5881 static int btrfs_real_readdir(struct file *file, struct dir_context *ctx)
5883 struct inode *inode = file_inode(file);
5884 struct btrfs_root *root = BTRFS_I(inode)->root;
5885 struct btrfs_file_private *private = file->private_data;
5886 struct btrfs_dir_item *di;
5887 struct btrfs_key key;
5888 struct btrfs_key found_key;
5889 struct btrfs_path *path;
5891 struct list_head ins_list;
5892 struct list_head del_list;
5894 struct extent_buffer *leaf;
5901 struct btrfs_key location;
5903 if (!dir_emit_dots(file, ctx))
5906 path = btrfs_alloc_path();
5910 addr = private->filldir_buf;
5911 path->reada = READA_FORWARD;
5913 INIT_LIST_HEAD(&ins_list);
5914 INIT_LIST_HEAD(&del_list);
5915 put = btrfs_readdir_get_delayed_items(inode, &ins_list, &del_list);
5918 key.type = BTRFS_DIR_INDEX_KEY;
5919 key.offset = ctx->pos;
5920 key.objectid = btrfs_ino(BTRFS_I(inode));
5922 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
5927 struct dir_entry *entry;
5929 leaf = path->nodes[0];
5930 slot = path->slots[0];
5931 if (slot >= btrfs_header_nritems(leaf)) {
5932 ret = btrfs_next_leaf(root, path);
5940 btrfs_item_key_to_cpu(leaf, &found_key, slot);
5942 if (found_key.objectid != key.objectid)
5944 if (found_key.type != BTRFS_DIR_INDEX_KEY)
5946 if (found_key.offset < ctx->pos)
5948 if (btrfs_should_delete_dir_index(&del_list, found_key.offset))
5950 di = btrfs_item_ptr(leaf, slot, struct btrfs_dir_item);
5951 name_len = btrfs_dir_name_len(leaf, di);
5952 if ((total_len + sizeof(struct dir_entry) + name_len) >=
5954 btrfs_release_path(path);
5955 ret = btrfs_filldir(private->filldir_buf, entries, ctx);
5958 addr = private->filldir_buf;
5965 put_unaligned(name_len, &entry->name_len);
5966 name_ptr = (char *)(entry + 1);
5967 read_extent_buffer(leaf, name_ptr, (unsigned long)(di + 1),
5969 put_unaligned(btrfs_filetype_table[btrfs_dir_type(leaf, di)],
5971 btrfs_dir_item_key_to_cpu(leaf, di, &location);
5972 put_unaligned(location.objectid, &entry->ino);
5973 put_unaligned(found_key.offset, &entry->offset);
5975 addr += sizeof(struct dir_entry) + name_len;
5976 total_len += sizeof(struct dir_entry) + name_len;
5980 btrfs_release_path(path);
5982 ret = btrfs_filldir(private->filldir_buf, entries, ctx);
5986 ret = btrfs_readdir_delayed_dir_index(ctx, &ins_list);
5991 * Stop new entries from being returned after we return the last
5994 * New directory entries are assigned a strictly increasing
5995 * offset. This means that new entries created during readdir
5996 * are *guaranteed* to be seen in the future by that readdir.
5997 * This has broken buggy programs which operate on names as
5998 * they're returned by readdir. Until we re-use freed offsets
5999 * we have this hack to stop new entries from being returned
6000 * under the assumption that they'll never reach this huge
6003 * This is being careful not to overflow 32bit loff_t unless the
6004 * last entry requires it because doing so has broken 32bit apps
6007 if (ctx->pos >= INT_MAX)
6008 ctx->pos = LLONG_MAX;
6015 btrfs_readdir_put_delayed_items(inode, &ins_list, &del_list);
6016 btrfs_free_path(path);
6020 int btrfs_write_inode(struct inode *inode, struct writeback_control *wbc)
6022 struct btrfs_root *root = BTRFS_I(inode)->root;
6023 struct btrfs_trans_handle *trans;
6025 bool nolock = false;
6027 if (test_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags))
6030 if (btrfs_fs_closing(root->fs_info) &&
6031 btrfs_is_free_space_inode(BTRFS_I(inode)))
6034 if (wbc->sync_mode == WB_SYNC_ALL) {
6036 trans = btrfs_join_transaction_nolock(root);
6038 trans = btrfs_join_transaction(root);
6040 return PTR_ERR(trans);
6041 ret = btrfs_commit_transaction(trans);
6047 * This is somewhat expensive, updating the tree every time the
6048 * inode changes. But, it is most likely to find the inode in cache.
6049 * FIXME, needs more benchmarking...there are no reasons other than performance
6050 * to keep or drop this code.
6052 static int btrfs_dirty_inode(struct inode *inode)
6054 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
6055 struct btrfs_root *root = BTRFS_I(inode)->root;
6056 struct btrfs_trans_handle *trans;
6059 if (test_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags))
6062 trans = btrfs_join_transaction(root);
6064 return PTR_ERR(trans);
6066 ret = btrfs_update_inode(trans, root, inode);
6067 if (ret && ret == -ENOSPC) {
6068 /* whoops, lets try again with the full transaction */
6069 btrfs_end_transaction(trans);
6070 trans = btrfs_start_transaction(root, 1);
6072 return PTR_ERR(trans);
6074 ret = btrfs_update_inode(trans, root, inode);
6076 btrfs_end_transaction(trans);
6077 if (BTRFS_I(inode)->delayed_node)
6078 btrfs_balance_delayed_items(fs_info);
6084 * This is a copy of file_update_time. We need this so we can return error on
6085 * ENOSPC for updating the inode in the case of file write and mmap writes.
6087 static int btrfs_update_time(struct inode *inode, struct timespec *now,
6090 struct btrfs_root *root = BTRFS_I(inode)->root;
6091 bool dirty = flags & ~S_VERSION;
6093 if (btrfs_root_readonly(root))
6096 if (flags & S_VERSION)
6097 dirty |= inode_maybe_inc_iversion(inode, dirty);
6098 if (flags & S_CTIME)
6099 inode->i_ctime = *now;
6100 if (flags & S_MTIME)
6101 inode->i_mtime = *now;
6102 if (flags & S_ATIME)
6103 inode->i_atime = *now;
6104 return dirty ? btrfs_dirty_inode(inode) : 0;
6108 * find the highest existing sequence number in a directory
6109 * and then set the in-memory index_cnt variable to reflect
6110 * free sequence numbers
6112 static int btrfs_set_inode_index_count(struct btrfs_inode *inode)
6114 struct btrfs_root *root = inode->root;
6115 struct btrfs_key key, found_key;
6116 struct btrfs_path *path;
6117 struct extent_buffer *leaf;
6120 key.objectid = btrfs_ino(inode);
6121 key.type = BTRFS_DIR_INDEX_KEY;
6122 key.offset = (u64)-1;
6124 path = btrfs_alloc_path();
6128 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
6131 /* FIXME: we should be able to handle this */
6137 * MAGIC NUMBER EXPLANATION:
6138 * since we search a directory based on f_pos we have to start at 2
6139 * since '.' and '..' have f_pos of 0 and 1 respectively, so everybody
6140 * else has to start at 2
6142 if (path->slots[0] == 0) {
6143 inode->index_cnt = 2;
6149 leaf = path->nodes[0];
6150 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
6152 if (found_key.objectid != btrfs_ino(inode) ||
6153 found_key.type != BTRFS_DIR_INDEX_KEY) {
6154 inode->index_cnt = 2;
6158 inode->index_cnt = found_key.offset + 1;
6160 btrfs_free_path(path);
6165 * helper to find a free sequence number in a given directory. This current
6166 * code is very simple, later versions will do smarter things in the btree
6168 int btrfs_set_inode_index(struct btrfs_inode *dir, u64 *index)
6172 if (dir->index_cnt == (u64)-1) {
6173 ret = btrfs_inode_delayed_dir_index_count(dir);
6175 ret = btrfs_set_inode_index_count(dir);
6181 *index = dir->index_cnt;
6187 static int btrfs_insert_inode_locked(struct inode *inode)
6189 struct btrfs_iget_args args;
6190 args.location = &BTRFS_I(inode)->location;
6191 args.root = BTRFS_I(inode)->root;
6193 return insert_inode_locked4(inode,
6194 btrfs_inode_hash(inode->i_ino, BTRFS_I(inode)->root),
6195 btrfs_find_actor, &args);
6199 * Inherit flags from the parent inode.
6201 * Currently only the compression flags and the cow flags are inherited.
6203 static void btrfs_inherit_iflags(struct inode *inode, struct inode *dir)
6210 flags = BTRFS_I(dir)->flags;
6212 if (flags & BTRFS_INODE_NOCOMPRESS) {
6213 BTRFS_I(inode)->flags &= ~BTRFS_INODE_COMPRESS;
6214 BTRFS_I(inode)->flags |= BTRFS_INODE_NOCOMPRESS;
6215 } else if (flags & BTRFS_INODE_COMPRESS) {
6216 BTRFS_I(inode)->flags &= ~BTRFS_INODE_NOCOMPRESS;
6217 BTRFS_I(inode)->flags |= BTRFS_INODE_COMPRESS;
6220 if (flags & BTRFS_INODE_NODATACOW) {
6221 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATACOW;
6222 if (S_ISREG(inode->i_mode))
6223 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATASUM;
6226 btrfs_sync_inode_flags_to_i_flags(inode);
6229 static struct inode *btrfs_new_inode(struct btrfs_trans_handle *trans,
6230 struct btrfs_root *root,
6232 const char *name, int name_len,
6233 u64 ref_objectid, u64 objectid,
6234 umode_t mode, u64 *index)
6236 struct btrfs_fs_info *fs_info = root->fs_info;
6237 struct inode *inode;
6238 struct btrfs_inode_item *inode_item;
6239 struct btrfs_key *location;
6240 struct btrfs_path *path;
6241 struct btrfs_inode_ref *ref;
6242 struct btrfs_key key[2];
6244 int nitems = name ? 2 : 1;
6248 path = btrfs_alloc_path();
6250 return ERR_PTR(-ENOMEM);
6252 inode = new_inode(fs_info->sb);
6254 btrfs_free_path(path);
6255 return ERR_PTR(-ENOMEM);
6259 * O_TMPFILE, set link count to 0, so that after this point,
6260 * we fill in an inode item with the correct link count.
6263 set_nlink(inode, 0);
6266 * we have to initialize this early, so we can reclaim the inode
6267 * number if we fail afterwards in this function.
6269 inode->i_ino = objectid;
6272 trace_btrfs_inode_request(dir);
6274 ret = btrfs_set_inode_index(BTRFS_I(dir), index);
6276 btrfs_free_path(path);
6278 return ERR_PTR(ret);
6284 * index_cnt is ignored for everything but a dir,
6285 * btrfs_set_inode_index_count has an explanation for the magic
6288 BTRFS_I(inode)->index_cnt = 2;
6289 BTRFS_I(inode)->dir_index = *index;
6290 BTRFS_I(inode)->root = root;
6291 BTRFS_I(inode)->generation = trans->transid;
6292 inode->i_generation = BTRFS_I(inode)->generation;
6295 * We could have gotten an inode number from somebody who was fsynced
6296 * and then removed in this same transaction, so let's just set full
6297 * sync since it will be a full sync anyway and this will blow away the
6298 * old info in the log.
6300 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &BTRFS_I(inode)->runtime_flags);
6302 key[0].objectid = objectid;
6303 key[0].type = BTRFS_INODE_ITEM_KEY;
6306 sizes[0] = sizeof(struct btrfs_inode_item);
6310 * Start new inodes with an inode_ref. This is slightly more
6311 * efficient for small numbers of hard links since they will
6312 * be packed into one item. Extended refs will kick in if we
6313 * add more hard links than can fit in the ref item.
6315 key[1].objectid = objectid;
6316 key[1].type = BTRFS_INODE_REF_KEY;
6317 key[1].offset = ref_objectid;
6319 sizes[1] = name_len + sizeof(*ref);
6322 location = &BTRFS_I(inode)->location;
6323 location->objectid = objectid;
6324 location->offset = 0;
6325 location->type = BTRFS_INODE_ITEM_KEY;
6327 ret = btrfs_insert_inode_locked(inode);
6331 path->leave_spinning = 1;
6332 ret = btrfs_insert_empty_items(trans, root, path, key, sizes, nitems);
6336 inode_init_owner(inode, dir, mode);
6337 inode_set_bytes(inode, 0);
6339 inode->i_mtime = current_time(inode);
6340 inode->i_atime = inode->i_mtime;
6341 inode->i_ctime = inode->i_mtime;
6342 BTRFS_I(inode)->i_otime = inode->i_mtime;
6344 inode_item = btrfs_item_ptr(path->nodes[0], path->slots[0],
6345 struct btrfs_inode_item);
6346 memzero_extent_buffer(path->nodes[0], (unsigned long)inode_item,
6347 sizeof(*inode_item));
6348 fill_inode_item(trans, path->nodes[0], inode_item, inode);
6351 ref = btrfs_item_ptr(path->nodes[0], path->slots[0] + 1,
6352 struct btrfs_inode_ref);
6353 btrfs_set_inode_ref_name_len(path->nodes[0], ref, name_len);
6354 btrfs_set_inode_ref_index(path->nodes[0], ref, *index);
6355 ptr = (unsigned long)(ref + 1);
6356 write_extent_buffer(path->nodes[0], name, ptr, name_len);
6359 btrfs_mark_buffer_dirty(path->nodes[0]);
6360 btrfs_free_path(path);
6362 btrfs_inherit_iflags(inode, dir);
6364 if (S_ISREG(mode)) {
6365 if (btrfs_test_opt(fs_info, NODATASUM))
6366 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATASUM;
6367 if (btrfs_test_opt(fs_info, NODATACOW))
6368 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATACOW |
6369 BTRFS_INODE_NODATASUM;
6372 inode_tree_add(inode);
6374 trace_btrfs_inode_new(inode);
6375 btrfs_set_inode_last_trans(trans, inode);
6377 btrfs_update_root_times(trans, root);
6379 ret = btrfs_inode_inherit_props(trans, inode, dir);
6382 "error inheriting props for ino %llu (root %llu): %d",
6383 btrfs_ino(BTRFS_I(inode)), root->root_key.objectid, ret);
6388 unlock_new_inode(inode);
6391 BTRFS_I(dir)->index_cnt--;
6392 btrfs_free_path(path);
6394 return ERR_PTR(ret);
6397 static inline u8 btrfs_inode_type(struct inode *inode)
6399 return btrfs_type_by_mode[(inode->i_mode & S_IFMT) >> S_SHIFT];
6403 * utility function to add 'inode' into 'parent_inode' with
6404 * a give name and a given sequence number.
6405 * if 'add_backref' is true, also insert a backref from the
6406 * inode to the parent directory.
6408 int btrfs_add_link(struct btrfs_trans_handle *trans,
6409 struct btrfs_inode *parent_inode, struct btrfs_inode *inode,
6410 const char *name, int name_len, int add_backref, u64 index)
6412 struct btrfs_fs_info *fs_info = btrfs_sb(inode->vfs_inode.i_sb);
6414 struct btrfs_key key;
6415 struct btrfs_root *root = parent_inode->root;
6416 u64 ino = btrfs_ino(inode);
6417 u64 parent_ino = btrfs_ino(parent_inode);
6419 if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
6420 memcpy(&key, &inode->root->root_key, sizeof(key));
6423 key.type = BTRFS_INODE_ITEM_KEY;
6427 if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
6428 ret = btrfs_add_root_ref(trans, fs_info, key.objectid,
6429 root->root_key.objectid, parent_ino,
6430 index, name, name_len);
6431 } else if (add_backref) {
6432 ret = btrfs_insert_inode_ref(trans, root, name, name_len, ino,
6436 /* Nothing to clean up yet */
6440 ret = btrfs_insert_dir_item(trans, root, name, name_len,
6442 btrfs_inode_type(&inode->vfs_inode), index);
6443 if (ret == -EEXIST || ret == -EOVERFLOW)
6446 btrfs_abort_transaction(trans, ret);
6450 btrfs_i_size_write(parent_inode, parent_inode->vfs_inode.i_size +
6452 inode_inc_iversion(&parent_inode->vfs_inode);
6453 parent_inode->vfs_inode.i_mtime = parent_inode->vfs_inode.i_ctime =
6454 current_time(&parent_inode->vfs_inode);
6455 ret = btrfs_update_inode(trans, root, &parent_inode->vfs_inode);
6457 btrfs_abort_transaction(trans, ret);
6461 if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
6464 err = btrfs_del_root_ref(trans, fs_info, key.objectid,
6465 root->root_key.objectid, parent_ino,
6466 &local_index, name, name_len);
6468 } else if (add_backref) {
6472 err = btrfs_del_inode_ref(trans, root, name, name_len,
6473 ino, parent_ino, &local_index);
6478 static int btrfs_add_nondir(struct btrfs_trans_handle *trans,
6479 struct btrfs_inode *dir, struct dentry *dentry,
6480 struct btrfs_inode *inode, int backref, u64 index)
6482 int err = btrfs_add_link(trans, dir, inode,
6483 dentry->d_name.name, dentry->d_name.len,
6490 static int btrfs_mknod(struct inode *dir, struct dentry *dentry,
6491 umode_t mode, dev_t rdev)
6493 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
6494 struct btrfs_trans_handle *trans;
6495 struct btrfs_root *root = BTRFS_I(dir)->root;
6496 struct inode *inode = NULL;
6503 * 2 for inode item and ref
6505 * 1 for xattr if selinux is on
6507 trans = btrfs_start_transaction(root, 5);
6509 return PTR_ERR(trans);
6511 err = btrfs_find_free_ino(root, &objectid);
6515 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
6516 dentry->d_name.len, btrfs_ino(BTRFS_I(dir)), objectid,
6518 if (IS_ERR(inode)) {
6519 err = PTR_ERR(inode);
6524 * If the active LSM wants to access the inode during
6525 * d_instantiate it needs these. Smack checks to see
6526 * if the filesystem supports xattrs by looking at the
6529 inode->i_op = &btrfs_special_inode_operations;
6530 init_special_inode(inode, inode->i_mode, rdev);
6532 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
6534 goto out_unlock_inode;
6536 err = btrfs_add_nondir(trans, BTRFS_I(dir), dentry, BTRFS_I(inode),
6539 goto out_unlock_inode;
6541 btrfs_update_inode(trans, root, inode);
6542 d_instantiate_new(dentry, inode);
6546 btrfs_end_transaction(trans);
6547 btrfs_btree_balance_dirty(fs_info);
6549 inode_dec_link_count(inode);
6556 unlock_new_inode(inode);
6561 static int btrfs_create(struct inode *dir, struct dentry *dentry,
6562 umode_t mode, bool excl)
6564 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
6565 struct btrfs_trans_handle *trans;
6566 struct btrfs_root *root = BTRFS_I(dir)->root;
6567 struct inode *inode = NULL;
6568 int drop_inode_on_err = 0;
6574 * 2 for inode item and ref
6576 * 1 for xattr if selinux is on
6578 trans = btrfs_start_transaction(root, 5);
6580 return PTR_ERR(trans);
6582 err = btrfs_find_free_ino(root, &objectid);
6586 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
6587 dentry->d_name.len, btrfs_ino(BTRFS_I(dir)), objectid,
6589 if (IS_ERR(inode)) {
6590 err = PTR_ERR(inode);
6593 drop_inode_on_err = 1;
6595 * If the active LSM wants to access the inode during
6596 * d_instantiate it needs these. Smack checks to see
6597 * if the filesystem supports xattrs by looking at the
6600 inode->i_fop = &btrfs_file_operations;
6601 inode->i_op = &btrfs_file_inode_operations;
6602 inode->i_mapping->a_ops = &btrfs_aops;
6604 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
6606 goto out_unlock_inode;
6608 err = btrfs_update_inode(trans, root, inode);
6610 goto out_unlock_inode;
6612 err = btrfs_add_nondir(trans, BTRFS_I(dir), dentry, BTRFS_I(inode),
6615 goto out_unlock_inode;
6617 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
6618 d_instantiate_new(dentry, inode);
6621 btrfs_end_transaction(trans);
6622 if (err && drop_inode_on_err) {
6623 inode_dec_link_count(inode);
6626 btrfs_btree_balance_dirty(fs_info);
6630 unlock_new_inode(inode);
6635 static int btrfs_link(struct dentry *old_dentry, struct inode *dir,
6636 struct dentry *dentry)
6638 struct btrfs_trans_handle *trans = NULL;
6639 struct btrfs_root *root = BTRFS_I(dir)->root;
6640 struct inode *inode = d_inode(old_dentry);
6641 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
6646 /* do not allow sys_link's with other subvols of the same device */
6647 if (root->objectid != BTRFS_I(inode)->root->objectid)
6650 if (inode->i_nlink >= BTRFS_LINK_MAX)
6653 err = btrfs_set_inode_index(BTRFS_I(dir), &index);
6658 * 2 items for inode and inode ref
6659 * 2 items for dir items
6660 * 1 item for parent inode
6661 * 1 item for orphan item deletion if O_TMPFILE
6663 trans = btrfs_start_transaction(root, inode->i_nlink ? 5 : 6);
6664 if (IS_ERR(trans)) {
6665 err = PTR_ERR(trans);
6670 /* There are several dir indexes for this inode, clear the cache. */
6671 BTRFS_I(inode)->dir_index = 0ULL;
6673 inode_inc_iversion(inode);
6674 inode->i_ctime = current_time(inode);
6676 set_bit(BTRFS_INODE_COPY_EVERYTHING, &BTRFS_I(inode)->runtime_flags);
6678 err = btrfs_add_nondir(trans, BTRFS_I(dir), dentry, BTRFS_I(inode),
6684 struct dentry *parent = dentry->d_parent;
6685 err = btrfs_update_inode(trans, root, inode);
6688 if (inode->i_nlink == 1) {
6690 * If new hard link count is 1, it's a file created
6691 * with open(2) O_TMPFILE flag.
6693 err = btrfs_orphan_del(trans, BTRFS_I(inode));
6697 d_instantiate(dentry, inode);
6698 btrfs_log_new_name(trans, BTRFS_I(inode), NULL, parent);
6703 btrfs_end_transaction(trans);
6705 inode_dec_link_count(inode);
6708 btrfs_btree_balance_dirty(fs_info);
6712 static int btrfs_mkdir(struct inode *dir, struct dentry *dentry, umode_t mode)
6714 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
6715 struct inode *inode = NULL;
6716 struct btrfs_trans_handle *trans;
6717 struct btrfs_root *root = BTRFS_I(dir)->root;
6719 int drop_on_err = 0;
6724 * 2 items for inode and ref
6725 * 2 items for dir items
6726 * 1 for xattr if selinux is on
6728 trans = btrfs_start_transaction(root, 5);
6730 return PTR_ERR(trans);
6732 err = btrfs_find_free_ino(root, &objectid);
6736 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
6737 dentry->d_name.len, btrfs_ino(BTRFS_I(dir)), objectid,
6738 S_IFDIR | mode, &index);
6739 if (IS_ERR(inode)) {
6740 err = PTR_ERR(inode);
6745 /* these must be set before we unlock the inode */
6746 inode->i_op = &btrfs_dir_inode_operations;
6747 inode->i_fop = &btrfs_dir_file_operations;
6749 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
6751 goto out_fail_inode;
6753 btrfs_i_size_write(BTRFS_I(inode), 0);
6754 err = btrfs_update_inode(trans, root, inode);
6756 goto out_fail_inode;
6758 err = btrfs_add_link(trans, BTRFS_I(dir), BTRFS_I(inode),
6759 dentry->d_name.name,
6760 dentry->d_name.len, 0, index);
6762 goto out_fail_inode;
6764 d_instantiate_new(dentry, inode);
6768 btrfs_end_transaction(trans);
6770 inode_dec_link_count(inode);
6773 btrfs_btree_balance_dirty(fs_info);
6777 unlock_new_inode(inode);
6781 static noinline int uncompress_inline(struct btrfs_path *path,
6783 size_t pg_offset, u64 extent_offset,
6784 struct btrfs_file_extent_item *item)
6787 struct extent_buffer *leaf = path->nodes[0];
6790 unsigned long inline_size;
6794 WARN_ON(pg_offset != 0);
6795 compress_type = btrfs_file_extent_compression(leaf, item);
6796 max_size = btrfs_file_extent_ram_bytes(leaf, item);
6797 inline_size = btrfs_file_extent_inline_item_len(leaf,
6798 btrfs_item_nr(path->slots[0]));
6799 tmp = kmalloc(inline_size, GFP_NOFS);
6802 ptr = btrfs_file_extent_inline_start(item);
6804 read_extent_buffer(leaf, tmp, ptr, inline_size);
6806 max_size = min_t(unsigned long, PAGE_SIZE, max_size);
6807 ret = btrfs_decompress(compress_type, tmp, page,
6808 extent_offset, inline_size, max_size);
6811 * decompression code contains a memset to fill in any space between the end
6812 * of the uncompressed data and the end of max_size in case the decompressed
6813 * data ends up shorter than ram_bytes. That doesn't cover the hole between
6814 * the end of an inline extent and the beginning of the next block, so we
6815 * cover that region here.
6818 if (max_size + pg_offset < PAGE_SIZE) {
6819 char *map = kmap(page);
6820 memset(map + pg_offset + max_size, 0, PAGE_SIZE - max_size - pg_offset);
6828 * a bit scary, this does extent mapping from logical file offset to the disk.
6829 * the ugly parts come from merging extents from the disk with the in-ram
6830 * representation. This gets more complex because of the data=ordered code,
6831 * where the in-ram extents might be locked pending data=ordered completion.
6833 * This also copies inline extents directly into the page.
6835 struct extent_map *btrfs_get_extent(struct btrfs_inode *inode,
6837 size_t pg_offset, u64 start, u64 len,
6840 struct btrfs_fs_info *fs_info = btrfs_sb(inode->vfs_inode.i_sb);
6843 u64 extent_start = 0;
6845 u64 objectid = btrfs_ino(inode);
6847 struct btrfs_path *path = NULL;
6848 struct btrfs_root *root = inode->root;
6849 struct btrfs_file_extent_item *item;
6850 struct extent_buffer *leaf;
6851 struct btrfs_key found_key;
6852 struct extent_map *em = NULL;
6853 struct extent_map_tree *em_tree = &inode->extent_tree;
6854 struct extent_io_tree *io_tree = &inode->io_tree;
6855 const bool new_inline = !page || create;
6857 read_lock(&em_tree->lock);
6858 em = lookup_extent_mapping(em_tree, start, len);
6860 em->bdev = fs_info->fs_devices->latest_bdev;
6861 read_unlock(&em_tree->lock);
6864 if (em->start > start || em->start + em->len <= start)
6865 free_extent_map(em);
6866 else if (em->block_start == EXTENT_MAP_INLINE && page)
6867 free_extent_map(em);
6871 em = alloc_extent_map();
6876 em->bdev = fs_info->fs_devices->latest_bdev;
6877 em->start = EXTENT_MAP_HOLE;
6878 em->orig_start = EXTENT_MAP_HOLE;
6880 em->block_len = (u64)-1;
6883 path = btrfs_alloc_path();
6889 * Chances are we'll be called again, so go ahead and do
6892 path->reada = READA_FORWARD;
6895 ret = btrfs_lookup_file_extent(NULL, root, path, objectid, start, 0);
6902 if (path->slots[0] == 0)
6907 leaf = path->nodes[0];
6908 item = btrfs_item_ptr(leaf, path->slots[0],
6909 struct btrfs_file_extent_item);
6910 /* are we inside the extent that was found? */
6911 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
6912 found_type = found_key.type;
6913 if (found_key.objectid != objectid ||
6914 found_type != BTRFS_EXTENT_DATA_KEY) {
6916 * If we backup past the first extent we want to move forward
6917 * and see if there is an extent in front of us, otherwise we'll
6918 * say there is a hole for our whole search range which can
6925 found_type = btrfs_file_extent_type(leaf, item);
6926 extent_start = found_key.offset;
6927 if (found_type == BTRFS_FILE_EXTENT_REG ||
6928 found_type == BTRFS_FILE_EXTENT_PREALLOC) {
6929 extent_end = extent_start +
6930 btrfs_file_extent_num_bytes(leaf, item);
6932 trace_btrfs_get_extent_show_fi_regular(inode, leaf, item,
6934 } else if (found_type == BTRFS_FILE_EXTENT_INLINE) {
6936 size = btrfs_file_extent_inline_len(leaf, path->slots[0], item);
6937 extent_end = ALIGN(extent_start + size,
6938 fs_info->sectorsize);
6940 trace_btrfs_get_extent_show_fi_inline(inode, leaf, item,
6945 if (start >= extent_end) {
6947 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
6948 ret = btrfs_next_leaf(root, path);
6955 leaf = path->nodes[0];
6957 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
6958 if (found_key.objectid != objectid ||
6959 found_key.type != BTRFS_EXTENT_DATA_KEY)
6961 if (start + len <= found_key.offset)
6963 if (start > found_key.offset)
6966 em->orig_start = start;
6967 em->len = found_key.offset - start;
6971 btrfs_extent_item_to_extent_map(inode, path, item,
6974 if (found_type == BTRFS_FILE_EXTENT_REG ||
6975 found_type == BTRFS_FILE_EXTENT_PREALLOC) {
6977 } else if (found_type == BTRFS_FILE_EXTENT_INLINE) {
6981 size_t extent_offset;
6987 size = btrfs_file_extent_inline_len(leaf, path->slots[0], item);
6988 extent_offset = page_offset(page) + pg_offset - extent_start;
6989 copy_size = min_t(u64, PAGE_SIZE - pg_offset,
6990 size - extent_offset);
6991 em->start = extent_start + extent_offset;
6992 em->len = ALIGN(copy_size, fs_info->sectorsize);
6993 em->orig_block_len = em->len;
6994 em->orig_start = em->start;
6995 ptr = btrfs_file_extent_inline_start(item) + extent_offset;
6996 if (!PageUptodate(page)) {
6997 if (btrfs_file_extent_compression(leaf, item) !=
6998 BTRFS_COMPRESS_NONE) {
6999 ret = uncompress_inline(path, page, pg_offset,
7000 extent_offset, item);
7007 read_extent_buffer(leaf, map + pg_offset, ptr,
7009 if (pg_offset + copy_size < PAGE_SIZE) {
7010 memset(map + pg_offset + copy_size, 0,
7011 PAGE_SIZE - pg_offset -
7016 flush_dcache_page(page);
7018 set_extent_uptodate(io_tree, em->start,
7019 extent_map_end(em) - 1, NULL, GFP_NOFS);
7024 em->orig_start = start;
7027 em->block_start = EXTENT_MAP_HOLE;
7029 btrfs_release_path(path);
7030 if (em->start > start || extent_map_end(em) <= start) {
7032 "bad extent! em: [%llu %llu] passed [%llu %llu]",
7033 em->start, em->len, start, len);
7039 write_lock(&em_tree->lock);
7040 err = btrfs_add_extent_mapping(fs_info, em_tree, &em, start, len);
7041 write_unlock(&em_tree->lock);
7044 trace_btrfs_get_extent(root, inode, em);
7046 btrfs_free_path(path);
7048 free_extent_map(em);
7049 return ERR_PTR(err);
7051 BUG_ON(!em); /* Error is always set */
7055 struct extent_map *btrfs_get_extent_fiemap(struct btrfs_inode *inode,
7057 size_t pg_offset, u64 start, u64 len,
7060 struct extent_map *em;
7061 struct extent_map *hole_em = NULL;
7062 u64 range_start = start;
7068 em = btrfs_get_extent(inode, page, pg_offset, start, len, create);
7072 * If our em maps to:
7074 * - a pre-alloc extent,
7075 * there might actually be delalloc bytes behind it.
7077 if (em->block_start != EXTENT_MAP_HOLE &&
7078 !test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
7083 /* check to see if we've wrapped (len == -1 or similar) */
7092 /* ok, we didn't find anything, lets look for delalloc */
7093 found = count_range_bits(&inode->io_tree, &range_start,
7094 end, len, EXTENT_DELALLOC, 1);
7095 found_end = range_start + found;
7096 if (found_end < range_start)
7097 found_end = (u64)-1;
7100 * we didn't find anything useful, return
7101 * the original results from get_extent()
7103 if (range_start > end || found_end <= start) {
7109 /* adjust the range_start to make sure it doesn't
7110 * go backwards from the start they passed in
7112 range_start = max(start, range_start);
7113 found = found_end - range_start;
7116 u64 hole_start = start;
7119 em = alloc_extent_map();
7125 * when btrfs_get_extent can't find anything it
7126 * returns one huge hole
7128 * make sure what it found really fits our range, and
7129 * adjust to make sure it is based on the start from
7133 u64 calc_end = extent_map_end(hole_em);
7135 if (calc_end <= start || (hole_em->start > end)) {
7136 free_extent_map(hole_em);
7139 hole_start = max(hole_em->start, start);
7140 hole_len = calc_end - hole_start;
7144 if (hole_em && range_start > hole_start) {
7145 /* our hole starts before our delalloc, so we
7146 * have to return just the parts of the hole
7147 * that go until the delalloc starts
7149 em->len = min(hole_len,
7150 range_start - hole_start);
7151 em->start = hole_start;
7152 em->orig_start = hole_start;
7154 * don't adjust block start at all,
7155 * it is fixed at EXTENT_MAP_HOLE
7157 em->block_start = hole_em->block_start;
7158 em->block_len = hole_len;
7159 if (test_bit(EXTENT_FLAG_PREALLOC, &hole_em->flags))
7160 set_bit(EXTENT_FLAG_PREALLOC, &em->flags);
7162 em->start = range_start;
7164 em->orig_start = range_start;
7165 em->block_start = EXTENT_MAP_DELALLOC;
7166 em->block_len = found;
7173 free_extent_map(hole_em);
7175 free_extent_map(em);
7176 return ERR_PTR(err);
7181 static struct extent_map *btrfs_create_dio_extent(struct inode *inode,
7184 const u64 orig_start,
7185 const u64 block_start,
7186 const u64 block_len,
7187 const u64 orig_block_len,
7188 const u64 ram_bytes,
7191 struct extent_map *em = NULL;
7194 if (type != BTRFS_ORDERED_NOCOW) {
7195 em = create_io_em(inode, start, len, orig_start,
7196 block_start, block_len, orig_block_len,
7198 BTRFS_COMPRESS_NONE, /* compress_type */
7203 ret = btrfs_add_ordered_extent_dio(inode, start, block_start,
7204 len, block_len, type);
7207 free_extent_map(em);
7208 btrfs_drop_extent_cache(BTRFS_I(inode), start,
7209 start + len - 1, 0);
7218 static struct extent_map *btrfs_new_extent_direct(struct inode *inode,
7221 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7222 struct btrfs_root *root = BTRFS_I(inode)->root;
7223 struct extent_map *em;
7224 struct btrfs_key ins;
7228 alloc_hint = get_extent_allocation_hint(inode, start, len);
7229 ret = btrfs_reserve_extent(root, len, len, fs_info->sectorsize,
7230 0, alloc_hint, &ins, 1, 1);
7232 return ERR_PTR(ret);
7234 em = btrfs_create_dio_extent(inode, start, ins.offset, start,
7235 ins.objectid, ins.offset, ins.offset,
7236 ins.offset, BTRFS_ORDERED_REGULAR);
7237 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
7239 btrfs_free_reserved_extent(fs_info, ins.objectid,
7246 * returns 1 when the nocow is safe, < 1 on error, 0 if the
7247 * block must be cow'd
7249 noinline int can_nocow_extent(struct inode *inode, u64 offset, u64 *len,
7250 u64 *orig_start, u64 *orig_block_len,
7253 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7254 struct btrfs_path *path;
7256 struct extent_buffer *leaf;
7257 struct btrfs_root *root = BTRFS_I(inode)->root;
7258 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
7259 struct btrfs_file_extent_item *fi;
7260 struct btrfs_key key;
7267 bool nocow = (BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW);
7269 path = btrfs_alloc_path();
7273 ret = btrfs_lookup_file_extent(NULL, root, path,
7274 btrfs_ino(BTRFS_I(inode)), offset, 0);
7278 slot = path->slots[0];
7281 /* can't find the item, must cow */
7288 leaf = path->nodes[0];
7289 btrfs_item_key_to_cpu(leaf, &key, slot);
7290 if (key.objectid != btrfs_ino(BTRFS_I(inode)) ||
7291 key.type != BTRFS_EXTENT_DATA_KEY) {
7292 /* not our file or wrong item type, must cow */
7296 if (key.offset > offset) {
7297 /* Wrong offset, must cow */
7301 fi = btrfs_item_ptr(leaf, slot, struct btrfs_file_extent_item);
7302 found_type = btrfs_file_extent_type(leaf, fi);
7303 if (found_type != BTRFS_FILE_EXTENT_REG &&
7304 found_type != BTRFS_FILE_EXTENT_PREALLOC) {
7305 /* not a regular extent, must cow */
7309 if (!nocow && found_type == BTRFS_FILE_EXTENT_REG)
7312 extent_end = key.offset + btrfs_file_extent_num_bytes(leaf, fi);
7313 if (extent_end <= offset)
7316 disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
7317 if (disk_bytenr == 0)
7320 if (btrfs_file_extent_compression(leaf, fi) ||
7321 btrfs_file_extent_encryption(leaf, fi) ||
7322 btrfs_file_extent_other_encoding(leaf, fi))
7325 backref_offset = btrfs_file_extent_offset(leaf, fi);
7328 *orig_start = key.offset - backref_offset;
7329 *orig_block_len = btrfs_file_extent_disk_num_bytes(leaf, fi);
7330 *ram_bytes = btrfs_file_extent_ram_bytes(leaf, fi);
7333 if (btrfs_extent_readonly(fs_info, disk_bytenr))
7336 num_bytes = min(offset + *len, extent_end) - offset;
7337 if (!nocow && found_type == BTRFS_FILE_EXTENT_PREALLOC) {
7340 range_end = round_up(offset + num_bytes,
7341 root->fs_info->sectorsize) - 1;
7342 ret = test_range_bit(io_tree, offset, range_end,
7343 EXTENT_DELALLOC, 0, NULL);
7350 btrfs_release_path(path);
7353 * look for other files referencing this extent, if we
7354 * find any we must cow
7357 ret = btrfs_cross_ref_exist(root, btrfs_ino(BTRFS_I(inode)),
7358 key.offset - backref_offset, disk_bytenr);
7365 * adjust disk_bytenr and num_bytes to cover just the bytes
7366 * in this extent we are about to write. If there
7367 * are any csums in that range we have to cow in order
7368 * to keep the csums correct
7370 disk_bytenr += backref_offset;
7371 disk_bytenr += offset - key.offset;
7372 if (csum_exist_in_range(fs_info, disk_bytenr, num_bytes))
7375 * all of the above have passed, it is safe to overwrite this extent
7381 btrfs_free_path(path);
7385 static int lock_extent_direct(struct inode *inode, u64 lockstart, u64 lockend,
7386 struct extent_state **cached_state, int writing)
7388 struct btrfs_ordered_extent *ordered;
7392 lock_extent_bits(&BTRFS_I(inode)->io_tree, lockstart, lockend,
7395 * We're concerned with the entire range that we're going to be
7396 * doing DIO to, so we need to make sure there's no ordered
7397 * extents in this range.
7399 ordered = btrfs_lookup_ordered_range(BTRFS_I(inode), lockstart,
7400 lockend - lockstart + 1);
7403 * We need to make sure there are no buffered pages in this
7404 * range either, we could have raced between the invalidate in
7405 * generic_file_direct_write and locking the extent. The
7406 * invalidate needs to happen so that reads after a write do not
7410 (!writing || !filemap_range_has_page(inode->i_mapping,
7411 lockstart, lockend)))
7414 unlock_extent_cached(&BTRFS_I(inode)->io_tree, lockstart, lockend,
7419 * If we are doing a DIO read and the ordered extent we
7420 * found is for a buffered write, we can not wait for it
7421 * to complete and retry, because if we do so we can
7422 * deadlock with concurrent buffered writes on page
7423 * locks. This happens only if our DIO read covers more
7424 * than one extent map, if at this point has already
7425 * created an ordered extent for a previous extent map
7426 * and locked its range in the inode's io tree, and a
7427 * concurrent write against that previous extent map's
7428 * range and this range started (we unlock the ranges
7429 * in the io tree only when the bios complete and
7430 * buffered writes always lock pages before attempting
7431 * to lock range in the io tree).
7434 test_bit(BTRFS_ORDERED_DIRECT, &ordered->flags))
7435 btrfs_start_ordered_extent(inode, ordered, 1);
7438 btrfs_put_ordered_extent(ordered);
7441 * We could trigger writeback for this range (and wait
7442 * for it to complete) and then invalidate the pages for
7443 * this range (through invalidate_inode_pages2_range()),
7444 * but that can lead us to a deadlock with a concurrent
7445 * call to readpages() (a buffered read or a defrag call
7446 * triggered a readahead) on a page lock due to an
7447 * ordered dio extent we created before but did not have
7448 * yet a corresponding bio submitted (whence it can not
7449 * complete), which makes readpages() wait for that
7450 * ordered extent to complete while holding a lock on
7465 /* The callers of this must take lock_extent() */
7466 static struct extent_map *create_io_em(struct inode *inode, u64 start, u64 len,
7467 u64 orig_start, u64 block_start,
7468 u64 block_len, u64 orig_block_len,
7469 u64 ram_bytes, int compress_type,
7472 struct extent_map_tree *em_tree;
7473 struct extent_map *em;
7474 struct btrfs_root *root = BTRFS_I(inode)->root;
7477 ASSERT(type == BTRFS_ORDERED_PREALLOC ||
7478 type == BTRFS_ORDERED_COMPRESSED ||
7479 type == BTRFS_ORDERED_NOCOW ||
7480 type == BTRFS_ORDERED_REGULAR);
7482 em_tree = &BTRFS_I(inode)->extent_tree;
7483 em = alloc_extent_map();
7485 return ERR_PTR(-ENOMEM);
7488 em->orig_start = orig_start;
7490 em->block_len = block_len;
7491 em->block_start = block_start;
7492 em->bdev = root->fs_info->fs_devices->latest_bdev;
7493 em->orig_block_len = orig_block_len;
7494 em->ram_bytes = ram_bytes;
7495 em->generation = -1;
7496 set_bit(EXTENT_FLAG_PINNED, &em->flags);
7497 if (type == BTRFS_ORDERED_PREALLOC) {
7498 set_bit(EXTENT_FLAG_FILLING, &em->flags);
7499 } else if (type == BTRFS_ORDERED_COMPRESSED) {
7500 set_bit(EXTENT_FLAG_COMPRESSED, &em->flags);
7501 em->compress_type = compress_type;
7505 btrfs_drop_extent_cache(BTRFS_I(inode), em->start,
7506 em->start + em->len - 1, 0);
7507 write_lock(&em_tree->lock);
7508 ret = add_extent_mapping(em_tree, em, 1);
7509 write_unlock(&em_tree->lock);
7511 * The caller has taken lock_extent(), who could race with us
7514 } while (ret == -EEXIST);
7517 free_extent_map(em);
7518 return ERR_PTR(ret);
7521 /* em got 2 refs now, callers needs to do free_extent_map once. */
7525 static int btrfs_get_blocks_direct(struct inode *inode, sector_t iblock,
7526 struct buffer_head *bh_result, int create)
7528 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7529 struct extent_map *em;
7530 struct extent_state *cached_state = NULL;
7531 struct btrfs_dio_data *dio_data = NULL;
7532 u64 start = iblock << inode->i_blkbits;
7533 u64 lockstart, lockend;
7534 u64 len = bh_result->b_size;
7535 int unlock_bits = EXTENT_LOCKED;
7539 unlock_bits |= EXTENT_DIRTY;
7541 len = min_t(u64, len, fs_info->sectorsize);
7544 lockend = start + len - 1;
7546 if (current->journal_info) {
7548 * Need to pull our outstanding extents and set journal_info to NULL so
7549 * that anything that needs to check if there's a transaction doesn't get
7552 dio_data = current->journal_info;
7553 current->journal_info = NULL;
7557 * If this errors out it's because we couldn't invalidate pagecache for
7558 * this range and we need to fallback to buffered.
7560 if (lock_extent_direct(inode, lockstart, lockend, &cached_state,
7566 em = btrfs_get_extent(BTRFS_I(inode), NULL, 0, start, len, 0);
7573 * Ok for INLINE and COMPRESSED extents we need to fallback on buffered
7574 * io. INLINE is special, and we could probably kludge it in here, but
7575 * it's still buffered so for safety lets just fall back to the generic
7578 * For COMPRESSED we _have_ to read the entire extent in so we can
7579 * decompress it, so there will be buffering required no matter what we
7580 * do, so go ahead and fallback to buffered.
7582 * We return -ENOTBLK because that's what makes DIO go ahead and go back
7583 * to buffered IO. Don't blame me, this is the price we pay for using
7586 if (test_bit(EXTENT_FLAG_COMPRESSED, &em->flags) ||
7587 em->block_start == EXTENT_MAP_INLINE) {
7588 free_extent_map(em);
7593 /* Just a good old fashioned hole, return */
7594 if (!create && (em->block_start == EXTENT_MAP_HOLE ||
7595 test_bit(EXTENT_FLAG_PREALLOC, &em->flags))) {
7596 free_extent_map(em);
7601 * We don't allocate a new extent in the following cases
7603 * 1) The inode is marked as NODATACOW. In this case we'll just use the
7605 * 2) The extent is marked as PREALLOC. We're good to go here and can
7606 * just use the extent.
7610 len = min(len, em->len - (start - em->start));
7611 lockstart = start + len;
7615 if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags) ||
7616 ((BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW) &&
7617 em->block_start != EXTENT_MAP_HOLE)) {
7619 u64 block_start, orig_start, orig_block_len, ram_bytes;
7621 if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
7622 type = BTRFS_ORDERED_PREALLOC;
7624 type = BTRFS_ORDERED_NOCOW;
7625 len = min(len, em->len - (start - em->start));
7626 block_start = em->block_start + (start - em->start);
7628 if (can_nocow_extent(inode, start, &len, &orig_start,
7629 &orig_block_len, &ram_bytes) == 1 &&
7630 btrfs_inc_nocow_writers(fs_info, block_start)) {
7631 struct extent_map *em2;
7633 em2 = btrfs_create_dio_extent(inode, start, len,
7634 orig_start, block_start,
7635 len, orig_block_len,
7637 btrfs_dec_nocow_writers(fs_info, block_start);
7638 if (type == BTRFS_ORDERED_PREALLOC) {
7639 free_extent_map(em);
7642 if (em2 && IS_ERR(em2)) {
7647 * For inode marked NODATACOW or extent marked PREALLOC,
7648 * use the existing or preallocated extent, so does not
7649 * need to adjust btrfs_space_info's bytes_may_use.
7651 btrfs_free_reserved_data_space_noquota(inode,
7658 * this will cow the extent, reset the len in case we changed
7661 len = bh_result->b_size;
7662 free_extent_map(em);
7663 em = btrfs_new_extent_direct(inode, start, len);
7668 len = min(len, em->len - (start - em->start));
7670 bh_result->b_blocknr = (em->block_start + (start - em->start)) >>
7672 bh_result->b_size = len;
7673 bh_result->b_bdev = em->bdev;
7674 set_buffer_mapped(bh_result);
7676 if (!test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
7677 set_buffer_new(bh_result);
7680 * Need to update the i_size under the extent lock so buffered
7681 * readers will get the updated i_size when we unlock.
7683 if (!dio_data->overwrite && start + len > i_size_read(inode))
7684 i_size_write(inode, start + len);
7686 WARN_ON(dio_data->reserve < len);
7687 dio_data->reserve -= len;
7688 dio_data->unsubmitted_oe_range_end = start + len;
7689 current->journal_info = dio_data;
7693 * In the case of write we need to clear and unlock the entire range,
7694 * in the case of read we need to unlock only the end area that we
7695 * aren't using if there is any left over space.
7697 if (lockstart < lockend) {
7698 clear_extent_bit(&BTRFS_I(inode)->io_tree, lockstart,
7699 lockend, unlock_bits, 1, 0,
7702 free_extent_state(cached_state);
7705 free_extent_map(em);
7710 clear_extent_bit(&BTRFS_I(inode)->io_tree, lockstart, lockend,
7711 unlock_bits, 1, 0, &cached_state);
7714 current->journal_info = dio_data;
7718 static inline blk_status_t submit_dio_repair_bio(struct inode *inode,
7722 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7725 BUG_ON(bio_op(bio) == REQ_OP_WRITE);
7727 ret = btrfs_bio_wq_end_io(fs_info, bio, BTRFS_WQ_ENDIO_DIO_REPAIR);
7731 ret = btrfs_map_bio(fs_info, bio, mirror_num, 0);
7736 static int btrfs_check_dio_repairable(struct inode *inode,
7737 struct bio *failed_bio,
7738 struct io_failure_record *failrec,
7741 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7744 num_copies = btrfs_num_copies(fs_info, failrec->logical, failrec->len);
7745 if (num_copies == 1) {
7747 * we only have a single copy of the data, so don't bother with
7748 * all the retry and error correction code that follows. no
7749 * matter what the error is, it is very likely to persist.
7751 btrfs_debug(fs_info,
7752 "Check DIO Repairable: cannot repair, num_copies=%d, next_mirror %d, failed_mirror %d",
7753 num_copies, failrec->this_mirror, failed_mirror);
7757 failrec->failed_mirror = failed_mirror;
7758 failrec->this_mirror++;
7759 if (failrec->this_mirror == failed_mirror)
7760 failrec->this_mirror++;
7762 if (failrec->this_mirror > num_copies) {
7763 btrfs_debug(fs_info,
7764 "Check DIO Repairable: (fail) num_copies=%d, next_mirror %d, failed_mirror %d",
7765 num_copies, failrec->this_mirror, failed_mirror);
7772 static blk_status_t dio_read_error(struct inode *inode, struct bio *failed_bio,
7773 struct page *page, unsigned int pgoff,
7774 u64 start, u64 end, int failed_mirror,
7775 bio_end_io_t *repair_endio, void *repair_arg)
7777 struct io_failure_record *failrec;
7778 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
7779 struct extent_io_tree *failure_tree = &BTRFS_I(inode)->io_failure_tree;
7782 unsigned int read_mode = 0;
7785 blk_status_t status;
7786 struct bio_vec bvec;
7788 BUG_ON(bio_op(failed_bio) == REQ_OP_WRITE);
7790 ret = btrfs_get_io_failure_record(inode, start, end, &failrec);
7792 return errno_to_blk_status(ret);
7794 ret = btrfs_check_dio_repairable(inode, failed_bio, failrec,
7797 free_io_failure(failure_tree, io_tree, failrec);
7798 return BLK_STS_IOERR;
7801 segs = bio_segments(failed_bio);
7802 bio_get_first_bvec(failed_bio, &bvec);
7804 (bvec.bv_len > btrfs_inode_sectorsize(inode)))
7805 read_mode |= REQ_FAILFAST_DEV;
7807 isector = start - btrfs_io_bio(failed_bio)->logical;
7808 isector >>= inode->i_sb->s_blocksize_bits;
7809 bio = btrfs_create_repair_bio(inode, failed_bio, failrec, page,
7810 pgoff, isector, repair_endio, repair_arg);
7811 bio_set_op_attrs(bio, REQ_OP_READ, read_mode);
7813 btrfs_debug(BTRFS_I(inode)->root->fs_info,
7814 "repair DIO read error: submitting new dio read[%#x] to this_mirror=%d, in_validation=%d",
7815 read_mode, failrec->this_mirror, failrec->in_validation);
7817 status = submit_dio_repair_bio(inode, bio, failrec->this_mirror);
7819 free_io_failure(failure_tree, io_tree, failrec);
7826 struct btrfs_retry_complete {
7827 struct completion done;
7828 struct inode *inode;
7833 static void btrfs_retry_endio_nocsum(struct bio *bio)
7835 struct btrfs_retry_complete *done = bio->bi_private;
7836 struct inode *inode = done->inode;
7837 struct bio_vec *bvec;
7838 struct extent_io_tree *io_tree, *failure_tree;
7844 ASSERT(bio->bi_vcnt == 1);
7845 io_tree = &BTRFS_I(inode)->io_tree;
7846 failure_tree = &BTRFS_I(inode)->io_failure_tree;
7847 ASSERT(bio_first_bvec_all(bio)->bv_len == btrfs_inode_sectorsize(inode));
7850 ASSERT(!bio_flagged(bio, BIO_CLONED));
7851 bio_for_each_segment_all(bvec, bio, i)
7852 clean_io_failure(BTRFS_I(inode)->root->fs_info, failure_tree,
7853 io_tree, done->start, bvec->bv_page,
7854 btrfs_ino(BTRFS_I(inode)), 0);
7856 complete(&done->done);
7860 static blk_status_t __btrfs_correct_data_nocsum(struct inode *inode,
7861 struct btrfs_io_bio *io_bio)
7863 struct btrfs_fs_info *fs_info;
7864 struct bio_vec bvec;
7865 struct bvec_iter iter;
7866 struct btrfs_retry_complete done;
7872 blk_status_t err = BLK_STS_OK;
7874 fs_info = BTRFS_I(inode)->root->fs_info;
7875 sectorsize = fs_info->sectorsize;
7877 start = io_bio->logical;
7879 io_bio->bio.bi_iter = io_bio->iter;
7881 bio_for_each_segment(bvec, &io_bio->bio, iter) {
7882 nr_sectors = BTRFS_BYTES_TO_BLKS(fs_info, bvec.bv_len);
7883 pgoff = bvec.bv_offset;
7885 next_block_or_try_again:
7888 init_completion(&done.done);
7890 ret = dio_read_error(inode, &io_bio->bio, bvec.bv_page,
7891 pgoff, start, start + sectorsize - 1,
7893 btrfs_retry_endio_nocsum, &done);
7899 wait_for_completion_io(&done.done);
7901 if (!done.uptodate) {
7902 /* We might have another mirror, so try again */
7903 goto next_block_or_try_again;
7907 start += sectorsize;
7911 pgoff += sectorsize;
7912 ASSERT(pgoff < PAGE_SIZE);
7913 goto next_block_or_try_again;
7920 static void btrfs_retry_endio(struct bio *bio)
7922 struct btrfs_retry_complete *done = bio->bi_private;
7923 struct btrfs_io_bio *io_bio = btrfs_io_bio(bio);
7924 struct extent_io_tree *io_tree, *failure_tree;
7925 struct inode *inode = done->inode;
7926 struct bio_vec *bvec;
7936 ASSERT(bio->bi_vcnt == 1);
7937 ASSERT(bio_first_bvec_all(bio)->bv_len == btrfs_inode_sectorsize(done->inode));
7939 io_tree = &BTRFS_I(inode)->io_tree;
7940 failure_tree = &BTRFS_I(inode)->io_failure_tree;
7942 ASSERT(!bio_flagged(bio, BIO_CLONED));
7943 bio_for_each_segment_all(bvec, bio, i) {
7944 ret = __readpage_endio_check(inode, io_bio, i, bvec->bv_page,
7945 bvec->bv_offset, done->start,
7948 clean_io_failure(BTRFS_I(inode)->root->fs_info,
7949 failure_tree, io_tree, done->start,
7951 btrfs_ino(BTRFS_I(inode)),
7957 done->uptodate = uptodate;
7959 complete(&done->done);
7963 static blk_status_t __btrfs_subio_endio_read(struct inode *inode,
7964 struct btrfs_io_bio *io_bio, blk_status_t err)
7966 struct btrfs_fs_info *fs_info;
7967 struct bio_vec bvec;
7968 struct bvec_iter iter;
7969 struct btrfs_retry_complete done;
7976 bool uptodate = (err == 0);
7978 blk_status_t status;
7980 fs_info = BTRFS_I(inode)->root->fs_info;
7981 sectorsize = fs_info->sectorsize;
7984 start = io_bio->logical;
7986 io_bio->bio.bi_iter = io_bio->iter;
7988 bio_for_each_segment(bvec, &io_bio->bio, iter) {
7989 nr_sectors = BTRFS_BYTES_TO_BLKS(fs_info, bvec.bv_len);
7991 pgoff = bvec.bv_offset;
7994 csum_pos = BTRFS_BYTES_TO_BLKS(fs_info, offset);
7995 ret = __readpage_endio_check(inode, io_bio, csum_pos,
7996 bvec.bv_page, pgoff, start, sectorsize);
8003 init_completion(&done.done);
8005 status = dio_read_error(inode, &io_bio->bio, bvec.bv_page,
8006 pgoff, start, start + sectorsize - 1,
8007 io_bio->mirror_num, btrfs_retry_endio,
8014 wait_for_completion_io(&done.done);
8016 if (!done.uptodate) {
8017 /* We might have another mirror, so try again */
8021 offset += sectorsize;
8022 start += sectorsize;
8028 pgoff += sectorsize;
8029 ASSERT(pgoff < PAGE_SIZE);
8037 static blk_status_t btrfs_subio_endio_read(struct inode *inode,
8038 struct btrfs_io_bio *io_bio, blk_status_t err)
8040 bool skip_csum = BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM;
8044 return __btrfs_correct_data_nocsum(inode, io_bio);
8048 return __btrfs_subio_endio_read(inode, io_bio, err);
8052 static void btrfs_endio_direct_read(struct bio *bio)
8054 struct btrfs_dio_private *dip = bio->bi_private;
8055 struct inode *inode = dip->inode;
8056 struct bio *dio_bio;
8057 struct btrfs_io_bio *io_bio = btrfs_io_bio(bio);
8058 blk_status_t err = bio->bi_status;
8060 if (dip->flags & BTRFS_DIO_ORIG_BIO_SUBMITTED)
8061 err = btrfs_subio_endio_read(inode, io_bio, err);
8063 unlock_extent(&BTRFS_I(inode)->io_tree, dip->logical_offset,
8064 dip->logical_offset + dip->bytes - 1);
8065 dio_bio = dip->dio_bio;
8069 dio_bio->bi_status = err;
8070 dio_end_io(dio_bio);
8073 io_bio->end_io(io_bio, blk_status_to_errno(err));
8077 static void __endio_write_update_ordered(struct inode *inode,
8078 const u64 offset, const u64 bytes,
8079 const bool uptodate)
8081 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
8082 struct btrfs_ordered_extent *ordered = NULL;
8083 struct btrfs_workqueue *wq;
8084 btrfs_work_func_t func;
8085 u64 ordered_offset = offset;
8086 u64 ordered_bytes = bytes;
8089 if (btrfs_is_free_space_inode(BTRFS_I(inode))) {
8090 wq = fs_info->endio_freespace_worker;
8091 func = btrfs_freespace_write_helper;
8093 wq = fs_info->endio_write_workers;
8094 func = btrfs_endio_write_helper;
8097 while (ordered_offset < offset + bytes) {
8098 last_offset = ordered_offset;
8099 if (btrfs_dec_test_first_ordered_pending(inode, &ordered,
8103 btrfs_init_work(&ordered->work, func,
8106 btrfs_queue_work(wq, &ordered->work);
8109 * If btrfs_dec_test_ordered_pending does not find any ordered
8110 * extent in the range, we can exit.
8112 if (ordered_offset == last_offset)
8115 * Our bio might span multiple ordered extents. In this case
8116 * we keep goin until we have accounted the whole dio.
8118 if (ordered_offset < offset + bytes) {
8119 ordered_bytes = offset + bytes - ordered_offset;
8125 static void btrfs_endio_direct_write(struct bio *bio)
8127 struct btrfs_dio_private *dip = bio->bi_private;
8128 struct bio *dio_bio = dip->dio_bio;
8130 __endio_write_update_ordered(dip->inode, dip->logical_offset,
8131 dip->bytes, !bio->bi_status);
8135 dio_bio->bi_status = bio->bi_status;
8136 dio_end_io(dio_bio);
8140 static blk_status_t btrfs_submit_bio_start_direct_io(void *private_data,
8141 struct bio *bio, u64 offset)
8143 struct inode *inode = private_data;
8145 ret = btrfs_csum_one_bio(inode, bio, offset, 1);
8146 BUG_ON(ret); /* -ENOMEM */
8150 static void btrfs_end_dio_bio(struct bio *bio)
8152 struct btrfs_dio_private *dip = bio->bi_private;
8153 blk_status_t err = bio->bi_status;
8156 btrfs_warn(BTRFS_I(dip->inode)->root->fs_info,
8157 "direct IO failed ino %llu rw %d,%u sector %#Lx len %u err no %d",
8158 btrfs_ino(BTRFS_I(dip->inode)), bio_op(bio),
8160 (unsigned long long)bio->bi_iter.bi_sector,
8161 bio->bi_iter.bi_size, err);
8163 if (dip->subio_endio)
8164 err = dip->subio_endio(dip->inode, btrfs_io_bio(bio), err);
8168 * We want to perceive the errors flag being set before
8169 * decrementing the reference count. We don't need a barrier
8170 * since atomic operations with a return value are fully
8171 * ordered as per atomic_t.txt
8176 /* if there are more bios still pending for this dio, just exit */
8177 if (!atomic_dec_and_test(&dip->pending_bios))
8181 bio_io_error(dip->orig_bio);
8183 dip->dio_bio->bi_status = BLK_STS_OK;
8184 bio_endio(dip->orig_bio);
8190 static inline blk_status_t btrfs_lookup_and_bind_dio_csum(struct inode *inode,
8191 struct btrfs_dio_private *dip,
8195 struct btrfs_io_bio *io_bio = btrfs_io_bio(bio);
8196 struct btrfs_io_bio *orig_io_bio = btrfs_io_bio(dip->orig_bio);
8200 * We load all the csum data we need when we submit
8201 * the first bio to reduce the csum tree search and
8204 if (dip->logical_offset == file_offset) {
8205 ret = btrfs_lookup_bio_sums_dio(inode, dip->orig_bio,
8211 if (bio == dip->orig_bio)
8214 file_offset -= dip->logical_offset;
8215 file_offset >>= inode->i_sb->s_blocksize_bits;
8216 io_bio->csum = (u8 *)(((u32 *)orig_io_bio->csum) + file_offset);
8221 static inline blk_status_t btrfs_submit_dio_bio(struct bio *bio,
8222 struct inode *inode, u64 file_offset, int async_submit)
8224 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
8225 struct btrfs_dio_private *dip = bio->bi_private;
8226 bool write = bio_op(bio) == REQ_OP_WRITE;
8229 /* Check btrfs_submit_bio_hook() for rules about async submit. */
8231 async_submit = !atomic_read(&BTRFS_I(inode)->sync_writers);
8234 ret = btrfs_bio_wq_end_io(fs_info, bio, BTRFS_WQ_ENDIO_DATA);
8239 if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)
8242 if (write && async_submit) {
8243 ret = btrfs_wq_submit_bio(fs_info, bio, 0, 0,
8245 btrfs_submit_bio_start_direct_io,
8246 btrfs_submit_bio_done);
8250 * If we aren't doing async submit, calculate the csum of the
8253 ret = btrfs_csum_one_bio(inode, bio, file_offset, 1);
8257 ret = btrfs_lookup_and_bind_dio_csum(inode, dip, bio,
8263 ret = btrfs_map_bio(fs_info, bio, 0, 0);
8268 static int btrfs_submit_direct_hook(struct btrfs_dio_private *dip)
8270 struct inode *inode = dip->inode;
8271 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
8273 struct bio *orig_bio = dip->orig_bio;
8274 u64 start_sector = orig_bio->bi_iter.bi_sector;
8275 u64 file_offset = dip->logical_offset;
8277 int async_submit = 0;
8279 int clone_offset = 0;
8282 blk_status_t status;
8284 map_length = orig_bio->bi_iter.bi_size;
8285 submit_len = map_length;
8286 ret = btrfs_map_block(fs_info, btrfs_op(orig_bio), start_sector << 9,
8287 &map_length, NULL, 0);
8291 if (map_length >= submit_len) {
8293 dip->flags |= BTRFS_DIO_ORIG_BIO_SUBMITTED;
8297 /* async crcs make it difficult to collect full stripe writes. */
8298 if (btrfs_data_alloc_profile(fs_info) & BTRFS_BLOCK_GROUP_RAID56_MASK)
8304 ASSERT(map_length <= INT_MAX);
8305 atomic_inc(&dip->pending_bios);
8307 clone_len = min_t(int, submit_len, map_length);
8310 * This will never fail as it's passing GPF_NOFS and
8311 * the allocation is backed by btrfs_bioset.
8313 bio = btrfs_bio_clone_partial(orig_bio, clone_offset,
8315 bio->bi_private = dip;
8316 bio->bi_end_io = btrfs_end_dio_bio;
8317 btrfs_io_bio(bio)->logical = file_offset;
8319 ASSERT(submit_len >= clone_len);
8320 submit_len -= clone_len;
8321 if (submit_len == 0)
8325 * Increase the count before we submit the bio so we know
8326 * the end IO handler won't happen before we increase the
8327 * count. Otherwise, the dip might get freed before we're
8328 * done setting it up.
8330 atomic_inc(&dip->pending_bios);
8332 status = btrfs_submit_dio_bio(bio, inode, file_offset,
8336 atomic_dec(&dip->pending_bios);
8340 clone_offset += clone_len;
8341 start_sector += clone_len >> 9;
8342 file_offset += clone_len;
8344 map_length = submit_len;
8345 ret = btrfs_map_block(fs_info, btrfs_op(orig_bio),
8346 start_sector << 9, &map_length, NULL, 0);
8349 } while (submit_len > 0);
8352 status = btrfs_submit_dio_bio(bio, inode, file_offset, async_submit);
8360 * Before atomic variable goto zero, we must make sure dip->errors is
8361 * perceived to be set. This ordering is ensured by the fact that an
8362 * atomic operations with a return value are fully ordered as per
8365 if (atomic_dec_and_test(&dip->pending_bios))
8366 bio_io_error(dip->orig_bio);
8368 /* bio_end_io() will handle error, so we needn't return it */
8372 static void btrfs_submit_direct(struct bio *dio_bio, struct inode *inode,
8375 struct btrfs_dio_private *dip = NULL;
8376 struct bio *bio = NULL;
8377 struct btrfs_io_bio *io_bio;
8378 bool write = (bio_op(dio_bio) == REQ_OP_WRITE);
8381 bio = btrfs_bio_clone(dio_bio);
8383 dip = kzalloc(sizeof(*dip), GFP_NOFS);
8389 dip->private = dio_bio->bi_private;
8391 dip->logical_offset = file_offset;
8392 dip->bytes = dio_bio->bi_iter.bi_size;
8393 dip->disk_bytenr = (u64)dio_bio->bi_iter.bi_sector << 9;
8394 bio->bi_private = dip;
8395 dip->orig_bio = bio;
8396 dip->dio_bio = dio_bio;
8397 atomic_set(&dip->pending_bios, 0);
8398 io_bio = btrfs_io_bio(bio);
8399 io_bio->logical = file_offset;
8402 bio->bi_end_io = btrfs_endio_direct_write;
8404 bio->bi_end_io = btrfs_endio_direct_read;
8405 dip->subio_endio = btrfs_subio_endio_read;
8409 * Reset the range for unsubmitted ordered extents (to a 0 length range)
8410 * even if we fail to submit a bio, because in such case we do the
8411 * corresponding error handling below and it must not be done a second
8412 * time by btrfs_direct_IO().
8415 struct btrfs_dio_data *dio_data = current->journal_info;
8417 dio_data->unsubmitted_oe_range_end = dip->logical_offset +
8419 dio_data->unsubmitted_oe_range_start =
8420 dio_data->unsubmitted_oe_range_end;
8423 ret = btrfs_submit_direct_hook(dip);
8428 io_bio->end_io(io_bio, ret);
8432 * If we arrived here it means either we failed to submit the dip
8433 * or we either failed to clone the dio_bio or failed to allocate the
8434 * dip. If we cloned the dio_bio and allocated the dip, we can just
8435 * call bio_endio against our io_bio so that we get proper resource
8436 * cleanup if we fail to submit the dip, otherwise, we must do the
8437 * same as btrfs_endio_direct_[write|read] because we can't call these
8438 * callbacks - they require an allocated dip and a clone of dio_bio.
8443 * The end io callbacks free our dip, do the final put on bio
8444 * and all the cleanup and final put for dio_bio (through
8451 __endio_write_update_ordered(inode,
8453 dio_bio->bi_iter.bi_size,
8456 unlock_extent(&BTRFS_I(inode)->io_tree, file_offset,
8457 file_offset + dio_bio->bi_iter.bi_size - 1);
8459 dio_bio->bi_status = BLK_STS_IOERR;
8461 * Releases and cleans up our dio_bio, no need to bio_put()
8462 * nor bio_endio()/bio_io_error() against dio_bio.
8464 dio_end_io(dio_bio);
8471 static ssize_t check_direct_IO(struct btrfs_fs_info *fs_info,
8472 const struct iov_iter *iter, loff_t offset)
8476 unsigned int blocksize_mask = fs_info->sectorsize - 1;
8477 ssize_t retval = -EINVAL;
8479 if (offset & blocksize_mask)
8482 if (iov_iter_alignment(iter) & blocksize_mask)
8485 /* If this is a write we don't need to check anymore */
8486 if (iov_iter_rw(iter) != READ || !iter_is_iovec(iter))
8489 * Check to make sure we don't have duplicate iov_base's in this
8490 * iovec, if so return EINVAL, otherwise we'll get csum errors
8491 * when reading back.
8493 for (seg = 0; seg < iter->nr_segs; seg++) {
8494 for (i = seg + 1; i < iter->nr_segs; i++) {
8495 if (iter->iov[seg].iov_base == iter->iov[i].iov_base)
8504 static ssize_t btrfs_direct_IO(struct kiocb *iocb, struct iov_iter *iter)
8506 struct file *file = iocb->ki_filp;
8507 struct inode *inode = file->f_mapping->host;
8508 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
8509 struct btrfs_dio_data dio_data = { 0 };
8510 struct extent_changeset *data_reserved = NULL;
8511 loff_t offset = iocb->ki_pos;
8515 bool relock = false;
8518 if (check_direct_IO(fs_info, iter, offset))
8521 inode_dio_begin(inode);
8524 * The generic stuff only does filemap_write_and_wait_range, which
8525 * isn't enough if we've written compressed pages to this area, so
8526 * we need to flush the dirty pages again to make absolutely sure
8527 * that any outstanding dirty pages are on disk.
8529 count = iov_iter_count(iter);
8530 if (test_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
8531 &BTRFS_I(inode)->runtime_flags))
8532 filemap_fdatawrite_range(inode->i_mapping, offset,
8533 offset + count - 1);
8535 if (iov_iter_rw(iter) == WRITE) {
8537 * If the write DIO is beyond the EOF, we need update
8538 * the isize, but it is protected by i_mutex. So we can
8539 * not unlock the i_mutex at this case.
8541 if (offset + count <= inode->i_size) {
8542 dio_data.overwrite = 1;
8543 inode_unlock(inode);
8545 } else if (iocb->ki_flags & IOCB_NOWAIT) {
8549 ret = btrfs_delalloc_reserve_space(inode, &data_reserved,
8555 * We need to know how many extents we reserved so that we can
8556 * do the accounting properly if we go over the number we
8557 * originally calculated. Abuse current->journal_info for this.
8559 dio_data.reserve = round_up(count,
8560 fs_info->sectorsize);
8561 dio_data.unsubmitted_oe_range_start = (u64)offset;
8562 dio_data.unsubmitted_oe_range_end = (u64)offset;
8563 current->journal_info = &dio_data;
8564 down_read(&BTRFS_I(inode)->dio_sem);
8565 } else if (test_bit(BTRFS_INODE_READDIO_NEED_LOCK,
8566 &BTRFS_I(inode)->runtime_flags)) {
8567 inode_dio_end(inode);
8568 flags = DIO_LOCKING | DIO_SKIP_HOLES;
8572 ret = __blockdev_direct_IO(iocb, inode,
8573 fs_info->fs_devices->latest_bdev,
8574 iter, btrfs_get_blocks_direct, NULL,
8575 btrfs_submit_direct, flags);
8576 if (iov_iter_rw(iter) == WRITE) {
8577 up_read(&BTRFS_I(inode)->dio_sem);
8578 current->journal_info = NULL;
8579 if (ret < 0 && ret != -EIOCBQUEUED) {
8580 if (dio_data.reserve)
8581 btrfs_delalloc_release_space(inode, data_reserved,
8582 offset, dio_data.reserve, true);
8584 * On error we might have left some ordered extents
8585 * without submitting corresponding bios for them, so
8586 * cleanup them up to avoid other tasks getting them
8587 * and waiting for them to complete forever.
8589 if (dio_data.unsubmitted_oe_range_start <
8590 dio_data.unsubmitted_oe_range_end)
8591 __endio_write_update_ordered(inode,
8592 dio_data.unsubmitted_oe_range_start,
8593 dio_data.unsubmitted_oe_range_end -
8594 dio_data.unsubmitted_oe_range_start,
8596 } else if (ret >= 0 && (size_t)ret < count)
8597 btrfs_delalloc_release_space(inode, data_reserved,
8598 offset, count - (size_t)ret, true);
8599 btrfs_delalloc_release_extents(BTRFS_I(inode), count, false);
8603 inode_dio_end(inode);
8607 extent_changeset_free(data_reserved);
8611 #define BTRFS_FIEMAP_FLAGS (FIEMAP_FLAG_SYNC)
8613 static int btrfs_fiemap(struct inode *inode, struct fiemap_extent_info *fieinfo,
8614 __u64 start, __u64 len)
8618 ret = fiemap_check_flags(fieinfo, BTRFS_FIEMAP_FLAGS);
8622 return extent_fiemap(inode, fieinfo, start, len);
8625 int btrfs_readpage(struct file *file, struct page *page)
8627 struct extent_io_tree *tree;
8628 tree = &BTRFS_I(page->mapping->host)->io_tree;
8629 return extent_read_full_page(tree, page, btrfs_get_extent, 0);
8632 static int btrfs_writepage(struct page *page, struct writeback_control *wbc)
8634 struct inode *inode = page->mapping->host;
8637 if (current->flags & PF_MEMALLOC) {
8638 redirty_page_for_writepage(wbc, page);
8644 * If we are under memory pressure we will call this directly from the
8645 * VM, we need to make sure we have the inode referenced for the ordered
8646 * extent. If not just return like we didn't do anything.
8648 if (!igrab(inode)) {
8649 redirty_page_for_writepage(wbc, page);
8650 return AOP_WRITEPAGE_ACTIVATE;
8652 ret = extent_write_full_page(page, wbc);
8653 btrfs_add_delayed_iput(inode);
8657 static int btrfs_writepages(struct address_space *mapping,
8658 struct writeback_control *wbc)
8660 return extent_writepages(mapping, wbc);
8664 btrfs_readpages(struct file *file, struct address_space *mapping,
8665 struct list_head *pages, unsigned nr_pages)
8667 return extent_readpages(mapping, pages, nr_pages);
8670 static int __btrfs_releasepage(struct page *page, gfp_t gfp_flags)
8672 int ret = try_release_extent_mapping(page, gfp_flags);
8674 ClearPagePrivate(page);
8675 set_page_private(page, 0);
8681 static int btrfs_releasepage(struct page *page, gfp_t gfp_flags)
8683 if (PageWriteback(page) || PageDirty(page))
8685 return __btrfs_releasepage(page, gfp_flags);
8688 static void btrfs_invalidatepage(struct page *page, unsigned int offset,
8689 unsigned int length)
8691 struct inode *inode = page->mapping->host;
8692 struct extent_io_tree *tree;
8693 struct btrfs_ordered_extent *ordered;
8694 struct extent_state *cached_state = NULL;
8695 u64 page_start = page_offset(page);
8696 u64 page_end = page_start + PAGE_SIZE - 1;
8699 int inode_evicting = inode->i_state & I_FREEING;
8702 * we have the page locked, so new writeback can't start,
8703 * and the dirty bit won't be cleared while we are here.
8705 * Wait for IO on this page so that we can safely clear
8706 * the PagePrivate2 bit and do ordered accounting
8708 wait_on_page_writeback(page);
8710 tree = &BTRFS_I(inode)->io_tree;
8712 btrfs_releasepage(page, GFP_NOFS);
8716 if (!inode_evicting)
8717 lock_extent_bits(tree, page_start, page_end, &cached_state);
8720 ordered = btrfs_lookup_ordered_range(BTRFS_I(inode), start,
8721 page_end - start + 1);
8723 end = min(page_end, ordered->file_offset + ordered->len - 1);
8725 * IO on this page will never be started, so we need
8726 * to account for any ordered extents now
8728 if (!inode_evicting)
8729 clear_extent_bit(tree, start, end,
8730 EXTENT_DIRTY | EXTENT_DELALLOC |
8731 EXTENT_DELALLOC_NEW |
8732 EXTENT_LOCKED | EXTENT_DO_ACCOUNTING |
8733 EXTENT_DEFRAG, 1, 0, &cached_state);
8735 * whoever cleared the private bit is responsible
8736 * for the finish_ordered_io
8738 if (TestClearPagePrivate2(page)) {
8739 struct btrfs_ordered_inode_tree *tree;
8742 tree = &BTRFS_I(inode)->ordered_tree;
8744 spin_lock_irq(&tree->lock);
8745 set_bit(BTRFS_ORDERED_TRUNCATED, &ordered->flags);
8746 new_len = start - ordered->file_offset;
8747 if (new_len < ordered->truncated_len)
8748 ordered->truncated_len = new_len;
8749 spin_unlock_irq(&tree->lock);
8751 if (btrfs_dec_test_ordered_pending(inode, &ordered,
8753 end - start + 1, 1))
8754 btrfs_finish_ordered_io(ordered);
8756 btrfs_put_ordered_extent(ordered);
8757 if (!inode_evicting) {
8758 cached_state = NULL;
8759 lock_extent_bits(tree, start, end,
8764 if (start < page_end)
8769 * Qgroup reserved space handler
8770 * Page here will be either
8771 * 1) Already written to disk
8772 * In this case, its reserved space is released from data rsv map
8773 * and will be freed by delayed_ref handler finally.
8774 * So even we call qgroup_free_data(), it won't decrease reserved
8776 * 2) Not written to disk
8777 * This means the reserved space should be freed here. However,
8778 * if a truncate invalidates the page (by clearing PageDirty)
8779 * and the page is accounted for while allocating extent
8780 * in btrfs_check_data_free_space() we let delayed_ref to
8781 * free the entire extent.
8783 if (PageDirty(page))
8784 btrfs_qgroup_free_data(inode, NULL, page_start, PAGE_SIZE);
8785 if (!inode_evicting) {
8786 clear_extent_bit(tree, page_start, page_end,
8787 EXTENT_LOCKED | EXTENT_DIRTY |
8788 EXTENT_DELALLOC | EXTENT_DELALLOC_NEW |
8789 EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG, 1, 1,
8792 __btrfs_releasepage(page, GFP_NOFS);
8795 ClearPageChecked(page);
8796 if (PagePrivate(page)) {
8797 ClearPagePrivate(page);
8798 set_page_private(page, 0);
8804 * btrfs_page_mkwrite() is not allowed to change the file size as it gets
8805 * called from a page fault handler when a page is first dirtied. Hence we must
8806 * be careful to check for EOF conditions here. We set the page up correctly
8807 * for a written page which means we get ENOSPC checking when writing into
8808 * holes and correct delalloc and unwritten extent mapping on filesystems that
8809 * support these features.
8811 * We are not allowed to take the i_mutex here so we have to play games to
8812 * protect against truncate races as the page could now be beyond EOF. Because
8813 * truncate_setsize() writes the inode size before removing pages, once we have
8814 * the page lock we can determine safely if the page is beyond EOF. If it is not
8815 * beyond EOF, then the page is guaranteed safe against truncation until we
8818 int btrfs_page_mkwrite(struct vm_fault *vmf)
8820 struct page *page = vmf->page;
8821 struct inode *inode = file_inode(vmf->vma->vm_file);
8822 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
8823 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
8824 struct btrfs_ordered_extent *ordered;
8825 struct extent_state *cached_state = NULL;
8826 struct extent_changeset *data_reserved = NULL;
8828 unsigned long zero_start;
8837 reserved_space = PAGE_SIZE;
8839 sb_start_pagefault(inode->i_sb);
8840 page_start = page_offset(page);
8841 page_end = page_start + PAGE_SIZE - 1;
8845 * Reserving delalloc space after obtaining the page lock can lead to
8846 * deadlock. For example, if a dirty page is locked by this function
8847 * and the call to btrfs_delalloc_reserve_space() ends up triggering
8848 * dirty page write out, then the btrfs_writepage() function could
8849 * end up waiting indefinitely to get a lock on the page currently
8850 * being processed by btrfs_page_mkwrite() function.
8852 ret = btrfs_delalloc_reserve_space(inode, &data_reserved, page_start,
8855 ret = file_update_time(vmf->vma->vm_file);
8861 else /* -ENOSPC, -EIO, etc */
8862 ret = VM_FAULT_SIGBUS;
8868 ret = VM_FAULT_NOPAGE; /* make the VM retry the fault */
8871 size = i_size_read(inode);
8873 if ((page->mapping != inode->i_mapping) ||
8874 (page_start >= size)) {
8875 /* page got truncated out from underneath us */
8878 wait_on_page_writeback(page);
8880 lock_extent_bits(io_tree, page_start, page_end, &cached_state);
8881 set_page_extent_mapped(page);
8884 * we can't set the delalloc bits if there are pending ordered
8885 * extents. Drop our locks and wait for them to finish
8887 ordered = btrfs_lookup_ordered_range(BTRFS_I(inode), page_start,
8890 unlock_extent_cached(io_tree, page_start, page_end,
8893 btrfs_start_ordered_extent(inode, ordered, 1);
8894 btrfs_put_ordered_extent(ordered);
8898 if (page->index == ((size - 1) >> PAGE_SHIFT)) {
8899 reserved_space = round_up(size - page_start,
8900 fs_info->sectorsize);
8901 if (reserved_space < PAGE_SIZE) {
8902 end = page_start + reserved_space - 1;
8903 btrfs_delalloc_release_space(inode, data_reserved,
8904 page_start, PAGE_SIZE - reserved_space,
8910 * page_mkwrite gets called when the page is firstly dirtied after it's
8911 * faulted in, but write(2) could also dirty a page and set delalloc
8912 * bits, thus in this case for space account reason, we still need to
8913 * clear any delalloc bits within this page range since we have to
8914 * reserve data&meta space before lock_page() (see above comments).
8916 clear_extent_bit(&BTRFS_I(inode)->io_tree, page_start, end,
8917 EXTENT_DIRTY | EXTENT_DELALLOC |
8918 EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG,
8919 0, 0, &cached_state);
8921 ret = btrfs_set_extent_delalloc(inode, page_start, end, 0,
8924 unlock_extent_cached(io_tree, page_start, page_end,
8926 ret = VM_FAULT_SIGBUS;
8931 /* page is wholly or partially inside EOF */
8932 if (page_start + PAGE_SIZE > size)
8933 zero_start = size & ~PAGE_MASK;
8935 zero_start = PAGE_SIZE;
8937 if (zero_start != PAGE_SIZE) {
8939 memset(kaddr + zero_start, 0, PAGE_SIZE - zero_start);
8940 flush_dcache_page(page);
8943 ClearPageChecked(page);
8944 set_page_dirty(page);
8945 SetPageUptodate(page);
8947 BTRFS_I(inode)->last_trans = fs_info->generation;
8948 BTRFS_I(inode)->last_sub_trans = BTRFS_I(inode)->root->log_transid;
8949 BTRFS_I(inode)->last_log_commit = BTRFS_I(inode)->root->last_log_commit;
8951 unlock_extent_cached(io_tree, page_start, page_end, &cached_state);
8955 btrfs_delalloc_release_extents(BTRFS_I(inode), PAGE_SIZE, true);
8956 sb_end_pagefault(inode->i_sb);
8957 extent_changeset_free(data_reserved);
8958 return VM_FAULT_LOCKED;
8962 btrfs_delalloc_release_extents(BTRFS_I(inode), PAGE_SIZE, (ret != 0));
8963 btrfs_delalloc_release_space(inode, data_reserved, page_start,
8964 reserved_space, (ret != 0));
8966 sb_end_pagefault(inode->i_sb);
8967 extent_changeset_free(data_reserved);
8971 static int btrfs_truncate(struct inode *inode, bool skip_writeback)
8973 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
8974 struct btrfs_root *root = BTRFS_I(inode)->root;
8975 struct btrfs_block_rsv *rsv;
8978 struct btrfs_trans_handle *trans;
8979 u64 mask = fs_info->sectorsize - 1;
8980 u64 min_size = btrfs_calc_trunc_metadata_size(fs_info, 1);
8982 if (!skip_writeback) {
8983 ret = btrfs_wait_ordered_range(inode, inode->i_size & (~mask),
8990 * Yes ladies and gentlemen, this is indeed ugly. We have a couple of
8991 * things going on here:
8993 * 1) We need to reserve space to update our inode.
8995 * 2) We need to have something to cache all the space that is going to
8996 * be free'd up by the truncate operation, but also have some slack
8997 * space reserved in case it uses space during the truncate (thank you
8998 * very much snapshotting).
9000 * And we need these to be separate. The fact is we can use a lot of
9001 * space doing the truncate, and we have no earthly idea how much space
9002 * we will use, so we need the truncate reservation to be separate so it
9003 * doesn't end up using space reserved for updating the inode. We also
9004 * need to be able to stop the transaction and start a new one, which
9005 * means we need to be able to update the inode several times, and we
9006 * have no idea of knowing how many times that will be, so we can't just
9007 * reserve 1 item for the entirety of the operation, so that has to be
9008 * done separately as well.
9010 * So that leaves us with
9012 * 1) rsv - for the truncate reservation, which we will steal from the
9013 * transaction reservation.
9014 * 2) fs_info->trans_block_rsv - this will have 1 items worth left for
9015 * updating the inode.
9017 rsv = btrfs_alloc_block_rsv(fs_info, BTRFS_BLOCK_RSV_TEMP);
9020 rsv->size = min_size;
9024 * 1 for the truncate slack space
9025 * 1 for updating the inode.
9027 trans = btrfs_start_transaction(root, 2);
9028 if (IS_ERR(trans)) {
9029 err = PTR_ERR(trans);
9033 /* Migrate the slack space for the truncate to our reserve */
9034 ret = btrfs_block_rsv_migrate(&fs_info->trans_block_rsv, rsv,
9039 * So if we truncate and then write and fsync we normally would just
9040 * write the extents that changed, which is a problem if we need to
9041 * first truncate that entire inode. So set this flag so we write out
9042 * all of the extents in the inode to the sync log so we're completely
9045 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &BTRFS_I(inode)->runtime_flags);
9046 trans->block_rsv = rsv;
9049 ret = btrfs_truncate_inode_items(trans, root, inode,
9051 BTRFS_EXTENT_DATA_KEY);
9052 trans->block_rsv = &fs_info->trans_block_rsv;
9053 if (ret != -ENOSPC && ret != -EAGAIN) {
9059 ret = btrfs_update_inode(trans, root, inode);
9065 btrfs_end_transaction(trans);
9066 btrfs_btree_balance_dirty(fs_info);
9068 trans = btrfs_start_transaction(root, 2);
9069 if (IS_ERR(trans)) {
9070 ret = err = PTR_ERR(trans);
9075 btrfs_block_rsv_release(fs_info, rsv, -1);
9076 ret = btrfs_block_rsv_migrate(&fs_info->trans_block_rsv,
9078 BUG_ON(ret); /* shouldn't happen */
9079 trans->block_rsv = rsv;
9083 * We can't call btrfs_truncate_block inside a trans handle as we could
9084 * deadlock with freeze, if we got NEED_TRUNCATE_BLOCK then we know
9085 * we've truncated everything except the last little bit, and can do
9086 * btrfs_truncate_block and then update the disk_i_size.
9088 if (ret == NEED_TRUNCATE_BLOCK) {
9089 btrfs_end_transaction(trans);
9090 btrfs_btree_balance_dirty(fs_info);
9092 ret = btrfs_truncate_block(inode, inode->i_size, 0, 0);
9095 trans = btrfs_start_transaction(root, 1);
9096 if (IS_ERR(trans)) {
9097 ret = PTR_ERR(trans);
9100 btrfs_ordered_update_i_size(inode, inode->i_size, NULL);
9104 trans->block_rsv = &fs_info->trans_block_rsv;
9105 ret = btrfs_update_inode(trans, root, inode);
9109 ret = btrfs_end_transaction(trans);
9110 btrfs_btree_balance_dirty(fs_info);
9113 btrfs_free_block_rsv(fs_info, rsv);
9122 * create a new subvolume directory/inode (helper for the ioctl).
9124 int btrfs_create_subvol_root(struct btrfs_trans_handle *trans,
9125 struct btrfs_root *new_root,
9126 struct btrfs_root *parent_root,
9129 struct inode *inode;
9133 inode = btrfs_new_inode(trans, new_root, NULL, "..", 2,
9134 new_dirid, new_dirid,
9135 S_IFDIR | (~current_umask() & S_IRWXUGO),
9138 return PTR_ERR(inode);
9139 inode->i_op = &btrfs_dir_inode_operations;
9140 inode->i_fop = &btrfs_dir_file_operations;
9142 set_nlink(inode, 1);
9143 btrfs_i_size_write(BTRFS_I(inode), 0);
9144 unlock_new_inode(inode);
9146 err = btrfs_subvol_inherit_props(trans, new_root, parent_root);
9148 btrfs_err(new_root->fs_info,
9149 "error inheriting subvolume %llu properties: %d",
9150 new_root->root_key.objectid, err);
9152 err = btrfs_update_inode(trans, new_root, inode);
9158 struct inode *btrfs_alloc_inode(struct super_block *sb)
9160 struct btrfs_fs_info *fs_info = btrfs_sb(sb);
9161 struct btrfs_inode *ei;
9162 struct inode *inode;
9164 ei = kmem_cache_alloc(btrfs_inode_cachep, GFP_KERNEL);
9171 ei->last_sub_trans = 0;
9172 ei->logged_trans = 0;
9173 ei->delalloc_bytes = 0;
9174 ei->new_delalloc_bytes = 0;
9175 ei->defrag_bytes = 0;
9176 ei->disk_i_size = 0;
9179 ei->index_cnt = (u64)-1;
9181 ei->last_unlink_trans = 0;
9182 ei->last_log_commit = 0;
9184 spin_lock_init(&ei->lock);
9185 ei->outstanding_extents = 0;
9186 if (sb->s_magic != BTRFS_TEST_MAGIC)
9187 btrfs_init_metadata_block_rsv(fs_info, &ei->block_rsv,
9188 BTRFS_BLOCK_RSV_DELALLOC);
9189 ei->runtime_flags = 0;
9190 ei->prop_compress = BTRFS_COMPRESS_NONE;
9191 ei->defrag_compress = BTRFS_COMPRESS_NONE;
9193 ei->delayed_node = NULL;
9195 ei->i_otime.tv_sec = 0;
9196 ei->i_otime.tv_nsec = 0;
9198 inode = &ei->vfs_inode;
9199 extent_map_tree_init(&ei->extent_tree);
9200 extent_io_tree_init(&ei->io_tree, inode);
9201 extent_io_tree_init(&ei->io_failure_tree, inode);
9202 ei->io_tree.track_uptodate = 1;
9203 ei->io_failure_tree.track_uptodate = 1;
9204 atomic_set(&ei->sync_writers, 0);
9205 mutex_init(&ei->log_mutex);
9206 mutex_init(&ei->delalloc_mutex);
9207 btrfs_ordered_inode_tree_init(&ei->ordered_tree);
9208 INIT_LIST_HEAD(&ei->delalloc_inodes);
9209 INIT_LIST_HEAD(&ei->delayed_iput);
9210 RB_CLEAR_NODE(&ei->rb_node);
9211 init_rwsem(&ei->dio_sem);
9216 #ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
9217 void btrfs_test_destroy_inode(struct inode *inode)
9219 btrfs_drop_extent_cache(BTRFS_I(inode), 0, (u64)-1, 0);
9220 kmem_cache_free(btrfs_inode_cachep, BTRFS_I(inode));
9224 static void btrfs_i_callback(struct rcu_head *head)
9226 struct inode *inode = container_of(head, struct inode, i_rcu);
9227 kmem_cache_free(btrfs_inode_cachep, BTRFS_I(inode));
9230 void btrfs_destroy_inode(struct inode *inode)
9232 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
9233 struct btrfs_ordered_extent *ordered;
9234 struct btrfs_root *root = BTRFS_I(inode)->root;
9236 WARN_ON(!hlist_empty(&inode->i_dentry));
9237 WARN_ON(inode->i_data.nrpages);
9238 WARN_ON(BTRFS_I(inode)->block_rsv.reserved);
9239 WARN_ON(BTRFS_I(inode)->block_rsv.size);
9240 WARN_ON(BTRFS_I(inode)->outstanding_extents);
9241 WARN_ON(BTRFS_I(inode)->delalloc_bytes);
9242 WARN_ON(BTRFS_I(inode)->new_delalloc_bytes);
9243 WARN_ON(BTRFS_I(inode)->csum_bytes);
9244 WARN_ON(BTRFS_I(inode)->defrag_bytes);
9247 * This can happen where we create an inode, but somebody else also
9248 * created the same inode and we need to destroy the one we already
9255 ordered = btrfs_lookup_first_ordered_extent(inode, (u64)-1);
9260 "found ordered extent %llu %llu on inode cleanup",
9261 ordered->file_offset, ordered->len);
9262 btrfs_remove_ordered_extent(inode, ordered);
9263 btrfs_put_ordered_extent(ordered);
9264 btrfs_put_ordered_extent(ordered);
9267 btrfs_qgroup_check_reserved_leak(inode);
9268 inode_tree_del(inode);
9269 btrfs_drop_extent_cache(BTRFS_I(inode), 0, (u64)-1, 0);
9271 call_rcu(&inode->i_rcu, btrfs_i_callback);
9274 int btrfs_drop_inode(struct inode *inode)
9276 struct btrfs_root *root = BTRFS_I(inode)->root;
9281 /* the snap/subvol tree is on deleting */
9282 if (btrfs_root_refs(&root->root_item) == 0)
9285 return generic_drop_inode(inode);
9288 static void init_once(void *foo)
9290 struct btrfs_inode *ei = (struct btrfs_inode *) foo;
9292 inode_init_once(&ei->vfs_inode);
9295 void __cold btrfs_destroy_cachep(void)
9298 * Make sure all delayed rcu free inodes are flushed before we
9302 kmem_cache_destroy(btrfs_inode_cachep);
9303 kmem_cache_destroy(btrfs_trans_handle_cachep);
9304 kmem_cache_destroy(btrfs_path_cachep);
9305 kmem_cache_destroy(btrfs_free_space_cachep);
9308 int __init btrfs_init_cachep(void)
9310 btrfs_inode_cachep = kmem_cache_create("btrfs_inode",
9311 sizeof(struct btrfs_inode), 0,
9312 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD | SLAB_ACCOUNT,
9314 if (!btrfs_inode_cachep)
9317 btrfs_trans_handle_cachep = kmem_cache_create("btrfs_trans_handle",
9318 sizeof(struct btrfs_trans_handle), 0,
9319 SLAB_TEMPORARY | SLAB_MEM_SPREAD, NULL);
9320 if (!btrfs_trans_handle_cachep)
9323 btrfs_path_cachep = kmem_cache_create("btrfs_path",
9324 sizeof(struct btrfs_path), 0,
9325 SLAB_MEM_SPREAD, NULL);
9326 if (!btrfs_path_cachep)
9329 btrfs_free_space_cachep = kmem_cache_create("btrfs_free_space",
9330 sizeof(struct btrfs_free_space), 0,
9331 SLAB_MEM_SPREAD, NULL);
9332 if (!btrfs_free_space_cachep)
9337 btrfs_destroy_cachep();
9341 static int btrfs_getattr(const struct path *path, struct kstat *stat,
9342 u32 request_mask, unsigned int flags)
9345 struct inode *inode = d_inode(path->dentry);
9346 u32 blocksize = inode->i_sb->s_blocksize;
9347 u32 bi_flags = BTRFS_I(inode)->flags;
9349 stat->result_mask |= STATX_BTIME;
9350 stat->btime.tv_sec = BTRFS_I(inode)->i_otime.tv_sec;
9351 stat->btime.tv_nsec = BTRFS_I(inode)->i_otime.tv_nsec;
9352 if (bi_flags & BTRFS_INODE_APPEND)
9353 stat->attributes |= STATX_ATTR_APPEND;
9354 if (bi_flags & BTRFS_INODE_COMPRESS)
9355 stat->attributes |= STATX_ATTR_COMPRESSED;
9356 if (bi_flags & BTRFS_INODE_IMMUTABLE)
9357 stat->attributes |= STATX_ATTR_IMMUTABLE;
9358 if (bi_flags & BTRFS_INODE_NODUMP)
9359 stat->attributes |= STATX_ATTR_NODUMP;
9361 stat->attributes_mask |= (STATX_ATTR_APPEND |
9362 STATX_ATTR_COMPRESSED |
9363 STATX_ATTR_IMMUTABLE |
9366 generic_fillattr(inode, stat);
9367 stat->dev = BTRFS_I(inode)->root->anon_dev;
9369 spin_lock(&BTRFS_I(inode)->lock);
9370 delalloc_bytes = BTRFS_I(inode)->new_delalloc_bytes;
9371 spin_unlock(&BTRFS_I(inode)->lock);
9372 stat->blocks = (ALIGN(inode_get_bytes(inode), blocksize) +
9373 ALIGN(delalloc_bytes, blocksize)) >> 9;
9377 static int btrfs_rename_exchange(struct inode *old_dir,
9378 struct dentry *old_dentry,
9379 struct inode *new_dir,
9380 struct dentry *new_dentry)
9382 struct btrfs_fs_info *fs_info = btrfs_sb(old_dir->i_sb);
9383 struct btrfs_trans_handle *trans;
9384 struct btrfs_root *root = BTRFS_I(old_dir)->root;
9385 struct btrfs_root *dest = BTRFS_I(new_dir)->root;
9386 struct inode *new_inode = new_dentry->d_inode;
9387 struct inode *old_inode = old_dentry->d_inode;
9388 struct timespec ctime = current_time(old_inode);
9389 struct dentry *parent;
9390 u64 old_ino = btrfs_ino(BTRFS_I(old_inode));
9391 u64 new_ino = btrfs_ino(BTRFS_I(new_inode));
9396 bool root_log_pinned = false;
9397 bool dest_log_pinned = false;
9399 /* we only allow rename subvolume link between subvolumes */
9400 if (old_ino != BTRFS_FIRST_FREE_OBJECTID && root != dest)
9403 /* close the race window with snapshot create/destroy ioctl */
9404 if (old_ino == BTRFS_FIRST_FREE_OBJECTID)
9405 down_read(&fs_info->subvol_sem);
9406 if (new_ino == BTRFS_FIRST_FREE_OBJECTID)
9407 down_read(&fs_info->subvol_sem);
9410 * We want to reserve the absolute worst case amount of items. So if
9411 * both inodes are subvols and we need to unlink them then that would
9412 * require 4 item modifications, but if they are both normal inodes it
9413 * would require 5 item modifications, so we'll assume their normal
9414 * inodes. So 5 * 2 is 10, plus 2 for the new links, so 12 total items
9415 * should cover the worst case number of items we'll modify.
9417 trans = btrfs_start_transaction(root, 12);
9418 if (IS_ERR(trans)) {
9419 ret = PTR_ERR(trans);
9424 * We need to find a free sequence number both in the source and
9425 * in the destination directory for the exchange.
9427 ret = btrfs_set_inode_index(BTRFS_I(new_dir), &old_idx);
9430 ret = btrfs_set_inode_index(BTRFS_I(old_dir), &new_idx);
9434 BTRFS_I(old_inode)->dir_index = 0ULL;
9435 BTRFS_I(new_inode)->dir_index = 0ULL;
9437 /* Reference for the source. */
9438 if (old_ino == BTRFS_FIRST_FREE_OBJECTID) {
9439 /* force full log commit if subvolume involved. */
9440 btrfs_set_log_full_commit(fs_info, trans);
9442 btrfs_pin_log_trans(root);
9443 root_log_pinned = true;
9444 ret = btrfs_insert_inode_ref(trans, dest,
9445 new_dentry->d_name.name,
9446 new_dentry->d_name.len,
9448 btrfs_ino(BTRFS_I(new_dir)),
9454 /* And now for the dest. */
9455 if (new_ino == BTRFS_FIRST_FREE_OBJECTID) {
9456 /* force full log commit if subvolume involved. */
9457 btrfs_set_log_full_commit(fs_info, trans);
9459 btrfs_pin_log_trans(dest);
9460 dest_log_pinned = true;
9461 ret = btrfs_insert_inode_ref(trans, root,
9462 old_dentry->d_name.name,
9463 old_dentry->d_name.len,
9465 btrfs_ino(BTRFS_I(old_dir)),
9471 /* Update inode version and ctime/mtime. */
9472 inode_inc_iversion(old_dir);
9473 inode_inc_iversion(new_dir);
9474 inode_inc_iversion(old_inode);
9475 inode_inc_iversion(new_inode);
9476 old_dir->i_ctime = old_dir->i_mtime = ctime;
9477 new_dir->i_ctime = new_dir->i_mtime = ctime;
9478 old_inode->i_ctime = ctime;
9479 new_inode->i_ctime = ctime;
9481 if (old_dentry->d_parent != new_dentry->d_parent) {
9482 btrfs_record_unlink_dir(trans, BTRFS_I(old_dir),
9483 BTRFS_I(old_inode), 1);
9484 btrfs_record_unlink_dir(trans, BTRFS_I(new_dir),
9485 BTRFS_I(new_inode), 1);
9488 /* src is a subvolume */
9489 if (old_ino == BTRFS_FIRST_FREE_OBJECTID) {
9490 root_objectid = BTRFS_I(old_inode)->root->root_key.objectid;
9491 ret = btrfs_unlink_subvol(trans, root, old_dir,
9493 old_dentry->d_name.name,
9494 old_dentry->d_name.len);
9495 } else { /* src is an inode */
9496 ret = __btrfs_unlink_inode(trans, root, BTRFS_I(old_dir),
9497 BTRFS_I(old_dentry->d_inode),
9498 old_dentry->d_name.name,
9499 old_dentry->d_name.len);
9501 ret = btrfs_update_inode(trans, root, old_inode);
9504 btrfs_abort_transaction(trans, ret);
9508 /* dest is a subvolume */
9509 if (new_ino == BTRFS_FIRST_FREE_OBJECTID) {
9510 root_objectid = BTRFS_I(new_inode)->root->root_key.objectid;
9511 ret = btrfs_unlink_subvol(trans, dest, new_dir,
9513 new_dentry->d_name.name,
9514 new_dentry->d_name.len);
9515 } else { /* dest is an inode */
9516 ret = __btrfs_unlink_inode(trans, dest, BTRFS_I(new_dir),
9517 BTRFS_I(new_dentry->d_inode),
9518 new_dentry->d_name.name,
9519 new_dentry->d_name.len);
9521 ret = btrfs_update_inode(trans, dest, new_inode);
9524 btrfs_abort_transaction(trans, ret);
9528 ret = btrfs_add_link(trans, BTRFS_I(new_dir), BTRFS_I(old_inode),
9529 new_dentry->d_name.name,
9530 new_dentry->d_name.len, 0, old_idx);
9532 btrfs_abort_transaction(trans, ret);
9536 ret = btrfs_add_link(trans, BTRFS_I(old_dir), BTRFS_I(new_inode),
9537 old_dentry->d_name.name,
9538 old_dentry->d_name.len, 0, new_idx);
9540 btrfs_abort_transaction(trans, ret);
9544 if (old_inode->i_nlink == 1)
9545 BTRFS_I(old_inode)->dir_index = old_idx;
9546 if (new_inode->i_nlink == 1)
9547 BTRFS_I(new_inode)->dir_index = new_idx;
9549 if (root_log_pinned) {
9550 parent = new_dentry->d_parent;
9551 btrfs_log_new_name(trans, BTRFS_I(old_inode), BTRFS_I(old_dir),
9553 btrfs_end_log_trans(root);
9554 root_log_pinned = false;
9556 if (dest_log_pinned) {
9557 parent = old_dentry->d_parent;
9558 btrfs_log_new_name(trans, BTRFS_I(new_inode), BTRFS_I(new_dir),
9560 btrfs_end_log_trans(dest);
9561 dest_log_pinned = false;
9565 * If we have pinned a log and an error happened, we unpin tasks
9566 * trying to sync the log and force them to fallback to a transaction
9567 * commit if the log currently contains any of the inodes involved in
9568 * this rename operation (to ensure we do not persist a log with an
9569 * inconsistent state for any of these inodes or leading to any
9570 * inconsistencies when replayed). If the transaction was aborted, the
9571 * abortion reason is propagated to userspace when attempting to commit
9572 * the transaction. If the log does not contain any of these inodes, we
9573 * allow the tasks to sync it.
9575 if (ret && (root_log_pinned || dest_log_pinned)) {
9576 if (btrfs_inode_in_log(BTRFS_I(old_dir), fs_info->generation) ||
9577 btrfs_inode_in_log(BTRFS_I(new_dir), fs_info->generation) ||
9578 btrfs_inode_in_log(BTRFS_I(old_inode), fs_info->generation) ||
9580 btrfs_inode_in_log(BTRFS_I(new_inode), fs_info->generation)))
9581 btrfs_set_log_full_commit(fs_info, trans);
9583 if (root_log_pinned) {
9584 btrfs_end_log_trans(root);
9585 root_log_pinned = false;
9587 if (dest_log_pinned) {
9588 btrfs_end_log_trans(dest);
9589 dest_log_pinned = false;
9592 ret = btrfs_end_transaction(trans);
9594 if (new_ino == BTRFS_FIRST_FREE_OBJECTID)
9595 up_read(&fs_info->subvol_sem);
9596 if (old_ino == BTRFS_FIRST_FREE_OBJECTID)
9597 up_read(&fs_info->subvol_sem);
9602 static int btrfs_whiteout_for_rename(struct btrfs_trans_handle *trans,
9603 struct btrfs_root *root,
9605 struct dentry *dentry)
9608 struct inode *inode;
9612 ret = btrfs_find_free_ino(root, &objectid);
9616 inode = btrfs_new_inode(trans, root, dir,
9617 dentry->d_name.name,
9619 btrfs_ino(BTRFS_I(dir)),
9621 S_IFCHR | WHITEOUT_MODE,
9624 if (IS_ERR(inode)) {
9625 ret = PTR_ERR(inode);
9629 inode->i_op = &btrfs_special_inode_operations;
9630 init_special_inode(inode, inode->i_mode,
9633 ret = btrfs_init_inode_security(trans, inode, dir,
9638 ret = btrfs_add_nondir(trans, BTRFS_I(dir), dentry,
9639 BTRFS_I(inode), 0, index);
9643 ret = btrfs_update_inode(trans, root, inode);
9645 unlock_new_inode(inode);
9647 inode_dec_link_count(inode);
9653 static int btrfs_rename(struct inode *old_dir, struct dentry *old_dentry,
9654 struct inode *new_dir, struct dentry *new_dentry,
9657 struct btrfs_fs_info *fs_info = btrfs_sb(old_dir->i_sb);
9658 struct btrfs_trans_handle *trans;
9659 unsigned int trans_num_items;
9660 struct btrfs_root *root = BTRFS_I(old_dir)->root;
9661 struct btrfs_root *dest = BTRFS_I(new_dir)->root;
9662 struct inode *new_inode = d_inode(new_dentry);
9663 struct inode *old_inode = d_inode(old_dentry);
9667 u64 old_ino = btrfs_ino(BTRFS_I(old_inode));
9668 bool log_pinned = false;
9670 if (btrfs_ino(BTRFS_I(new_dir)) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)
9673 /* we only allow rename subvolume link between subvolumes */
9674 if (old_ino != BTRFS_FIRST_FREE_OBJECTID && root != dest)
9677 if (old_ino == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID ||
9678 (new_inode && btrfs_ino(BTRFS_I(new_inode)) == BTRFS_FIRST_FREE_OBJECTID))
9681 if (S_ISDIR(old_inode->i_mode) && new_inode &&
9682 new_inode->i_size > BTRFS_EMPTY_DIR_SIZE)
9686 /* check for collisions, even if the name isn't there */
9687 ret = btrfs_check_dir_item_collision(dest, new_dir->i_ino,
9688 new_dentry->d_name.name,
9689 new_dentry->d_name.len);
9692 if (ret == -EEXIST) {
9694 * eexist without a new_inode */
9695 if (WARN_ON(!new_inode)) {
9699 /* maybe -EOVERFLOW */
9706 * we're using rename to replace one file with another. Start IO on it
9707 * now so we don't add too much work to the end of the transaction
9709 if (new_inode && S_ISREG(old_inode->i_mode) && new_inode->i_size)
9710 filemap_flush(old_inode->i_mapping);
9712 /* close the racy window with snapshot create/destroy ioctl */
9713 if (old_ino == BTRFS_FIRST_FREE_OBJECTID)
9714 down_read(&fs_info->subvol_sem);
9716 * We want to reserve the absolute worst case amount of items. So if
9717 * both inodes are subvols and we need to unlink them then that would
9718 * require 4 item modifications, but if they are both normal inodes it
9719 * would require 5 item modifications, so we'll assume they are normal
9720 * inodes. So 5 * 2 is 10, plus 1 for the new link, so 11 total items
9721 * should cover the worst case number of items we'll modify.
9722 * If our rename has the whiteout flag, we need more 5 units for the
9723 * new inode (1 inode item, 1 inode ref, 2 dir items and 1 xattr item
9724 * when selinux is enabled).
9726 trans_num_items = 11;
9727 if (flags & RENAME_WHITEOUT)
9728 trans_num_items += 5;
9729 trans = btrfs_start_transaction(root, trans_num_items);
9730 if (IS_ERR(trans)) {
9731 ret = PTR_ERR(trans);
9736 btrfs_record_root_in_trans(trans, dest);
9738 ret = btrfs_set_inode_index(BTRFS_I(new_dir), &index);
9742 BTRFS_I(old_inode)->dir_index = 0ULL;
9743 if (unlikely(old_ino == BTRFS_FIRST_FREE_OBJECTID)) {
9744 /* force full log commit if subvolume involved. */
9745 btrfs_set_log_full_commit(fs_info, trans);
9747 btrfs_pin_log_trans(root);
9749 ret = btrfs_insert_inode_ref(trans, dest,
9750 new_dentry->d_name.name,
9751 new_dentry->d_name.len,
9753 btrfs_ino(BTRFS_I(new_dir)), index);
9758 inode_inc_iversion(old_dir);
9759 inode_inc_iversion(new_dir);
9760 inode_inc_iversion(old_inode);
9761 old_dir->i_ctime = old_dir->i_mtime =
9762 new_dir->i_ctime = new_dir->i_mtime =
9763 old_inode->i_ctime = current_time(old_dir);
9765 if (old_dentry->d_parent != new_dentry->d_parent)
9766 btrfs_record_unlink_dir(trans, BTRFS_I(old_dir),
9767 BTRFS_I(old_inode), 1);
9769 if (unlikely(old_ino == BTRFS_FIRST_FREE_OBJECTID)) {
9770 root_objectid = BTRFS_I(old_inode)->root->root_key.objectid;
9771 ret = btrfs_unlink_subvol(trans, root, old_dir, root_objectid,
9772 old_dentry->d_name.name,
9773 old_dentry->d_name.len);
9775 ret = __btrfs_unlink_inode(trans, root, BTRFS_I(old_dir),
9776 BTRFS_I(d_inode(old_dentry)),
9777 old_dentry->d_name.name,
9778 old_dentry->d_name.len);
9780 ret = btrfs_update_inode(trans, root, old_inode);
9783 btrfs_abort_transaction(trans, ret);
9788 inode_inc_iversion(new_inode);
9789 new_inode->i_ctime = current_time(new_inode);
9790 if (unlikely(btrfs_ino(BTRFS_I(new_inode)) ==
9791 BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)) {
9792 root_objectid = BTRFS_I(new_inode)->location.objectid;
9793 ret = btrfs_unlink_subvol(trans, dest, new_dir,
9795 new_dentry->d_name.name,
9796 new_dentry->d_name.len);
9797 BUG_ON(new_inode->i_nlink == 0);
9799 ret = btrfs_unlink_inode(trans, dest, BTRFS_I(new_dir),
9800 BTRFS_I(d_inode(new_dentry)),
9801 new_dentry->d_name.name,
9802 new_dentry->d_name.len);
9804 if (!ret && new_inode->i_nlink == 0)
9805 ret = btrfs_orphan_add(trans,
9806 BTRFS_I(d_inode(new_dentry)));
9808 btrfs_abort_transaction(trans, ret);
9813 ret = btrfs_add_link(trans, BTRFS_I(new_dir), BTRFS_I(old_inode),
9814 new_dentry->d_name.name,
9815 new_dentry->d_name.len, 0, index);
9817 btrfs_abort_transaction(trans, ret);
9821 if (old_inode->i_nlink == 1)
9822 BTRFS_I(old_inode)->dir_index = index;
9825 struct dentry *parent = new_dentry->d_parent;
9827 btrfs_log_new_name(trans, BTRFS_I(old_inode), BTRFS_I(old_dir),
9829 btrfs_end_log_trans(root);
9833 if (flags & RENAME_WHITEOUT) {
9834 ret = btrfs_whiteout_for_rename(trans, root, old_dir,
9838 btrfs_abort_transaction(trans, ret);
9844 * If we have pinned the log and an error happened, we unpin tasks
9845 * trying to sync the log and force them to fallback to a transaction
9846 * commit if the log currently contains any of the inodes involved in
9847 * this rename operation (to ensure we do not persist a log with an
9848 * inconsistent state for any of these inodes or leading to any
9849 * inconsistencies when replayed). If the transaction was aborted, the
9850 * abortion reason is propagated to userspace when attempting to commit
9851 * the transaction. If the log does not contain any of these inodes, we
9852 * allow the tasks to sync it.
9854 if (ret && log_pinned) {
9855 if (btrfs_inode_in_log(BTRFS_I(old_dir), fs_info->generation) ||
9856 btrfs_inode_in_log(BTRFS_I(new_dir), fs_info->generation) ||
9857 btrfs_inode_in_log(BTRFS_I(old_inode), fs_info->generation) ||
9859 btrfs_inode_in_log(BTRFS_I(new_inode), fs_info->generation)))
9860 btrfs_set_log_full_commit(fs_info, trans);
9862 btrfs_end_log_trans(root);
9865 btrfs_end_transaction(trans);
9867 if (old_ino == BTRFS_FIRST_FREE_OBJECTID)
9868 up_read(&fs_info->subvol_sem);
9873 static int btrfs_rename2(struct inode *old_dir, struct dentry *old_dentry,
9874 struct inode *new_dir, struct dentry *new_dentry,
9877 if (flags & ~(RENAME_NOREPLACE | RENAME_EXCHANGE | RENAME_WHITEOUT))
9880 if (flags & RENAME_EXCHANGE)
9881 return btrfs_rename_exchange(old_dir, old_dentry, new_dir,
9884 return btrfs_rename(old_dir, old_dentry, new_dir, new_dentry, flags);
9887 struct btrfs_delalloc_work {
9888 struct inode *inode;
9889 struct completion completion;
9890 struct list_head list;
9891 struct btrfs_work work;
9894 static void btrfs_run_delalloc_work(struct btrfs_work *work)
9896 struct btrfs_delalloc_work *delalloc_work;
9897 struct inode *inode;
9899 delalloc_work = container_of(work, struct btrfs_delalloc_work,
9901 inode = delalloc_work->inode;
9902 filemap_flush(inode->i_mapping);
9903 if (test_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
9904 &BTRFS_I(inode)->runtime_flags))
9905 filemap_flush(inode->i_mapping);
9908 complete(&delalloc_work->completion);
9911 static struct btrfs_delalloc_work *btrfs_alloc_delalloc_work(struct inode *inode)
9913 struct btrfs_delalloc_work *work;
9915 work = kmalloc(sizeof(*work), GFP_NOFS);
9919 init_completion(&work->completion);
9920 INIT_LIST_HEAD(&work->list);
9921 work->inode = inode;
9922 WARN_ON_ONCE(!inode);
9923 btrfs_init_work(&work->work, btrfs_flush_delalloc_helper,
9924 btrfs_run_delalloc_work, NULL, NULL);
9930 * some fairly slow code that needs optimization. This walks the list
9931 * of all the inodes with pending delalloc and forces them to disk.
9933 static int start_delalloc_inodes(struct btrfs_root *root, int nr)
9935 struct btrfs_inode *binode;
9936 struct inode *inode;
9937 struct btrfs_delalloc_work *work, *next;
9938 struct list_head works;
9939 struct list_head splice;
9942 INIT_LIST_HEAD(&works);
9943 INIT_LIST_HEAD(&splice);
9945 mutex_lock(&root->delalloc_mutex);
9946 spin_lock(&root->delalloc_lock);
9947 list_splice_init(&root->delalloc_inodes, &splice);
9948 while (!list_empty(&splice)) {
9949 binode = list_entry(splice.next, struct btrfs_inode,
9952 list_move_tail(&binode->delalloc_inodes,
9953 &root->delalloc_inodes);
9954 inode = igrab(&binode->vfs_inode);
9956 cond_resched_lock(&root->delalloc_lock);
9959 spin_unlock(&root->delalloc_lock);
9961 work = btrfs_alloc_delalloc_work(inode);
9967 list_add_tail(&work->list, &works);
9968 btrfs_queue_work(root->fs_info->flush_workers,
9971 if (nr != -1 && ret >= nr)
9974 spin_lock(&root->delalloc_lock);
9976 spin_unlock(&root->delalloc_lock);
9979 list_for_each_entry_safe(work, next, &works, list) {
9980 list_del_init(&work->list);
9981 wait_for_completion(&work->completion);
9985 if (!list_empty(&splice)) {
9986 spin_lock(&root->delalloc_lock);
9987 list_splice_tail(&splice, &root->delalloc_inodes);
9988 spin_unlock(&root->delalloc_lock);
9990 mutex_unlock(&root->delalloc_mutex);
9994 int btrfs_start_delalloc_inodes(struct btrfs_root *root)
9996 struct btrfs_fs_info *fs_info = root->fs_info;
9999 if (test_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state))
10002 ret = start_delalloc_inodes(root, -1);
10008 int btrfs_start_delalloc_roots(struct btrfs_fs_info *fs_info, int nr)
10010 struct btrfs_root *root;
10011 struct list_head splice;
10014 if (test_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state))
10017 INIT_LIST_HEAD(&splice);
10019 mutex_lock(&fs_info->delalloc_root_mutex);
10020 spin_lock(&fs_info->delalloc_root_lock);
10021 list_splice_init(&fs_info->delalloc_roots, &splice);
10022 while (!list_empty(&splice) && nr) {
10023 root = list_first_entry(&splice, struct btrfs_root,
10025 root = btrfs_grab_fs_root(root);
10027 list_move_tail(&root->delalloc_root,
10028 &fs_info->delalloc_roots);
10029 spin_unlock(&fs_info->delalloc_root_lock);
10031 ret = start_delalloc_inodes(root, nr);
10032 btrfs_put_fs_root(root);
10040 spin_lock(&fs_info->delalloc_root_lock);
10042 spin_unlock(&fs_info->delalloc_root_lock);
10046 if (!list_empty(&splice)) {
10047 spin_lock(&fs_info->delalloc_root_lock);
10048 list_splice_tail(&splice, &fs_info->delalloc_roots);
10049 spin_unlock(&fs_info->delalloc_root_lock);
10051 mutex_unlock(&fs_info->delalloc_root_mutex);
10055 static int btrfs_symlink(struct inode *dir, struct dentry *dentry,
10056 const char *symname)
10058 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
10059 struct btrfs_trans_handle *trans;
10060 struct btrfs_root *root = BTRFS_I(dir)->root;
10061 struct btrfs_path *path;
10062 struct btrfs_key key;
10063 struct inode *inode = NULL;
10065 int drop_inode = 0;
10071 struct btrfs_file_extent_item *ei;
10072 struct extent_buffer *leaf;
10074 name_len = strlen(symname);
10075 if (name_len > BTRFS_MAX_INLINE_DATA_SIZE(fs_info))
10076 return -ENAMETOOLONG;
10079 * 2 items for inode item and ref
10080 * 2 items for dir items
10081 * 1 item for updating parent inode item
10082 * 1 item for the inline extent item
10083 * 1 item for xattr if selinux is on
10085 trans = btrfs_start_transaction(root, 7);
10087 return PTR_ERR(trans);
10089 err = btrfs_find_free_ino(root, &objectid);
10093 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
10094 dentry->d_name.len, btrfs_ino(BTRFS_I(dir)),
10095 objectid, S_IFLNK|S_IRWXUGO, &index);
10096 if (IS_ERR(inode)) {
10097 err = PTR_ERR(inode);
10102 * If the active LSM wants to access the inode during
10103 * d_instantiate it needs these. Smack checks to see
10104 * if the filesystem supports xattrs by looking at the
10107 inode->i_fop = &btrfs_file_operations;
10108 inode->i_op = &btrfs_file_inode_operations;
10109 inode->i_mapping->a_ops = &btrfs_aops;
10110 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
10112 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
10114 goto out_unlock_inode;
10116 path = btrfs_alloc_path();
10119 goto out_unlock_inode;
10121 key.objectid = btrfs_ino(BTRFS_I(inode));
10123 key.type = BTRFS_EXTENT_DATA_KEY;
10124 datasize = btrfs_file_extent_calc_inline_size(name_len);
10125 err = btrfs_insert_empty_item(trans, root, path, &key,
10128 btrfs_free_path(path);
10129 goto out_unlock_inode;
10131 leaf = path->nodes[0];
10132 ei = btrfs_item_ptr(leaf, path->slots[0],
10133 struct btrfs_file_extent_item);
10134 btrfs_set_file_extent_generation(leaf, ei, trans->transid);
10135 btrfs_set_file_extent_type(leaf, ei,
10136 BTRFS_FILE_EXTENT_INLINE);
10137 btrfs_set_file_extent_encryption(leaf, ei, 0);
10138 btrfs_set_file_extent_compression(leaf, ei, 0);
10139 btrfs_set_file_extent_other_encoding(leaf, ei, 0);
10140 btrfs_set_file_extent_ram_bytes(leaf, ei, name_len);
10142 ptr = btrfs_file_extent_inline_start(ei);
10143 write_extent_buffer(leaf, symname, ptr, name_len);
10144 btrfs_mark_buffer_dirty(leaf);
10145 btrfs_free_path(path);
10147 inode->i_op = &btrfs_symlink_inode_operations;
10148 inode_nohighmem(inode);
10149 inode->i_mapping->a_ops = &btrfs_symlink_aops;
10150 inode_set_bytes(inode, name_len);
10151 btrfs_i_size_write(BTRFS_I(inode), name_len);
10152 err = btrfs_update_inode(trans, root, inode);
10154 * Last step, add directory indexes for our symlink inode. This is the
10155 * last step to avoid extra cleanup of these indexes if an error happens
10159 err = btrfs_add_nondir(trans, BTRFS_I(dir), dentry,
10160 BTRFS_I(inode), 0, index);
10163 goto out_unlock_inode;
10166 d_instantiate_new(dentry, inode);
10169 btrfs_end_transaction(trans);
10171 inode_dec_link_count(inode);
10174 btrfs_btree_balance_dirty(fs_info);
10179 unlock_new_inode(inode);
10183 static int __btrfs_prealloc_file_range(struct inode *inode, int mode,
10184 u64 start, u64 num_bytes, u64 min_size,
10185 loff_t actual_len, u64 *alloc_hint,
10186 struct btrfs_trans_handle *trans)
10188 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
10189 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
10190 struct extent_map *em;
10191 struct btrfs_root *root = BTRFS_I(inode)->root;
10192 struct btrfs_key ins;
10193 u64 cur_offset = start;
10196 u64 last_alloc = (u64)-1;
10198 bool own_trans = true;
10199 u64 end = start + num_bytes - 1;
10203 while (num_bytes > 0) {
10205 trans = btrfs_start_transaction(root, 3);
10206 if (IS_ERR(trans)) {
10207 ret = PTR_ERR(trans);
10212 cur_bytes = min_t(u64, num_bytes, SZ_256M);
10213 cur_bytes = max(cur_bytes, min_size);
10215 * If we are severely fragmented we could end up with really
10216 * small allocations, so if the allocator is returning small
10217 * chunks lets make its job easier by only searching for those
10220 cur_bytes = min(cur_bytes, last_alloc);
10221 ret = btrfs_reserve_extent(root, cur_bytes, cur_bytes,
10222 min_size, 0, *alloc_hint, &ins, 1, 0);
10225 btrfs_end_transaction(trans);
10228 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
10230 last_alloc = ins.offset;
10231 ret = insert_reserved_file_extent(trans, inode,
10232 cur_offset, ins.objectid,
10233 ins.offset, ins.offset,
10234 ins.offset, 0, 0, 0,
10235 BTRFS_FILE_EXTENT_PREALLOC);
10237 btrfs_free_reserved_extent(fs_info, ins.objectid,
10239 btrfs_abort_transaction(trans, ret);
10241 btrfs_end_transaction(trans);
10245 btrfs_drop_extent_cache(BTRFS_I(inode), cur_offset,
10246 cur_offset + ins.offset -1, 0);
10248 em = alloc_extent_map();
10250 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
10251 &BTRFS_I(inode)->runtime_flags);
10255 em->start = cur_offset;
10256 em->orig_start = cur_offset;
10257 em->len = ins.offset;
10258 em->block_start = ins.objectid;
10259 em->block_len = ins.offset;
10260 em->orig_block_len = ins.offset;
10261 em->ram_bytes = ins.offset;
10262 em->bdev = fs_info->fs_devices->latest_bdev;
10263 set_bit(EXTENT_FLAG_PREALLOC, &em->flags);
10264 em->generation = trans->transid;
10267 write_lock(&em_tree->lock);
10268 ret = add_extent_mapping(em_tree, em, 1);
10269 write_unlock(&em_tree->lock);
10270 if (ret != -EEXIST)
10272 btrfs_drop_extent_cache(BTRFS_I(inode), cur_offset,
10273 cur_offset + ins.offset - 1,
10276 free_extent_map(em);
10278 num_bytes -= ins.offset;
10279 cur_offset += ins.offset;
10280 *alloc_hint = ins.objectid + ins.offset;
10282 inode_inc_iversion(inode);
10283 inode->i_ctime = current_time(inode);
10284 BTRFS_I(inode)->flags |= BTRFS_INODE_PREALLOC;
10285 if (!(mode & FALLOC_FL_KEEP_SIZE) &&
10286 (actual_len > inode->i_size) &&
10287 (cur_offset > inode->i_size)) {
10288 if (cur_offset > actual_len)
10289 i_size = actual_len;
10291 i_size = cur_offset;
10292 i_size_write(inode, i_size);
10293 btrfs_ordered_update_i_size(inode, i_size, NULL);
10296 ret = btrfs_update_inode(trans, root, inode);
10299 btrfs_abort_transaction(trans, ret);
10301 btrfs_end_transaction(trans);
10306 btrfs_end_transaction(trans);
10308 if (cur_offset < end)
10309 btrfs_free_reserved_data_space(inode, NULL, cur_offset,
10310 end - cur_offset + 1);
10314 int btrfs_prealloc_file_range(struct inode *inode, int mode,
10315 u64 start, u64 num_bytes, u64 min_size,
10316 loff_t actual_len, u64 *alloc_hint)
10318 return __btrfs_prealloc_file_range(inode, mode, start, num_bytes,
10319 min_size, actual_len, alloc_hint,
10323 int btrfs_prealloc_file_range_trans(struct inode *inode,
10324 struct btrfs_trans_handle *trans, int mode,
10325 u64 start, u64 num_bytes, u64 min_size,
10326 loff_t actual_len, u64 *alloc_hint)
10328 return __btrfs_prealloc_file_range(inode, mode, start, num_bytes,
10329 min_size, actual_len, alloc_hint, trans);
10332 static int btrfs_set_page_dirty(struct page *page)
10334 return __set_page_dirty_nobuffers(page);
10337 static int btrfs_permission(struct inode *inode, int mask)
10339 struct btrfs_root *root = BTRFS_I(inode)->root;
10340 umode_t mode = inode->i_mode;
10342 if (mask & MAY_WRITE &&
10343 (S_ISREG(mode) || S_ISDIR(mode) || S_ISLNK(mode))) {
10344 if (btrfs_root_readonly(root))
10346 if (BTRFS_I(inode)->flags & BTRFS_INODE_READONLY)
10349 return generic_permission(inode, mask);
10352 static int btrfs_tmpfile(struct inode *dir, struct dentry *dentry, umode_t mode)
10354 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
10355 struct btrfs_trans_handle *trans;
10356 struct btrfs_root *root = BTRFS_I(dir)->root;
10357 struct inode *inode = NULL;
10363 * 5 units required for adding orphan entry
10365 trans = btrfs_start_transaction(root, 5);
10367 return PTR_ERR(trans);
10369 ret = btrfs_find_free_ino(root, &objectid);
10373 inode = btrfs_new_inode(trans, root, dir, NULL, 0,
10374 btrfs_ino(BTRFS_I(dir)), objectid, mode, &index);
10375 if (IS_ERR(inode)) {
10376 ret = PTR_ERR(inode);
10381 inode->i_fop = &btrfs_file_operations;
10382 inode->i_op = &btrfs_file_inode_operations;
10384 inode->i_mapping->a_ops = &btrfs_aops;
10385 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
10387 ret = btrfs_init_inode_security(trans, inode, dir, NULL);
10391 ret = btrfs_update_inode(trans, root, inode);
10394 ret = btrfs_orphan_add(trans, BTRFS_I(inode));
10399 * We set number of links to 0 in btrfs_new_inode(), and here we set
10400 * it to 1 because d_tmpfile() will issue a warning if the count is 0,
10403 * d_tmpfile() -> inode_dec_link_count() -> drop_nlink()
10405 set_nlink(inode, 1);
10406 unlock_new_inode(inode);
10407 d_tmpfile(dentry, inode);
10408 mark_inode_dirty(inode);
10411 btrfs_end_transaction(trans);
10414 btrfs_btree_balance_dirty(fs_info);
10418 unlock_new_inode(inode);
10423 __attribute__((const))
10424 static int btrfs_readpage_io_failed_hook(struct page *page, int failed_mirror)
10429 static struct btrfs_fs_info *iotree_fs_info(void *private_data)
10431 struct inode *inode = private_data;
10432 return btrfs_sb(inode->i_sb);
10435 static void btrfs_check_extent_io_range(void *private_data, const char *caller,
10436 u64 start, u64 end)
10438 struct inode *inode = private_data;
10441 isize = i_size_read(inode);
10442 if (end >= PAGE_SIZE && (end % 2) == 0 && end != isize - 1) {
10443 btrfs_debug_rl(BTRFS_I(inode)->root->fs_info,
10444 "%s: ino %llu isize %llu odd range [%llu,%llu]",
10445 caller, btrfs_ino(BTRFS_I(inode)), isize, start, end);
10449 void btrfs_set_range_writeback(void *private_data, u64 start, u64 end)
10451 struct inode *inode = private_data;
10452 unsigned long index = start >> PAGE_SHIFT;
10453 unsigned long end_index = end >> PAGE_SHIFT;
10456 while (index <= end_index) {
10457 page = find_get_page(inode->i_mapping, index);
10458 ASSERT(page); /* Pages should be in the extent_io_tree */
10459 set_page_writeback(page);
10465 static const struct inode_operations btrfs_dir_inode_operations = {
10466 .getattr = btrfs_getattr,
10467 .lookup = btrfs_lookup,
10468 .create = btrfs_create,
10469 .unlink = btrfs_unlink,
10470 .link = btrfs_link,
10471 .mkdir = btrfs_mkdir,
10472 .rmdir = btrfs_rmdir,
10473 .rename = btrfs_rename2,
10474 .symlink = btrfs_symlink,
10475 .setattr = btrfs_setattr,
10476 .mknod = btrfs_mknod,
10477 .listxattr = btrfs_listxattr,
10478 .permission = btrfs_permission,
10479 .get_acl = btrfs_get_acl,
10480 .set_acl = btrfs_set_acl,
10481 .update_time = btrfs_update_time,
10482 .tmpfile = btrfs_tmpfile,
10484 static const struct inode_operations btrfs_dir_ro_inode_operations = {
10485 .lookup = btrfs_lookup,
10486 .permission = btrfs_permission,
10487 .update_time = btrfs_update_time,
10490 static const struct file_operations btrfs_dir_file_operations = {
10491 .llseek = generic_file_llseek,
10492 .read = generic_read_dir,
10493 .iterate_shared = btrfs_real_readdir,
10494 .open = btrfs_opendir,
10495 .unlocked_ioctl = btrfs_ioctl,
10496 #ifdef CONFIG_COMPAT
10497 .compat_ioctl = btrfs_compat_ioctl,
10499 .release = btrfs_release_file,
10500 .fsync = btrfs_sync_file,
10503 static const struct extent_io_ops btrfs_extent_io_ops = {
10504 /* mandatory callbacks */
10505 .submit_bio_hook = btrfs_submit_bio_hook,
10506 .readpage_end_io_hook = btrfs_readpage_end_io_hook,
10507 .merge_bio_hook = btrfs_merge_bio_hook,
10508 .readpage_io_failed_hook = btrfs_readpage_io_failed_hook,
10509 .tree_fs_info = iotree_fs_info,
10510 .set_range_writeback = btrfs_set_range_writeback,
10512 /* optional callbacks */
10513 .fill_delalloc = run_delalloc_range,
10514 .writepage_end_io_hook = btrfs_writepage_end_io_hook,
10515 .writepage_start_hook = btrfs_writepage_start_hook,
10516 .set_bit_hook = btrfs_set_bit_hook,
10517 .clear_bit_hook = btrfs_clear_bit_hook,
10518 .merge_extent_hook = btrfs_merge_extent_hook,
10519 .split_extent_hook = btrfs_split_extent_hook,
10520 .check_extent_io_range = btrfs_check_extent_io_range,
10524 * btrfs doesn't support the bmap operation because swapfiles
10525 * use bmap to make a mapping of extents in the file. They assume
10526 * these extents won't change over the life of the file and they
10527 * use the bmap result to do IO directly to the drive.
10529 * the btrfs bmap call would return logical addresses that aren't
10530 * suitable for IO and they also will change frequently as COW
10531 * operations happen. So, swapfile + btrfs == corruption.
10533 * For now we're avoiding this by dropping bmap.
10535 static const struct address_space_operations btrfs_aops = {
10536 .readpage = btrfs_readpage,
10537 .writepage = btrfs_writepage,
10538 .writepages = btrfs_writepages,
10539 .readpages = btrfs_readpages,
10540 .direct_IO = btrfs_direct_IO,
10541 .invalidatepage = btrfs_invalidatepage,
10542 .releasepage = btrfs_releasepage,
10543 .set_page_dirty = btrfs_set_page_dirty,
10544 .error_remove_page = generic_error_remove_page,
10547 static const struct address_space_operations btrfs_symlink_aops = {
10548 .readpage = btrfs_readpage,
10549 .writepage = btrfs_writepage,
10550 .invalidatepage = btrfs_invalidatepage,
10551 .releasepage = btrfs_releasepage,
10554 static const struct inode_operations btrfs_file_inode_operations = {
10555 .getattr = btrfs_getattr,
10556 .setattr = btrfs_setattr,
10557 .listxattr = btrfs_listxattr,
10558 .permission = btrfs_permission,
10559 .fiemap = btrfs_fiemap,
10560 .get_acl = btrfs_get_acl,
10561 .set_acl = btrfs_set_acl,
10562 .update_time = btrfs_update_time,
10564 static const struct inode_operations btrfs_special_inode_operations = {
10565 .getattr = btrfs_getattr,
10566 .setattr = btrfs_setattr,
10567 .permission = btrfs_permission,
10568 .listxattr = btrfs_listxattr,
10569 .get_acl = btrfs_get_acl,
10570 .set_acl = btrfs_set_acl,
10571 .update_time = btrfs_update_time,
10573 static const struct inode_operations btrfs_symlink_inode_operations = {
10574 .get_link = page_get_link,
10575 .getattr = btrfs_getattr,
10576 .setattr = btrfs_setattr,
10577 .permission = btrfs_permission,
10578 .listxattr = btrfs_listxattr,
10579 .update_time = btrfs_update_time,
10582 const struct dentry_operations btrfs_dentry_operations = {
10583 .d_delete = btrfs_dentry_delete,