2 * Copyright (C) 2007 Oracle. All rights reserved.
4 * This program is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU General Public
6 * License v2 as published by the Free Software Foundation.
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
11 * General Public License for more details.
13 * You should have received a copy of the GNU General Public
14 * License along with this program; if not, write to the
15 * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
16 * Boston, MA 021110-1307, USA.
19 #include <linux/kernel.h>
20 #include <linux/bio.h>
21 #include <linux/buffer_head.h>
22 #include <linux/file.h>
24 #include <linux/pagemap.h>
25 #include <linux/highmem.h>
26 #include <linux/time.h>
27 #include <linux/init.h>
28 #include <linux/string.h>
29 #include <linux/backing-dev.h>
30 #include <linux/mpage.h>
31 #include <linux/swap.h>
32 #include <linux/writeback.h>
33 #include <linux/compat.h>
34 #include <linux/bit_spinlock.h>
35 #include <linux/xattr.h>
36 #include <linux/posix_acl.h>
37 #include <linux/falloc.h>
38 #include <linux/slab.h>
39 #include <linux/ratelimit.h>
40 #include <linux/mount.h>
41 #include <linux/btrfs.h>
42 #include <linux/blkdev.h>
43 #include <linux/posix_acl_xattr.h>
44 #include <linux/uio.h>
47 #include "transaction.h"
48 #include "btrfs_inode.h"
49 #include "print-tree.h"
50 #include "ordered-data.h"
54 #include "compression.h"
56 #include "free-space-cache.h"
57 #include "inode-map.h"
64 struct btrfs_iget_args {
65 struct btrfs_key *location;
66 struct btrfs_root *root;
69 struct btrfs_dio_data {
70 u64 outstanding_extents;
72 u64 unsubmitted_oe_range_start;
73 u64 unsubmitted_oe_range_end;
77 static const struct inode_operations btrfs_dir_inode_operations;
78 static const struct inode_operations btrfs_symlink_inode_operations;
79 static const struct inode_operations btrfs_dir_ro_inode_operations;
80 static const struct inode_operations btrfs_special_inode_operations;
81 static const struct inode_operations btrfs_file_inode_operations;
82 static const struct address_space_operations btrfs_aops;
83 static const struct address_space_operations btrfs_symlink_aops;
84 static const struct file_operations btrfs_dir_file_operations;
85 static const struct extent_io_ops btrfs_extent_io_ops;
87 static struct kmem_cache *btrfs_inode_cachep;
88 struct kmem_cache *btrfs_trans_handle_cachep;
89 struct kmem_cache *btrfs_transaction_cachep;
90 struct kmem_cache *btrfs_path_cachep;
91 struct kmem_cache *btrfs_free_space_cachep;
94 static const unsigned char btrfs_type_by_mode[S_IFMT >> S_SHIFT] = {
95 [S_IFREG >> S_SHIFT] = BTRFS_FT_REG_FILE,
96 [S_IFDIR >> S_SHIFT] = BTRFS_FT_DIR,
97 [S_IFCHR >> S_SHIFT] = BTRFS_FT_CHRDEV,
98 [S_IFBLK >> S_SHIFT] = BTRFS_FT_BLKDEV,
99 [S_IFIFO >> S_SHIFT] = BTRFS_FT_FIFO,
100 [S_IFSOCK >> S_SHIFT] = BTRFS_FT_SOCK,
101 [S_IFLNK >> S_SHIFT] = BTRFS_FT_SYMLINK,
104 static int btrfs_setsize(struct inode *inode, struct iattr *attr);
105 static int btrfs_truncate(struct inode *inode);
106 static int btrfs_finish_ordered_io(struct btrfs_ordered_extent *ordered_extent);
107 static noinline int cow_file_range(struct inode *inode,
108 struct page *locked_page,
109 u64 start, u64 end, u64 delalloc_end,
110 int *page_started, unsigned long *nr_written,
111 int unlock, struct btrfs_dedupe_hash *hash);
112 static struct extent_map *create_io_em(struct inode *inode, u64 start, u64 len,
113 u64 orig_start, u64 block_start,
114 u64 block_len, u64 orig_block_len,
115 u64 ram_bytes, int compress_type,
118 static int btrfs_dirty_inode(struct inode *inode);
120 #ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
121 void btrfs_test_inode_set_ops(struct inode *inode)
123 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
127 static int btrfs_init_inode_security(struct btrfs_trans_handle *trans,
128 struct inode *inode, struct inode *dir,
129 const struct qstr *qstr)
133 err = btrfs_init_acl(trans, inode, dir);
135 err = btrfs_xattr_security_init(trans, inode, dir, qstr);
140 * this does all the hard work for inserting an inline extent into
141 * the btree. The caller should have done a btrfs_drop_extents so that
142 * no overlapping inline items exist in the btree
144 static int insert_inline_extent(struct btrfs_trans_handle *trans,
145 struct btrfs_path *path, int extent_inserted,
146 struct btrfs_root *root, struct inode *inode,
147 u64 start, size_t size, size_t compressed_size,
149 struct page **compressed_pages)
151 struct extent_buffer *leaf;
152 struct page *page = NULL;
155 struct btrfs_file_extent_item *ei;
158 size_t cur_size = size;
159 unsigned long offset;
161 if (compressed_size && compressed_pages)
162 cur_size = compressed_size;
164 inode_add_bytes(inode, size);
166 if (!extent_inserted) {
167 struct btrfs_key key;
170 key.objectid = btrfs_ino(BTRFS_I(inode));
172 key.type = BTRFS_EXTENT_DATA_KEY;
174 datasize = btrfs_file_extent_calc_inline_size(cur_size);
175 path->leave_spinning = 1;
176 ret = btrfs_insert_empty_item(trans, root, path, &key,
183 leaf = path->nodes[0];
184 ei = btrfs_item_ptr(leaf, path->slots[0],
185 struct btrfs_file_extent_item);
186 btrfs_set_file_extent_generation(leaf, ei, trans->transid);
187 btrfs_set_file_extent_type(leaf, ei, BTRFS_FILE_EXTENT_INLINE);
188 btrfs_set_file_extent_encryption(leaf, ei, 0);
189 btrfs_set_file_extent_other_encoding(leaf, ei, 0);
190 btrfs_set_file_extent_ram_bytes(leaf, ei, size);
191 ptr = btrfs_file_extent_inline_start(ei);
193 if (compress_type != BTRFS_COMPRESS_NONE) {
196 while (compressed_size > 0) {
197 cpage = compressed_pages[i];
198 cur_size = min_t(unsigned long, compressed_size,
201 kaddr = kmap_atomic(cpage);
202 write_extent_buffer(leaf, kaddr, ptr, cur_size);
203 kunmap_atomic(kaddr);
207 compressed_size -= cur_size;
209 btrfs_set_file_extent_compression(leaf, ei,
212 page = find_get_page(inode->i_mapping,
213 start >> PAGE_SHIFT);
214 btrfs_set_file_extent_compression(leaf, ei, 0);
215 kaddr = kmap_atomic(page);
216 offset = start & (PAGE_SIZE - 1);
217 write_extent_buffer(leaf, kaddr + offset, ptr, size);
218 kunmap_atomic(kaddr);
221 btrfs_mark_buffer_dirty(leaf);
222 btrfs_release_path(path);
225 * we're an inline extent, so nobody can
226 * extend the file past i_size without locking
227 * a page we already have locked.
229 * We must do any isize and inode updates
230 * before we unlock the pages. Otherwise we
231 * could end up racing with unlink.
233 BTRFS_I(inode)->disk_i_size = inode->i_size;
234 ret = btrfs_update_inode(trans, root, inode);
243 * conditionally insert an inline extent into the file. This
244 * does the checks required to make sure the data is small enough
245 * to fit as an inline extent.
247 static noinline int cow_file_range_inline(struct btrfs_root *root,
248 struct inode *inode, u64 start,
249 u64 end, size_t compressed_size,
251 struct page **compressed_pages)
253 struct btrfs_fs_info *fs_info = root->fs_info;
254 struct btrfs_trans_handle *trans;
255 u64 isize = i_size_read(inode);
256 u64 actual_end = min(end + 1, isize);
257 u64 inline_len = actual_end - start;
258 u64 aligned_end = ALIGN(end, fs_info->sectorsize);
259 u64 data_len = inline_len;
261 struct btrfs_path *path;
262 int extent_inserted = 0;
263 u32 extent_item_size;
266 data_len = compressed_size;
269 actual_end > fs_info->sectorsize ||
270 data_len > BTRFS_MAX_INLINE_DATA_SIZE(fs_info) ||
272 (actual_end & (fs_info->sectorsize - 1)) == 0) ||
274 data_len > fs_info->max_inline) {
278 path = btrfs_alloc_path();
282 trans = btrfs_join_transaction(root);
284 btrfs_free_path(path);
285 return PTR_ERR(trans);
287 trans->block_rsv = &fs_info->delalloc_block_rsv;
289 if (compressed_size && compressed_pages)
290 extent_item_size = btrfs_file_extent_calc_inline_size(
293 extent_item_size = btrfs_file_extent_calc_inline_size(
296 ret = __btrfs_drop_extents(trans, root, inode, path,
297 start, aligned_end, NULL,
298 1, 1, extent_item_size, &extent_inserted);
300 btrfs_abort_transaction(trans, ret);
304 if (isize > actual_end)
305 inline_len = min_t(u64, isize, actual_end);
306 ret = insert_inline_extent(trans, path, extent_inserted,
308 inline_len, compressed_size,
309 compress_type, compressed_pages);
310 if (ret && ret != -ENOSPC) {
311 btrfs_abort_transaction(trans, ret);
313 } else if (ret == -ENOSPC) {
318 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &BTRFS_I(inode)->runtime_flags);
319 btrfs_delalloc_release_metadata(BTRFS_I(inode), end + 1 - start);
320 btrfs_drop_extent_cache(BTRFS_I(inode), start, aligned_end - 1, 0);
323 * Don't forget to free the reserved space, as for inlined extent
324 * it won't count as data extent, free them directly here.
325 * And at reserve time, it's always aligned to page size, so
326 * just free one page here.
328 btrfs_qgroup_free_data(inode, 0, PAGE_SIZE);
329 btrfs_free_path(path);
330 btrfs_end_transaction(trans);
334 struct async_extent {
339 unsigned long nr_pages;
341 struct list_head list;
346 struct btrfs_root *root;
347 struct page *locked_page;
350 struct list_head extents;
351 struct btrfs_work work;
354 static noinline int add_async_extent(struct async_cow *cow,
355 u64 start, u64 ram_size,
358 unsigned long nr_pages,
361 struct async_extent *async_extent;
363 async_extent = kmalloc(sizeof(*async_extent), GFP_NOFS);
364 BUG_ON(!async_extent); /* -ENOMEM */
365 async_extent->start = start;
366 async_extent->ram_size = ram_size;
367 async_extent->compressed_size = compressed_size;
368 async_extent->pages = pages;
369 async_extent->nr_pages = nr_pages;
370 async_extent->compress_type = compress_type;
371 list_add_tail(&async_extent->list, &cow->extents);
375 static inline int inode_need_compress(struct inode *inode)
377 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
380 if (btrfs_test_opt(fs_info, FORCE_COMPRESS))
382 /* bad compression ratios */
383 if (BTRFS_I(inode)->flags & BTRFS_INODE_NOCOMPRESS)
385 if (btrfs_test_opt(fs_info, COMPRESS) ||
386 BTRFS_I(inode)->flags & BTRFS_INODE_COMPRESS ||
387 BTRFS_I(inode)->force_compress)
392 static inline void inode_should_defrag(struct btrfs_inode *inode,
393 u64 start, u64 end, u64 num_bytes, u64 small_write)
395 /* If this is a small write inside eof, kick off a defrag */
396 if (num_bytes < small_write &&
397 (start > 0 || end + 1 < inode->disk_i_size))
398 btrfs_add_inode_defrag(NULL, inode);
402 * we create compressed extents in two phases. The first
403 * phase compresses a range of pages that have already been
404 * locked (both pages and state bits are locked).
406 * This is done inside an ordered work queue, and the compression
407 * is spread across many cpus. The actual IO submission is step
408 * two, and the ordered work queue takes care of making sure that
409 * happens in the same order things were put onto the queue by
410 * writepages and friends.
412 * If this code finds it can't get good compression, it puts an
413 * entry onto the work queue to write the uncompressed bytes. This
414 * makes sure that both compressed inodes and uncompressed inodes
415 * are written in the same order that the flusher thread sent them
418 static noinline void compress_file_range(struct inode *inode,
419 struct page *locked_page,
421 struct async_cow *async_cow,
424 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
425 struct btrfs_root *root = BTRFS_I(inode)->root;
427 u64 blocksize = fs_info->sectorsize;
429 u64 isize = i_size_read(inode);
431 struct page **pages = NULL;
432 unsigned long nr_pages;
433 unsigned long total_compressed = 0;
434 unsigned long total_in = 0;
437 int compress_type = fs_info->compress_type;
440 inode_should_defrag(BTRFS_I(inode), start, end, end - start + 1,
443 actual_end = min_t(u64, isize, end + 1);
446 nr_pages = (end >> PAGE_SHIFT) - (start >> PAGE_SHIFT) + 1;
447 BUILD_BUG_ON((BTRFS_MAX_COMPRESSED % PAGE_SIZE) != 0);
448 nr_pages = min_t(unsigned long, nr_pages,
449 BTRFS_MAX_COMPRESSED / PAGE_SIZE);
452 * we don't want to send crud past the end of i_size through
453 * compression, that's just a waste of CPU time. So, if the
454 * end of the file is before the start of our current
455 * requested range of bytes, we bail out to the uncompressed
456 * cleanup code that can deal with all of this.
458 * It isn't really the fastest way to fix things, but this is a
459 * very uncommon corner.
461 if (actual_end <= start)
462 goto cleanup_and_bail_uncompressed;
464 total_compressed = actual_end - start;
467 * skip compression for a small file range(<=blocksize) that
468 * isn't an inline extent, since it doesn't save disk space at all.
470 if (total_compressed <= blocksize &&
471 (start > 0 || end + 1 < BTRFS_I(inode)->disk_i_size))
472 goto cleanup_and_bail_uncompressed;
474 total_compressed = min_t(unsigned long, total_compressed,
475 BTRFS_MAX_UNCOMPRESSED);
476 num_bytes = ALIGN(end - start + 1, blocksize);
477 num_bytes = max(blocksize, num_bytes);
482 * we do compression for mount -o compress and when the
483 * inode has not been flagged as nocompress. This flag can
484 * change at any time if we discover bad compression ratios.
486 if (inode_need_compress(inode)) {
488 pages = kcalloc(nr_pages, sizeof(struct page *), GFP_NOFS);
490 /* just bail out to the uncompressed code */
494 if (BTRFS_I(inode)->force_compress)
495 compress_type = BTRFS_I(inode)->force_compress;
498 * we need to call clear_page_dirty_for_io on each
499 * page in the range. Otherwise applications with the file
500 * mmap'd can wander in and change the page contents while
501 * we are compressing them.
503 * If the compression fails for any reason, we set the pages
504 * dirty again later on.
506 extent_range_clear_dirty_for_io(inode, start, end);
508 ret = btrfs_compress_pages(compress_type,
509 inode->i_mapping, start,
514 BTRFS_MAX_COMPRESSED);
517 unsigned long offset = total_compressed &
519 struct page *page = pages[nr_pages - 1];
522 /* zero the tail end of the last page, we might be
523 * sending it down to disk
526 kaddr = kmap_atomic(page);
527 memset(kaddr + offset, 0,
529 kunmap_atomic(kaddr);
536 /* lets try to make an inline extent */
537 if (ret || total_in < (actual_end - start)) {
538 /* we didn't compress the entire range, try
539 * to make an uncompressed inline extent.
541 ret = cow_file_range_inline(root, inode, start, end,
542 0, BTRFS_COMPRESS_NONE, NULL);
544 /* try making a compressed inline extent */
545 ret = cow_file_range_inline(root, inode, start, end,
547 compress_type, pages);
550 unsigned long clear_flags = EXTENT_DELALLOC |
552 unsigned long page_error_op;
554 clear_flags |= (ret < 0) ? EXTENT_DO_ACCOUNTING : 0;
555 page_error_op = ret < 0 ? PAGE_SET_ERROR : 0;
558 * inline extent creation worked or returned error,
559 * we don't need to create any more async work items.
560 * Unlock and free up our temp pages.
562 extent_clear_unlock_delalloc(inode, start, end, end,
569 btrfs_free_reserved_data_space_noquota(inode, start,
577 * we aren't doing an inline extent round the compressed size
578 * up to a block size boundary so the allocator does sane
581 total_compressed = ALIGN(total_compressed, blocksize);
584 * one last check to make sure the compression is really a
585 * win, compare the page count read with the blocks on disk
587 total_in = ALIGN(total_in, PAGE_SIZE);
588 if (total_compressed >= total_in) {
591 num_bytes = total_in;
595 * The async work queues will take care of doing actual
596 * allocation on disk for these compressed pages, and
597 * will submit them to the elevator.
599 add_async_extent(async_cow, start, num_bytes,
600 total_compressed, pages, nr_pages,
603 if (start + num_bytes < end) {
614 * the compression code ran but failed to make things smaller,
615 * free any pages it allocated and our page pointer array
617 for (i = 0; i < nr_pages; i++) {
618 WARN_ON(pages[i]->mapping);
623 total_compressed = 0;
626 /* flag the file so we don't compress in the future */
627 if (!btrfs_test_opt(fs_info, FORCE_COMPRESS) &&
628 !(BTRFS_I(inode)->force_compress)) {
629 BTRFS_I(inode)->flags |= BTRFS_INODE_NOCOMPRESS;
632 cleanup_and_bail_uncompressed:
634 * No compression, but we still need to write the pages in the file
635 * we've been given so far. redirty the locked page if it corresponds
636 * to our extent and set things up for the async work queue to run
637 * cow_file_range to do the normal delalloc dance.
639 if (page_offset(locked_page) >= start &&
640 page_offset(locked_page) <= end)
641 __set_page_dirty_nobuffers(locked_page);
642 /* unlocked later on in the async handlers */
645 extent_range_redirty_for_io(inode, start, end);
646 add_async_extent(async_cow, start, end - start + 1, 0, NULL, 0,
647 BTRFS_COMPRESS_NONE);
653 for (i = 0; i < nr_pages; i++) {
654 WARN_ON(pages[i]->mapping);
660 static void free_async_extent_pages(struct async_extent *async_extent)
664 if (!async_extent->pages)
667 for (i = 0; i < async_extent->nr_pages; i++) {
668 WARN_ON(async_extent->pages[i]->mapping);
669 put_page(async_extent->pages[i]);
671 kfree(async_extent->pages);
672 async_extent->nr_pages = 0;
673 async_extent->pages = NULL;
677 * phase two of compressed writeback. This is the ordered portion
678 * of the code, which only gets called in the order the work was
679 * queued. We walk all the async extents created by compress_file_range
680 * and send them down to the disk.
682 static noinline void submit_compressed_extents(struct inode *inode,
683 struct async_cow *async_cow)
685 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
686 struct async_extent *async_extent;
688 struct btrfs_key ins;
689 struct extent_map *em;
690 struct btrfs_root *root = BTRFS_I(inode)->root;
691 struct extent_io_tree *io_tree;
695 while (!list_empty(&async_cow->extents)) {
696 async_extent = list_entry(async_cow->extents.next,
697 struct async_extent, list);
698 list_del(&async_extent->list);
700 io_tree = &BTRFS_I(inode)->io_tree;
703 /* did the compression code fall back to uncompressed IO? */
704 if (!async_extent->pages) {
705 int page_started = 0;
706 unsigned long nr_written = 0;
708 lock_extent(io_tree, async_extent->start,
709 async_extent->start +
710 async_extent->ram_size - 1);
712 /* allocate blocks */
713 ret = cow_file_range(inode, async_cow->locked_page,
715 async_extent->start +
716 async_extent->ram_size - 1,
717 async_extent->start +
718 async_extent->ram_size - 1,
719 &page_started, &nr_written, 0,
725 * if page_started, cow_file_range inserted an
726 * inline extent and took care of all the unlocking
727 * and IO for us. Otherwise, we need to submit
728 * all those pages down to the drive.
730 if (!page_started && !ret)
731 extent_write_locked_range(io_tree,
732 inode, async_extent->start,
733 async_extent->start +
734 async_extent->ram_size - 1,
738 unlock_page(async_cow->locked_page);
744 lock_extent(io_tree, async_extent->start,
745 async_extent->start + async_extent->ram_size - 1);
747 ret = btrfs_reserve_extent(root, async_extent->ram_size,
748 async_extent->compressed_size,
749 async_extent->compressed_size,
750 0, alloc_hint, &ins, 1, 1);
752 free_async_extent_pages(async_extent);
754 if (ret == -ENOSPC) {
755 unlock_extent(io_tree, async_extent->start,
756 async_extent->start +
757 async_extent->ram_size - 1);
760 * we need to redirty the pages if we decide to
761 * fallback to uncompressed IO, otherwise we
762 * will not submit these pages down to lower
765 extent_range_redirty_for_io(inode,
767 async_extent->start +
768 async_extent->ram_size - 1);
775 * here we're doing allocation and writeback of the
778 em = create_io_em(inode, async_extent->start,
779 async_extent->ram_size, /* len */
780 async_extent->start, /* orig_start */
781 ins.objectid, /* block_start */
782 ins.offset, /* block_len */
783 ins.offset, /* orig_block_len */
784 async_extent->ram_size, /* ram_bytes */
785 async_extent->compress_type,
786 BTRFS_ORDERED_COMPRESSED);
788 /* ret value is not necessary due to void function */
789 goto out_free_reserve;
792 ret = btrfs_add_ordered_extent_compress(inode,
795 async_extent->ram_size,
797 BTRFS_ORDERED_COMPRESSED,
798 async_extent->compress_type);
800 btrfs_drop_extent_cache(BTRFS_I(inode),
802 async_extent->start +
803 async_extent->ram_size - 1, 0);
804 goto out_free_reserve;
806 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
809 * clear dirty, set writeback and unlock the pages.
811 extent_clear_unlock_delalloc(inode, async_extent->start,
812 async_extent->start +
813 async_extent->ram_size - 1,
814 async_extent->start +
815 async_extent->ram_size - 1,
816 NULL, EXTENT_LOCKED | EXTENT_DELALLOC,
817 PAGE_UNLOCK | PAGE_CLEAR_DIRTY |
819 ret = btrfs_submit_compressed_write(inode,
821 async_extent->ram_size,
823 ins.offset, async_extent->pages,
824 async_extent->nr_pages);
826 struct extent_io_tree *tree = &BTRFS_I(inode)->io_tree;
827 struct page *p = async_extent->pages[0];
828 const u64 start = async_extent->start;
829 const u64 end = start + async_extent->ram_size - 1;
831 p->mapping = inode->i_mapping;
832 tree->ops->writepage_end_io_hook(p, start, end,
835 extent_clear_unlock_delalloc(inode, start, end, end,
839 free_async_extent_pages(async_extent);
841 alloc_hint = ins.objectid + ins.offset;
847 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
848 btrfs_free_reserved_extent(fs_info, ins.objectid, ins.offset, 1);
850 extent_clear_unlock_delalloc(inode, async_extent->start,
851 async_extent->start +
852 async_extent->ram_size - 1,
853 async_extent->start +
854 async_extent->ram_size - 1,
855 NULL, EXTENT_LOCKED | EXTENT_DELALLOC |
856 EXTENT_DEFRAG | EXTENT_DO_ACCOUNTING,
857 PAGE_UNLOCK | PAGE_CLEAR_DIRTY |
858 PAGE_SET_WRITEBACK | PAGE_END_WRITEBACK |
860 free_async_extent_pages(async_extent);
865 static u64 get_extent_allocation_hint(struct inode *inode, u64 start,
868 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
869 struct extent_map *em;
872 read_lock(&em_tree->lock);
873 em = search_extent_mapping(em_tree, start, num_bytes);
876 * if block start isn't an actual block number then find the
877 * first block in this inode and use that as a hint. If that
878 * block is also bogus then just don't worry about it.
880 if (em->block_start >= EXTENT_MAP_LAST_BYTE) {
882 em = search_extent_mapping(em_tree, 0, 0);
883 if (em && em->block_start < EXTENT_MAP_LAST_BYTE)
884 alloc_hint = em->block_start;
888 alloc_hint = em->block_start;
892 read_unlock(&em_tree->lock);
898 * when extent_io.c finds a delayed allocation range in the file,
899 * the call backs end up in this code. The basic idea is to
900 * allocate extents on disk for the range, and create ordered data structs
901 * in ram to track those extents.
903 * locked_page is the page that writepage had locked already. We use
904 * it to make sure we don't do extra locks or unlocks.
906 * *page_started is set to one if we unlock locked_page and do everything
907 * required to start IO on it. It may be clean and already done with
910 static noinline int cow_file_range(struct inode *inode,
911 struct page *locked_page,
912 u64 start, u64 end, u64 delalloc_end,
913 int *page_started, unsigned long *nr_written,
914 int unlock, struct btrfs_dedupe_hash *hash)
916 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
917 struct btrfs_root *root = BTRFS_I(inode)->root;
920 unsigned long ram_size;
923 u64 blocksize = fs_info->sectorsize;
924 struct btrfs_key ins;
925 struct extent_map *em;
928 if (btrfs_is_free_space_inode(BTRFS_I(inode))) {
934 num_bytes = ALIGN(end - start + 1, blocksize);
935 num_bytes = max(blocksize, num_bytes);
936 disk_num_bytes = num_bytes;
938 inode_should_defrag(BTRFS_I(inode), start, end, num_bytes, SZ_64K);
941 /* lets try to make an inline extent */
942 ret = cow_file_range_inline(root, inode, start, end, 0,
943 BTRFS_COMPRESS_NONE, NULL);
945 extent_clear_unlock_delalloc(inode, start, end,
947 EXTENT_LOCKED | EXTENT_DELALLOC |
948 EXTENT_DEFRAG, PAGE_UNLOCK |
949 PAGE_CLEAR_DIRTY | PAGE_SET_WRITEBACK |
951 btrfs_free_reserved_data_space_noquota(inode, start,
953 *nr_written = *nr_written +
954 (end - start + PAGE_SIZE) / PAGE_SIZE;
957 } else if (ret < 0) {
962 BUG_ON(disk_num_bytes >
963 btrfs_super_total_bytes(fs_info->super_copy));
965 alloc_hint = get_extent_allocation_hint(inode, start, num_bytes);
966 btrfs_drop_extent_cache(BTRFS_I(inode), start,
967 start + num_bytes - 1, 0);
969 while (disk_num_bytes > 0) {
972 cur_alloc_size = disk_num_bytes;
973 ret = btrfs_reserve_extent(root, cur_alloc_size, cur_alloc_size,
974 fs_info->sectorsize, 0, alloc_hint,
979 ram_size = ins.offset;
980 em = create_io_em(inode, start, ins.offset, /* len */
981 start, /* orig_start */
982 ins.objectid, /* block_start */
983 ins.offset, /* block_len */
984 ins.offset, /* orig_block_len */
985 ram_size, /* ram_bytes */
986 BTRFS_COMPRESS_NONE, /* compress_type */
987 BTRFS_ORDERED_REGULAR /* type */);
992 cur_alloc_size = ins.offset;
993 ret = btrfs_add_ordered_extent(inode, start, ins.objectid,
994 ram_size, cur_alloc_size, 0);
996 goto out_drop_extent_cache;
998 if (root->root_key.objectid ==
999 BTRFS_DATA_RELOC_TREE_OBJECTID) {
1000 ret = btrfs_reloc_clone_csums(inode, start,
1003 goto out_drop_extent_cache;
1006 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
1008 if (disk_num_bytes < cur_alloc_size)
1011 /* we're not doing compressed IO, don't unlock the first
1012 * page (which the caller expects to stay locked), don't
1013 * clear any dirty bits and don't set any writeback bits
1015 * Do set the Private2 bit so we know this page was properly
1016 * setup for writepage
1018 op = unlock ? PAGE_UNLOCK : 0;
1019 op |= PAGE_SET_PRIVATE2;
1021 extent_clear_unlock_delalloc(inode, start,
1022 start + ram_size - 1,
1023 delalloc_end, locked_page,
1024 EXTENT_LOCKED | EXTENT_DELALLOC,
1026 disk_num_bytes -= cur_alloc_size;
1027 num_bytes -= cur_alloc_size;
1028 alloc_hint = ins.objectid + ins.offset;
1029 start += cur_alloc_size;
1034 out_drop_extent_cache:
1035 btrfs_drop_extent_cache(BTRFS_I(inode), start, start + ram_size - 1, 0);
1037 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
1038 btrfs_free_reserved_extent(fs_info, ins.objectid, ins.offset, 1);
1040 extent_clear_unlock_delalloc(inode, start, end, delalloc_end,
1042 EXTENT_LOCKED | EXTENT_DO_ACCOUNTING |
1043 EXTENT_DELALLOC | EXTENT_DEFRAG,
1044 PAGE_UNLOCK | PAGE_CLEAR_DIRTY |
1045 PAGE_SET_WRITEBACK | PAGE_END_WRITEBACK);
1050 * work queue call back to started compression on a file and pages
1052 static noinline void async_cow_start(struct btrfs_work *work)
1054 struct async_cow *async_cow;
1056 async_cow = container_of(work, struct async_cow, work);
1058 compress_file_range(async_cow->inode, async_cow->locked_page,
1059 async_cow->start, async_cow->end, async_cow,
1061 if (num_added == 0) {
1062 btrfs_add_delayed_iput(async_cow->inode);
1063 async_cow->inode = NULL;
1068 * work queue call back to submit previously compressed pages
1070 static noinline void async_cow_submit(struct btrfs_work *work)
1072 struct btrfs_fs_info *fs_info;
1073 struct async_cow *async_cow;
1074 struct btrfs_root *root;
1075 unsigned long nr_pages;
1077 async_cow = container_of(work, struct async_cow, work);
1079 root = async_cow->root;
1080 fs_info = root->fs_info;
1081 nr_pages = (async_cow->end - async_cow->start + PAGE_SIZE) >>
1085 * atomic_sub_return implies a barrier for waitqueue_active
1087 if (atomic_sub_return(nr_pages, &fs_info->async_delalloc_pages) <
1089 waitqueue_active(&fs_info->async_submit_wait))
1090 wake_up(&fs_info->async_submit_wait);
1092 if (async_cow->inode)
1093 submit_compressed_extents(async_cow->inode, async_cow);
1096 static noinline void async_cow_free(struct btrfs_work *work)
1098 struct async_cow *async_cow;
1099 async_cow = container_of(work, struct async_cow, work);
1100 if (async_cow->inode)
1101 btrfs_add_delayed_iput(async_cow->inode);
1105 static int cow_file_range_async(struct inode *inode, struct page *locked_page,
1106 u64 start, u64 end, int *page_started,
1107 unsigned long *nr_written)
1109 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1110 struct async_cow *async_cow;
1111 struct btrfs_root *root = BTRFS_I(inode)->root;
1112 unsigned long nr_pages;
1115 clear_extent_bit(&BTRFS_I(inode)->io_tree, start, end, EXTENT_LOCKED,
1116 1, 0, NULL, GFP_NOFS);
1117 while (start < end) {
1118 async_cow = kmalloc(sizeof(*async_cow), GFP_NOFS);
1119 BUG_ON(!async_cow); /* -ENOMEM */
1120 async_cow->inode = igrab(inode);
1121 async_cow->root = root;
1122 async_cow->locked_page = locked_page;
1123 async_cow->start = start;
1125 if (BTRFS_I(inode)->flags & BTRFS_INODE_NOCOMPRESS &&
1126 !btrfs_test_opt(fs_info, FORCE_COMPRESS))
1129 cur_end = min(end, start + SZ_512K - 1);
1131 async_cow->end = cur_end;
1132 INIT_LIST_HEAD(&async_cow->extents);
1134 btrfs_init_work(&async_cow->work,
1135 btrfs_delalloc_helper,
1136 async_cow_start, async_cow_submit,
1139 nr_pages = (cur_end - start + PAGE_SIZE) >>
1141 atomic_add(nr_pages, &fs_info->async_delalloc_pages);
1143 btrfs_queue_work(fs_info->delalloc_workers, &async_cow->work);
1145 while (atomic_read(&fs_info->async_submit_draining) &&
1146 atomic_read(&fs_info->async_delalloc_pages)) {
1147 wait_event(fs_info->async_submit_wait,
1148 (atomic_read(&fs_info->async_delalloc_pages) ==
1152 *nr_written += nr_pages;
1153 start = cur_end + 1;
1159 static noinline int csum_exist_in_range(struct btrfs_fs_info *fs_info,
1160 u64 bytenr, u64 num_bytes)
1163 struct btrfs_ordered_sum *sums;
1166 ret = btrfs_lookup_csums_range(fs_info->csum_root, bytenr,
1167 bytenr + num_bytes - 1, &list, 0);
1168 if (ret == 0 && list_empty(&list))
1171 while (!list_empty(&list)) {
1172 sums = list_entry(list.next, struct btrfs_ordered_sum, list);
1173 list_del(&sums->list);
1180 * when nowcow writeback call back. This checks for snapshots or COW copies
1181 * of the extents that exist in the file, and COWs the file as required.
1183 * If no cow copies or snapshots exist, we write directly to the existing
1186 static noinline int run_delalloc_nocow(struct inode *inode,
1187 struct page *locked_page,
1188 u64 start, u64 end, int *page_started, int force,
1189 unsigned long *nr_written)
1191 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1192 struct btrfs_root *root = BTRFS_I(inode)->root;
1193 struct extent_buffer *leaf;
1194 struct btrfs_path *path;
1195 struct btrfs_file_extent_item *fi;
1196 struct btrfs_key found_key;
1197 struct extent_map *em;
1212 u64 ino = btrfs_ino(BTRFS_I(inode));
1214 path = btrfs_alloc_path();
1216 extent_clear_unlock_delalloc(inode, start, end, end,
1218 EXTENT_LOCKED | EXTENT_DELALLOC |
1219 EXTENT_DO_ACCOUNTING |
1220 EXTENT_DEFRAG, PAGE_UNLOCK |
1222 PAGE_SET_WRITEBACK |
1223 PAGE_END_WRITEBACK);
1227 nolock = btrfs_is_free_space_inode(BTRFS_I(inode));
1229 cow_start = (u64)-1;
1232 ret = btrfs_lookup_file_extent(NULL, root, path, ino,
1236 if (ret > 0 && path->slots[0] > 0 && check_prev) {
1237 leaf = path->nodes[0];
1238 btrfs_item_key_to_cpu(leaf, &found_key,
1239 path->slots[0] - 1);
1240 if (found_key.objectid == ino &&
1241 found_key.type == BTRFS_EXTENT_DATA_KEY)
1246 leaf = path->nodes[0];
1247 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
1248 ret = btrfs_next_leaf(root, path);
1253 leaf = path->nodes[0];
1259 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
1261 if (found_key.objectid > ino)
1263 if (WARN_ON_ONCE(found_key.objectid < ino) ||
1264 found_key.type < BTRFS_EXTENT_DATA_KEY) {
1268 if (found_key.type > BTRFS_EXTENT_DATA_KEY ||
1269 found_key.offset > end)
1272 if (found_key.offset > cur_offset) {
1273 extent_end = found_key.offset;
1278 fi = btrfs_item_ptr(leaf, path->slots[0],
1279 struct btrfs_file_extent_item);
1280 extent_type = btrfs_file_extent_type(leaf, fi);
1282 ram_bytes = btrfs_file_extent_ram_bytes(leaf, fi);
1283 if (extent_type == BTRFS_FILE_EXTENT_REG ||
1284 extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
1285 disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
1286 extent_offset = btrfs_file_extent_offset(leaf, fi);
1287 extent_end = found_key.offset +
1288 btrfs_file_extent_num_bytes(leaf, fi);
1290 btrfs_file_extent_disk_num_bytes(leaf, fi);
1291 if (extent_end <= start) {
1295 if (disk_bytenr == 0)
1297 if (btrfs_file_extent_compression(leaf, fi) ||
1298 btrfs_file_extent_encryption(leaf, fi) ||
1299 btrfs_file_extent_other_encoding(leaf, fi))
1301 if (extent_type == BTRFS_FILE_EXTENT_REG && !force)
1303 if (btrfs_extent_readonly(fs_info, disk_bytenr))
1305 if (btrfs_cross_ref_exist(root, ino,
1307 extent_offset, disk_bytenr))
1309 disk_bytenr += extent_offset;
1310 disk_bytenr += cur_offset - found_key.offset;
1311 num_bytes = min(end + 1, extent_end) - cur_offset;
1313 * if there are pending snapshots for this root,
1314 * we fall into common COW way.
1317 err = btrfs_start_write_no_snapshoting(root);
1322 * force cow if csum exists in the range.
1323 * this ensure that csum for a given extent are
1324 * either valid or do not exist.
1326 if (csum_exist_in_range(fs_info, disk_bytenr,
1329 if (!btrfs_inc_nocow_writers(fs_info, disk_bytenr))
1332 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
1333 extent_end = found_key.offset +
1334 btrfs_file_extent_inline_len(leaf,
1335 path->slots[0], fi);
1336 extent_end = ALIGN(extent_end,
1337 fs_info->sectorsize);
1342 if (extent_end <= start) {
1344 if (!nolock && nocow)
1345 btrfs_end_write_no_snapshoting(root);
1347 btrfs_dec_nocow_writers(fs_info, disk_bytenr);
1351 if (cow_start == (u64)-1)
1352 cow_start = cur_offset;
1353 cur_offset = extent_end;
1354 if (cur_offset > end)
1360 btrfs_release_path(path);
1361 if (cow_start != (u64)-1) {
1362 ret = cow_file_range(inode, locked_page,
1363 cow_start, found_key.offset - 1,
1364 end, page_started, nr_written, 1,
1367 if (!nolock && nocow)
1368 btrfs_end_write_no_snapshoting(root);
1370 btrfs_dec_nocow_writers(fs_info,
1374 cow_start = (u64)-1;
1377 if (extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
1378 u64 orig_start = found_key.offset - extent_offset;
1380 em = create_io_em(inode, cur_offset, num_bytes,
1382 disk_bytenr, /* block_start */
1383 num_bytes, /* block_len */
1384 disk_num_bytes, /* orig_block_len */
1385 ram_bytes, BTRFS_COMPRESS_NONE,
1386 BTRFS_ORDERED_PREALLOC);
1388 if (!nolock && nocow)
1389 btrfs_end_write_no_snapshoting(root);
1391 btrfs_dec_nocow_writers(fs_info,
1396 free_extent_map(em);
1399 if (extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
1400 type = BTRFS_ORDERED_PREALLOC;
1402 type = BTRFS_ORDERED_NOCOW;
1405 ret = btrfs_add_ordered_extent(inode, cur_offset, disk_bytenr,
1406 num_bytes, num_bytes, type);
1408 btrfs_dec_nocow_writers(fs_info, disk_bytenr);
1409 BUG_ON(ret); /* -ENOMEM */
1411 if (root->root_key.objectid ==
1412 BTRFS_DATA_RELOC_TREE_OBJECTID) {
1413 ret = btrfs_reloc_clone_csums(inode, cur_offset,
1416 if (!nolock && nocow)
1417 btrfs_end_write_no_snapshoting(root);
1422 extent_clear_unlock_delalloc(inode, cur_offset,
1423 cur_offset + num_bytes - 1, end,
1424 locked_page, EXTENT_LOCKED |
1426 EXTENT_CLEAR_DATA_RESV,
1427 PAGE_UNLOCK | PAGE_SET_PRIVATE2);
1429 if (!nolock && nocow)
1430 btrfs_end_write_no_snapshoting(root);
1431 cur_offset = extent_end;
1432 if (cur_offset > end)
1435 btrfs_release_path(path);
1437 if (cur_offset <= end && cow_start == (u64)-1) {
1438 cow_start = cur_offset;
1442 if (cow_start != (u64)-1) {
1443 ret = cow_file_range(inode, locked_page, cow_start, end, end,
1444 page_started, nr_written, 1, NULL);
1450 if (ret && cur_offset < end)
1451 extent_clear_unlock_delalloc(inode, cur_offset, end, end,
1452 locked_page, EXTENT_LOCKED |
1453 EXTENT_DELALLOC | EXTENT_DEFRAG |
1454 EXTENT_DO_ACCOUNTING, PAGE_UNLOCK |
1456 PAGE_SET_WRITEBACK |
1457 PAGE_END_WRITEBACK);
1458 btrfs_free_path(path);
1462 static inline int need_force_cow(struct inode *inode, u64 start, u64 end)
1465 if (!(BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW) &&
1466 !(BTRFS_I(inode)->flags & BTRFS_INODE_PREALLOC))
1470 * @defrag_bytes is a hint value, no spinlock held here,
1471 * if is not zero, it means the file is defragging.
1472 * Force cow if given extent needs to be defragged.
1474 if (BTRFS_I(inode)->defrag_bytes &&
1475 test_range_bit(&BTRFS_I(inode)->io_tree, start, end,
1476 EXTENT_DEFRAG, 0, NULL))
1483 * extent_io.c call back to do delayed allocation processing
1485 static int run_delalloc_range(struct inode *inode, struct page *locked_page,
1486 u64 start, u64 end, int *page_started,
1487 unsigned long *nr_written)
1490 int force_cow = need_force_cow(inode, start, end);
1492 if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW && !force_cow) {
1493 ret = run_delalloc_nocow(inode, locked_page, start, end,
1494 page_started, 1, nr_written);
1495 } else if (BTRFS_I(inode)->flags & BTRFS_INODE_PREALLOC && !force_cow) {
1496 ret = run_delalloc_nocow(inode, locked_page, start, end,
1497 page_started, 0, nr_written);
1498 } else if (!inode_need_compress(inode)) {
1499 ret = cow_file_range(inode, locked_page, start, end, end,
1500 page_started, nr_written, 1, NULL);
1502 set_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
1503 &BTRFS_I(inode)->runtime_flags);
1504 ret = cow_file_range_async(inode, locked_page, start, end,
1505 page_started, nr_written);
1510 static void btrfs_split_extent_hook(struct inode *inode,
1511 struct extent_state *orig, u64 split)
1515 /* not delalloc, ignore it */
1516 if (!(orig->state & EXTENT_DELALLOC))
1519 size = orig->end - orig->start + 1;
1520 if (size > BTRFS_MAX_EXTENT_SIZE) {
1525 * See the explanation in btrfs_merge_extent_hook, the same
1526 * applies here, just in reverse.
1528 new_size = orig->end - split + 1;
1529 num_extents = count_max_extents(new_size);
1530 new_size = split - orig->start;
1531 num_extents += count_max_extents(new_size);
1532 if (count_max_extents(size) >= num_extents)
1536 spin_lock(&BTRFS_I(inode)->lock);
1537 BTRFS_I(inode)->outstanding_extents++;
1538 spin_unlock(&BTRFS_I(inode)->lock);
1542 * extent_io.c merge_extent_hook, used to track merged delayed allocation
1543 * extents so we can keep track of new extents that are just merged onto old
1544 * extents, such as when we are doing sequential writes, so we can properly
1545 * account for the metadata space we'll need.
1547 static void btrfs_merge_extent_hook(struct inode *inode,
1548 struct extent_state *new,
1549 struct extent_state *other)
1551 u64 new_size, old_size;
1554 /* not delalloc, ignore it */
1555 if (!(other->state & EXTENT_DELALLOC))
1558 if (new->start > other->start)
1559 new_size = new->end - other->start + 1;
1561 new_size = other->end - new->start + 1;
1563 /* we're not bigger than the max, unreserve the space and go */
1564 if (new_size <= BTRFS_MAX_EXTENT_SIZE) {
1565 spin_lock(&BTRFS_I(inode)->lock);
1566 BTRFS_I(inode)->outstanding_extents--;
1567 spin_unlock(&BTRFS_I(inode)->lock);
1572 * We have to add up either side to figure out how many extents were
1573 * accounted for before we merged into one big extent. If the number of
1574 * extents we accounted for is <= the amount we need for the new range
1575 * then we can return, otherwise drop. Think of it like this
1579 * So we've grown the extent by a MAX_SIZE extent, this would mean we
1580 * need 2 outstanding extents, on one side we have 1 and the other side
1581 * we have 1 so they are == and we can return. But in this case
1583 * [MAX_SIZE+4k][MAX_SIZE+4k]
1585 * Each range on their own accounts for 2 extents, but merged together
1586 * they are only 3 extents worth of accounting, so we need to drop in
1589 old_size = other->end - other->start + 1;
1590 num_extents = count_max_extents(old_size);
1591 old_size = new->end - new->start + 1;
1592 num_extents += count_max_extents(old_size);
1593 if (count_max_extents(new_size) >= num_extents)
1596 spin_lock(&BTRFS_I(inode)->lock);
1597 BTRFS_I(inode)->outstanding_extents--;
1598 spin_unlock(&BTRFS_I(inode)->lock);
1601 static void btrfs_add_delalloc_inodes(struct btrfs_root *root,
1602 struct inode *inode)
1604 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1606 spin_lock(&root->delalloc_lock);
1607 if (list_empty(&BTRFS_I(inode)->delalloc_inodes)) {
1608 list_add_tail(&BTRFS_I(inode)->delalloc_inodes,
1609 &root->delalloc_inodes);
1610 set_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1611 &BTRFS_I(inode)->runtime_flags);
1612 root->nr_delalloc_inodes++;
1613 if (root->nr_delalloc_inodes == 1) {
1614 spin_lock(&fs_info->delalloc_root_lock);
1615 BUG_ON(!list_empty(&root->delalloc_root));
1616 list_add_tail(&root->delalloc_root,
1617 &fs_info->delalloc_roots);
1618 spin_unlock(&fs_info->delalloc_root_lock);
1621 spin_unlock(&root->delalloc_lock);
1624 static void btrfs_del_delalloc_inode(struct btrfs_root *root,
1625 struct btrfs_inode *inode)
1627 struct btrfs_fs_info *fs_info = btrfs_sb(inode->vfs_inode.i_sb);
1629 spin_lock(&root->delalloc_lock);
1630 if (!list_empty(&inode->delalloc_inodes)) {
1631 list_del_init(&inode->delalloc_inodes);
1632 clear_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1633 &inode->runtime_flags);
1634 root->nr_delalloc_inodes--;
1635 if (!root->nr_delalloc_inodes) {
1636 spin_lock(&fs_info->delalloc_root_lock);
1637 BUG_ON(list_empty(&root->delalloc_root));
1638 list_del_init(&root->delalloc_root);
1639 spin_unlock(&fs_info->delalloc_root_lock);
1642 spin_unlock(&root->delalloc_lock);
1646 * extent_io.c set_bit_hook, used to track delayed allocation
1647 * bytes in this file, and to maintain the list of inodes that
1648 * have pending delalloc work to be done.
1650 static void btrfs_set_bit_hook(struct inode *inode,
1651 struct extent_state *state, unsigned *bits)
1654 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1656 if ((*bits & EXTENT_DEFRAG) && !(*bits & EXTENT_DELALLOC))
1659 * set_bit and clear bit hooks normally require _irqsave/restore
1660 * but in this case, we are only testing for the DELALLOC
1661 * bit, which is only set or cleared with irqs on
1663 if (!(state->state & EXTENT_DELALLOC) && (*bits & EXTENT_DELALLOC)) {
1664 struct btrfs_root *root = BTRFS_I(inode)->root;
1665 u64 len = state->end + 1 - state->start;
1666 bool do_list = !btrfs_is_free_space_inode(BTRFS_I(inode));
1668 if (*bits & EXTENT_FIRST_DELALLOC) {
1669 *bits &= ~EXTENT_FIRST_DELALLOC;
1671 spin_lock(&BTRFS_I(inode)->lock);
1672 BTRFS_I(inode)->outstanding_extents++;
1673 spin_unlock(&BTRFS_I(inode)->lock);
1676 /* For sanity tests */
1677 if (btrfs_is_testing(fs_info))
1680 __percpu_counter_add(&fs_info->delalloc_bytes, len,
1681 fs_info->delalloc_batch);
1682 spin_lock(&BTRFS_I(inode)->lock);
1683 BTRFS_I(inode)->delalloc_bytes += len;
1684 if (*bits & EXTENT_DEFRAG)
1685 BTRFS_I(inode)->defrag_bytes += len;
1686 if (do_list && !test_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1687 &BTRFS_I(inode)->runtime_flags))
1688 btrfs_add_delalloc_inodes(root, inode);
1689 spin_unlock(&BTRFS_I(inode)->lock);
1694 * extent_io.c clear_bit_hook, see set_bit_hook for why
1696 static void btrfs_clear_bit_hook(struct btrfs_inode *inode,
1697 struct extent_state *state,
1700 struct btrfs_fs_info *fs_info = btrfs_sb(inode->vfs_inode.i_sb);
1701 u64 len = state->end + 1 - state->start;
1702 u32 num_extents = count_max_extents(len);
1704 spin_lock(&inode->lock);
1705 if ((state->state & EXTENT_DEFRAG) && (*bits & EXTENT_DEFRAG))
1706 inode->defrag_bytes -= len;
1707 spin_unlock(&inode->lock);
1710 * set_bit and clear bit hooks normally require _irqsave/restore
1711 * but in this case, we are only testing for the DELALLOC
1712 * bit, which is only set or cleared with irqs on
1714 if ((state->state & EXTENT_DELALLOC) && (*bits & EXTENT_DELALLOC)) {
1715 struct btrfs_root *root = inode->root;
1716 bool do_list = !btrfs_is_free_space_inode(inode);
1718 if (*bits & EXTENT_FIRST_DELALLOC) {
1719 *bits &= ~EXTENT_FIRST_DELALLOC;
1720 } else if (!(*bits & EXTENT_DO_ACCOUNTING)) {
1721 spin_lock(&inode->lock);
1722 inode->outstanding_extents -= num_extents;
1723 spin_unlock(&inode->lock);
1727 * We don't reserve metadata space for space cache inodes so we
1728 * don't need to call dellalloc_release_metadata if there is an
1731 if (*bits & EXTENT_DO_ACCOUNTING &&
1732 root != fs_info->tree_root)
1733 btrfs_delalloc_release_metadata(inode, len);
1735 /* For sanity tests. */
1736 if (btrfs_is_testing(fs_info))
1739 if (root->root_key.objectid != BTRFS_DATA_RELOC_TREE_OBJECTID
1740 && do_list && !(state->state & EXTENT_NORESERVE)
1741 && (*bits & (EXTENT_DO_ACCOUNTING |
1742 EXTENT_CLEAR_DATA_RESV)))
1743 btrfs_free_reserved_data_space_noquota(
1747 __percpu_counter_add(&fs_info->delalloc_bytes, -len,
1748 fs_info->delalloc_batch);
1749 spin_lock(&inode->lock);
1750 inode->delalloc_bytes -= len;
1751 if (do_list && inode->delalloc_bytes == 0 &&
1752 test_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1753 &inode->runtime_flags))
1754 btrfs_del_delalloc_inode(root, inode);
1755 spin_unlock(&inode->lock);
1760 * extent_io.c merge_bio_hook, this must check the chunk tree to make sure
1761 * we don't create bios that span stripes or chunks
1763 * return 1 if page cannot be merged to bio
1764 * return 0 if page can be merged to bio
1765 * return error otherwise
1767 int btrfs_merge_bio_hook(struct page *page, unsigned long offset,
1768 size_t size, struct bio *bio,
1769 unsigned long bio_flags)
1771 struct inode *inode = page->mapping->host;
1772 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1773 u64 logical = (u64)bio->bi_iter.bi_sector << 9;
1778 if (bio_flags & EXTENT_BIO_COMPRESSED)
1781 length = bio->bi_iter.bi_size;
1782 map_length = length;
1783 ret = btrfs_map_block(fs_info, btrfs_op(bio), logical, &map_length,
1787 if (map_length < length + size)
1793 * in order to insert checksums into the metadata in large chunks,
1794 * we wait until bio submission time. All the pages in the bio are
1795 * checksummed and sums are attached onto the ordered extent record.
1797 * At IO completion time the cums attached on the ordered extent record
1798 * are inserted into the btree
1800 static int __btrfs_submit_bio_start(struct inode *inode, struct bio *bio,
1801 int mirror_num, unsigned long bio_flags,
1806 ret = btrfs_csum_one_bio(inode, bio, 0, 0);
1807 BUG_ON(ret); /* -ENOMEM */
1812 * in order to insert checksums into the metadata in large chunks,
1813 * we wait until bio submission time. All the pages in the bio are
1814 * checksummed and sums are attached onto the ordered extent record.
1816 * At IO completion time the cums attached on the ordered extent record
1817 * are inserted into the btree
1819 static int __btrfs_submit_bio_done(struct inode *inode, struct bio *bio,
1820 int mirror_num, unsigned long bio_flags,
1823 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1826 ret = btrfs_map_bio(fs_info, bio, mirror_num, 1);
1828 bio->bi_error = ret;
1835 * extent_io.c submission hook. This does the right thing for csum calculation
1836 * on write, or reading the csums from the tree before a read
1838 static int btrfs_submit_bio_hook(struct inode *inode, struct bio *bio,
1839 int mirror_num, unsigned long bio_flags,
1842 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1843 struct btrfs_root *root = BTRFS_I(inode)->root;
1844 enum btrfs_wq_endio_type metadata = BTRFS_WQ_ENDIO_DATA;
1847 int async = !atomic_read(&BTRFS_I(inode)->sync_writers);
1849 skip_sum = BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM;
1851 if (btrfs_is_free_space_inode(BTRFS_I(inode)))
1852 metadata = BTRFS_WQ_ENDIO_FREE_SPACE;
1854 if (bio_op(bio) != REQ_OP_WRITE) {
1855 ret = btrfs_bio_wq_end_io(fs_info, bio, metadata);
1859 if (bio_flags & EXTENT_BIO_COMPRESSED) {
1860 ret = btrfs_submit_compressed_read(inode, bio,
1864 } else if (!skip_sum) {
1865 ret = btrfs_lookup_bio_sums(inode, bio, NULL);
1870 } else if (async && !skip_sum) {
1871 /* csum items have already been cloned */
1872 if (root->root_key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID)
1874 /* we're doing a write, do the async checksumming */
1875 ret = btrfs_wq_submit_bio(fs_info, inode, bio, mirror_num,
1876 bio_flags, bio_offset,
1877 __btrfs_submit_bio_start,
1878 __btrfs_submit_bio_done);
1880 } else if (!skip_sum) {
1881 ret = btrfs_csum_one_bio(inode, bio, 0, 0);
1887 ret = btrfs_map_bio(fs_info, bio, mirror_num, 0);
1891 bio->bi_error = ret;
1898 * given a list of ordered sums record them in the inode. This happens
1899 * at IO completion time based on sums calculated at bio submission time.
1901 static noinline int add_pending_csums(struct btrfs_trans_handle *trans,
1902 struct inode *inode, struct list_head *list)
1904 struct btrfs_ordered_sum *sum;
1906 list_for_each_entry(sum, list, list) {
1907 trans->adding_csums = 1;
1908 btrfs_csum_file_blocks(trans,
1909 BTRFS_I(inode)->root->fs_info->csum_root, sum);
1910 trans->adding_csums = 0;
1915 int btrfs_set_extent_delalloc(struct inode *inode, u64 start, u64 end,
1916 struct extent_state **cached_state, int dedupe)
1918 WARN_ON((end & (PAGE_SIZE - 1)) == 0);
1919 return set_extent_delalloc(&BTRFS_I(inode)->io_tree, start, end,
1923 /* see btrfs_writepage_start_hook for details on why this is required */
1924 struct btrfs_writepage_fixup {
1926 struct btrfs_work work;
1929 static void btrfs_writepage_fixup_worker(struct btrfs_work *work)
1931 struct btrfs_writepage_fixup *fixup;
1932 struct btrfs_ordered_extent *ordered;
1933 struct extent_state *cached_state = NULL;
1935 struct inode *inode;
1940 fixup = container_of(work, struct btrfs_writepage_fixup, work);
1944 if (!page->mapping || !PageDirty(page) || !PageChecked(page)) {
1945 ClearPageChecked(page);
1949 inode = page->mapping->host;
1950 page_start = page_offset(page);
1951 page_end = page_offset(page) + PAGE_SIZE - 1;
1953 lock_extent_bits(&BTRFS_I(inode)->io_tree, page_start, page_end,
1956 /* already ordered? We're done */
1957 if (PagePrivate2(page))
1960 ordered = btrfs_lookup_ordered_range(BTRFS_I(inode), page_start,
1963 unlock_extent_cached(&BTRFS_I(inode)->io_tree, page_start,
1964 page_end, &cached_state, GFP_NOFS);
1966 btrfs_start_ordered_extent(inode, ordered, 1);
1967 btrfs_put_ordered_extent(ordered);
1971 ret = btrfs_delalloc_reserve_space(inode, page_start,
1974 mapping_set_error(page->mapping, ret);
1975 end_extent_writepage(page, ret, page_start, page_end);
1976 ClearPageChecked(page);
1980 btrfs_set_extent_delalloc(inode, page_start, page_end, &cached_state,
1982 ClearPageChecked(page);
1983 set_page_dirty(page);
1985 unlock_extent_cached(&BTRFS_I(inode)->io_tree, page_start, page_end,
1986 &cached_state, GFP_NOFS);
1994 * There are a few paths in the higher layers of the kernel that directly
1995 * set the page dirty bit without asking the filesystem if it is a
1996 * good idea. This causes problems because we want to make sure COW
1997 * properly happens and the data=ordered rules are followed.
1999 * In our case any range that doesn't have the ORDERED bit set
2000 * hasn't been properly setup for IO. We kick off an async process
2001 * to fix it up. The async helper will wait for ordered extents, set
2002 * the delalloc bit and make it safe to write the page.
2004 static int btrfs_writepage_start_hook(struct page *page, u64 start, u64 end)
2006 struct inode *inode = page->mapping->host;
2007 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2008 struct btrfs_writepage_fixup *fixup;
2010 /* this page is properly in the ordered list */
2011 if (TestClearPagePrivate2(page))
2014 if (PageChecked(page))
2017 fixup = kzalloc(sizeof(*fixup), GFP_NOFS);
2021 SetPageChecked(page);
2023 btrfs_init_work(&fixup->work, btrfs_fixup_helper,
2024 btrfs_writepage_fixup_worker, NULL, NULL);
2026 btrfs_queue_work(fs_info->fixup_workers, &fixup->work);
2030 static int insert_reserved_file_extent(struct btrfs_trans_handle *trans,
2031 struct inode *inode, u64 file_pos,
2032 u64 disk_bytenr, u64 disk_num_bytes,
2033 u64 num_bytes, u64 ram_bytes,
2034 u8 compression, u8 encryption,
2035 u16 other_encoding, int extent_type)
2037 struct btrfs_root *root = BTRFS_I(inode)->root;
2038 struct btrfs_file_extent_item *fi;
2039 struct btrfs_path *path;
2040 struct extent_buffer *leaf;
2041 struct btrfs_key ins;
2042 int extent_inserted = 0;
2045 path = btrfs_alloc_path();
2050 * we may be replacing one extent in the tree with another.
2051 * The new extent is pinned in the extent map, and we don't want
2052 * to drop it from the cache until it is completely in the btree.
2054 * So, tell btrfs_drop_extents to leave this extent in the cache.
2055 * the caller is expected to unpin it and allow it to be merged
2058 ret = __btrfs_drop_extents(trans, root, inode, path, file_pos,
2059 file_pos + num_bytes, NULL, 0,
2060 1, sizeof(*fi), &extent_inserted);
2064 if (!extent_inserted) {
2065 ins.objectid = btrfs_ino(BTRFS_I(inode));
2066 ins.offset = file_pos;
2067 ins.type = BTRFS_EXTENT_DATA_KEY;
2069 path->leave_spinning = 1;
2070 ret = btrfs_insert_empty_item(trans, root, path, &ins,
2075 leaf = path->nodes[0];
2076 fi = btrfs_item_ptr(leaf, path->slots[0],
2077 struct btrfs_file_extent_item);
2078 btrfs_set_file_extent_generation(leaf, fi, trans->transid);
2079 btrfs_set_file_extent_type(leaf, fi, extent_type);
2080 btrfs_set_file_extent_disk_bytenr(leaf, fi, disk_bytenr);
2081 btrfs_set_file_extent_disk_num_bytes(leaf, fi, disk_num_bytes);
2082 btrfs_set_file_extent_offset(leaf, fi, 0);
2083 btrfs_set_file_extent_num_bytes(leaf, fi, num_bytes);
2084 btrfs_set_file_extent_ram_bytes(leaf, fi, ram_bytes);
2085 btrfs_set_file_extent_compression(leaf, fi, compression);
2086 btrfs_set_file_extent_encryption(leaf, fi, encryption);
2087 btrfs_set_file_extent_other_encoding(leaf, fi, other_encoding);
2089 btrfs_mark_buffer_dirty(leaf);
2090 btrfs_release_path(path);
2092 inode_add_bytes(inode, num_bytes);
2094 ins.objectid = disk_bytenr;
2095 ins.offset = disk_num_bytes;
2096 ins.type = BTRFS_EXTENT_ITEM_KEY;
2097 ret = btrfs_alloc_reserved_file_extent(trans, root->root_key.objectid,
2098 btrfs_ino(BTRFS_I(inode)), file_pos, ram_bytes, &ins);
2100 * Release the reserved range from inode dirty range map, as it is
2101 * already moved into delayed_ref_head
2103 btrfs_qgroup_release_data(inode, file_pos, ram_bytes);
2105 btrfs_free_path(path);
2110 /* snapshot-aware defrag */
2111 struct sa_defrag_extent_backref {
2112 struct rb_node node;
2113 struct old_sa_defrag_extent *old;
2122 struct old_sa_defrag_extent {
2123 struct list_head list;
2124 struct new_sa_defrag_extent *new;
2133 struct new_sa_defrag_extent {
2134 struct rb_root root;
2135 struct list_head head;
2136 struct btrfs_path *path;
2137 struct inode *inode;
2145 static int backref_comp(struct sa_defrag_extent_backref *b1,
2146 struct sa_defrag_extent_backref *b2)
2148 if (b1->root_id < b2->root_id)
2150 else if (b1->root_id > b2->root_id)
2153 if (b1->inum < b2->inum)
2155 else if (b1->inum > b2->inum)
2158 if (b1->file_pos < b2->file_pos)
2160 else if (b1->file_pos > b2->file_pos)
2164 * [------------------------------] ===> (a range of space)
2165 * |<--->| |<---->| =============> (fs/file tree A)
2166 * |<---------------------------->| ===> (fs/file tree B)
2168 * A range of space can refer to two file extents in one tree while
2169 * refer to only one file extent in another tree.
2171 * So we may process a disk offset more than one time(two extents in A)
2172 * and locate at the same extent(one extent in B), then insert two same
2173 * backrefs(both refer to the extent in B).
2178 static void backref_insert(struct rb_root *root,
2179 struct sa_defrag_extent_backref *backref)
2181 struct rb_node **p = &root->rb_node;
2182 struct rb_node *parent = NULL;
2183 struct sa_defrag_extent_backref *entry;
2188 entry = rb_entry(parent, struct sa_defrag_extent_backref, node);
2190 ret = backref_comp(backref, entry);
2194 p = &(*p)->rb_right;
2197 rb_link_node(&backref->node, parent, p);
2198 rb_insert_color(&backref->node, root);
2202 * Note the backref might has changed, and in this case we just return 0.
2204 static noinline int record_one_backref(u64 inum, u64 offset, u64 root_id,
2207 struct btrfs_file_extent_item *extent;
2208 struct old_sa_defrag_extent *old = ctx;
2209 struct new_sa_defrag_extent *new = old->new;
2210 struct btrfs_path *path = new->path;
2211 struct btrfs_key key;
2212 struct btrfs_root *root;
2213 struct sa_defrag_extent_backref *backref;
2214 struct extent_buffer *leaf;
2215 struct inode *inode = new->inode;
2216 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2222 if (BTRFS_I(inode)->root->root_key.objectid == root_id &&
2223 inum == btrfs_ino(BTRFS_I(inode)))
2226 key.objectid = root_id;
2227 key.type = BTRFS_ROOT_ITEM_KEY;
2228 key.offset = (u64)-1;
2230 root = btrfs_read_fs_root_no_name(fs_info, &key);
2232 if (PTR_ERR(root) == -ENOENT)
2235 btrfs_debug(fs_info, "inum=%llu, offset=%llu, root_id=%llu",
2236 inum, offset, root_id);
2237 return PTR_ERR(root);
2240 key.objectid = inum;
2241 key.type = BTRFS_EXTENT_DATA_KEY;
2242 if (offset > (u64)-1 << 32)
2245 key.offset = offset;
2247 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2248 if (WARN_ON(ret < 0))
2255 leaf = path->nodes[0];
2256 slot = path->slots[0];
2258 if (slot >= btrfs_header_nritems(leaf)) {
2259 ret = btrfs_next_leaf(root, path);
2262 } else if (ret > 0) {
2271 btrfs_item_key_to_cpu(leaf, &key, slot);
2273 if (key.objectid > inum)
2276 if (key.objectid < inum || key.type != BTRFS_EXTENT_DATA_KEY)
2279 extent = btrfs_item_ptr(leaf, slot,
2280 struct btrfs_file_extent_item);
2282 if (btrfs_file_extent_disk_bytenr(leaf, extent) != old->bytenr)
2286 * 'offset' refers to the exact key.offset,
2287 * NOT the 'offset' field in btrfs_extent_data_ref, ie.
2288 * (key.offset - extent_offset).
2290 if (key.offset != offset)
2293 extent_offset = btrfs_file_extent_offset(leaf, extent);
2294 num_bytes = btrfs_file_extent_num_bytes(leaf, extent);
2296 if (extent_offset >= old->extent_offset + old->offset +
2297 old->len || extent_offset + num_bytes <=
2298 old->extent_offset + old->offset)
2303 backref = kmalloc(sizeof(*backref), GFP_NOFS);
2309 backref->root_id = root_id;
2310 backref->inum = inum;
2311 backref->file_pos = offset;
2312 backref->num_bytes = num_bytes;
2313 backref->extent_offset = extent_offset;
2314 backref->generation = btrfs_file_extent_generation(leaf, extent);
2316 backref_insert(&new->root, backref);
2319 btrfs_release_path(path);
2324 static noinline bool record_extent_backrefs(struct btrfs_path *path,
2325 struct new_sa_defrag_extent *new)
2327 struct btrfs_fs_info *fs_info = btrfs_sb(new->inode->i_sb);
2328 struct old_sa_defrag_extent *old, *tmp;
2333 list_for_each_entry_safe(old, tmp, &new->head, list) {
2334 ret = iterate_inodes_from_logical(old->bytenr +
2335 old->extent_offset, fs_info,
2336 path, record_one_backref,
2338 if (ret < 0 && ret != -ENOENT)
2341 /* no backref to be processed for this extent */
2343 list_del(&old->list);
2348 if (list_empty(&new->head))
2354 static int relink_is_mergable(struct extent_buffer *leaf,
2355 struct btrfs_file_extent_item *fi,
2356 struct new_sa_defrag_extent *new)
2358 if (btrfs_file_extent_disk_bytenr(leaf, fi) != new->bytenr)
2361 if (btrfs_file_extent_type(leaf, fi) != BTRFS_FILE_EXTENT_REG)
2364 if (btrfs_file_extent_compression(leaf, fi) != new->compress_type)
2367 if (btrfs_file_extent_encryption(leaf, fi) ||
2368 btrfs_file_extent_other_encoding(leaf, fi))
2375 * Note the backref might has changed, and in this case we just return 0.
2377 static noinline int relink_extent_backref(struct btrfs_path *path,
2378 struct sa_defrag_extent_backref *prev,
2379 struct sa_defrag_extent_backref *backref)
2381 struct btrfs_file_extent_item *extent;
2382 struct btrfs_file_extent_item *item;
2383 struct btrfs_ordered_extent *ordered;
2384 struct btrfs_trans_handle *trans;
2385 struct btrfs_root *root;
2386 struct btrfs_key key;
2387 struct extent_buffer *leaf;
2388 struct old_sa_defrag_extent *old = backref->old;
2389 struct new_sa_defrag_extent *new = old->new;
2390 struct btrfs_fs_info *fs_info = btrfs_sb(new->inode->i_sb);
2391 struct inode *inode;
2392 struct extent_state *cached = NULL;
2401 if (prev && prev->root_id == backref->root_id &&
2402 prev->inum == backref->inum &&
2403 prev->file_pos + prev->num_bytes == backref->file_pos)
2406 /* step 1: get root */
2407 key.objectid = backref->root_id;
2408 key.type = BTRFS_ROOT_ITEM_KEY;
2409 key.offset = (u64)-1;
2411 index = srcu_read_lock(&fs_info->subvol_srcu);
2413 root = btrfs_read_fs_root_no_name(fs_info, &key);
2415 srcu_read_unlock(&fs_info->subvol_srcu, index);
2416 if (PTR_ERR(root) == -ENOENT)
2418 return PTR_ERR(root);
2421 if (btrfs_root_readonly(root)) {
2422 srcu_read_unlock(&fs_info->subvol_srcu, index);
2426 /* step 2: get inode */
2427 key.objectid = backref->inum;
2428 key.type = BTRFS_INODE_ITEM_KEY;
2431 inode = btrfs_iget(fs_info->sb, &key, root, NULL);
2432 if (IS_ERR(inode)) {
2433 srcu_read_unlock(&fs_info->subvol_srcu, index);
2437 srcu_read_unlock(&fs_info->subvol_srcu, index);
2439 /* step 3: relink backref */
2440 lock_start = backref->file_pos;
2441 lock_end = backref->file_pos + backref->num_bytes - 1;
2442 lock_extent_bits(&BTRFS_I(inode)->io_tree, lock_start, lock_end,
2445 ordered = btrfs_lookup_first_ordered_extent(inode, lock_end);
2447 btrfs_put_ordered_extent(ordered);
2451 trans = btrfs_join_transaction(root);
2452 if (IS_ERR(trans)) {
2453 ret = PTR_ERR(trans);
2457 key.objectid = backref->inum;
2458 key.type = BTRFS_EXTENT_DATA_KEY;
2459 key.offset = backref->file_pos;
2461 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2464 } else if (ret > 0) {
2469 extent = btrfs_item_ptr(path->nodes[0], path->slots[0],
2470 struct btrfs_file_extent_item);
2472 if (btrfs_file_extent_generation(path->nodes[0], extent) !=
2473 backref->generation)
2476 btrfs_release_path(path);
2478 start = backref->file_pos;
2479 if (backref->extent_offset < old->extent_offset + old->offset)
2480 start += old->extent_offset + old->offset -
2481 backref->extent_offset;
2483 len = min(backref->extent_offset + backref->num_bytes,
2484 old->extent_offset + old->offset + old->len);
2485 len -= max(backref->extent_offset, old->extent_offset + old->offset);
2487 ret = btrfs_drop_extents(trans, root, inode, start,
2492 key.objectid = btrfs_ino(BTRFS_I(inode));
2493 key.type = BTRFS_EXTENT_DATA_KEY;
2496 path->leave_spinning = 1;
2498 struct btrfs_file_extent_item *fi;
2500 struct btrfs_key found_key;
2502 ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
2507 leaf = path->nodes[0];
2508 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
2510 fi = btrfs_item_ptr(leaf, path->slots[0],
2511 struct btrfs_file_extent_item);
2512 extent_len = btrfs_file_extent_num_bytes(leaf, fi);
2514 if (extent_len + found_key.offset == start &&
2515 relink_is_mergable(leaf, fi, new)) {
2516 btrfs_set_file_extent_num_bytes(leaf, fi,
2518 btrfs_mark_buffer_dirty(leaf);
2519 inode_add_bytes(inode, len);
2525 btrfs_release_path(path);
2530 ret = btrfs_insert_empty_item(trans, root, path, &key,
2533 btrfs_abort_transaction(trans, ret);
2537 leaf = path->nodes[0];
2538 item = btrfs_item_ptr(leaf, path->slots[0],
2539 struct btrfs_file_extent_item);
2540 btrfs_set_file_extent_disk_bytenr(leaf, item, new->bytenr);
2541 btrfs_set_file_extent_disk_num_bytes(leaf, item, new->disk_len);
2542 btrfs_set_file_extent_offset(leaf, item, start - new->file_pos);
2543 btrfs_set_file_extent_num_bytes(leaf, item, len);
2544 btrfs_set_file_extent_ram_bytes(leaf, item, new->len);
2545 btrfs_set_file_extent_generation(leaf, item, trans->transid);
2546 btrfs_set_file_extent_type(leaf, item, BTRFS_FILE_EXTENT_REG);
2547 btrfs_set_file_extent_compression(leaf, item, new->compress_type);
2548 btrfs_set_file_extent_encryption(leaf, item, 0);
2549 btrfs_set_file_extent_other_encoding(leaf, item, 0);
2551 btrfs_mark_buffer_dirty(leaf);
2552 inode_add_bytes(inode, len);
2553 btrfs_release_path(path);
2555 ret = btrfs_inc_extent_ref(trans, fs_info, new->bytenr,
2557 backref->root_id, backref->inum,
2558 new->file_pos); /* start - extent_offset */
2560 btrfs_abort_transaction(trans, ret);
2566 btrfs_release_path(path);
2567 path->leave_spinning = 0;
2568 btrfs_end_transaction(trans);
2570 unlock_extent_cached(&BTRFS_I(inode)->io_tree, lock_start, lock_end,
2576 static void free_sa_defrag_extent(struct new_sa_defrag_extent *new)
2578 struct old_sa_defrag_extent *old, *tmp;
2583 list_for_each_entry_safe(old, tmp, &new->head, list) {
2589 static void relink_file_extents(struct new_sa_defrag_extent *new)
2591 struct btrfs_fs_info *fs_info = btrfs_sb(new->inode->i_sb);
2592 struct btrfs_path *path;
2593 struct sa_defrag_extent_backref *backref;
2594 struct sa_defrag_extent_backref *prev = NULL;
2595 struct inode *inode;
2596 struct btrfs_root *root;
2597 struct rb_node *node;
2601 root = BTRFS_I(inode)->root;
2603 path = btrfs_alloc_path();
2607 if (!record_extent_backrefs(path, new)) {
2608 btrfs_free_path(path);
2611 btrfs_release_path(path);
2614 node = rb_first(&new->root);
2617 rb_erase(node, &new->root);
2619 backref = rb_entry(node, struct sa_defrag_extent_backref, node);
2621 ret = relink_extent_backref(path, prev, backref);
2634 btrfs_free_path(path);
2636 free_sa_defrag_extent(new);
2638 atomic_dec(&fs_info->defrag_running);
2639 wake_up(&fs_info->transaction_wait);
2642 static struct new_sa_defrag_extent *
2643 record_old_file_extents(struct inode *inode,
2644 struct btrfs_ordered_extent *ordered)
2646 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2647 struct btrfs_root *root = BTRFS_I(inode)->root;
2648 struct btrfs_path *path;
2649 struct btrfs_key key;
2650 struct old_sa_defrag_extent *old;
2651 struct new_sa_defrag_extent *new;
2654 new = kmalloc(sizeof(*new), GFP_NOFS);
2659 new->file_pos = ordered->file_offset;
2660 new->len = ordered->len;
2661 new->bytenr = ordered->start;
2662 new->disk_len = ordered->disk_len;
2663 new->compress_type = ordered->compress_type;
2664 new->root = RB_ROOT;
2665 INIT_LIST_HEAD(&new->head);
2667 path = btrfs_alloc_path();
2671 key.objectid = btrfs_ino(BTRFS_I(inode));
2672 key.type = BTRFS_EXTENT_DATA_KEY;
2673 key.offset = new->file_pos;
2675 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2678 if (ret > 0 && path->slots[0] > 0)
2681 /* find out all the old extents for the file range */
2683 struct btrfs_file_extent_item *extent;
2684 struct extent_buffer *l;
2693 slot = path->slots[0];
2695 if (slot >= btrfs_header_nritems(l)) {
2696 ret = btrfs_next_leaf(root, path);
2704 btrfs_item_key_to_cpu(l, &key, slot);
2706 if (key.objectid != btrfs_ino(BTRFS_I(inode)))
2708 if (key.type != BTRFS_EXTENT_DATA_KEY)
2710 if (key.offset >= new->file_pos + new->len)
2713 extent = btrfs_item_ptr(l, slot, struct btrfs_file_extent_item);
2715 num_bytes = btrfs_file_extent_num_bytes(l, extent);
2716 if (key.offset + num_bytes < new->file_pos)
2719 disk_bytenr = btrfs_file_extent_disk_bytenr(l, extent);
2723 extent_offset = btrfs_file_extent_offset(l, extent);
2725 old = kmalloc(sizeof(*old), GFP_NOFS);
2729 offset = max(new->file_pos, key.offset);
2730 end = min(new->file_pos + new->len, key.offset + num_bytes);
2732 old->bytenr = disk_bytenr;
2733 old->extent_offset = extent_offset;
2734 old->offset = offset - key.offset;
2735 old->len = end - offset;
2738 list_add_tail(&old->list, &new->head);
2744 btrfs_free_path(path);
2745 atomic_inc(&fs_info->defrag_running);
2750 btrfs_free_path(path);
2752 free_sa_defrag_extent(new);
2756 static void btrfs_release_delalloc_bytes(struct btrfs_fs_info *fs_info,
2759 struct btrfs_block_group_cache *cache;
2761 cache = btrfs_lookup_block_group(fs_info, start);
2764 spin_lock(&cache->lock);
2765 cache->delalloc_bytes -= len;
2766 spin_unlock(&cache->lock);
2768 btrfs_put_block_group(cache);
2771 /* as ordered data IO finishes, this gets called so we can finish
2772 * an ordered extent if the range of bytes in the file it covers are
2775 static int btrfs_finish_ordered_io(struct btrfs_ordered_extent *ordered_extent)
2777 struct inode *inode = ordered_extent->inode;
2778 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2779 struct btrfs_root *root = BTRFS_I(inode)->root;
2780 struct btrfs_trans_handle *trans = NULL;
2781 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
2782 struct extent_state *cached_state = NULL;
2783 struct new_sa_defrag_extent *new = NULL;
2784 int compress_type = 0;
2786 u64 logical_len = ordered_extent->len;
2788 bool truncated = false;
2790 nolock = btrfs_is_free_space_inode(BTRFS_I(inode));
2792 if (test_bit(BTRFS_ORDERED_IOERR, &ordered_extent->flags)) {
2797 btrfs_free_io_failure_record(BTRFS_I(inode),
2798 ordered_extent->file_offset,
2799 ordered_extent->file_offset +
2800 ordered_extent->len - 1);
2802 if (test_bit(BTRFS_ORDERED_TRUNCATED, &ordered_extent->flags)) {
2804 logical_len = ordered_extent->truncated_len;
2805 /* Truncated the entire extent, don't bother adding */
2810 if (test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags)) {
2811 BUG_ON(!list_empty(&ordered_extent->list)); /* Logic error */
2814 * For mwrite(mmap + memset to write) case, we still reserve
2815 * space for NOCOW range.
2816 * As NOCOW won't cause a new delayed ref, just free the space
2818 btrfs_qgroup_free_data(inode, ordered_extent->file_offset,
2819 ordered_extent->len);
2820 btrfs_ordered_update_i_size(inode, 0, ordered_extent);
2822 trans = btrfs_join_transaction_nolock(root);
2824 trans = btrfs_join_transaction(root);
2825 if (IS_ERR(trans)) {
2826 ret = PTR_ERR(trans);
2830 trans->block_rsv = &fs_info->delalloc_block_rsv;
2831 ret = btrfs_update_inode_fallback(trans, root, inode);
2832 if (ret) /* -ENOMEM or corruption */
2833 btrfs_abort_transaction(trans, ret);
2837 lock_extent_bits(io_tree, ordered_extent->file_offset,
2838 ordered_extent->file_offset + ordered_extent->len - 1,
2841 ret = test_range_bit(io_tree, ordered_extent->file_offset,
2842 ordered_extent->file_offset + ordered_extent->len - 1,
2843 EXTENT_DEFRAG, 1, cached_state);
2845 u64 last_snapshot = btrfs_root_last_snapshot(&root->root_item);
2846 if (0 && last_snapshot >= BTRFS_I(inode)->generation)
2847 /* the inode is shared */
2848 new = record_old_file_extents(inode, ordered_extent);
2850 clear_extent_bit(io_tree, ordered_extent->file_offset,
2851 ordered_extent->file_offset + ordered_extent->len - 1,
2852 EXTENT_DEFRAG, 0, 0, &cached_state, GFP_NOFS);
2856 trans = btrfs_join_transaction_nolock(root);
2858 trans = btrfs_join_transaction(root);
2859 if (IS_ERR(trans)) {
2860 ret = PTR_ERR(trans);
2865 trans->block_rsv = &fs_info->delalloc_block_rsv;
2867 if (test_bit(BTRFS_ORDERED_COMPRESSED, &ordered_extent->flags))
2868 compress_type = ordered_extent->compress_type;
2869 if (test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags)) {
2870 BUG_ON(compress_type);
2871 ret = btrfs_mark_extent_written(trans, BTRFS_I(inode),
2872 ordered_extent->file_offset,
2873 ordered_extent->file_offset +
2876 BUG_ON(root == fs_info->tree_root);
2877 ret = insert_reserved_file_extent(trans, inode,
2878 ordered_extent->file_offset,
2879 ordered_extent->start,
2880 ordered_extent->disk_len,
2881 logical_len, logical_len,
2882 compress_type, 0, 0,
2883 BTRFS_FILE_EXTENT_REG);
2885 btrfs_release_delalloc_bytes(fs_info,
2886 ordered_extent->start,
2887 ordered_extent->disk_len);
2889 unpin_extent_cache(&BTRFS_I(inode)->extent_tree,
2890 ordered_extent->file_offset, ordered_extent->len,
2893 btrfs_abort_transaction(trans, ret);
2897 add_pending_csums(trans, inode, &ordered_extent->list);
2899 btrfs_ordered_update_i_size(inode, 0, ordered_extent);
2900 ret = btrfs_update_inode_fallback(trans, root, inode);
2901 if (ret) { /* -ENOMEM or corruption */
2902 btrfs_abort_transaction(trans, ret);
2907 unlock_extent_cached(io_tree, ordered_extent->file_offset,
2908 ordered_extent->file_offset +
2909 ordered_extent->len - 1, &cached_state, GFP_NOFS);
2911 if (root != fs_info->tree_root)
2912 btrfs_delalloc_release_metadata(BTRFS_I(inode),
2913 ordered_extent->len);
2915 btrfs_end_transaction(trans);
2917 if (ret || truncated) {
2921 start = ordered_extent->file_offset + logical_len;
2923 start = ordered_extent->file_offset;
2924 end = ordered_extent->file_offset + ordered_extent->len - 1;
2925 clear_extent_uptodate(io_tree, start, end, NULL, GFP_NOFS);
2927 /* Drop the cache for the part of the extent we didn't write. */
2928 btrfs_drop_extent_cache(BTRFS_I(inode), start, end, 0);
2931 * If the ordered extent had an IOERR or something else went
2932 * wrong we need to return the space for this ordered extent
2933 * back to the allocator. We only free the extent in the
2934 * truncated case if we didn't write out the extent at all.
2936 if ((ret || !logical_len) &&
2937 !test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags) &&
2938 !test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags))
2939 btrfs_free_reserved_extent(fs_info,
2940 ordered_extent->start,
2941 ordered_extent->disk_len, 1);
2946 * This needs to be done to make sure anybody waiting knows we are done
2947 * updating everything for this ordered extent.
2949 btrfs_remove_ordered_extent(inode, ordered_extent);
2951 /* for snapshot-aware defrag */
2954 free_sa_defrag_extent(new);
2955 atomic_dec(&fs_info->defrag_running);
2957 relink_file_extents(new);
2962 btrfs_put_ordered_extent(ordered_extent);
2963 /* once for the tree */
2964 btrfs_put_ordered_extent(ordered_extent);
2969 static void finish_ordered_fn(struct btrfs_work *work)
2971 struct btrfs_ordered_extent *ordered_extent;
2972 ordered_extent = container_of(work, struct btrfs_ordered_extent, work);
2973 btrfs_finish_ordered_io(ordered_extent);
2976 static int btrfs_writepage_end_io_hook(struct page *page, u64 start, u64 end,
2977 struct extent_state *state, int uptodate)
2979 struct inode *inode = page->mapping->host;
2980 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2981 struct btrfs_ordered_extent *ordered_extent = NULL;
2982 struct btrfs_workqueue *wq;
2983 btrfs_work_func_t func;
2985 trace_btrfs_writepage_end_io_hook(page, start, end, uptodate);
2987 ClearPagePrivate2(page);
2988 if (!btrfs_dec_test_ordered_pending(inode, &ordered_extent, start,
2989 end - start + 1, uptodate))
2992 if (btrfs_is_free_space_inode(BTRFS_I(inode))) {
2993 wq = fs_info->endio_freespace_worker;
2994 func = btrfs_freespace_write_helper;
2996 wq = fs_info->endio_write_workers;
2997 func = btrfs_endio_write_helper;
3000 btrfs_init_work(&ordered_extent->work, func, finish_ordered_fn, NULL,
3002 btrfs_queue_work(wq, &ordered_extent->work);
3007 static int __readpage_endio_check(struct inode *inode,
3008 struct btrfs_io_bio *io_bio,
3009 int icsum, struct page *page,
3010 int pgoff, u64 start, size_t len)
3016 csum_expected = *(((u32 *)io_bio->csum) + icsum);
3018 kaddr = kmap_atomic(page);
3019 csum = btrfs_csum_data(kaddr + pgoff, csum, len);
3020 btrfs_csum_final(csum, (u8 *)&csum);
3021 if (csum != csum_expected)
3024 kunmap_atomic(kaddr);
3027 btrfs_print_data_csum_error(BTRFS_I(inode), start, csum, csum_expected,
3028 io_bio->mirror_num);
3029 memset(kaddr + pgoff, 1, len);
3030 flush_dcache_page(page);
3031 kunmap_atomic(kaddr);
3032 if (csum_expected == 0)
3038 * when reads are done, we need to check csums to verify the data is correct
3039 * if there's a match, we allow the bio to finish. If not, the code in
3040 * extent_io.c will try to find good copies for us.
3042 static int btrfs_readpage_end_io_hook(struct btrfs_io_bio *io_bio,
3043 u64 phy_offset, struct page *page,
3044 u64 start, u64 end, int mirror)
3046 size_t offset = start - page_offset(page);
3047 struct inode *inode = page->mapping->host;
3048 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
3049 struct btrfs_root *root = BTRFS_I(inode)->root;
3051 if (PageChecked(page)) {
3052 ClearPageChecked(page);
3056 if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)
3059 if (root->root_key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID &&
3060 test_range_bit(io_tree, start, end, EXTENT_NODATASUM, 1, NULL)) {
3061 clear_extent_bits(io_tree, start, end, EXTENT_NODATASUM);
3065 phy_offset >>= inode->i_sb->s_blocksize_bits;
3066 return __readpage_endio_check(inode, io_bio, phy_offset, page, offset,
3067 start, (size_t)(end - start + 1));
3070 void btrfs_add_delayed_iput(struct inode *inode)
3072 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
3073 struct btrfs_inode *binode = BTRFS_I(inode);
3075 if (atomic_add_unless(&inode->i_count, -1, 1))
3078 spin_lock(&fs_info->delayed_iput_lock);
3079 if (binode->delayed_iput_count == 0) {
3080 ASSERT(list_empty(&binode->delayed_iput));
3081 list_add_tail(&binode->delayed_iput, &fs_info->delayed_iputs);
3083 binode->delayed_iput_count++;
3085 spin_unlock(&fs_info->delayed_iput_lock);
3088 void btrfs_run_delayed_iputs(struct btrfs_fs_info *fs_info)
3091 spin_lock(&fs_info->delayed_iput_lock);
3092 while (!list_empty(&fs_info->delayed_iputs)) {
3093 struct btrfs_inode *inode;
3095 inode = list_first_entry(&fs_info->delayed_iputs,
3096 struct btrfs_inode, delayed_iput);
3097 if (inode->delayed_iput_count) {
3098 inode->delayed_iput_count--;
3099 list_move_tail(&inode->delayed_iput,
3100 &fs_info->delayed_iputs);
3102 list_del_init(&inode->delayed_iput);
3104 spin_unlock(&fs_info->delayed_iput_lock);
3105 iput(&inode->vfs_inode);
3106 spin_lock(&fs_info->delayed_iput_lock);
3108 spin_unlock(&fs_info->delayed_iput_lock);
3112 * This is called in transaction commit time. If there are no orphan
3113 * files in the subvolume, it removes orphan item and frees block_rsv
3116 void btrfs_orphan_commit_root(struct btrfs_trans_handle *trans,
3117 struct btrfs_root *root)
3119 struct btrfs_fs_info *fs_info = root->fs_info;
3120 struct btrfs_block_rsv *block_rsv;
3123 if (atomic_read(&root->orphan_inodes) ||
3124 root->orphan_cleanup_state != ORPHAN_CLEANUP_DONE)
3127 spin_lock(&root->orphan_lock);
3128 if (atomic_read(&root->orphan_inodes)) {
3129 spin_unlock(&root->orphan_lock);
3133 if (root->orphan_cleanup_state != ORPHAN_CLEANUP_DONE) {
3134 spin_unlock(&root->orphan_lock);
3138 block_rsv = root->orphan_block_rsv;
3139 root->orphan_block_rsv = NULL;
3140 spin_unlock(&root->orphan_lock);
3142 if (test_bit(BTRFS_ROOT_ORPHAN_ITEM_INSERTED, &root->state) &&
3143 btrfs_root_refs(&root->root_item) > 0) {
3144 ret = btrfs_del_orphan_item(trans, fs_info->tree_root,
3145 root->root_key.objectid);
3147 btrfs_abort_transaction(trans, ret);
3149 clear_bit(BTRFS_ROOT_ORPHAN_ITEM_INSERTED,
3154 WARN_ON(block_rsv->size > 0);
3155 btrfs_free_block_rsv(fs_info, block_rsv);
3160 * This creates an orphan entry for the given inode in case something goes
3161 * wrong in the middle of an unlink/truncate.
3163 * NOTE: caller of this function should reserve 5 units of metadata for
3166 int btrfs_orphan_add(struct btrfs_trans_handle *trans,
3167 struct btrfs_inode *inode)
3169 struct btrfs_fs_info *fs_info = btrfs_sb(inode->vfs_inode.i_sb);
3170 struct btrfs_root *root = inode->root;
3171 struct btrfs_block_rsv *block_rsv = NULL;
3176 if (!root->orphan_block_rsv) {
3177 block_rsv = btrfs_alloc_block_rsv(fs_info,
3178 BTRFS_BLOCK_RSV_TEMP);
3183 spin_lock(&root->orphan_lock);
3184 if (!root->orphan_block_rsv) {
3185 root->orphan_block_rsv = block_rsv;
3186 } else if (block_rsv) {
3187 btrfs_free_block_rsv(fs_info, block_rsv);
3191 if (!test_and_set_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
3192 &inode->runtime_flags)) {
3195 * For proper ENOSPC handling, we should do orphan
3196 * cleanup when mounting. But this introduces backward
3197 * compatibility issue.
3199 if (!xchg(&root->orphan_item_inserted, 1))
3205 atomic_inc(&root->orphan_inodes);
3208 if (!test_and_set_bit(BTRFS_INODE_ORPHAN_META_RESERVED,
3209 &inode->runtime_flags))
3211 spin_unlock(&root->orphan_lock);
3213 /* grab metadata reservation from transaction handle */
3215 ret = btrfs_orphan_reserve_metadata(trans, inode);
3218 atomic_dec(&root->orphan_inodes);
3219 clear_bit(BTRFS_INODE_ORPHAN_META_RESERVED,
3220 &inode->runtime_flags);
3222 clear_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
3223 &inode->runtime_flags);
3228 /* insert an orphan item to track this unlinked/truncated file */
3230 ret = btrfs_insert_orphan_item(trans, root, btrfs_ino(inode));
3232 atomic_dec(&root->orphan_inodes);
3234 clear_bit(BTRFS_INODE_ORPHAN_META_RESERVED,
3235 &inode->runtime_flags);
3236 btrfs_orphan_release_metadata(inode);
3238 if (ret != -EEXIST) {
3239 clear_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
3240 &inode->runtime_flags);
3241 btrfs_abort_transaction(trans, ret);
3248 /* insert an orphan item to track subvolume contains orphan files */
3250 ret = btrfs_insert_orphan_item(trans, fs_info->tree_root,
3251 root->root_key.objectid);
3252 if (ret && ret != -EEXIST) {
3253 btrfs_abort_transaction(trans, ret);
3261 * We have done the truncate/delete so we can go ahead and remove the orphan
3262 * item for this particular inode.
3264 static int btrfs_orphan_del(struct btrfs_trans_handle *trans,
3265 struct btrfs_inode *inode)
3267 struct btrfs_root *root = inode->root;
3268 int delete_item = 0;
3269 int release_rsv = 0;
3272 spin_lock(&root->orphan_lock);
3273 if (test_and_clear_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
3274 &inode->runtime_flags))
3277 if (test_and_clear_bit(BTRFS_INODE_ORPHAN_META_RESERVED,
3278 &inode->runtime_flags))
3280 spin_unlock(&root->orphan_lock);
3283 atomic_dec(&root->orphan_inodes);
3285 ret = btrfs_del_orphan_item(trans, root,
3290 btrfs_orphan_release_metadata(inode);
3296 * this cleans up any orphans that may be left on the list from the last use
3299 int btrfs_orphan_cleanup(struct btrfs_root *root)
3301 struct btrfs_fs_info *fs_info = root->fs_info;
3302 struct btrfs_path *path;
3303 struct extent_buffer *leaf;
3304 struct btrfs_key key, found_key;
3305 struct btrfs_trans_handle *trans;
3306 struct inode *inode;
3307 u64 last_objectid = 0;
3308 int ret = 0, nr_unlink = 0, nr_truncate = 0;
3310 if (cmpxchg(&root->orphan_cleanup_state, 0, ORPHAN_CLEANUP_STARTED))
3313 path = btrfs_alloc_path();
3318 path->reada = READA_BACK;
3320 key.objectid = BTRFS_ORPHAN_OBJECTID;
3321 key.type = BTRFS_ORPHAN_ITEM_KEY;
3322 key.offset = (u64)-1;
3325 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
3330 * if ret == 0 means we found what we were searching for, which
3331 * is weird, but possible, so only screw with path if we didn't
3332 * find the key and see if we have stuff that matches
3336 if (path->slots[0] == 0)
3341 /* pull out the item */
3342 leaf = path->nodes[0];
3343 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
3345 /* make sure the item matches what we want */
3346 if (found_key.objectid != BTRFS_ORPHAN_OBJECTID)
3348 if (found_key.type != BTRFS_ORPHAN_ITEM_KEY)
3351 /* release the path since we're done with it */
3352 btrfs_release_path(path);
3355 * this is where we are basically btrfs_lookup, without the
3356 * crossing root thing. we store the inode number in the
3357 * offset of the orphan item.
3360 if (found_key.offset == last_objectid) {
3362 "Error removing orphan entry, stopping orphan cleanup");
3367 last_objectid = found_key.offset;
3369 found_key.objectid = found_key.offset;
3370 found_key.type = BTRFS_INODE_ITEM_KEY;
3371 found_key.offset = 0;
3372 inode = btrfs_iget(fs_info->sb, &found_key, root, NULL);
3373 ret = PTR_ERR_OR_ZERO(inode);
3374 if (ret && ret != -ENOENT)
3377 if (ret == -ENOENT && root == fs_info->tree_root) {
3378 struct btrfs_root *dead_root;
3379 struct btrfs_fs_info *fs_info = root->fs_info;
3380 int is_dead_root = 0;
3383 * this is an orphan in the tree root. Currently these
3384 * could come from 2 sources:
3385 * a) a snapshot deletion in progress
3386 * b) a free space cache inode
3387 * We need to distinguish those two, as the snapshot
3388 * orphan must not get deleted.
3389 * find_dead_roots already ran before us, so if this
3390 * is a snapshot deletion, we should find the root
3391 * in the dead_roots list
3393 spin_lock(&fs_info->trans_lock);
3394 list_for_each_entry(dead_root, &fs_info->dead_roots,
3396 if (dead_root->root_key.objectid ==
3397 found_key.objectid) {
3402 spin_unlock(&fs_info->trans_lock);
3404 /* prevent this orphan from being found again */
3405 key.offset = found_key.objectid - 1;
3410 * Inode is already gone but the orphan item is still there,
3411 * kill the orphan item.
3413 if (ret == -ENOENT) {
3414 trans = btrfs_start_transaction(root, 1);
3415 if (IS_ERR(trans)) {
3416 ret = PTR_ERR(trans);
3419 btrfs_debug(fs_info, "auto deleting %Lu",
3420 found_key.objectid);
3421 ret = btrfs_del_orphan_item(trans, root,
3422 found_key.objectid);
3423 btrfs_end_transaction(trans);
3430 * add this inode to the orphan list so btrfs_orphan_del does
3431 * the proper thing when we hit it
3433 set_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
3434 &BTRFS_I(inode)->runtime_flags);
3435 atomic_inc(&root->orphan_inodes);
3437 /* if we have links, this was a truncate, lets do that */
3438 if (inode->i_nlink) {
3439 if (WARN_ON(!S_ISREG(inode->i_mode))) {
3445 /* 1 for the orphan item deletion. */
3446 trans = btrfs_start_transaction(root, 1);
3447 if (IS_ERR(trans)) {
3449 ret = PTR_ERR(trans);
3452 ret = btrfs_orphan_add(trans, BTRFS_I(inode));
3453 btrfs_end_transaction(trans);
3459 ret = btrfs_truncate(inode);
3461 btrfs_orphan_del(NULL, BTRFS_I(inode));
3466 /* this will do delete_inode and everything for us */
3471 /* release the path since we're done with it */
3472 btrfs_release_path(path);
3474 root->orphan_cleanup_state = ORPHAN_CLEANUP_DONE;
3476 if (root->orphan_block_rsv)
3477 btrfs_block_rsv_release(fs_info, root->orphan_block_rsv,
3480 if (root->orphan_block_rsv ||
3481 test_bit(BTRFS_ROOT_ORPHAN_ITEM_INSERTED, &root->state)) {
3482 trans = btrfs_join_transaction(root);
3484 btrfs_end_transaction(trans);
3488 btrfs_debug(fs_info, "unlinked %d orphans", nr_unlink);
3490 btrfs_debug(fs_info, "truncated %d orphans", nr_truncate);
3494 btrfs_err(fs_info, "could not do orphan cleanup %d", ret);
3495 btrfs_free_path(path);
3500 * very simple check to peek ahead in the leaf looking for xattrs. If we
3501 * don't find any xattrs, we know there can't be any acls.
3503 * slot is the slot the inode is in, objectid is the objectid of the inode
3505 static noinline int acls_after_inode_item(struct extent_buffer *leaf,
3506 int slot, u64 objectid,
3507 int *first_xattr_slot)
3509 u32 nritems = btrfs_header_nritems(leaf);
3510 struct btrfs_key found_key;
3511 static u64 xattr_access = 0;
3512 static u64 xattr_default = 0;
3515 if (!xattr_access) {
3516 xattr_access = btrfs_name_hash(XATTR_NAME_POSIX_ACL_ACCESS,
3517 strlen(XATTR_NAME_POSIX_ACL_ACCESS));
3518 xattr_default = btrfs_name_hash(XATTR_NAME_POSIX_ACL_DEFAULT,
3519 strlen(XATTR_NAME_POSIX_ACL_DEFAULT));
3523 *first_xattr_slot = -1;
3524 while (slot < nritems) {
3525 btrfs_item_key_to_cpu(leaf, &found_key, slot);
3527 /* we found a different objectid, there must not be acls */
3528 if (found_key.objectid != objectid)
3531 /* we found an xattr, assume we've got an acl */
3532 if (found_key.type == BTRFS_XATTR_ITEM_KEY) {
3533 if (*first_xattr_slot == -1)
3534 *first_xattr_slot = slot;
3535 if (found_key.offset == xattr_access ||
3536 found_key.offset == xattr_default)
3541 * we found a key greater than an xattr key, there can't
3542 * be any acls later on
3544 if (found_key.type > BTRFS_XATTR_ITEM_KEY)
3551 * it goes inode, inode backrefs, xattrs, extents,
3552 * so if there are a ton of hard links to an inode there can
3553 * be a lot of backrefs. Don't waste time searching too hard,
3554 * this is just an optimization
3559 /* we hit the end of the leaf before we found an xattr or
3560 * something larger than an xattr. We have to assume the inode
3563 if (*first_xattr_slot == -1)
3564 *first_xattr_slot = slot;
3569 * read an inode from the btree into the in-memory inode
3571 static int btrfs_read_locked_inode(struct inode *inode)
3573 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
3574 struct btrfs_path *path;
3575 struct extent_buffer *leaf;
3576 struct btrfs_inode_item *inode_item;
3577 struct btrfs_root *root = BTRFS_I(inode)->root;
3578 struct btrfs_key location;
3583 bool filled = false;
3584 int first_xattr_slot;
3586 ret = btrfs_fill_inode(inode, &rdev);
3590 path = btrfs_alloc_path();
3596 memcpy(&location, &BTRFS_I(inode)->location, sizeof(location));
3598 ret = btrfs_lookup_inode(NULL, root, path, &location, 0);
3605 leaf = path->nodes[0];
3610 inode_item = btrfs_item_ptr(leaf, path->slots[0],
3611 struct btrfs_inode_item);
3612 inode->i_mode = btrfs_inode_mode(leaf, inode_item);
3613 set_nlink(inode, btrfs_inode_nlink(leaf, inode_item));
3614 i_uid_write(inode, btrfs_inode_uid(leaf, inode_item));
3615 i_gid_write(inode, btrfs_inode_gid(leaf, inode_item));
3616 btrfs_i_size_write(BTRFS_I(inode), btrfs_inode_size(leaf, inode_item));
3618 inode->i_atime.tv_sec = btrfs_timespec_sec(leaf, &inode_item->atime);
3619 inode->i_atime.tv_nsec = btrfs_timespec_nsec(leaf, &inode_item->atime);
3621 inode->i_mtime.tv_sec = btrfs_timespec_sec(leaf, &inode_item->mtime);
3622 inode->i_mtime.tv_nsec = btrfs_timespec_nsec(leaf, &inode_item->mtime);
3624 inode->i_ctime.tv_sec = btrfs_timespec_sec(leaf, &inode_item->ctime);
3625 inode->i_ctime.tv_nsec = btrfs_timespec_nsec(leaf, &inode_item->ctime);
3627 BTRFS_I(inode)->i_otime.tv_sec =
3628 btrfs_timespec_sec(leaf, &inode_item->otime);
3629 BTRFS_I(inode)->i_otime.tv_nsec =
3630 btrfs_timespec_nsec(leaf, &inode_item->otime);
3632 inode_set_bytes(inode, btrfs_inode_nbytes(leaf, inode_item));
3633 BTRFS_I(inode)->generation = btrfs_inode_generation(leaf, inode_item);
3634 BTRFS_I(inode)->last_trans = btrfs_inode_transid(leaf, inode_item);
3636 inode->i_version = btrfs_inode_sequence(leaf, inode_item);
3637 inode->i_generation = BTRFS_I(inode)->generation;
3639 rdev = btrfs_inode_rdev(leaf, inode_item);
3641 BTRFS_I(inode)->index_cnt = (u64)-1;
3642 BTRFS_I(inode)->flags = btrfs_inode_flags(leaf, inode_item);
3646 * If we were modified in the current generation and evicted from memory
3647 * and then re-read we need to do a full sync since we don't have any
3648 * idea about which extents were modified before we were evicted from
3651 * This is required for both inode re-read from disk and delayed inode
3652 * in delayed_nodes_tree.
3654 if (BTRFS_I(inode)->last_trans == fs_info->generation)
3655 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
3656 &BTRFS_I(inode)->runtime_flags);
3659 * We don't persist the id of the transaction where an unlink operation
3660 * against the inode was last made. So here we assume the inode might
3661 * have been evicted, and therefore the exact value of last_unlink_trans
3662 * lost, and set it to last_trans to avoid metadata inconsistencies
3663 * between the inode and its parent if the inode is fsync'ed and the log
3664 * replayed. For example, in the scenario:
3667 * ln mydir/foo mydir/bar
3670 * echo 2 > /proc/sys/vm/drop_caches # evicts inode
3671 * xfs_io -c fsync mydir/foo
3673 * mount fs, triggers fsync log replay
3675 * We must make sure that when we fsync our inode foo we also log its
3676 * parent inode, otherwise after log replay the parent still has the
3677 * dentry with the "bar" name but our inode foo has a link count of 1
3678 * and doesn't have an inode ref with the name "bar" anymore.
3680 * Setting last_unlink_trans to last_trans is a pessimistic approach,
3681 * but it guarantees correctness at the expense of occasional full
3682 * transaction commits on fsync if our inode is a directory, or if our
3683 * inode is not a directory, logging its parent unnecessarily.
3685 BTRFS_I(inode)->last_unlink_trans = BTRFS_I(inode)->last_trans;
3688 if (inode->i_nlink != 1 ||
3689 path->slots[0] >= btrfs_header_nritems(leaf))
3692 btrfs_item_key_to_cpu(leaf, &location, path->slots[0]);
3693 if (location.objectid != btrfs_ino(BTRFS_I(inode)))
3696 ptr = btrfs_item_ptr_offset(leaf, path->slots[0]);
3697 if (location.type == BTRFS_INODE_REF_KEY) {
3698 struct btrfs_inode_ref *ref;
3700 ref = (struct btrfs_inode_ref *)ptr;
3701 BTRFS_I(inode)->dir_index = btrfs_inode_ref_index(leaf, ref);
3702 } else if (location.type == BTRFS_INODE_EXTREF_KEY) {
3703 struct btrfs_inode_extref *extref;
3705 extref = (struct btrfs_inode_extref *)ptr;
3706 BTRFS_I(inode)->dir_index = btrfs_inode_extref_index(leaf,
3711 * try to precache a NULL acl entry for files that don't have
3712 * any xattrs or acls
3714 maybe_acls = acls_after_inode_item(leaf, path->slots[0],
3715 btrfs_ino(BTRFS_I(inode)), &first_xattr_slot);
3716 if (first_xattr_slot != -1) {
3717 path->slots[0] = first_xattr_slot;
3718 ret = btrfs_load_inode_props(inode, path);
3721 "error loading props for ino %llu (root %llu): %d",
3722 btrfs_ino(BTRFS_I(inode)),
3723 root->root_key.objectid, ret);
3725 btrfs_free_path(path);
3728 cache_no_acl(inode);
3730 switch (inode->i_mode & S_IFMT) {
3732 inode->i_mapping->a_ops = &btrfs_aops;
3733 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
3734 inode->i_fop = &btrfs_file_operations;
3735 inode->i_op = &btrfs_file_inode_operations;
3738 inode->i_fop = &btrfs_dir_file_operations;
3739 inode->i_op = &btrfs_dir_inode_operations;
3742 inode->i_op = &btrfs_symlink_inode_operations;
3743 inode_nohighmem(inode);
3744 inode->i_mapping->a_ops = &btrfs_symlink_aops;
3747 inode->i_op = &btrfs_special_inode_operations;
3748 init_special_inode(inode, inode->i_mode, rdev);
3752 btrfs_update_iflags(inode);
3756 btrfs_free_path(path);
3757 make_bad_inode(inode);
3762 * given a leaf and an inode, copy the inode fields into the leaf
3764 static void fill_inode_item(struct btrfs_trans_handle *trans,
3765 struct extent_buffer *leaf,
3766 struct btrfs_inode_item *item,
3767 struct inode *inode)
3769 struct btrfs_map_token token;
3771 btrfs_init_map_token(&token);
3773 btrfs_set_token_inode_uid(leaf, item, i_uid_read(inode), &token);
3774 btrfs_set_token_inode_gid(leaf, item, i_gid_read(inode), &token);
3775 btrfs_set_token_inode_size(leaf, item, BTRFS_I(inode)->disk_i_size,
3777 btrfs_set_token_inode_mode(leaf, item, inode->i_mode, &token);
3778 btrfs_set_token_inode_nlink(leaf, item, inode->i_nlink, &token);
3780 btrfs_set_token_timespec_sec(leaf, &item->atime,
3781 inode->i_atime.tv_sec, &token);
3782 btrfs_set_token_timespec_nsec(leaf, &item->atime,
3783 inode->i_atime.tv_nsec, &token);
3785 btrfs_set_token_timespec_sec(leaf, &item->mtime,
3786 inode->i_mtime.tv_sec, &token);
3787 btrfs_set_token_timespec_nsec(leaf, &item->mtime,
3788 inode->i_mtime.tv_nsec, &token);
3790 btrfs_set_token_timespec_sec(leaf, &item->ctime,
3791 inode->i_ctime.tv_sec, &token);
3792 btrfs_set_token_timespec_nsec(leaf, &item->ctime,
3793 inode->i_ctime.tv_nsec, &token);
3795 btrfs_set_token_timespec_sec(leaf, &item->otime,
3796 BTRFS_I(inode)->i_otime.tv_sec, &token);
3797 btrfs_set_token_timespec_nsec(leaf, &item->otime,
3798 BTRFS_I(inode)->i_otime.tv_nsec, &token);
3800 btrfs_set_token_inode_nbytes(leaf, item, inode_get_bytes(inode),
3802 btrfs_set_token_inode_generation(leaf, item, BTRFS_I(inode)->generation,
3804 btrfs_set_token_inode_sequence(leaf, item, inode->i_version, &token);
3805 btrfs_set_token_inode_transid(leaf, item, trans->transid, &token);
3806 btrfs_set_token_inode_rdev(leaf, item, inode->i_rdev, &token);
3807 btrfs_set_token_inode_flags(leaf, item, BTRFS_I(inode)->flags, &token);
3808 btrfs_set_token_inode_block_group(leaf, item, 0, &token);
3812 * copy everything in the in-memory inode into the btree.
3814 static noinline int btrfs_update_inode_item(struct btrfs_trans_handle *trans,
3815 struct btrfs_root *root, struct inode *inode)
3817 struct btrfs_inode_item *inode_item;
3818 struct btrfs_path *path;
3819 struct extent_buffer *leaf;
3822 path = btrfs_alloc_path();
3826 path->leave_spinning = 1;
3827 ret = btrfs_lookup_inode(trans, root, path, &BTRFS_I(inode)->location,
3835 leaf = path->nodes[0];
3836 inode_item = btrfs_item_ptr(leaf, path->slots[0],
3837 struct btrfs_inode_item);
3839 fill_inode_item(trans, leaf, inode_item, inode);
3840 btrfs_mark_buffer_dirty(leaf);
3841 btrfs_set_inode_last_trans(trans, inode);
3844 btrfs_free_path(path);
3849 * copy everything in the in-memory inode into the btree.
3851 noinline int btrfs_update_inode(struct btrfs_trans_handle *trans,
3852 struct btrfs_root *root, struct inode *inode)
3854 struct btrfs_fs_info *fs_info = root->fs_info;
3858 * If the inode is a free space inode, we can deadlock during commit
3859 * if we put it into the delayed code.
3861 * The data relocation inode should also be directly updated
3864 if (!btrfs_is_free_space_inode(BTRFS_I(inode))
3865 && root->root_key.objectid != BTRFS_DATA_RELOC_TREE_OBJECTID
3866 && !test_bit(BTRFS_FS_LOG_RECOVERING, &fs_info->flags)) {
3867 btrfs_update_root_times(trans, root);
3869 ret = btrfs_delayed_update_inode(trans, root, inode);
3871 btrfs_set_inode_last_trans(trans, inode);
3875 return btrfs_update_inode_item(trans, root, inode);
3878 noinline int btrfs_update_inode_fallback(struct btrfs_trans_handle *trans,
3879 struct btrfs_root *root,
3880 struct inode *inode)
3884 ret = btrfs_update_inode(trans, root, inode);
3886 return btrfs_update_inode_item(trans, root, inode);
3891 * unlink helper that gets used here in inode.c and in the tree logging
3892 * recovery code. It remove a link in a directory with a given name, and
3893 * also drops the back refs in the inode to the directory
3895 static int __btrfs_unlink_inode(struct btrfs_trans_handle *trans,
3896 struct btrfs_root *root,
3897 struct btrfs_inode *dir,
3898 struct btrfs_inode *inode,
3899 const char *name, int name_len)
3901 struct btrfs_fs_info *fs_info = root->fs_info;
3902 struct btrfs_path *path;
3904 struct extent_buffer *leaf;
3905 struct btrfs_dir_item *di;
3906 struct btrfs_key key;
3908 u64 ino = btrfs_ino(inode);
3909 u64 dir_ino = btrfs_ino(dir);
3911 path = btrfs_alloc_path();
3917 path->leave_spinning = 1;
3918 di = btrfs_lookup_dir_item(trans, root, path, dir_ino,
3919 name, name_len, -1);
3928 leaf = path->nodes[0];
3929 btrfs_dir_item_key_to_cpu(leaf, di, &key);
3930 ret = btrfs_delete_one_dir_name(trans, root, path, di);
3933 btrfs_release_path(path);
3936 * If we don't have dir index, we have to get it by looking up
3937 * the inode ref, since we get the inode ref, remove it directly,
3938 * it is unnecessary to do delayed deletion.
3940 * But if we have dir index, needn't search inode ref to get it.
3941 * Since the inode ref is close to the inode item, it is better
3942 * that we delay to delete it, and just do this deletion when
3943 * we update the inode item.
3945 if (inode->dir_index) {
3946 ret = btrfs_delayed_delete_inode_ref(inode);
3948 index = inode->dir_index;
3953 ret = btrfs_del_inode_ref(trans, root, name, name_len, ino,
3957 "failed to delete reference to %.*s, inode %llu parent %llu",
3958 name_len, name, ino, dir_ino);
3959 btrfs_abort_transaction(trans, ret);
3963 ret = btrfs_delete_delayed_dir_index(trans, fs_info, dir, index);
3965 btrfs_abort_transaction(trans, ret);
3969 ret = btrfs_del_inode_ref_in_log(trans, root, name, name_len, inode,
3971 if (ret != 0 && ret != -ENOENT) {
3972 btrfs_abort_transaction(trans, ret);
3976 ret = btrfs_del_dir_entries_in_log(trans, root, name, name_len, dir,
3981 btrfs_abort_transaction(trans, ret);
3983 btrfs_free_path(path);
3987 btrfs_i_size_write(dir, dir->vfs_inode.i_size - name_len * 2);
3988 inode_inc_iversion(&inode->vfs_inode);
3989 inode_inc_iversion(&dir->vfs_inode);
3990 inode->vfs_inode.i_ctime = dir->vfs_inode.i_mtime =
3991 dir->vfs_inode.i_ctime = current_time(&inode->vfs_inode);
3992 ret = btrfs_update_inode(trans, root, &dir->vfs_inode);
3997 int btrfs_unlink_inode(struct btrfs_trans_handle *trans,
3998 struct btrfs_root *root,
3999 struct btrfs_inode *dir, struct btrfs_inode *inode,
4000 const char *name, int name_len)
4003 ret = __btrfs_unlink_inode(trans, root, dir, inode, name, name_len);
4005 drop_nlink(&inode->vfs_inode);
4006 ret = btrfs_update_inode(trans, root, &inode->vfs_inode);
4012 * helper to start transaction for unlink and rmdir.
4014 * unlink and rmdir are special in btrfs, they do not always free space, so
4015 * if we cannot make our reservations the normal way try and see if there is
4016 * plenty of slack room in the global reserve to migrate, otherwise we cannot
4017 * allow the unlink to occur.
4019 static struct btrfs_trans_handle *__unlink_start_trans(struct inode *dir)
4021 struct btrfs_root *root = BTRFS_I(dir)->root;
4024 * 1 for the possible orphan item
4025 * 1 for the dir item
4026 * 1 for the dir index
4027 * 1 for the inode ref
4030 return btrfs_start_transaction_fallback_global_rsv(root, 5, 5);
4033 static int btrfs_unlink(struct inode *dir, struct dentry *dentry)
4035 struct btrfs_root *root = BTRFS_I(dir)->root;
4036 struct btrfs_trans_handle *trans;
4037 struct inode *inode = d_inode(dentry);
4040 trans = __unlink_start_trans(dir);
4042 return PTR_ERR(trans);
4044 btrfs_record_unlink_dir(trans, BTRFS_I(dir), BTRFS_I(d_inode(dentry)),
4047 ret = btrfs_unlink_inode(trans, root, BTRFS_I(dir),
4048 BTRFS_I(d_inode(dentry)), dentry->d_name.name,
4049 dentry->d_name.len);
4053 if (inode->i_nlink == 0) {
4054 ret = btrfs_orphan_add(trans, BTRFS_I(inode));
4060 btrfs_end_transaction(trans);
4061 btrfs_btree_balance_dirty(root->fs_info);
4065 int btrfs_unlink_subvol(struct btrfs_trans_handle *trans,
4066 struct btrfs_root *root,
4067 struct inode *dir, u64 objectid,
4068 const char *name, int name_len)
4070 struct btrfs_fs_info *fs_info = root->fs_info;
4071 struct btrfs_path *path;
4072 struct extent_buffer *leaf;
4073 struct btrfs_dir_item *di;
4074 struct btrfs_key key;
4077 u64 dir_ino = btrfs_ino(BTRFS_I(dir));
4079 path = btrfs_alloc_path();
4083 di = btrfs_lookup_dir_item(trans, root, path, dir_ino,
4084 name, name_len, -1);
4085 if (IS_ERR_OR_NULL(di)) {
4093 leaf = path->nodes[0];
4094 btrfs_dir_item_key_to_cpu(leaf, di, &key);
4095 WARN_ON(key.type != BTRFS_ROOT_ITEM_KEY || key.objectid != objectid);
4096 ret = btrfs_delete_one_dir_name(trans, root, path, di);
4098 btrfs_abort_transaction(trans, ret);
4101 btrfs_release_path(path);
4103 ret = btrfs_del_root_ref(trans, fs_info, objectid,
4104 root->root_key.objectid, dir_ino,
4105 &index, name, name_len);
4107 if (ret != -ENOENT) {
4108 btrfs_abort_transaction(trans, ret);
4111 di = btrfs_search_dir_index_item(root, path, dir_ino,
4113 if (IS_ERR_OR_NULL(di)) {
4118 btrfs_abort_transaction(trans, ret);
4122 leaf = path->nodes[0];
4123 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
4124 btrfs_release_path(path);
4127 btrfs_release_path(path);
4129 ret = btrfs_delete_delayed_dir_index(trans, fs_info, BTRFS_I(dir), index);
4131 btrfs_abort_transaction(trans, ret);
4135 btrfs_i_size_write(BTRFS_I(dir), dir->i_size - name_len * 2);
4136 inode_inc_iversion(dir);
4137 dir->i_mtime = dir->i_ctime = current_time(dir);
4138 ret = btrfs_update_inode_fallback(trans, root, dir);
4140 btrfs_abort_transaction(trans, ret);
4142 btrfs_free_path(path);
4146 static int btrfs_rmdir(struct inode *dir, struct dentry *dentry)
4148 struct inode *inode = d_inode(dentry);
4150 struct btrfs_root *root = BTRFS_I(dir)->root;
4151 struct btrfs_trans_handle *trans;
4152 u64 last_unlink_trans;
4154 if (inode->i_size > BTRFS_EMPTY_DIR_SIZE)
4156 if (btrfs_ino(BTRFS_I(inode)) == BTRFS_FIRST_FREE_OBJECTID)
4159 trans = __unlink_start_trans(dir);
4161 return PTR_ERR(trans);
4163 if (unlikely(btrfs_ino(BTRFS_I(inode)) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)) {
4164 err = btrfs_unlink_subvol(trans, root, dir,
4165 BTRFS_I(inode)->location.objectid,
4166 dentry->d_name.name,
4167 dentry->d_name.len);
4171 err = btrfs_orphan_add(trans, BTRFS_I(inode));
4175 last_unlink_trans = BTRFS_I(inode)->last_unlink_trans;
4177 /* now the directory is empty */
4178 err = btrfs_unlink_inode(trans, root, BTRFS_I(dir),
4179 BTRFS_I(d_inode(dentry)), dentry->d_name.name,
4180 dentry->d_name.len);
4182 btrfs_i_size_write(BTRFS_I(inode), 0);
4184 * Propagate the last_unlink_trans value of the deleted dir to
4185 * its parent directory. This is to prevent an unrecoverable
4186 * log tree in the case we do something like this:
4188 * 2) create snapshot under dir foo
4189 * 3) delete the snapshot
4192 * 6) fsync foo or some file inside foo
4194 if (last_unlink_trans >= trans->transid)
4195 BTRFS_I(dir)->last_unlink_trans = last_unlink_trans;
4198 btrfs_end_transaction(trans);
4199 btrfs_btree_balance_dirty(root->fs_info);
4204 static int truncate_space_check(struct btrfs_trans_handle *trans,
4205 struct btrfs_root *root,
4208 struct btrfs_fs_info *fs_info = root->fs_info;
4212 * This is only used to apply pressure to the enospc system, we don't
4213 * intend to use this reservation at all.
4215 bytes_deleted = btrfs_csum_bytes_to_leaves(fs_info, bytes_deleted);
4216 bytes_deleted *= fs_info->nodesize;
4217 ret = btrfs_block_rsv_add(root, &fs_info->trans_block_rsv,
4218 bytes_deleted, BTRFS_RESERVE_NO_FLUSH);
4220 trace_btrfs_space_reservation(fs_info, "transaction",
4223 trans->bytes_reserved += bytes_deleted;
4229 static int truncate_inline_extent(struct inode *inode,
4230 struct btrfs_path *path,
4231 struct btrfs_key *found_key,
4235 struct extent_buffer *leaf = path->nodes[0];
4236 int slot = path->slots[0];
4237 struct btrfs_file_extent_item *fi;
4238 u32 size = (u32)(new_size - found_key->offset);
4239 struct btrfs_root *root = BTRFS_I(inode)->root;
4241 fi = btrfs_item_ptr(leaf, slot, struct btrfs_file_extent_item);
4243 if (btrfs_file_extent_compression(leaf, fi) != BTRFS_COMPRESS_NONE) {
4244 loff_t offset = new_size;
4245 loff_t page_end = ALIGN(offset, PAGE_SIZE);
4248 * Zero out the remaining of the last page of our inline extent,
4249 * instead of directly truncating our inline extent here - that
4250 * would be much more complex (decompressing all the data, then
4251 * compressing the truncated data, which might be bigger than
4252 * the size of the inline extent, resize the extent, etc).
4253 * We release the path because to get the page we might need to
4254 * read the extent item from disk (data not in the page cache).
4256 btrfs_release_path(path);
4257 return btrfs_truncate_block(inode, offset, page_end - offset,
4261 btrfs_set_file_extent_ram_bytes(leaf, fi, size);
4262 size = btrfs_file_extent_calc_inline_size(size);
4263 btrfs_truncate_item(root->fs_info, path, size, 1);
4265 if (test_bit(BTRFS_ROOT_REF_COWS, &root->state))
4266 inode_sub_bytes(inode, item_end + 1 - new_size);
4272 * this can truncate away extent items, csum items and directory items.
4273 * It starts at a high offset and removes keys until it can't find
4274 * any higher than new_size
4276 * csum items that cross the new i_size are truncated to the new size
4279 * min_type is the minimum key type to truncate down to. If set to 0, this
4280 * will kill all the items on this inode, including the INODE_ITEM_KEY.
4282 int btrfs_truncate_inode_items(struct btrfs_trans_handle *trans,
4283 struct btrfs_root *root,
4284 struct inode *inode,
4285 u64 new_size, u32 min_type)
4287 struct btrfs_fs_info *fs_info = root->fs_info;
4288 struct btrfs_path *path;
4289 struct extent_buffer *leaf;
4290 struct btrfs_file_extent_item *fi;
4291 struct btrfs_key key;
4292 struct btrfs_key found_key;
4293 u64 extent_start = 0;
4294 u64 extent_num_bytes = 0;
4295 u64 extent_offset = 0;
4297 u64 last_size = new_size;
4298 u32 found_type = (u8)-1;
4301 int pending_del_nr = 0;
4302 int pending_del_slot = 0;
4303 int extent_type = -1;
4306 u64 ino = btrfs_ino(BTRFS_I(inode));
4307 u64 bytes_deleted = 0;
4309 bool should_throttle = 0;
4310 bool should_end = 0;
4312 BUG_ON(new_size > 0 && min_type != BTRFS_EXTENT_DATA_KEY);
4315 * for non-free space inodes and ref cows, we want to back off from
4318 if (!btrfs_is_free_space_inode(BTRFS_I(inode)) &&
4319 test_bit(BTRFS_ROOT_REF_COWS, &root->state))
4322 path = btrfs_alloc_path();
4325 path->reada = READA_BACK;
4328 * We want to drop from the next block forward in case this new size is
4329 * not block aligned since we will be keeping the last block of the
4330 * extent just the way it is.
4332 if (test_bit(BTRFS_ROOT_REF_COWS, &root->state) ||
4333 root == fs_info->tree_root)
4334 btrfs_drop_extent_cache(BTRFS_I(inode), ALIGN(new_size,
4335 fs_info->sectorsize),
4339 * This function is also used to drop the items in the log tree before
4340 * we relog the inode, so if root != BTRFS_I(inode)->root, it means
4341 * it is used to drop the loged items. So we shouldn't kill the delayed
4344 if (min_type == 0 && root == BTRFS_I(inode)->root)
4345 btrfs_kill_delayed_inode_items(BTRFS_I(inode));
4348 key.offset = (u64)-1;
4353 * with a 16K leaf size and 128MB extents, you can actually queue
4354 * up a huge file in a single leaf. Most of the time that
4355 * bytes_deleted is > 0, it will be huge by the time we get here
4357 if (be_nice && bytes_deleted > SZ_32M) {
4358 if (btrfs_should_end_transaction(trans)) {
4365 path->leave_spinning = 1;
4366 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
4373 /* there are no items in the tree for us to truncate, we're
4376 if (path->slots[0] == 0)
4383 leaf = path->nodes[0];
4384 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
4385 found_type = found_key.type;
4387 if (found_key.objectid != ino)
4390 if (found_type < min_type)
4393 item_end = found_key.offset;
4394 if (found_type == BTRFS_EXTENT_DATA_KEY) {
4395 fi = btrfs_item_ptr(leaf, path->slots[0],
4396 struct btrfs_file_extent_item);
4397 extent_type = btrfs_file_extent_type(leaf, fi);
4398 if (extent_type != BTRFS_FILE_EXTENT_INLINE) {
4400 btrfs_file_extent_num_bytes(leaf, fi);
4401 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
4402 item_end += btrfs_file_extent_inline_len(leaf,
4403 path->slots[0], fi);
4407 if (found_type > min_type) {
4410 if (item_end < new_size) {
4412 * With NO_HOLES mode, for the following mapping
4414 * [0-4k][hole][8k-12k]
4416 * if truncating isize down to 6k, it ends up
4419 if (btrfs_fs_incompat(root->fs_info, NO_HOLES))
4420 last_size = new_size;
4423 if (found_key.offset >= new_size)
4429 /* FIXME, shrink the extent if the ref count is only 1 */
4430 if (found_type != BTRFS_EXTENT_DATA_KEY)
4434 last_size = found_key.offset;
4436 last_size = new_size;
4438 if (extent_type != BTRFS_FILE_EXTENT_INLINE) {
4440 extent_start = btrfs_file_extent_disk_bytenr(leaf, fi);
4442 u64 orig_num_bytes =
4443 btrfs_file_extent_num_bytes(leaf, fi);
4444 extent_num_bytes = ALIGN(new_size -
4446 fs_info->sectorsize);
4447 btrfs_set_file_extent_num_bytes(leaf, fi,
4449 num_dec = (orig_num_bytes -
4451 if (test_bit(BTRFS_ROOT_REF_COWS,
4454 inode_sub_bytes(inode, num_dec);
4455 btrfs_mark_buffer_dirty(leaf);
4458 btrfs_file_extent_disk_num_bytes(leaf,
4460 extent_offset = found_key.offset -
4461 btrfs_file_extent_offset(leaf, fi);
4463 /* FIXME blocksize != 4096 */
4464 num_dec = btrfs_file_extent_num_bytes(leaf, fi);
4465 if (extent_start != 0) {
4467 if (test_bit(BTRFS_ROOT_REF_COWS,
4469 inode_sub_bytes(inode, num_dec);
4472 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
4474 * we can't truncate inline items that have had
4478 btrfs_file_extent_encryption(leaf, fi) == 0 &&
4479 btrfs_file_extent_other_encoding(leaf, fi) == 0) {
4482 * Need to release path in order to truncate a
4483 * compressed extent. So delete any accumulated
4484 * extent items so far.
4486 if (btrfs_file_extent_compression(leaf, fi) !=
4487 BTRFS_COMPRESS_NONE && pending_del_nr) {
4488 err = btrfs_del_items(trans, root, path,
4492 btrfs_abort_transaction(trans,
4499 err = truncate_inline_extent(inode, path,
4504 btrfs_abort_transaction(trans, err);
4507 } else if (test_bit(BTRFS_ROOT_REF_COWS,
4509 inode_sub_bytes(inode, item_end + 1 - new_size);
4514 if (!pending_del_nr) {
4515 /* no pending yet, add ourselves */
4516 pending_del_slot = path->slots[0];
4518 } else if (pending_del_nr &&
4519 path->slots[0] + 1 == pending_del_slot) {
4520 /* hop on the pending chunk */
4522 pending_del_slot = path->slots[0];
4529 should_throttle = 0;
4532 (test_bit(BTRFS_ROOT_REF_COWS, &root->state) ||
4533 root == fs_info->tree_root)) {
4534 btrfs_set_path_blocking(path);
4535 bytes_deleted += extent_num_bytes;
4536 ret = btrfs_free_extent(trans, fs_info, extent_start,
4537 extent_num_bytes, 0,
4538 btrfs_header_owner(leaf),
4539 ino, extent_offset);
4541 if (btrfs_should_throttle_delayed_refs(trans, fs_info))
4542 btrfs_async_run_delayed_refs(fs_info,
4543 trans->delayed_ref_updates * 2,
4546 if (truncate_space_check(trans, root,
4547 extent_num_bytes)) {
4550 if (btrfs_should_throttle_delayed_refs(trans,
4552 should_throttle = 1;
4556 if (found_type == BTRFS_INODE_ITEM_KEY)
4559 if (path->slots[0] == 0 ||
4560 path->slots[0] != pending_del_slot ||
4561 should_throttle || should_end) {
4562 if (pending_del_nr) {
4563 ret = btrfs_del_items(trans, root, path,
4567 btrfs_abort_transaction(trans, ret);
4572 btrfs_release_path(path);
4573 if (should_throttle) {
4574 unsigned long updates = trans->delayed_ref_updates;
4576 trans->delayed_ref_updates = 0;
4577 ret = btrfs_run_delayed_refs(trans,
4585 * if we failed to refill our space rsv, bail out
4586 * and let the transaction restart
4598 if (pending_del_nr) {
4599 ret = btrfs_del_items(trans, root, path, pending_del_slot,
4602 btrfs_abort_transaction(trans, ret);
4605 if (root->root_key.objectid != BTRFS_TREE_LOG_OBJECTID)
4606 btrfs_ordered_update_i_size(inode, last_size, NULL);
4608 btrfs_free_path(path);
4611 /* only inline file may have last_size != new_size */
4612 if (new_size >= fs_info->sectorsize ||
4613 new_size > fs_info->max_inline)
4614 ASSERT(last_size == new_size);
4617 if (be_nice && bytes_deleted > SZ_32M) {
4618 unsigned long updates = trans->delayed_ref_updates;
4620 trans->delayed_ref_updates = 0;
4621 ret = btrfs_run_delayed_refs(trans, fs_info,
4631 * btrfs_truncate_block - read, zero a chunk and write a block
4632 * @inode - inode that we're zeroing
4633 * @from - the offset to start zeroing
4634 * @len - the length to zero, 0 to zero the entire range respective to the
4636 * @front - zero up to the offset instead of from the offset on
4638 * This will find the block for the "from" offset and cow the block and zero the
4639 * part we want to zero. This is used with truncate and hole punching.
4641 int btrfs_truncate_block(struct inode *inode, loff_t from, loff_t len,
4644 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
4645 struct address_space *mapping = inode->i_mapping;
4646 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
4647 struct btrfs_ordered_extent *ordered;
4648 struct extent_state *cached_state = NULL;
4650 u32 blocksize = fs_info->sectorsize;
4651 pgoff_t index = from >> PAGE_SHIFT;
4652 unsigned offset = from & (blocksize - 1);
4654 gfp_t mask = btrfs_alloc_write_mask(mapping);
4659 if ((offset & (blocksize - 1)) == 0 &&
4660 (!len || ((len & (blocksize - 1)) == 0)))
4663 ret = btrfs_delalloc_reserve_space(inode,
4664 round_down(from, blocksize), blocksize);
4669 page = find_or_create_page(mapping, index, mask);
4671 btrfs_delalloc_release_space(inode,
4672 round_down(from, blocksize),
4678 block_start = round_down(from, blocksize);
4679 block_end = block_start + blocksize - 1;
4681 if (!PageUptodate(page)) {
4682 ret = btrfs_readpage(NULL, page);
4684 if (page->mapping != mapping) {
4689 if (!PageUptodate(page)) {
4694 wait_on_page_writeback(page);
4696 lock_extent_bits(io_tree, block_start, block_end, &cached_state);
4697 set_page_extent_mapped(page);
4699 ordered = btrfs_lookup_ordered_extent(inode, block_start);
4701 unlock_extent_cached(io_tree, block_start, block_end,
4702 &cached_state, GFP_NOFS);
4705 btrfs_start_ordered_extent(inode, ordered, 1);
4706 btrfs_put_ordered_extent(ordered);
4710 clear_extent_bit(&BTRFS_I(inode)->io_tree, block_start, block_end,
4711 EXTENT_DIRTY | EXTENT_DELALLOC |
4712 EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG,
4713 0, 0, &cached_state, GFP_NOFS);
4715 ret = btrfs_set_extent_delalloc(inode, block_start, block_end,
4718 unlock_extent_cached(io_tree, block_start, block_end,
4719 &cached_state, GFP_NOFS);
4723 if (offset != blocksize) {
4725 len = blocksize - offset;
4728 memset(kaddr + (block_start - page_offset(page)),
4731 memset(kaddr + (block_start - page_offset(page)) + offset,
4733 flush_dcache_page(page);
4736 ClearPageChecked(page);
4737 set_page_dirty(page);
4738 unlock_extent_cached(io_tree, block_start, block_end, &cached_state,
4743 btrfs_delalloc_release_space(inode, block_start,
4751 static int maybe_insert_hole(struct btrfs_root *root, struct inode *inode,
4752 u64 offset, u64 len)
4754 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
4755 struct btrfs_trans_handle *trans;
4759 * Still need to make sure the inode looks like it's been updated so
4760 * that any holes get logged if we fsync.
4762 if (btrfs_fs_incompat(fs_info, NO_HOLES)) {
4763 BTRFS_I(inode)->last_trans = fs_info->generation;
4764 BTRFS_I(inode)->last_sub_trans = root->log_transid;
4765 BTRFS_I(inode)->last_log_commit = root->last_log_commit;
4770 * 1 - for the one we're dropping
4771 * 1 - for the one we're adding
4772 * 1 - for updating the inode.
4774 trans = btrfs_start_transaction(root, 3);
4776 return PTR_ERR(trans);
4778 ret = btrfs_drop_extents(trans, root, inode, offset, offset + len, 1);
4780 btrfs_abort_transaction(trans, ret);
4781 btrfs_end_transaction(trans);
4785 ret = btrfs_insert_file_extent(trans, root, btrfs_ino(BTRFS_I(inode)),
4786 offset, 0, 0, len, 0, len, 0, 0, 0);
4788 btrfs_abort_transaction(trans, ret);
4790 btrfs_update_inode(trans, root, inode);
4791 btrfs_end_transaction(trans);
4796 * This function puts in dummy file extents for the area we're creating a hole
4797 * for. So if we are truncating this file to a larger size we need to insert
4798 * these file extents so that btrfs_get_extent will return a EXTENT_MAP_HOLE for
4799 * the range between oldsize and size
4801 int btrfs_cont_expand(struct inode *inode, loff_t oldsize, loff_t size)
4803 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
4804 struct btrfs_root *root = BTRFS_I(inode)->root;
4805 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
4806 struct extent_map *em = NULL;
4807 struct extent_state *cached_state = NULL;
4808 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
4809 u64 hole_start = ALIGN(oldsize, fs_info->sectorsize);
4810 u64 block_end = ALIGN(size, fs_info->sectorsize);
4817 * If our size started in the middle of a block we need to zero out the
4818 * rest of the block before we expand the i_size, otherwise we could
4819 * expose stale data.
4821 err = btrfs_truncate_block(inode, oldsize, 0, 0);
4825 if (size <= hole_start)
4829 struct btrfs_ordered_extent *ordered;
4831 lock_extent_bits(io_tree, hole_start, block_end - 1,
4833 ordered = btrfs_lookup_ordered_range(BTRFS_I(inode), hole_start,
4834 block_end - hole_start);
4837 unlock_extent_cached(io_tree, hole_start, block_end - 1,
4838 &cached_state, GFP_NOFS);
4839 btrfs_start_ordered_extent(inode, ordered, 1);
4840 btrfs_put_ordered_extent(ordered);
4843 cur_offset = hole_start;
4845 em = btrfs_get_extent(BTRFS_I(inode), NULL, 0, cur_offset,
4846 block_end - cur_offset, 0);
4852 last_byte = min(extent_map_end(em), block_end);
4853 last_byte = ALIGN(last_byte, fs_info->sectorsize);
4854 if (!test_bit(EXTENT_FLAG_PREALLOC, &em->flags)) {
4855 struct extent_map *hole_em;
4856 hole_size = last_byte - cur_offset;
4858 err = maybe_insert_hole(root, inode, cur_offset,
4862 btrfs_drop_extent_cache(BTRFS_I(inode), cur_offset,
4863 cur_offset + hole_size - 1, 0);
4864 hole_em = alloc_extent_map();
4866 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
4867 &BTRFS_I(inode)->runtime_flags);
4870 hole_em->start = cur_offset;
4871 hole_em->len = hole_size;
4872 hole_em->orig_start = cur_offset;
4874 hole_em->block_start = EXTENT_MAP_HOLE;
4875 hole_em->block_len = 0;
4876 hole_em->orig_block_len = 0;
4877 hole_em->ram_bytes = hole_size;
4878 hole_em->bdev = fs_info->fs_devices->latest_bdev;
4879 hole_em->compress_type = BTRFS_COMPRESS_NONE;
4880 hole_em->generation = fs_info->generation;
4883 write_lock(&em_tree->lock);
4884 err = add_extent_mapping(em_tree, hole_em, 1);
4885 write_unlock(&em_tree->lock);
4888 btrfs_drop_extent_cache(BTRFS_I(inode),
4893 free_extent_map(hole_em);
4896 free_extent_map(em);
4898 cur_offset = last_byte;
4899 if (cur_offset >= block_end)
4902 free_extent_map(em);
4903 unlock_extent_cached(io_tree, hole_start, block_end - 1, &cached_state,
4908 static int btrfs_setsize(struct inode *inode, struct iattr *attr)
4910 struct btrfs_root *root = BTRFS_I(inode)->root;
4911 struct btrfs_trans_handle *trans;
4912 loff_t oldsize = i_size_read(inode);
4913 loff_t newsize = attr->ia_size;
4914 int mask = attr->ia_valid;
4918 * The regular truncate() case without ATTR_CTIME and ATTR_MTIME is a
4919 * special case where we need to update the times despite not having
4920 * these flags set. For all other operations the VFS set these flags
4921 * explicitly if it wants a timestamp update.
4923 if (newsize != oldsize) {
4924 inode_inc_iversion(inode);
4925 if (!(mask & (ATTR_CTIME | ATTR_MTIME)))
4926 inode->i_ctime = inode->i_mtime =
4927 current_time(inode);
4930 if (newsize > oldsize) {
4932 * Don't do an expanding truncate while snapshoting is ongoing.
4933 * This is to ensure the snapshot captures a fully consistent
4934 * state of this file - if the snapshot captures this expanding
4935 * truncation, it must capture all writes that happened before
4938 btrfs_wait_for_snapshot_creation(root);
4939 ret = btrfs_cont_expand(inode, oldsize, newsize);
4941 btrfs_end_write_no_snapshoting(root);
4945 trans = btrfs_start_transaction(root, 1);
4946 if (IS_ERR(trans)) {
4947 btrfs_end_write_no_snapshoting(root);
4948 return PTR_ERR(trans);
4951 i_size_write(inode, newsize);
4952 btrfs_ordered_update_i_size(inode, i_size_read(inode), NULL);
4953 pagecache_isize_extended(inode, oldsize, newsize);
4954 ret = btrfs_update_inode(trans, root, inode);
4955 btrfs_end_write_no_snapshoting(root);
4956 btrfs_end_transaction(trans);
4960 * We're truncating a file that used to have good data down to
4961 * zero. Make sure it gets into the ordered flush list so that
4962 * any new writes get down to disk quickly.
4965 set_bit(BTRFS_INODE_ORDERED_DATA_CLOSE,
4966 &BTRFS_I(inode)->runtime_flags);
4969 * 1 for the orphan item we're going to add
4970 * 1 for the orphan item deletion.
4972 trans = btrfs_start_transaction(root, 2);
4974 return PTR_ERR(trans);
4977 * We need to do this in case we fail at _any_ point during the
4978 * actual truncate. Once we do the truncate_setsize we could
4979 * invalidate pages which forces any outstanding ordered io to
4980 * be instantly completed which will give us extents that need
4981 * to be truncated. If we fail to get an orphan inode down we
4982 * could have left over extents that were never meant to live,
4983 * so we need to guarantee from this point on that everything
4984 * will be consistent.
4986 ret = btrfs_orphan_add(trans, BTRFS_I(inode));
4987 btrfs_end_transaction(trans);
4991 /* we don't support swapfiles, so vmtruncate shouldn't fail */
4992 truncate_setsize(inode, newsize);
4994 /* Disable nonlocked read DIO to avoid the end less truncate */
4995 btrfs_inode_block_unlocked_dio(BTRFS_I(inode));
4996 inode_dio_wait(inode);
4997 btrfs_inode_resume_unlocked_dio(BTRFS_I(inode));
4999 ret = btrfs_truncate(inode);
5000 if (ret && inode->i_nlink) {
5003 /* To get a stable disk_i_size */
5004 err = btrfs_wait_ordered_range(inode, 0, (u64)-1);
5006 btrfs_orphan_del(NULL, BTRFS_I(inode));
5011 * failed to truncate, disk_i_size is only adjusted down
5012 * as we remove extents, so it should represent the true
5013 * size of the inode, so reset the in memory size and
5014 * delete our orphan entry.
5016 trans = btrfs_join_transaction(root);
5017 if (IS_ERR(trans)) {
5018 btrfs_orphan_del(NULL, BTRFS_I(inode));
5021 i_size_write(inode, BTRFS_I(inode)->disk_i_size);
5022 err = btrfs_orphan_del(trans, BTRFS_I(inode));
5024 btrfs_abort_transaction(trans, err);
5025 btrfs_end_transaction(trans);
5032 static int btrfs_setattr(struct dentry *dentry, struct iattr *attr)
5034 struct inode *inode = d_inode(dentry);
5035 struct btrfs_root *root = BTRFS_I(inode)->root;
5038 if (btrfs_root_readonly(root))
5041 err = setattr_prepare(dentry, attr);
5045 if (S_ISREG(inode->i_mode) && (attr->ia_valid & ATTR_SIZE)) {
5046 err = btrfs_setsize(inode, attr);
5051 if (attr->ia_valid) {
5052 setattr_copy(inode, attr);
5053 inode_inc_iversion(inode);
5054 err = btrfs_dirty_inode(inode);
5056 if (!err && attr->ia_valid & ATTR_MODE)
5057 err = posix_acl_chmod(inode, inode->i_mode);
5064 * While truncating the inode pages during eviction, we get the VFS calling
5065 * btrfs_invalidatepage() against each page of the inode. This is slow because
5066 * the calls to btrfs_invalidatepage() result in a huge amount of calls to
5067 * lock_extent_bits() and clear_extent_bit(), which keep merging and splitting
5068 * extent_state structures over and over, wasting lots of time.
5070 * Therefore if the inode is being evicted, let btrfs_invalidatepage() skip all
5071 * those expensive operations on a per page basis and do only the ordered io
5072 * finishing, while we release here the extent_map and extent_state structures,
5073 * without the excessive merging and splitting.
5075 static void evict_inode_truncate_pages(struct inode *inode)
5077 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
5078 struct extent_map_tree *map_tree = &BTRFS_I(inode)->extent_tree;
5079 struct rb_node *node;
5081 ASSERT(inode->i_state & I_FREEING);
5082 truncate_inode_pages_final(&inode->i_data);
5084 write_lock(&map_tree->lock);
5085 while (!RB_EMPTY_ROOT(&map_tree->map)) {
5086 struct extent_map *em;
5088 node = rb_first(&map_tree->map);
5089 em = rb_entry(node, struct extent_map, rb_node);
5090 clear_bit(EXTENT_FLAG_PINNED, &em->flags);
5091 clear_bit(EXTENT_FLAG_LOGGING, &em->flags);
5092 remove_extent_mapping(map_tree, em);
5093 free_extent_map(em);
5094 if (need_resched()) {
5095 write_unlock(&map_tree->lock);
5097 write_lock(&map_tree->lock);
5100 write_unlock(&map_tree->lock);
5103 * Keep looping until we have no more ranges in the io tree.
5104 * We can have ongoing bios started by readpages (called from readahead)
5105 * that have their endio callback (extent_io.c:end_bio_extent_readpage)
5106 * still in progress (unlocked the pages in the bio but did not yet
5107 * unlocked the ranges in the io tree). Therefore this means some
5108 * ranges can still be locked and eviction started because before
5109 * submitting those bios, which are executed by a separate task (work
5110 * queue kthread), inode references (inode->i_count) were not taken
5111 * (which would be dropped in the end io callback of each bio).
5112 * Therefore here we effectively end up waiting for those bios and
5113 * anyone else holding locked ranges without having bumped the inode's
5114 * reference count - if we don't do it, when they access the inode's
5115 * io_tree to unlock a range it may be too late, leading to an
5116 * use-after-free issue.
5118 spin_lock(&io_tree->lock);
5119 while (!RB_EMPTY_ROOT(&io_tree->state)) {
5120 struct extent_state *state;
5121 struct extent_state *cached_state = NULL;
5125 node = rb_first(&io_tree->state);
5126 state = rb_entry(node, struct extent_state, rb_node);
5127 start = state->start;
5129 spin_unlock(&io_tree->lock);
5131 lock_extent_bits(io_tree, start, end, &cached_state);
5134 * If still has DELALLOC flag, the extent didn't reach disk,
5135 * and its reserved space won't be freed by delayed_ref.
5136 * So we need to free its reserved space here.
5137 * (Refer to comment in btrfs_invalidatepage, case 2)
5139 * Note, end is the bytenr of last byte, so we need + 1 here.
5141 if (state->state & EXTENT_DELALLOC)
5142 btrfs_qgroup_free_data(inode, start, end - start + 1);
5144 clear_extent_bit(io_tree, start, end,
5145 EXTENT_LOCKED | EXTENT_DIRTY |
5146 EXTENT_DELALLOC | EXTENT_DO_ACCOUNTING |
5147 EXTENT_DEFRAG, 1, 1,
5148 &cached_state, GFP_NOFS);
5151 spin_lock(&io_tree->lock);
5153 spin_unlock(&io_tree->lock);
5156 void btrfs_evict_inode(struct inode *inode)
5158 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
5159 struct btrfs_trans_handle *trans;
5160 struct btrfs_root *root = BTRFS_I(inode)->root;
5161 struct btrfs_block_rsv *rsv, *global_rsv;
5162 int steal_from_global = 0;
5166 trace_btrfs_inode_evict(inode);
5169 kmem_cache_free(btrfs_inode_cachep, BTRFS_I(inode));
5173 min_size = btrfs_calc_trunc_metadata_size(fs_info, 1);
5175 evict_inode_truncate_pages(inode);
5177 if (inode->i_nlink &&
5178 ((btrfs_root_refs(&root->root_item) != 0 &&
5179 root->root_key.objectid != BTRFS_ROOT_TREE_OBJECTID) ||
5180 btrfs_is_free_space_inode(BTRFS_I(inode))))
5183 if (is_bad_inode(inode)) {
5184 btrfs_orphan_del(NULL, BTRFS_I(inode));
5187 /* do we really want it for ->i_nlink > 0 and zero btrfs_root_refs? */
5188 if (!special_file(inode->i_mode))
5189 btrfs_wait_ordered_range(inode, 0, (u64)-1);
5191 btrfs_free_io_failure_record(BTRFS_I(inode), 0, (u64)-1);
5193 if (test_bit(BTRFS_FS_LOG_RECOVERING, &fs_info->flags)) {
5194 BUG_ON(test_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
5195 &BTRFS_I(inode)->runtime_flags));
5199 if (inode->i_nlink > 0) {
5200 BUG_ON(btrfs_root_refs(&root->root_item) != 0 &&
5201 root->root_key.objectid != BTRFS_ROOT_TREE_OBJECTID);
5205 ret = btrfs_commit_inode_delayed_inode(BTRFS_I(inode));
5207 btrfs_orphan_del(NULL, BTRFS_I(inode));
5211 rsv = btrfs_alloc_block_rsv(fs_info, BTRFS_BLOCK_RSV_TEMP);
5213 btrfs_orphan_del(NULL, BTRFS_I(inode));
5216 rsv->size = min_size;
5218 global_rsv = &fs_info->global_block_rsv;
5220 btrfs_i_size_write(BTRFS_I(inode), 0);
5223 * This is a bit simpler than btrfs_truncate since we've already
5224 * reserved our space for our orphan item in the unlink, so we just
5225 * need to reserve some slack space in case we add bytes and update
5226 * inode item when doing the truncate.
5229 ret = btrfs_block_rsv_refill(root, rsv, min_size,
5230 BTRFS_RESERVE_FLUSH_LIMIT);
5233 * Try and steal from the global reserve since we will
5234 * likely not use this space anyway, we want to try as
5235 * hard as possible to get this to work.
5238 steal_from_global++;
5240 steal_from_global = 0;
5244 * steal_from_global == 0: we reserved stuff, hooray!
5245 * steal_from_global == 1: we didn't reserve stuff, boo!
5246 * steal_from_global == 2: we've committed, still not a lot of
5247 * room but maybe we'll have room in the global reserve this
5249 * steal_from_global == 3: abandon all hope!
5251 if (steal_from_global > 2) {
5253 "Could not get space for a delete, will truncate on mount %d",
5255 btrfs_orphan_del(NULL, BTRFS_I(inode));
5256 btrfs_free_block_rsv(fs_info, rsv);
5260 trans = btrfs_join_transaction(root);
5261 if (IS_ERR(trans)) {
5262 btrfs_orphan_del(NULL, BTRFS_I(inode));
5263 btrfs_free_block_rsv(fs_info, rsv);
5268 * We can't just steal from the global reserve, we need to make
5269 * sure there is room to do it, if not we need to commit and try
5272 if (steal_from_global) {
5273 if (!btrfs_check_space_for_delayed_refs(trans, fs_info))
5274 ret = btrfs_block_rsv_migrate(global_rsv, rsv,
5281 * Couldn't steal from the global reserve, we have too much
5282 * pending stuff built up, commit the transaction and try it
5286 ret = btrfs_commit_transaction(trans);
5288 btrfs_orphan_del(NULL, BTRFS_I(inode));
5289 btrfs_free_block_rsv(fs_info, rsv);
5294 steal_from_global = 0;
5297 trans->block_rsv = rsv;
5299 ret = btrfs_truncate_inode_items(trans, root, inode, 0, 0);
5300 if (ret != -ENOSPC && ret != -EAGAIN)
5303 trans->block_rsv = &fs_info->trans_block_rsv;
5304 btrfs_end_transaction(trans);
5306 btrfs_btree_balance_dirty(fs_info);
5309 btrfs_free_block_rsv(fs_info, rsv);
5312 * Errors here aren't a big deal, it just means we leave orphan items
5313 * in the tree. They will be cleaned up on the next mount.
5316 trans->block_rsv = root->orphan_block_rsv;
5317 btrfs_orphan_del(trans, BTRFS_I(inode));
5319 btrfs_orphan_del(NULL, BTRFS_I(inode));
5322 trans->block_rsv = &fs_info->trans_block_rsv;
5323 if (!(root == fs_info->tree_root ||
5324 root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID))
5325 btrfs_return_ino(root, btrfs_ino(BTRFS_I(inode)));
5327 btrfs_end_transaction(trans);
5328 btrfs_btree_balance_dirty(fs_info);
5330 btrfs_remove_delayed_node(BTRFS_I(inode));
5335 * this returns the key found in the dir entry in the location pointer.
5336 * If no dir entries were found, location->objectid is 0.
5338 static int btrfs_inode_by_name(struct inode *dir, struct dentry *dentry,
5339 struct btrfs_key *location)
5341 const char *name = dentry->d_name.name;
5342 int namelen = dentry->d_name.len;
5343 struct btrfs_dir_item *di;
5344 struct btrfs_path *path;
5345 struct btrfs_root *root = BTRFS_I(dir)->root;
5348 path = btrfs_alloc_path();
5352 di = btrfs_lookup_dir_item(NULL, root, path, btrfs_ino(BTRFS_I(dir)),
5357 if (IS_ERR_OR_NULL(di))
5360 btrfs_dir_item_key_to_cpu(path->nodes[0], di, location);
5362 btrfs_free_path(path);
5365 location->objectid = 0;
5370 * when we hit a tree root in a directory, the btrfs part of the inode
5371 * needs to be changed to reflect the root directory of the tree root. This
5372 * is kind of like crossing a mount point.
5374 static int fixup_tree_root_location(struct btrfs_fs_info *fs_info,
5376 struct dentry *dentry,
5377 struct btrfs_key *location,
5378 struct btrfs_root **sub_root)
5380 struct btrfs_path *path;
5381 struct btrfs_root *new_root;
5382 struct btrfs_root_ref *ref;
5383 struct extent_buffer *leaf;
5384 struct btrfs_key key;
5388 path = btrfs_alloc_path();
5395 key.objectid = BTRFS_I(dir)->root->root_key.objectid;
5396 key.type = BTRFS_ROOT_REF_KEY;
5397 key.offset = location->objectid;
5399 ret = btrfs_search_slot(NULL, fs_info->tree_root, &key, path, 0, 0);
5406 leaf = path->nodes[0];
5407 ref = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_root_ref);
5408 if (btrfs_root_ref_dirid(leaf, ref) != btrfs_ino(BTRFS_I(dir)) ||
5409 btrfs_root_ref_name_len(leaf, ref) != dentry->d_name.len)
5412 ret = memcmp_extent_buffer(leaf, dentry->d_name.name,
5413 (unsigned long)(ref + 1),
5414 dentry->d_name.len);
5418 btrfs_release_path(path);
5420 new_root = btrfs_read_fs_root_no_name(fs_info, location);
5421 if (IS_ERR(new_root)) {
5422 err = PTR_ERR(new_root);
5426 *sub_root = new_root;
5427 location->objectid = btrfs_root_dirid(&new_root->root_item);
5428 location->type = BTRFS_INODE_ITEM_KEY;
5429 location->offset = 0;
5432 btrfs_free_path(path);
5436 static void inode_tree_add(struct inode *inode)
5438 struct btrfs_root *root = BTRFS_I(inode)->root;
5439 struct btrfs_inode *entry;
5441 struct rb_node *parent;
5442 struct rb_node *new = &BTRFS_I(inode)->rb_node;
5443 u64 ino = btrfs_ino(BTRFS_I(inode));
5445 if (inode_unhashed(inode))
5448 spin_lock(&root->inode_lock);
5449 p = &root->inode_tree.rb_node;
5452 entry = rb_entry(parent, struct btrfs_inode, rb_node);
5454 if (ino < btrfs_ino(BTRFS_I(&entry->vfs_inode)))
5455 p = &parent->rb_left;
5456 else if (ino > btrfs_ino(BTRFS_I(&entry->vfs_inode)))
5457 p = &parent->rb_right;
5459 WARN_ON(!(entry->vfs_inode.i_state &
5460 (I_WILL_FREE | I_FREEING)));
5461 rb_replace_node(parent, new, &root->inode_tree);
5462 RB_CLEAR_NODE(parent);
5463 spin_unlock(&root->inode_lock);
5467 rb_link_node(new, parent, p);
5468 rb_insert_color(new, &root->inode_tree);
5469 spin_unlock(&root->inode_lock);
5472 static void inode_tree_del(struct inode *inode)
5474 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
5475 struct btrfs_root *root = BTRFS_I(inode)->root;
5478 spin_lock(&root->inode_lock);
5479 if (!RB_EMPTY_NODE(&BTRFS_I(inode)->rb_node)) {
5480 rb_erase(&BTRFS_I(inode)->rb_node, &root->inode_tree);
5481 RB_CLEAR_NODE(&BTRFS_I(inode)->rb_node);
5482 empty = RB_EMPTY_ROOT(&root->inode_tree);
5484 spin_unlock(&root->inode_lock);
5486 if (empty && btrfs_root_refs(&root->root_item) == 0) {
5487 synchronize_srcu(&fs_info->subvol_srcu);
5488 spin_lock(&root->inode_lock);
5489 empty = RB_EMPTY_ROOT(&root->inode_tree);
5490 spin_unlock(&root->inode_lock);
5492 btrfs_add_dead_root(root);
5496 void btrfs_invalidate_inodes(struct btrfs_root *root)
5498 struct btrfs_fs_info *fs_info = root->fs_info;
5499 struct rb_node *node;
5500 struct rb_node *prev;
5501 struct btrfs_inode *entry;
5502 struct inode *inode;
5505 if (!test_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state))
5506 WARN_ON(btrfs_root_refs(&root->root_item) != 0);
5508 spin_lock(&root->inode_lock);
5510 node = root->inode_tree.rb_node;
5514 entry = rb_entry(node, struct btrfs_inode, rb_node);
5516 if (objectid < btrfs_ino(BTRFS_I(&entry->vfs_inode)))
5517 node = node->rb_left;
5518 else if (objectid > btrfs_ino(BTRFS_I(&entry->vfs_inode)))
5519 node = node->rb_right;
5525 entry = rb_entry(prev, struct btrfs_inode, rb_node);
5526 if (objectid <= btrfs_ino(BTRFS_I(&entry->vfs_inode))) {
5530 prev = rb_next(prev);
5534 entry = rb_entry(node, struct btrfs_inode, rb_node);
5535 objectid = btrfs_ino(BTRFS_I(&entry->vfs_inode)) + 1;
5536 inode = igrab(&entry->vfs_inode);
5538 spin_unlock(&root->inode_lock);
5539 if (atomic_read(&inode->i_count) > 1)
5540 d_prune_aliases(inode);
5542 * btrfs_drop_inode will have it removed from
5543 * the inode cache when its usage count
5548 spin_lock(&root->inode_lock);
5552 if (cond_resched_lock(&root->inode_lock))
5555 node = rb_next(node);
5557 spin_unlock(&root->inode_lock);
5560 static int btrfs_init_locked_inode(struct inode *inode, void *p)
5562 struct btrfs_iget_args *args = p;
5563 inode->i_ino = args->location->objectid;
5564 memcpy(&BTRFS_I(inode)->location, args->location,
5565 sizeof(*args->location));
5566 BTRFS_I(inode)->root = args->root;
5570 static int btrfs_find_actor(struct inode *inode, void *opaque)
5572 struct btrfs_iget_args *args = opaque;
5573 return args->location->objectid == BTRFS_I(inode)->location.objectid &&
5574 args->root == BTRFS_I(inode)->root;
5577 static struct inode *btrfs_iget_locked(struct super_block *s,
5578 struct btrfs_key *location,
5579 struct btrfs_root *root)
5581 struct inode *inode;
5582 struct btrfs_iget_args args;
5583 unsigned long hashval = btrfs_inode_hash(location->objectid, root);
5585 args.location = location;
5588 inode = iget5_locked(s, hashval, btrfs_find_actor,
5589 btrfs_init_locked_inode,
5594 /* Get an inode object given its location and corresponding root.
5595 * Returns in *is_new if the inode was read from disk
5597 struct inode *btrfs_iget(struct super_block *s, struct btrfs_key *location,
5598 struct btrfs_root *root, int *new)
5600 struct inode *inode;
5602 inode = btrfs_iget_locked(s, location, root);
5604 return ERR_PTR(-ENOMEM);
5606 if (inode->i_state & I_NEW) {
5609 ret = btrfs_read_locked_inode(inode);
5610 if (!is_bad_inode(inode)) {
5611 inode_tree_add(inode);
5612 unlock_new_inode(inode);
5616 unlock_new_inode(inode);
5619 inode = ERR_PTR(ret < 0 ? ret : -ESTALE);
5626 static struct inode *new_simple_dir(struct super_block *s,
5627 struct btrfs_key *key,
5628 struct btrfs_root *root)
5630 struct inode *inode = new_inode(s);
5633 return ERR_PTR(-ENOMEM);
5635 BTRFS_I(inode)->root = root;
5636 memcpy(&BTRFS_I(inode)->location, key, sizeof(*key));
5637 set_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags);
5639 inode->i_ino = BTRFS_EMPTY_SUBVOL_DIR_OBJECTID;
5640 inode->i_op = &btrfs_dir_ro_inode_operations;
5641 inode->i_opflags &= ~IOP_XATTR;
5642 inode->i_fop = &simple_dir_operations;
5643 inode->i_mode = S_IFDIR | S_IRUGO | S_IWUSR | S_IXUGO;
5644 inode->i_mtime = current_time(inode);
5645 inode->i_atime = inode->i_mtime;
5646 inode->i_ctime = inode->i_mtime;
5647 BTRFS_I(inode)->i_otime = inode->i_mtime;
5652 struct inode *btrfs_lookup_dentry(struct inode *dir, struct dentry *dentry)
5654 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
5655 struct inode *inode;
5656 struct btrfs_root *root = BTRFS_I(dir)->root;
5657 struct btrfs_root *sub_root = root;
5658 struct btrfs_key location;
5662 if (dentry->d_name.len > BTRFS_NAME_LEN)
5663 return ERR_PTR(-ENAMETOOLONG);
5665 ret = btrfs_inode_by_name(dir, dentry, &location);
5667 return ERR_PTR(ret);
5669 if (location.objectid == 0)
5670 return ERR_PTR(-ENOENT);
5672 if (location.type == BTRFS_INODE_ITEM_KEY) {
5673 inode = btrfs_iget(dir->i_sb, &location, root, NULL);
5677 BUG_ON(location.type != BTRFS_ROOT_ITEM_KEY);
5679 index = srcu_read_lock(&fs_info->subvol_srcu);
5680 ret = fixup_tree_root_location(fs_info, dir, dentry,
5681 &location, &sub_root);
5684 inode = ERR_PTR(ret);
5686 inode = new_simple_dir(dir->i_sb, &location, sub_root);
5688 inode = btrfs_iget(dir->i_sb, &location, sub_root, NULL);
5690 srcu_read_unlock(&fs_info->subvol_srcu, index);
5692 if (!IS_ERR(inode) && root != sub_root) {
5693 down_read(&fs_info->cleanup_work_sem);
5694 if (!(inode->i_sb->s_flags & MS_RDONLY))
5695 ret = btrfs_orphan_cleanup(sub_root);
5696 up_read(&fs_info->cleanup_work_sem);
5699 inode = ERR_PTR(ret);
5706 static int btrfs_dentry_delete(const struct dentry *dentry)
5708 struct btrfs_root *root;
5709 struct inode *inode = d_inode(dentry);
5711 if (!inode && !IS_ROOT(dentry))
5712 inode = d_inode(dentry->d_parent);
5715 root = BTRFS_I(inode)->root;
5716 if (btrfs_root_refs(&root->root_item) == 0)
5719 if (btrfs_ino(BTRFS_I(inode)) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)
5725 static void btrfs_dentry_release(struct dentry *dentry)
5727 kfree(dentry->d_fsdata);
5730 static struct dentry *btrfs_lookup(struct inode *dir, struct dentry *dentry,
5733 struct inode *inode;
5735 inode = btrfs_lookup_dentry(dir, dentry);
5736 if (IS_ERR(inode)) {
5737 if (PTR_ERR(inode) == -ENOENT)
5740 return ERR_CAST(inode);
5743 return d_splice_alias(inode, dentry);
5746 unsigned char btrfs_filetype_table[] = {
5747 DT_UNKNOWN, DT_REG, DT_DIR, DT_CHR, DT_BLK, DT_FIFO, DT_SOCK, DT_LNK
5750 static int btrfs_real_readdir(struct file *file, struct dir_context *ctx)
5752 struct inode *inode = file_inode(file);
5753 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
5754 struct btrfs_root *root = BTRFS_I(inode)->root;
5755 struct btrfs_item *item;
5756 struct btrfs_dir_item *di;
5757 struct btrfs_key key;
5758 struct btrfs_key found_key;
5759 struct btrfs_path *path;
5760 struct list_head ins_list;
5761 struct list_head del_list;
5763 struct extent_buffer *leaf;
5765 unsigned char d_type;
5771 struct btrfs_key location;
5773 if (!dir_emit_dots(file, ctx))
5776 path = btrfs_alloc_path();
5780 path->reada = READA_FORWARD;
5782 INIT_LIST_HEAD(&ins_list);
5783 INIT_LIST_HEAD(&del_list);
5784 put = btrfs_readdir_get_delayed_items(inode, &ins_list, &del_list);
5786 key.type = BTRFS_DIR_INDEX_KEY;
5787 key.offset = ctx->pos;
5788 key.objectid = btrfs_ino(BTRFS_I(inode));
5790 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
5795 leaf = path->nodes[0];
5796 slot = path->slots[0];
5797 if (slot >= btrfs_header_nritems(leaf)) {
5798 ret = btrfs_next_leaf(root, path);
5806 item = btrfs_item_nr(slot);
5807 btrfs_item_key_to_cpu(leaf, &found_key, slot);
5809 if (found_key.objectid != key.objectid)
5811 if (found_key.type != BTRFS_DIR_INDEX_KEY)
5813 if (found_key.offset < ctx->pos)
5815 if (btrfs_should_delete_dir_index(&del_list, found_key.offset))
5818 ctx->pos = found_key.offset;
5820 di = btrfs_item_ptr(leaf, slot, struct btrfs_dir_item);
5821 if (verify_dir_item(fs_info, leaf, di))
5824 name_len = btrfs_dir_name_len(leaf, di);
5825 if (name_len <= sizeof(tmp_name)) {
5826 name_ptr = tmp_name;
5828 name_ptr = kmalloc(name_len, GFP_KERNEL);
5834 read_extent_buffer(leaf, name_ptr, (unsigned long)(di + 1),
5837 d_type = btrfs_filetype_table[btrfs_dir_type(leaf, di)];
5838 btrfs_dir_item_key_to_cpu(leaf, di, &location);
5840 over = !dir_emit(ctx, name_ptr, name_len, location.objectid,
5843 if (name_ptr != tmp_name)
5853 ret = btrfs_readdir_delayed_dir_index(ctx, &ins_list);
5858 * Stop new entries from being returned after we return the last
5861 * New directory entries are assigned a strictly increasing
5862 * offset. This means that new entries created during readdir
5863 * are *guaranteed* to be seen in the future by that readdir.
5864 * This has broken buggy programs which operate on names as
5865 * they're returned by readdir. Until we re-use freed offsets
5866 * we have this hack to stop new entries from being returned
5867 * under the assumption that they'll never reach this huge
5870 * This is being careful not to overflow 32bit loff_t unless the
5871 * last entry requires it because doing so has broken 32bit apps
5874 if (ctx->pos >= INT_MAX)
5875 ctx->pos = LLONG_MAX;
5882 btrfs_readdir_put_delayed_items(inode, &ins_list, &del_list);
5883 btrfs_free_path(path);
5887 int btrfs_write_inode(struct inode *inode, struct writeback_control *wbc)
5889 struct btrfs_root *root = BTRFS_I(inode)->root;
5890 struct btrfs_trans_handle *trans;
5892 bool nolock = false;
5894 if (test_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags))
5897 if (btrfs_fs_closing(root->fs_info) &&
5898 btrfs_is_free_space_inode(BTRFS_I(inode)))
5901 if (wbc->sync_mode == WB_SYNC_ALL) {
5903 trans = btrfs_join_transaction_nolock(root);
5905 trans = btrfs_join_transaction(root);
5907 return PTR_ERR(trans);
5908 ret = btrfs_commit_transaction(trans);
5914 * This is somewhat expensive, updating the tree every time the
5915 * inode changes. But, it is most likely to find the inode in cache.
5916 * FIXME, needs more benchmarking...there are no reasons other than performance
5917 * to keep or drop this code.
5919 static int btrfs_dirty_inode(struct inode *inode)
5921 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
5922 struct btrfs_root *root = BTRFS_I(inode)->root;
5923 struct btrfs_trans_handle *trans;
5926 if (test_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags))
5929 trans = btrfs_join_transaction(root);
5931 return PTR_ERR(trans);
5933 ret = btrfs_update_inode(trans, root, inode);
5934 if (ret && ret == -ENOSPC) {
5935 /* whoops, lets try again with the full transaction */
5936 btrfs_end_transaction(trans);
5937 trans = btrfs_start_transaction(root, 1);
5939 return PTR_ERR(trans);
5941 ret = btrfs_update_inode(trans, root, inode);
5943 btrfs_end_transaction(trans);
5944 if (BTRFS_I(inode)->delayed_node)
5945 btrfs_balance_delayed_items(fs_info);
5951 * This is a copy of file_update_time. We need this so we can return error on
5952 * ENOSPC for updating the inode in the case of file write and mmap writes.
5954 static int btrfs_update_time(struct inode *inode, struct timespec *now,
5957 struct btrfs_root *root = BTRFS_I(inode)->root;
5959 if (btrfs_root_readonly(root))
5962 if (flags & S_VERSION)
5963 inode_inc_iversion(inode);
5964 if (flags & S_CTIME)
5965 inode->i_ctime = *now;
5966 if (flags & S_MTIME)
5967 inode->i_mtime = *now;
5968 if (flags & S_ATIME)
5969 inode->i_atime = *now;
5970 return btrfs_dirty_inode(inode);
5974 * find the highest existing sequence number in a directory
5975 * and then set the in-memory index_cnt variable to reflect
5976 * free sequence numbers
5978 static int btrfs_set_inode_index_count(struct btrfs_inode *inode)
5980 struct btrfs_root *root = inode->root;
5981 struct btrfs_key key, found_key;
5982 struct btrfs_path *path;
5983 struct extent_buffer *leaf;
5986 key.objectid = btrfs_ino(inode);
5987 key.type = BTRFS_DIR_INDEX_KEY;
5988 key.offset = (u64)-1;
5990 path = btrfs_alloc_path();
5994 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
5997 /* FIXME: we should be able to handle this */
6003 * MAGIC NUMBER EXPLANATION:
6004 * since we search a directory based on f_pos we have to start at 2
6005 * since '.' and '..' have f_pos of 0 and 1 respectively, so everybody
6006 * else has to start at 2
6008 if (path->slots[0] == 0) {
6009 inode->index_cnt = 2;
6015 leaf = path->nodes[0];
6016 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
6018 if (found_key.objectid != btrfs_ino(inode) ||
6019 found_key.type != BTRFS_DIR_INDEX_KEY) {
6020 inode->index_cnt = 2;
6024 inode->index_cnt = found_key.offset + 1;
6026 btrfs_free_path(path);
6031 * helper to find a free sequence number in a given directory. This current
6032 * code is very simple, later versions will do smarter things in the btree
6034 int btrfs_set_inode_index(struct btrfs_inode *dir, u64 *index)
6038 if (dir->index_cnt == (u64)-1) {
6039 ret = btrfs_inode_delayed_dir_index_count(dir);
6041 ret = btrfs_set_inode_index_count(dir);
6047 *index = dir->index_cnt;
6053 static int btrfs_insert_inode_locked(struct inode *inode)
6055 struct btrfs_iget_args args;
6056 args.location = &BTRFS_I(inode)->location;
6057 args.root = BTRFS_I(inode)->root;
6059 return insert_inode_locked4(inode,
6060 btrfs_inode_hash(inode->i_ino, BTRFS_I(inode)->root),
6061 btrfs_find_actor, &args);
6064 static struct inode *btrfs_new_inode(struct btrfs_trans_handle *trans,
6065 struct btrfs_root *root,
6067 const char *name, int name_len,
6068 u64 ref_objectid, u64 objectid,
6069 umode_t mode, u64 *index)
6071 struct btrfs_fs_info *fs_info = root->fs_info;
6072 struct inode *inode;
6073 struct btrfs_inode_item *inode_item;
6074 struct btrfs_key *location;
6075 struct btrfs_path *path;
6076 struct btrfs_inode_ref *ref;
6077 struct btrfs_key key[2];
6079 int nitems = name ? 2 : 1;
6083 path = btrfs_alloc_path();
6085 return ERR_PTR(-ENOMEM);
6087 inode = new_inode(fs_info->sb);
6089 btrfs_free_path(path);
6090 return ERR_PTR(-ENOMEM);
6094 * O_TMPFILE, set link count to 0, so that after this point,
6095 * we fill in an inode item with the correct link count.
6098 set_nlink(inode, 0);
6101 * we have to initialize this early, so we can reclaim the inode
6102 * number if we fail afterwards in this function.
6104 inode->i_ino = objectid;
6107 trace_btrfs_inode_request(dir);
6109 ret = btrfs_set_inode_index(BTRFS_I(dir), index);
6111 btrfs_free_path(path);
6113 return ERR_PTR(ret);
6119 * index_cnt is ignored for everything but a dir,
6120 * btrfs_get_inode_index_count has an explanation for the magic
6123 BTRFS_I(inode)->index_cnt = 2;
6124 BTRFS_I(inode)->dir_index = *index;
6125 BTRFS_I(inode)->root = root;
6126 BTRFS_I(inode)->generation = trans->transid;
6127 inode->i_generation = BTRFS_I(inode)->generation;
6130 * We could have gotten an inode number from somebody who was fsynced
6131 * and then removed in this same transaction, so let's just set full
6132 * sync since it will be a full sync anyway and this will blow away the
6133 * old info in the log.
6135 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &BTRFS_I(inode)->runtime_flags);
6137 key[0].objectid = objectid;
6138 key[0].type = BTRFS_INODE_ITEM_KEY;
6141 sizes[0] = sizeof(struct btrfs_inode_item);
6145 * Start new inodes with an inode_ref. This is slightly more
6146 * efficient for small numbers of hard links since they will
6147 * be packed into one item. Extended refs will kick in if we
6148 * add more hard links than can fit in the ref item.
6150 key[1].objectid = objectid;
6151 key[1].type = BTRFS_INODE_REF_KEY;
6152 key[1].offset = ref_objectid;
6154 sizes[1] = name_len + sizeof(*ref);
6157 location = &BTRFS_I(inode)->location;
6158 location->objectid = objectid;
6159 location->offset = 0;
6160 location->type = BTRFS_INODE_ITEM_KEY;
6162 ret = btrfs_insert_inode_locked(inode);
6166 path->leave_spinning = 1;
6167 ret = btrfs_insert_empty_items(trans, root, path, key, sizes, nitems);
6171 inode_init_owner(inode, dir, mode);
6172 inode_set_bytes(inode, 0);
6174 inode->i_mtime = current_time(inode);
6175 inode->i_atime = inode->i_mtime;
6176 inode->i_ctime = inode->i_mtime;
6177 BTRFS_I(inode)->i_otime = inode->i_mtime;
6179 inode_item = btrfs_item_ptr(path->nodes[0], path->slots[0],
6180 struct btrfs_inode_item);
6181 memzero_extent_buffer(path->nodes[0], (unsigned long)inode_item,
6182 sizeof(*inode_item));
6183 fill_inode_item(trans, path->nodes[0], inode_item, inode);
6186 ref = btrfs_item_ptr(path->nodes[0], path->slots[0] + 1,
6187 struct btrfs_inode_ref);
6188 btrfs_set_inode_ref_name_len(path->nodes[0], ref, name_len);
6189 btrfs_set_inode_ref_index(path->nodes[0], ref, *index);
6190 ptr = (unsigned long)(ref + 1);
6191 write_extent_buffer(path->nodes[0], name, ptr, name_len);
6194 btrfs_mark_buffer_dirty(path->nodes[0]);
6195 btrfs_free_path(path);
6197 btrfs_inherit_iflags(inode, dir);
6199 if (S_ISREG(mode)) {
6200 if (btrfs_test_opt(fs_info, NODATASUM))
6201 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATASUM;
6202 if (btrfs_test_opt(fs_info, NODATACOW))
6203 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATACOW |
6204 BTRFS_INODE_NODATASUM;
6207 inode_tree_add(inode);
6209 trace_btrfs_inode_new(inode);
6210 btrfs_set_inode_last_trans(trans, inode);
6212 btrfs_update_root_times(trans, root);
6214 ret = btrfs_inode_inherit_props(trans, inode, dir);
6217 "error inheriting props for ino %llu (root %llu): %d",
6218 btrfs_ino(BTRFS_I(inode)), root->root_key.objectid, ret);
6223 unlock_new_inode(inode);
6226 BTRFS_I(dir)->index_cnt--;
6227 btrfs_free_path(path);
6229 return ERR_PTR(ret);
6232 static inline u8 btrfs_inode_type(struct inode *inode)
6234 return btrfs_type_by_mode[(inode->i_mode & S_IFMT) >> S_SHIFT];
6238 * utility function to add 'inode' into 'parent_inode' with
6239 * a give name and a given sequence number.
6240 * if 'add_backref' is true, also insert a backref from the
6241 * inode to the parent directory.
6243 int btrfs_add_link(struct btrfs_trans_handle *trans,
6244 struct btrfs_inode *parent_inode, struct btrfs_inode *inode,
6245 const char *name, int name_len, int add_backref, u64 index)
6247 struct btrfs_fs_info *fs_info = btrfs_sb(inode->vfs_inode.i_sb);
6249 struct btrfs_key key;
6250 struct btrfs_root *root = parent_inode->root;
6251 u64 ino = btrfs_ino(inode);
6252 u64 parent_ino = btrfs_ino(parent_inode);
6254 if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
6255 memcpy(&key, &inode->root->root_key, sizeof(key));
6258 key.type = BTRFS_INODE_ITEM_KEY;
6262 if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
6263 ret = btrfs_add_root_ref(trans, fs_info, key.objectid,
6264 root->root_key.objectid, parent_ino,
6265 index, name, name_len);
6266 } else if (add_backref) {
6267 ret = btrfs_insert_inode_ref(trans, root, name, name_len, ino,
6271 /* Nothing to clean up yet */
6275 ret = btrfs_insert_dir_item(trans, root, name, name_len,
6277 btrfs_inode_type(&inode->vfs_inode), index);
6278 if (ret == -EEXIST || ret == -EOVERFLOW)
6281 btrfs_abort_transaction(trans, ret);
6285 btrfs_i_size_write(parent_inode, parent_inode->vfs_inode.i_size +
6287 inode_inc_iversion(&parent_inode->vfs_inode);
6288 parent_inode->vfs_inode.i_mtime = parent_inode->vfs_inode.i_ctime =
6289 current_time(&parent_inode->vfs_inode);
6290 ret = btrfs_update_inode(trans, root, &parent_inode->vfs_inode);
6292 btrfs_abort_transaction(trans, ret);
6296 if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
6299 err = btrfs_del_root_ref(trans, fs_info, key.objectid,
6300 root->root_key.objectid, parent_ino,
6301 &local_index, name, name_len);
6303 } else if (add_backref) {
6307 err = btrfs_del_inode_ref(trans, root, name, name_len,
6308 ino, parent_ino, &local_index);
6313 static int btrfs_add_nondir(struct btrfs_trans_handle *trans,
6314 struct btrfs_inode *dir, struct dentry *dentry,
6315 struct btrfs_inode *inode, int backref, u64 index)
6317 int err = btrfs_add_link(trans, dir, inode,
6318 dentry->d_name.name, dentry->d_name.len,
6325 static int btrfs_mknod(struct inode *dir, struct dentry *dentry,
6326 umode_t mode, dev_t rdev)
6328 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
6329 struct btrfs_trans_handle *trans;
6330 struct btrfs_root *root = BTRFS_I(dir)->root;
6331 struct inode *inode = NULL;
6338 * 2 for inode item and ref
6340 * 1 for xattr if selinux is on
6342 trans = btrfs_start_transaction(root, 5);
6344 return PTR_ERR(trans);
6346 err = btrfs_find_free_ino(root, &objectid);
6350 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
6351 dentry->d_name.len, btrfs_ino(BTRFS_I(dir)), objectid,
6353 if (IS_ERR(inode)) {
6354 err = PTR_ERR(inode);
6359 * If the active LSM wants to access the inode during
6360 * d_instantiate it needs these. Smack checks to see
6361 * if the filesystem supports xattrs by looking at the
6364 inode->i_op = &btrfs_special_inode_operations;
6365 init_special_inode(inode, inode->i_mode, rdev);
6367 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
6369 goto out_unlock_inode;
6371 err = btrfs_add_nondir(trans, BTRFS_I(dir), dentry, BTRFS_I(inode),
6374 goto out_unlock_inode;
6376 btrfs_update_inode(trans, root, inode);
6377 unlock_new_inode(inode);
6378 d_instantiate(dentry, inode);
6382 btrfs_end_transaction(trans);
6383 btrfs_balance_delayed_items(fs_info);
6384 btrfs_btree_balance_dirty(fs_info);
6386 inode_dec_link_count(inode);
6393 unlock_new_inode(inode);
6398 static int btrfs_create(struct inode *dir, struct dentry *dentry,
6399 umode_t mode, bool excl)
6401 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
6402 struct btrfs_trans_handle *trans;
6403 struct btrfs_root *root = BTRFS_I(dir)->root;
6404 struct inode *inode = NULL;
6405 int drop_inode_on_err = 0;
6411 * 2 for inode item and ref
6413 * 1 for xattr if selinux is on
6415 trans = btrfs_start_transaction(root, 5);
6417 return PTR_ERR(trans);
6419 err = btrfs_find_free_ino(root, &objectid);
6423 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
6424 dentry->d_name.len, btrfs_ino(BTRFS_I(dir)), objectid,
6426 if (IS_ERR(inode)) {
6427 err = PTR_ERR(inode);
6430 drop_inode_on_err = 1;
6432 * If the active LSM wants to access the inode during
6433 * d_instantiate it needs these. Smack checks to see
6434 * if the filesystem supports xattrs by looking at the
6437 inode->i_fop = &btrfs_file_operations;
6438 inode->i_op = &btrfs_file_inode_operations;
6439 inode->i_mapping->a_ops = &btrfs_aops;
6441 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
6443 goto out_unlock_inode;
6445 err = btrfs_update_inode(trans, root, inode);
6447 goto out_unlock_inode;
6449 err = btrfs_add_nondir(trans, BTRFS_I(dir), dentry, BTRFS_I(inode),
6452 goto out_unlock_inode;
6454 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
6455 unlock_new_inode(inode);
6456 d_instantiate(dentry, inode);
6459 btrfs_end_transaction(trans);
6460 if (err && drop_inode_on_err) {
6461 inode_dec_link_count(inode);
6464 btrfs_balance_delayed_items(fs_info);
6465 btrfs_btree_balance_dirty(fs_info);
6469 unlock_new_inode(inode);
6474 static int btrfs_link(struct dentry *old_dentry, struct inode *dir,
6475 struct dentry *dentry)
6477 struct btrfs_trans_handle *trans = NULL;
6478 struct btrfs_root *root = BTRFS_I(dir)->root;
6479 struct inode *inode = d_inode(old_dentry);
6480 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
6485 /* do not allow sys_link's with other subvols of the same device */
6486 if (root->objectid != BTRFS_I(inode)->root->objectid)
6489 if (inode->i_nlink >= BTRFS_LINK_MAX)
6492 err = btrfs_set_inode_index(BTRFS_I(dir), &index);
6497 * 2 items for inode and inode ref
6498 * 2 items for dir items
6499 * 1 item for parent inode
6501 trans = btrfs_start_transaction(root, 5);
6502 if (IS_ERR(trans)) {
6503 err = PTR_ERR(trans);
6508 /* There are several dir indexes for this inode, clear the cache. */
6509 BTRFS_I(inode)->dir_index = 0ULL;
6511 inode_inc_iversion(inode);
6512 inode->i_ctime = current_time(inode);
6514 set_bit(BTRFS_INODE_COPY_EVERYTHING, &BTRFS_I(inode)->runtime_flags);
6516 err = btrfs_add_nondir(trans, BTRFS_I(dir), dentry, BTRFS_I(inode),
6522 struct dentry *parent = dentry->d_parent;
6523 err = btrfs_update_inode(trans, root, inode);
6526 if (inode->i_nlink == 1) {
6528 * If new hard link count is 1, it's a file created
6529 * with open(2) O_TMPFILE flag.
6531 err = btrfs_orphan_del(trans, BTRFS_I(inode));
6535 d_instantiate(dentry, inode);
6536 btrfs_log_new_name(trans, BTRFS_I(inode), NULL, parent);
6539 btrfs_balance_delayed_items(fs_info);
6542 btrfs_end_transaction(trans);
6544 inode_dec_link_count(inode);
6547 btrfs_btree_balance_dirty(fs_info);
6551 static int btrfs_mkdir(struct inode *dir, struct dentry *dentry, umode_t mode)
6553 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
6554 struct inode *inode = NULL;
6555 struct btrfs_trans_handle *trans;
6556 struct btrfs_root *root = BTRFS_I(dir)->root;
6558 int drop_on_err = 0;
6563 * 2 items for inode and ref
6564 * 2 items for dir items
6565 * 1 for xattr if selinux is on
6567 trans = btrfs_start_transaction(root, 5);
6569 return PTR_ERR(trans);
6571 err = btrfs_find_free_ino(root, &objectid);
6575 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
6576 dentry->d_name.len, btrfs_ino(BTRFS_I(dir)), objectid,
6577 S_IFDIR | mode, &index);
6578 if (IS_ERR(inode)) {
6579 err = PTR_ERR(inode);
6584 /* these must be set before we unlock the inode */
6585 inode->i_op = &btrfs_dir_inode_operations;
6586 inode->i_fop = &btrfs_dir_file_operations;
6588 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
6590 goto out_fail_inode;
6592 btrfs_i_size_write(BTRFS_I(inode), 0);
6593 err = btrfs_update_inode(trans, root, inode);
6595 goto out_fail_inode;
6597 err = btrfs_add_link(trans, BTRFS_I(dir), BTRFS_I(inode),
6598 dentry->d_name.name,
6599 dentry->d_name.len, 0, index);
6601 goto out_fail_inode;
6603 d_instantiate(dentry, inode);
6605 * mkdir is special. We're unlocking after we call d_instantiate
6606 * to avoid a race with nfsd calling d_instantiate.
6608 unlock_new_inode(inode);
6612 btrfs_end_transaction(trans);
6614 inode_dec_link_count(inode);
6617 btrfs_balance_delayed_items(fs_info);
6618 btrfs_btree_balance_dirty(fs_info);
6622 unlock_new_inode(inode);
6626 /* Find next extent map of a given extent map, caller needs to ensure locks */
6627 static struct extent_map *next_extent_map(struct extent_map *em)
6629 struct rb_node *next;
6631 next = rb_next(&em->rb_node);
6634 return container_of(next, struct extent_map, rb_node);
6637 static struct extent_map *prev_extent_map(struct extent_map *em)
6639 struct rb_node *prev;
6641 prev = rb_prev(&em->rb_node);
6644 return container_of(prev, struct extent_map, rb_node);
6647 /* helper for btfs_get_extent. Given an existing extent in the tree,
6648 * the existing extent is the nearest extent to map_start,
6649 * and an extent that you want to insert, deal with overlap and insert
6650 * the best fitted new extent into the tree.
6652 static int merge_extent_mapping(struct extent_map_tree *em_tree,
6653 struct extent_map *existing,
6654 struct extent_map *em,
6657 struct extent_map *prev;
6658 struct extent_map *next;
6663 BUG_ON(map_start < em->start || map_start >= extent_map_end(em));
6665 if (existing->start > map_start) {
6667 prev = prev_extent_map(next);
6670 next = next_extent_map(prev);
6673 start = prev ? extent_map_end(prev) : em->start;
6674 start = max_t(u64, start, em->start);
6675 end = next ? next->start : extent_map_end(em);
6676 end = min_t(u64, end, extent_map_end(em));
6677 start_diff = start - em->start;
6679 em->len = end - start;
6680 if (em->block_start < EXTENT_MAP_LAST_BYTE &&
6681 !test_bit(EXTENT_FLAG_COMPRESSED, &em->flags)) {
6682 em->block_start += start_diff;
6683 em->block_len -= start_diff;
6685 return add_extent_mapping(em_tree, em, 0);
6688 static noinline int uncompress_inline(struct btrfs_path *path,
6690 size_t pg_offset, u64 extent_offset,
6691 struct btrfs_file_extent_item *item)
6694 struct extent_buffer *leaf = path->nodes[0];
6697 unsigned long inline_size;
6701 WARN_ON(pg_offset != 0);
6702 compress_type = btrfs_file_extent_compression(leaf, item);
6703 max_size = btrfs_file_extent_ram_bytes(leaf, item);
6704 inline_size = btrfs_file_extent_inline_item_len(leaf,
6705 btrfs_item_nr(path->slots[0]));
6706 tmp = kmalloc(inline_size, GFP_NOFS);
6709 ptr = btrfs_file_extent_inline_start(item);
6711 read_extent_buffer(leaf, tmp, ptr, inline_size);
6713 max_size = min_t(unsigned long, PAGE_SIZE, max_size);
6714 ret = btrfs_decompress(compress_type, tmp, page,
6715 extent_offset, inline_size, max_size);
6721 * a bit scary, this does extent mapping from logical file offset to the disk.
6722 * the ugly parts come from merging extents from the disk with the in-ram
6723 * representation. This gets more complex because of the data=ordered code,
6724 * where the in-ram extents might be locked pending data=ordered completion.
6726 * This also copies inline extents directly into the page.
6729 struct extent_map *btrfs_get_extent(struct btrfs_inode *inode,
6731 size_t pg_offset, u64 start, u64 len,
6734 struct btrfs_fs_info *fs_info = btrfs_sb(inode->vfs_inode.i_sb);
6737 u64 extent_start = 0;
6739 u64 objectid = btrfs_ino(inode);
6741 struct btrfs_path *path = NULL;
6742 struct btrfs_root *root = inode->root;
6743 struct btrfs_file_extent_item *item;
6744 struct extent_buffer *leaf;
6745 struct btrfs_key found_key;
6746 struct extent_map *em = NULL;
6747 struct extent_map_tree *em_tree = &inode->extent_tree;
6748 struct extent_io_tree *io_tree = &inode->io_tree;
6749 struct btrfs_trans_handle *trans = NULL;
6750 const bool new_inline = !page || create;
6753 read_lock(&em_tree->lock);
6754 em = lookup_extent_mapping(em_tree, start, len);
6756 em->bdev = fs_info->fs_devices->latest_bdev;
6757 read_unlock(&em_tree->lock);
6760 if (em->start > start || em->start + em->len <= start)
6761 free_extent_map(em);
6762 else if (em->block_start == EXTENT_MAP_INLINE && page)
6763 free_extent_map(em);
6767 em = alloc_extent_map();
6772 em->bdev = fs_info->fs_devices->latest_bdev;
6773 em->start = EXTENT_MAP_HOLE;
6774 em->orig_start = EXTENT_MAP_HOLE;
6776 em->block_len = (u64)-1;
6779 path = btrfs_alloc_path();
6785 * Chances are we'll be called again, so go ahead and do
6788 path->reada = READA_FORWARD;
6791 ret = btrfs_lookup_file_extent(trans, root, path,
6792 objectid, start, trans != NULL);
6799 if (path->slots[0] == 0)
6804 leaf = path->nodes[0];
6805 item = btrfs_item_ptr(leaf, path->slots[0],
6806 struct btrfs_file_extent_item);
6807 /* are we inside the extent that was found? */
6808 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
6809 found_type = found_key.type;
6810 if (found_key.objectid != objectid ||
6811 found_type != BTRFS_EXTENT_DATA_KEY) {
6813 * If we backup past the first extent we want to move forward
6814 * and see if there is an extent in front of us, otherwise we'll
6815 * say there is a hole for our whole search range which can
6822 found_type = btrfs_file_extent_type(leaf, item);
6823 extent_start = found_key.offset;
6824 if (found_type == BTRFS_FILE_EXTENT_REG ||
6825 found_type == BTRFS_FILE_EXTENT_PREALLOC) {
6826 extent_end = extent_start +
6827 btrfs_file_extent_num_bytes(leaf, item);
6828 } else if (found_type == BTRFS_FILE_EXTENT_INLINE) {
6830 size = btrfs_file_extent_inline_len(leaf, path->slots[0], item);
6831 extent_end = ALIGN(extent_start + size,
6832 fs_info->sectorsize);
6835 if (start >= extent_end) {
6837 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
6838 ret = btrfs_next_leaf(root, path);
6845 leaf = path->nodes[0];
6847 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
6848 if (found_key.objectid != objectid ||
6849 found_key.type != BTRFS_EXTENT_DATA_KEY)
6851 if (start + len <= found_key.offset)
6853 if (start > found_key.offset)
6856 em->orig_start = start;
6857 em->len = found_key.offset - start;
6861 btrfs_extent_item_to_extent_map(inode, path, item,
6864 if (found_type == BTRFS_FILE_EXTENT_REG ||
6865 found_type == BTRFS_FILE_EXTENT_PREALLOC) {
6867 } else if (found_type == BTRFS_FILE_EXTENT_INLINE) {
6871 size_t extent_offset;
6877 size = btrfs_file_extent_inline_len(leaf, path->slots[0], item);
6878 extent_offset = page_offset(page) + pg_offset - extent_start;
6879 copy_size = min_t(u64, PAGE_SIZE - pg_offset,
6880 size - extent_offset);
6881 em->start = extent_start + extent_offset;
6882 em->len = ALIGN(copy_size, fs_info->sectorsize);
6883 em->orig_block_len = em->len;
6884 em->orig_start = em->start;
6885 ptr = btrfs_file_extent_inline_start(item) + extent_offset;
6886 if (create == 0 && !PageUptodate(page)) {
6887 if (btrfs_file_extent_compression(leaf, item) !=
6888 BTRFS_COMPRESS_NONE) {
6889 ret = uncompress_inline(path, page, pg_offset,
6890 extent_offset, item);
6897 read_extent_buffer(leaf, map + pg_offset, ptr,
6899 if (pg_offset + copy_size < PAGE_SIZE) {
6900 memset(map + pg_offset + copy_size, 0,
6901 PAGE_SIZE - pg_offset -
6906 flush_dcache_page(page);
6907 } else if (create && PageUptodate(page)) {
6911 free_extent_map(em);
6914 btrfs_release_path(path);
6915 trans = btrfs_join_transaction(root);
6918 return ERR_CAST(trans);
6922 write_extent_buffer(leaf, map + pg_offset, ptr,
6925 btrfs_mark_buffer_dirty(leaf);
6927 set_extent_uptodate(io_tree, em->start,
6928 extent_map_end(em) - 1, NULL, GFP_NOFS);
6933 em->orig_start = start;
6936 em->block_start = EXTENT_MAP_HOLE;
6937 set_bit(EXTENT_FLAG_VACANCY, &em->flags);
6939 btrfs_release_path(path);
6940 if (em->start > start || extent_map_end(em) <= start) {
6942 "bad extent! em: [%llu %llu] passed [%llu %llu]",
6943 em->start, em->len, start, len);
6949 write_lock(&em_tree->lock);
6950 ret = add_extent_mapping(em_tree, em, 0);
6951 /* it is possible that someone inserted the extent into the tree
6952 * while we had the lock dropped. It is also possible that
6953 * an overlapping map exists in the tree
6955 if (ret == -EEXIST) {
6956 struct extent_map *existing;
6960 existing = search_extent_mapping(em_tree, start, len);
6962 * existing will always be non-NULL, since there must be
6963 * extent causing the -EEXIST.
6965 if (existing->start == em->start &&
6966 extent_map_end(existing) >= extent_map_end(em) &&
6967 em->block_start == existing->block_start) {
6969 * The existing extent map already encompasses the
6970 * entire extent map we tried to add.
6972 free_extent_map(em);
6976 } else if (start >= extent_map_end(existing) ||
6977 start <= existing->start) {
6979 * The existing extent map is the one nearest to
6980 * the [start, start + len) range which overlaps
6982 err = merge_extent_mapping(em_tree, existing,
6984 free_extent_map(existing);
6986 free_extent_map(em);
6990 free_extent_map(em);
6995 write_unlock(&em_tree->lock);
6998 trace_btrfs_get_extent(root, inode, em);
7000 btrfs_free_path(path);
7002 ret = btrfs_end_transaction(trans);
7007 free_extent_map(em);
7008 return ERR_PTR(err);
7010 BUG_ON(!em); /* Error is always set */
7014 struct extent_map *btrfs_get_extent_fiemap(struct btrfs_inode *inode,
7016 size_t pg_offset, u64 start, u64 len,
7019 struct extent_map *em;
7020 struct extent_map *hole_em = NULL;
7021 u64 range_start = start;
7027 em = btrfs_get_extent(inode, page, pg_offset, start, len, create);
7034 * - a pre-alloc extent,
7035 * there might actually be delalloc bytes behind it.
7037 if (em->block_start != EXTENT_MAP_HOLE &&
7038 !test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
7044 /* check to see if we've wrapped (len == -1 or similar) */
7053 /* ok, we didn't find anything, lets look for delalloc */
7054 found = count_range_bits(&inode->io_tree, &range_start,
7055 end, len, EXTENT_DELALLOC, 1);
7056 found_end = range_start + found;
7057 if (found_end < range_start)
7058 found_end = (u64)-1;
7061 * we didn't find anything useful, return
7062 * the original results from get_extent()
7064 if (range_start > end || found_end <= start) {
7070 /* adjust the range_start to make sure it doesn't
7071 * go backwards from the start they passed in
7073 range_start = max(start, range_start);
7074 found = found_end - range_start;
7077 u64 hole_start = start;
7080 em = alloc_extent_map();
7086 * when btrfs_get_extent can't find anything it
7087 * returns one huge hole
7089 * make sure what it found really fits our range, and
7090 * adjust to make sure it is based on the start from
7094 u64 calc_end = extent_map_end(hole_em);
7096 if (calc_end <= start || (hole_em->start > end)) {
7097 free_extent_map(hole_em);
7100 hole_start = max(hole_em->start, start);
7101 hole_len = calc_end - hole_start;
7105 if (hole_em && range_start > hole_start) {
7106 /* our hole starts before our delalloc, so we
7107 * have to return just the parts of the hole
7108 * that go until the delalloc starts
7110 em->len = min(hole_len,
7111 range_start - hole_start);
7112 em->start = hole_start;
7113 em->orig_start = hole_start;
7115 * don't adjust block start at all,
7116 * it is fixed at EXTENT_MAP_HOLE
7118 em->block_start = hole_em->block_start;
7119 em->block_len = hole_len;
7120 if (test_bit(EXTENT_FLAG_PREALLOC, &hole_em->flags))
7121 set_bit(EXTENT_FLAG_PREALLOC, &em->flags);
7123 em->start = range_start;
7125 em->orig_start = range_start;
7126 em->block_start = EXTENT_MAP_DELALLOC;
7127 em->block_len = found;
7129 } else if (hole_em) {
7134 free_extent_map(hole_em);
7136 free_extent_map(em);
7137 return ERR_PTR(err);
7142 static struct extent_map *btrfs_create_dio_extent(struct inode *inode,
7145 const u64 orig_start,
7146 const u64 block_start,
7147 const u64 block_len,
7148 const u64 orig_block_len,
7149 const u64 ram_bytes,
7152 struct extent_map *em = NULL;
7155 if (type != BTRFS_ORDERED_NOCOW) {
7156 em = create_io_em(inode, start, len, orig_start,
7157 block_start, block_len, orig_block_len,
7159 BTRFS_COMPRESS_NONE, /* compress_type */
7164 ret = btrfs_add_ordered_extent_dio(inode, start, block_start,
7165 len, block_len, type);
7168 free_extent_map(em);
7169 btrfs_drop_extent_cache(BTRFS_I(inode), start,
7170 start + len - 1, 0);
7179 static struct extent_map *btrfs_new_extent_direct(struct inode *inode,
7182 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7183 struct btrfs_root *root = BTRFS_I(inode)->root;
7184 struct extent_map *em;
7185 struct btrfs_key ins;
7189 alloc_hint = get_extent_allocation_hint(inode, start, len);
7190 ret = btrfs_reserve_extent(root, len, len, fs_info->sectorsize,
7191 0, alloc_hint, &ins, 1, 1);
7193 return ERR_PTR(ret);
7195 em = btrfs_create_dio_extent(inode, start, ins.offset, start,
7196 ins.objectid, ins.offset, ins.offset,
7197 ins.offset, BTRFS_ORDERED_REGULAR);
7198 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
7200 btrfs_free_reserved_extent(fs_info, ins.objectid,
7207 * returns 1 when the nocow is safe, < 1 on error, 0 if the
7208 * block must be cow'd
7210 noinline int can_nocow_extent(struct inode *inode, u64 offset, u64 *len,
7211 u64 *orig_start, u64 *orig_block_len,
7214 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7215 struct btrfs_path *path;
7217 struct extent_buffer *leaf;
7218 struct btrfs_root *root = BTRFS_I(inode)->root;
7219 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
7220 struct btrfs_file_extent_item *fi;
7221 struct btrfs_key key;
7228 bool nocow = (BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW);
7230 path = btrfs_alloc_path();
7234 ret = btrfs_lookup_file_extent(NULL, root, path,
7235 btrfs_ino(BTRFS_I(inode)), offset, 0);
7239 slot = path->slots[0];
7242 /* can't find the item, must cow */
7249 leaf = path->nodes[0];
7250 btrfs_item_key_to_cpu(leaf, &key, slot);
7251 if (key.objectid != btrfs_ino(BTRFS_I(inode)) ||
7252 key.type != BTRFS_EXTENT_DATA_KEY) {
7253 /* not our file or wrong item type, must cow */
7257 if (key.offset > offset) {
7258 /* Wrong offset, must cow */
7262 fi = btrfs_item_ptr(leaf, slot, struct btrfs_file_extent_item);
7263 found_type = btrfs_file_extent_type(leaf, fi);
7264 if (found_type != BTRFS_FILE_EXTENT_REG &&
7265 found_type != BTRFS_FILE_EXTENT_PREALLOC) {
7266 /* not a regular extent, must cow */
7270 if (!nocow && found_type == BTRFS_FILE_EXTENT_REG)
7273 extent_end = key.offset + btrfs_file_extent_num_bytes(leaf, fi);
7274 if (extent_end <= offset)
7277 disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
7278 if (disk_bytenr == 0)
7281 if (btrfs_file_extent_compression(leaf, fi) ||
7282 btrfs_file_extent_encryption(leaf, fi) ||
7283 btrfs_file_extent_other_encoding(leaf, fi))
7286 backref_offset = btrfs_file_extent_offset(leaf, fi);
7289 *orig_start = key.offset - backref_offset;
7290 *orig_block_len = btrfs_file_extent_disk_num_bytes(leaf, fi);
7291 *ram_bytes = btrfs_file_extent_ram_bytes(leaf, fi);
7294 if (btrfs_extent_readonly(fs_info, disk_bytenr))
7297 num_bytes = min(offset + *len, extent_end) - offset;
7298 if (!nocow && found_type == BTRFS_FILE_EXTENT_PREALLOC) {
7301 range_end = round_up(offset + num_bytes,
7302 root->fs_info->sectorsize) - 1;
7303 ret = test_range_bit(io_tree, offset, range_end,
7304 EXTENT_DELALLOC, 0, NULL);
7311 btrfs_release_path(path);
7314 * look for other files referencing this extent, if we
7315 * find any we must cow
7318 ret = btrfs_cross_ref_exist(root, btrfs_ino(BTRFS_I(inode)),
7319 key.offset - backref_offset, disk_bytenr);
7326 * adjust disk_bytenr and num_bytes to cover just the bytes
7327 * in this extent we are about to write. If there
7328 * are any csums in that range we have to cow in order
7329 * to keep the csums correct
7331 disk_bytenr += backref_offset;
7332 disk_bytenr += offset - key.offset;
7333 if (csum_exist_in_range(fs_info, disk_bytenr, num_bytes))
7336 * all of the above have passed, it is safe to overwrite this extent
7342 btrfs_free_path(path);
7346 bool btrfs_page_exists_in_range(struct inode *inode, loff_t start, loff_t end)
7348 struct radix_tree_root *root = &inode->i_mapping->page_tree;
7350 void **pagep = NULL;
7351 struct page *page = NULL;
7355 start_idx = start >> PAGE_SHIFT;
7358 * end is the last byte in the last page. end == start is legal
7360 end_idx = end >> PAGE_SHIFT;
7364 /* Most of the code in this while loop is lifted from
7365 * find_get_page. It's been modified to begin searching from a
7366 * page and return just the first page found in that range. If the
7367 * found idx is less than or equal to the end idx then we know that
7368 * a page exists. If no pages are found or if those pages are
7369 * outside of the range then we're fine (yay!) */
7370 while (page == NULL &&
7371 radix_tree_gang_lookup_slot(root, &pagep, NULL, start_idx, 1)) {
7372 page = radix_tree_deref_slot(pagep);
7373 if (unlikely(!page))
7376 if (radix_tree_exception(page)) {
7377 if (radix_tree_deref_retry(page)) {
7382 * Otherwise, shmem/tmpfs must be storing a swap entry
7383 * here as an exceptional entry: so return it without
7384 * attempting to raise page count.
7387 break; /* TODO: Is this relevant for this use case? */
7390 if (!page_cache_get_speculative(page)) {
7396 * Has the page moved?
7397 * This is part of the lockless pagecache protocol. See
7398 * include/linux/pagemap.h for details.
7400 if (unlikely(page != *pagep)) {
7407 if (page->index <= end_idx)
7416 static int lock_extent_direct(struct inode *inode, u64 lockstart, u64 lockend,
7417 struct extent_state **cached_state, int writing)
7419 struct btrfs_ordered_extent *ordered;
7423 lock_extent_bits(&BTRFS_I(inode)->io_tree, lockstart, lockend,
7426 * We're concerned with the entire range that we're going to be
7427 * doing DIO to, so we need to make sure there's no ordered
7428 * extents in this range.
7430 ordered = btrfs_lookup_ordered_range(BTRFS_I(inode), lockstart,
7431 lockend - lockstart + 1);
7434 * We need to make sure there are no buffered pages in this
7435 * range either, we could have raced between the invalidate in
7436 * generic_file_direct_write and locking the extent. The
7437 * invalidate needs to happen so that reads after a write do not
7442 !btrfs_page_exists_in_range(inode, lockstart, lockend)))
7445 unlock_extent_cached(&BTRFS_I(inode)->io_tree, lockstart, lockend,
7446 cached_state, GFP_NOFS);
7450 * If we are doing a DIO read and the ordered extent we
7451 * found is for a buffered write, we can not wait for it
7452 * to complete and retry, because if we do so we can
7453 * deadlock with concurrent buffered writes on page
7454 * locks. This happens only if our DIO read covers more
7455 * than one extent map, if at this point has already
7456 * created an ordered extent for a previous extent map
7457 * and locked its range in the inode's io tree, and a
7458 * concurrent write against that previous extent map's
7459 * range and this range started (we unlock the ranges
7460 * in the io tree only when the bios complete and
7461 * buffered writes always lock pages before attempting
7462 * to lock range in the io tree).
7465 test_bit(BTRFS_ORDERED_DIRECT, &ordered->flags))
7466 btrfs_start_ordered_extent(inode, ordered, 1);
7469 btrfs_put_ordered_extent(ordered);
7472 * We could trigger writeback for this range (and wait
7473 * for it to complete) and then invalidate the pages for
7474 * this range (through invalidate_inode_pages2_range()),
7475 * but that can lead us to a deadlock with a concurrent
7476 * call to readpages() (a buffered read or a defrag call
7477 * triggered a readahead) on a page lock due to an
7478 * ordered dio extent we created before but did not have
7479 * yet a corresponding bio submitted (whence it can not
7480 * complete), which makes readpages() wait for that
7481 * ordered extent to complete while holding a lock on
7496 /* The callers of this must take lock_extent() */
7497 static struct extent_map *create_io_em(struct inode *inode, u64 start, u64 len,
7498 u64 orig_start, u64 block_start,
7499 u64 block_len, u64 orig_block_len,
7500 u64 ram_bytes, int compress_type,
7503 struct extent_map_tree *em_tree;
7504 struct extent_map *em;
7505 struct btrfs_root *root = BTRFS_I(inode)->root;
7508 ASSERT(type == BTRFS_ORDERED_PREALLOC ||
7509 type == BTRFS_ORDERED_COMPRESSED ||
7510 type == BTRFS_ORDERED_NOCOW ||
7511 type == BTRFS_ORDERED_REGULAR);
7513 em_tree = &BTRFS_I(inode)->extent_tree;
7514 em = alloc_extent_map();
7516 return ERR_PTR(-ENOMEM);
7519 em->orig_start = orig_start;
7521 em->block_len = block_len;
7522 em->block_start = block_start;
7523 em->bdev = root->fs_info->fs_devices->latest_bdev;
7524 em->orig_block_len = orig_block_len;
7525 em->ram_bytes = ram_bytes;
7526 em->generation = -1;
7527 set_bit(EXTENT_FLAG_PINNED, &em->flags);
7528 if (type == BTRFS_ORDERED_PREALLOC) {
7529 set_bit(EXTENT_FLAG_FILLING, &em->flags);
7530 } else if (type == BTRFS_ORDERED_COMPRESSED) {
7531 set_bit(EXTENT_FLAG_COMPRESSED, &em->flags);
7532 em->compress_type = compress_type;
7536 btrfs_drop_extent_cache(BTRFS_I(inode), em->start,
7537 em->start + em->len - 1, 0);
7538 write_lock(&em_tree->lock);
7539 ret = add_extent_mapping(em_tree, em, 1);
7540 write_unlock(&em_tree->lock);
7542 * The caller has taken lock_extent(), who could race with us
7545 } while (ret == -EEXIST);
7548 free_extent_map(em);
7549 return ERR_PTR(ret);
7552 /* em got 2 refs now, callers needs to do free_extent_map once. */
7556 static void adjust_dio_outstanding_extents(struct inode *inode,
7557 struct btrfs_dio_data *dio_data,
7560 unsigned num_extents = count_max_extents(len);
7563 * If we have an outstanding_extents count still set then we're
7564 * within our reservation, otherwise we need to adjust our inode
7565 * counter appropriately.
7567 if (dio_data->outstanding_extents >= num_extents) {
7568 dio_data->outstanding_extents -= num_extents;
7571 * If dio write length has been split due to no large enough
7572 * contiguous space, we need to compensate our inode counter
7575 u64 num_needed = num_extents - dio_data->outstanding_extents;
7577 spin_lock(&BTRFS_I(inode)->lock);
7578 BTRFS_I(inode)->outstanding_extents += num_needed;
7579 spin_unlock(&BTRFS_I(inode)->lock);
7583 static int btrfs_get_blocks_direct(struct inode *inode, sector_t iblock,
7584 struct buffer_head *bh_result, int create)
7586 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7587 struct extent_map *em;
7588 struct extent_state *cached_state = NULL;
7589 struct btrfs_dio_data *dio_data = NULL;
7590 u64 start = iblock << inode->i_blkbits;
7591 u64 lockstart, lockend;
7592 u64 len = bh_result->b_size;
7593 int unlock_bits = EXTENT_LOCKED;
7597 unlock_bits |= EXTENT_DIRTY;
7599 len = min_t(u64, len, fs_info->sectorsize);
7602 lockend = start + len - 1;
7604 if (current->journal_info) {
7606 * Need to pull our outstanding extents and set journal_info to NULL so
7607 * that anything that needs to check if there's a transaction doesn't get
7610 dio_data = current->journal_info;
7611 current->journal_info = NULL;
7615 * If this errors out it's because we couldn't invalidate pagecache for
7616 * this range and we need to fallback to buffered.
7618 if (lock_extent_direct(inode, lockstart, lockend, &cached_state,
7624 em = btrfs_get_extent(BTRFS_I(inode), NULL, 0, start, len, 0);
7631 * Ok for INLINE and COMPRESSED extents we need to fallback on buffered
7632 * io. INLINE is special, and we could probably kludge it in here, but
7633 * it's still buffered so for safety lets just fall back to the generic
7636 * For COMPRESSED we _have_ to read the entire extent in so we can
7637 * decompress it, so there will be buffering required no matter what we
7638 * do, so go ahead and fallback to buffered.
7640 * We return -ENOTBLK because that's what makes DIO go ahead and go back
7641 * to buffered IO. Don't blame me, this is the price we pay for using
7644 if (test_bit(EXTENT_FLAG_COMPRESSED, &em->flags) ||
7645 em->block_start == EXTENT_MAP_INLINE) {
7646 free_extent_map(em);
7651 /* Just a good old fashioned hole, return */
7652 if (!create && (em->block_start == EXTENT_MAP_HOLE ||
7653 test_bit(EXTENT_FLAG_PREALLOC, &em->flags))) {
7654 free_extent_map(em);
7659 * We don't allocate a new extent in the following cases
7661 * 1) The inode is marked as NODATACOW. In this case we'll just use the
7663 * 2) The extent is marked as PREALLOC. We're good to go here and can
7664 * just use the extent.
7668 len = min(len, em->len - (start - em->start));
7669 lockstart = start + len;
7673 if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags) ||
7674 ((BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW) &&
7675 em->block_start != EXTENT_MAP_HOLE)) {
7677 u64 block_start, orig_start, orig_block_len, ram_bytes;
7679 if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
7680 type = BTRFS_ORDERED_PREALLOC;
7682 type = BTRFS_ORDERED_NOCOW;
7683 len = min(len, em->len - (start - em->start));
7684 block_start = em->block_start + (start - em->start);
7686 if (can_nocow_extent(inode, start, &len, &orig_start,
7687 &orig_block_len, &ram_bytes) == 1 &&
7688 btrfs_inc_nocow_writers(fs_info, block_start)) {
7689 struct extent_map *em2;
7691 em2 = btrfs_create_dio_extent(inode, start, len,
7692 orig_start, block_start,
7693 len, orig_block_len,
7695 btrfs_dec_nocow_writers(fs_info, block_start);
7696 if (type == BTRFS_ORDERED_PREALLOC) {
7697 free_extent_map(em);
7700 if (em2 && IS_ERR(em2)) {
7705 * For inode marked NODATACOW or extent marked PREALLOC,
7706 * use the existing or preallocated extent, so does not
7707 * need to adjust btrfs_space_info's bytes_may_use.
7709 btrfs_free_reserved_data_space_noquota(inode,
7716 * this will cow the extent, reset the len in case we changed
7719 len = bh_result->b_size;
7720 free_extent_map(em);
7721 em = btrfs_new_extent_direct(inode, start, len);
7726 len = min(len, em->len - (start - em->start));
7728 bh_result->b_blocknr = (em->block_start + (start - em->start)) >>
7730 bh_result->b_size = len;
7731 bh_result->b_bdev = em->bdev;
7732 set_buffer_mapped(bh_result);
7734 if (!test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
7735 set_buffer_new(bh_result);
7738 * Need to update the i_size under the extent lock so buffered
7739 * readers will get the updated i_size when we unlock.
7741 if (!dio_data->overwrite && start + len > i_size_read(inode))
7742 i_size_write(inode, start + len);
7744 adjust_dio_outstanding_extents(inode, dio_data, len);
7745 WARN_ON(dio_data->reserve < len);
7746 dio_data->reserve -= len;
7747 dio_data->unsubmitted_oe_range_end = start + len;
7748 current->journal_info = dio_data;
7752 * In the case of write we need to clear and unlock the entire range,
7753 * in the case of read we need to unlock only the end area that we
7754 * aren't using if there is any left over space.
7756 if (lockstart < lockend) {
7757 clear_extent_bit(&BTRFS_I(inode)->io_tree, lockstart,
7758 lockend, unlock_bits, 1, 0,
7759 &cached_state, GFP_NOFS);
7761 free_extent_state(cached_state);
7764 free_extent_map(em);
7769 clear_extent_bit(&BTRFS_I(inode)->io_tree, lockstart, lockend,
7770 unlock_bits, 1, 0, &cached_state, GFP_NOFS);
7773 current->journal_info = dio_data;
7775 * Compensate the delalloc release we do in btrfs_direct_IO() when we
7776 * write less data then expected, so that we don't underflow our inode's
7777 * outstanding extents counter.
7779 if (create && dio_data)
7780 adjust_dio_outstanding_extents(inode, dio_data, len);
7785 static inline int submit_dio_repair_bio(struct inode *inode, struct bio *bio,
7788 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7791 BUG_ON(bio_op(bio) == REQ_OP_WRITE);
7795 ret = btrfs_bio_wq_end_io(fs_info, bio, BTRFS_WQ_ENDIO_DIO_REPAIR);
7799 ret = btrfs_map_bio(fs_info, bio, mirror_num, 0);
7805 static int btrfs_check_dio_repairable(struct inode *inode,
7806 struct bio *failed_bio,
7807 struct io_failure_record *failrec,
7810 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7813 num_copies = btrfs_num_copies(fs_info, failrec->logical, failrec->len);
7814 if (num_copies == 1) {
7816 * we only have a single copy of the data, so don't bother with
7817 * all the retry and error correction code that follows. no
7818 * matter what the error is, it is very likely to persist.
7820 btrfs_debug(fs_info,
7821 "Check DIO Repairable: cannot repair, num_copies=%d, next_mirror %d, failed_mirror %d",
7822 num_copies, failrec->this_mirror, failed_mirror);
7826 failrec->failed_mirror = failed_mirror;
7827 failrec->this_mirror++;
7828 if (failrec->this_mirror == failed_mirror)
7829 failrec->this_mirror++;
7831 if (failrec->this_mirror > num_copies) {
7832 btrfs_debug(fs_info,
7833 "Check DIO Repairable: (fail) num_copies=%d, next_mirror %d, failed_mirror %d",
7834 num_copies, failrec->this_mirror, failed_mirror);
7841 static int dio_read_error(struct inode *inode, struct bio *failed_bio,
7842 struct page *page, unsigned int pgoff,
7843 u64 start, u64 end, int failed_mirror,
7844 bio_end_io_t *repair_endio, void *repair_arg)
7846 struct io_failure_record *failrec;
7852 BUG_ON(bio_op(failed_bio) == REQ_OP_WRITE);
7854 ret = btrfs_get_io_failure_record(inode, start, end, &failrec);
7858 ret = btrfs_check_dio_repairable(inode, failed_bio, failrec,
7861 free_io_failure(BTRFS_I(inode), failrec);
7865 if ((failed_bio->bi_vcnt > 1)
7866 || (failed_bio->bi_io_vec->bv_len
7867 > btrfs_inode_sectorsize(inode)))
7868 read_mode |= REQ_FAILFAST_DEV;
7870 isector = start - btrfs_io_bio(failed_bio)->logical;
7871 isector >>= inode->i_sb->s_blocksize_bits;
7872 bio = btrfs_create_repair_bio(inode, failed_bio, failrec, page,
7873 pgoff, isector, repair_endio, repair_arg);
7875 free_io_failure(BTRFS_I(inode), failrec);
7878 bio_set_op_attrs(bio, REQ_OP_READ, read_mode);
7880 btrfs_debug(BTRFS_I(inode)->root->fs_info,
7881 "Repair DIO Read Error: submitting new dio read[%#x] to this_mirror=%d, in_validation=%d\n",
7882 read_mode, failrec->this_mirror, failrec->in_validation);
7884 ret = submit_dio_repair_bio(inode, bio, failrec->this_mirror);
7886 free_io_failure(BTRFS_I(inode), failrec);
7893 struct btrfs_retry_complete {
7894 struct completion done;
7895 struct inode *inode;
7900 static void btrfs_retry_endio_nocsum(struct bio *bio)
7902 struct btrfs_retry_complete *done = bio->bi_private;
7903 struct inode *inode;
7904 struct bio_vec *bvec;
7910 ASSERT(bio->bi_vcnt == 1);
7911 inode = bio->bi_io_vec->bv_page->mapping->host;
7912 ASSERT(bio->bi_io_vec->bv_len == btrfs_inode_sectorsize(inode));
7915 bio_for_each_segment_all(bvec, bio, i)
7916 clean_io_failure(BTRFS_I(done->inode), done->start, bvec->bv_page, 0);
7918 complete(&done->done);
7922 static int __btrfs_correct_data_nocsum(struct inode *inode,
7923 struct btrfs_io_bio *io_bio)
7925 struct btrfs_fs_info *fs_info;
7926 struct bio_vec *bvec;
7927 struct btrfs_retry_complete done;
7935 fs_info = BTRFS_I(inode)->root->fs_info;
7936 sectorsize = fs_info->sectorsize;
7938 start = io_bio->logical;
7941 bio_for_each_segment_all(bvec, &io_bio->bio, i) {
7942 nr_sectors = BTRFS_BYTES_TO_BLKS(fs_info, bvec->bv_len);
7943 pgoff = bvec->bv_offset;
7945 next_block_or_try_again:
7948 init_completion(&done.done);
7950 ret = dio_read_error(inode, &io_bio->bio, bvec->bv_page,
7951 pgoff, start, start + sectorsize - 1,
7953 btrfs_retry_endio_nocsum, &done);
7957 wait_for_completion(&done.done);
7959 if (!done.uptodate) {
7960 /* We might have another mirror, so try again */
7961 goto next_block_or_try_again;
7964 start += sectorsize;
7967 pgoff += sectorsize;
7968 goto next_block_or_try_again;
7975 static void btrfs_retry_endio(struct bio *bio)
7977 struct btrfs_retry_complete *done = bio->bi_private;
7978 struct btrfs_io_bio *io_bio = btrfs_io_bio(bio);
7979 struct inode *inode;
7980 struct bio_vec *bvec;
7991 start = done->start;
7993 ASSERT(bio->bi_vcnt == 1);
7994 inode = bio->bi_io_vec->bv_page->mapping->host;
7995 ASSERT(bio->bi_io_vec->bv_len == btrfs_inode_sectorsize(inode));
7997 bio_for_each_segment_all(bvec, bio, i) {
7998 ret = __readpage_endio_check(done->inode, io_bio, i,
7999 bvec->bv_page, bvec->bv_offset,
8000 done->start, bvec->bv_len);
8002 clean_io_failure(BTRFS_I(done->inode), done->start,
8003 bvec->bv_page, bvec->bv_offset);
8008 done->uptodate = uptodate;
8010 complete(&done->done);
8014 static int __btrfs_subio_endio_read(struct inode *inode,
8015 struct btrfs_io_bio *io_bio, int err)
8017 struct btrfs_fs_info *fs_info;
8018 struct bio_vec *bvec;
8019 struct btrfs_retry_complete done;
8029 fs_info = BTRFS_I(inode)->root->fs_info;
8030 sectorsize = fs_info->sectorsize;
8033 start = io_bio->logical;
8036 bio_for_each_segment_all(bvec, &io_bio->bio, i) {
8037 nr_sectors = BTRFS_BYTES_TO_BLKS(fs_info, bvec->bv_len);
8039 pgoff = bvec->bv_offset;
8041 csum_pos = BTRFS_BYTES_TO_BLKS(fs_info, offset);
8042 ret = __readpage_endio_check(inode, io_bio, csum_pos,
8043 bvec->bv_page, pgoff, start,
8050 init_completion(&done.done);
8052 ret = dio_read_error(inode, &io_bio->bio, bvec->bv_page,
8053 pgoff, start, start + sectorsize - 1,
8055 btrfs_retry_endio, &done);
8061 wait_for_completion(&done.done);
8063 if (!done.uptodate) {
8064 /* We might have another mirror, so try again */
8068 offset += sectorsize;
8069 start += sectorsize;
8074 pgoff += sectorsize;
8082 static int btrfs_subio_endio_read(struct inode *inode,
8083 struct btrfs_io_bio *io_bio, int err)
8085 bool skip_csum = BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM;
8089 return __btrfs_correct_data_nocsum(inode, io_bio);
8093 return __btrfs_subio_endio_read(inode, io_bio, err);
8097 static void btrfs_endio_direct_read(struct bio *bio)
8099 struct btrfs_dio_private *dip = bio->bi_private;
8100 struct inode *inode = dip->inode;
8101 struct bio *dio_bio;
8102 struct btrfs_io_bio *io_bio = btrfs_io_bio(bio);
8103 int err = bio->bi_error;
8105 if (dip->flags & BTRFS_DIO_ORIG_BIO_SUBMITTED)
8106 err = btrfs_subio_endio_read(inode, io_bio, err);
8108 unlock_extent(&BTRFS_I(inode)->io_tree, dip->logical_offset,
8109 dip->logical_offset + dip->bytes - 1);
8110 dio_bio = dip->dio_bio;
8114 dio_bio->bi_error = bio->bi_error;
8115 dio_end_io(dio_bio, bio->bi_error);
8118 io_bio->end_io(io_bio, err);
8122 static void btrfs_endio_direct_write_update_ordered(struct inode *inode,
8127 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
8128 struct btrfs_ordered_extent *ordered = NULL;
8129 u64 ordered_offset = offset;
8130 u64 ordered_bytes = bytes;
8134 ret = btrfs_dec_test_first_ordered_pending(inode, &ordered,
8141 btrfs_init_work(&ordered->work, btrfs_endio_write_helper,
8142 finish_ordered_fn, NULL, NULL);
8143 btrfs_queue_work(fs_info->endio_write_workers, &ordered->work);
8146 * our bio might span multiple ordered extents. If we haven't
8147 * completed the accounting for the whole dio, go back and try again
8149 if (ordered_offset < offset + bytes) {
8150 ordered_bytes = offset + bytes - ordered_offset;
8156 static void btrfs_endio_direct_write(struct bio *bio)
8158 struct btrfs_dio_private *dip = bio->bi_private;
8159 struct bio *dio_bio = dip->dio_bio;
8161 btrfs_endio_direct_write_update_ordered(dip->inode,
8162 dip->logical_offset,
8168 dio_bio->bi_error = bio->bi_error;
8169 dio_end_io(dio_bio, bio->bi_error);
8173 static int __btrfs_submit_bio_start_direct_io(struct inode *inode,
8174 struct bio *bio, int mirror_num,
8175 unsigned long bio_flags, u64 offset)
8178 ret = btrfs_csum_one_bio(inode, bio, offset, 1);
8179 BUG_ON(ret); /* -ENOMEM */
8183 static void btrfs_end_dio_bio(struct bio *bio)
8185 struct btrfs_dio_private *dip = bio->bi_private;
8186 int err = bio->bi_error;
8189 btrfs_warn(BTRFS_I(dip->inode)->root->fs_info,
8190 "direct IO failed ino %llu rw %d,%u sector %#Lx len %u err no %d",
8191 btrfs_ino(BTRFS_I(dip->inode)), bio_op(bio),
8193 (unsigned long long)bio->bi_iter.bi_sector,
8194 bio->bi_iter.bi_size, err);
8196 if (dip->subio_endio)
8197 err = dip->subio_endio(dip->inode, btrfs_io_bio(bio), err);
8203 * before atomic variable goto zero, we must make sure
8204 * dip->errors is perceived to be set.
8206 smp_mb__before_atomic();
8209 /* if there are more bios still pending for this dio, just exit */
8210 if (!atomic_dec_and_test(&dip->pending_bios))
8214 bio_io_error(dip->orig_bio);
8216 dip->dio_bio->bi_error = 0;
8217 bio_endio(dip->orig_bio);
8223 static struct bio *btrfs_dio_bio_alloc(struct block_device *bdev,
8224 u64 first_sector, gfp_t gfp_flags)
8227 bio = btrfs_bio_alloc(bdev, first_sector, BIO_MAX_PAGES, gfp_flags);
8229 bio_associate_current(bio);
8233 static inline int btrfs_lookup_and_bind_dio_csum(struct inode *inode,
8234 struct btrfs_dio_private *dip,
8238 struct btrfs_io_bio *io_bio = btrfs_io_bio(bio);
8239 struct btrfs_io_bio *orig_io_bio = btrfs_io_bio(dip->orig_bio);
8243 * We load all the csum data we need when we submit
8244 * the first bio to reduce the csum tree search and
8247 if (dip->logical_offset == file_offset) {
8248 ret = btrfs_lookup_bio_sums_dio(inode, dip->orig_bio,
8254 if (bio == dip->orig_bio)
8257 file_offset -= dip->logical_offset;
8258 file_offset >>= inode->i_sb->s_blocksize_bits;
8259 io_bio->csum = (u8 *)(((u32 *)orig_io_bio->csum) + file_offset);
8264 static inline int __btrfs_submit_dio_bio(struct bio *bio, struct inode *inode,
8265 u64 file_offset, int skip_sum,
8268 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
8269 struct btrfs_dio_private *dip = bio->bi_private;
8270 bool write = bio_op(bio) == REQ_OP_WRITE;
8274 async_submit = !atomic_read(&BTRFS_I(inode)->sync_writers);
8279 ret = btrfs_bio_wq_end_io(fs_info, bio, BTRFS_WQ_ENDIO_DATA);
8287 if (write && async_submit) {
8288 ret = btrfs_wq_submit_bio(fs_info, inode, bio, 0, 0,
8290 __btrfs_submit_bio_start_direct_io,
8291 __btrfs_submit_bio_done);
8295 * If we aren't doing async submit, calculate the csum of the
8298 ret = btrfs_csum_one_bio(inode, bio, file_offset, 1);
8302 ret = btrfs_lookup_and_bind_dio_csum(inode, dip, bio,
8308 ret = btrfs_map_bio(fs_info, bio, 0, async_submit);
8314 static int btrfs_submit_direct_hook(struct btrfs_dio_private *dip,
8317 struct inode *inode = dip->inode;
8318 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
8319 struct btrfs_root *root = BTRFS_I(inode)->root;
8321 struct bio *orig_bio = dip->orig_bio;
8322 struct bio_vec *bvec;
8323 u64 start_sector = orig_bio->bi_iter.bi_sector;
8324 u64 file_offset = dip->logical_offset;
8327 u32 blocksize = fs_info->sectorsize;
8328 int async_submit = 0;
8333 map_length = orig_bio->bi_iter.bi_size;
8334 ret = btrfs_map_block(fs_info, btrfs_op(orig_bio), start_sector << 9,
8335 &map_length, NULL, 0);
8339 if (map_length >= orig_bio->bi_iter.bi_size) {
8341 dip->flags |= BTRFS_DIO_ORIG_BIO_SUBMITTED;
8345 /* async crcs make it difficult to collect full stripe writes. */
8346 if (btrfs_get_alloc_profile(root, 1) & BTRFS_BLOCK_GROUP_RAID56_MASK)
8351 bio = btrfs_dio_bio_alloc(orig_bio->bi_bdev, start_sector, GFP_NOFS);
8355 bio->bi_opf = orig_bio->bi_opf;
8356 bio->bi_private = dip;
8357 bio->bi_end_io = btrfs_end_dio_bio;
8358 btrfs_io_bio(bio)->logical = file_offset;
8359 atomic_inc(&dip->pending_bios);
8361 bio_for_each_segment_all(bvec, orig_bio, j) {
8362 nr_sectors = BTRFS_BYTES_TO_BLKS(fs_info, bvec->bv_len);
8365 if (unlikely(map_length < submit_len + blocksize ||
8366 bio_add_page(bio, bvec->bv_page, blocksize,
8367 bvec->bv_offset + (i * blocksize)) < blocksize)) {
8369 * inc the count before we submit the bio so
8370 * we know the end IO handler won't happen before
8371 * we inc the count. Otherwise, the dip might get freed
8372 * before we're done setting it up
8374 atomic_inc(&dip->pending_bios);
8375 ret = __btrfs_submit_dio_bio(bio, inode,
8376 file_offset, skip_sum,
8380 atomic_dec(&dip->pending_bios);
8384 start_sector += submit_len >> 9;
8385 file_offset += submit_len;
8389 bio = btrfs_dio_bio_alloc(orig_bio->bi_bdev,
8390 start_sector, GFP_NOFS);
8393 bio->bi_opf = orig_bio->bi_opf;
8394 bio->bi_private = dip;
8395 bio->bi_end_io = btrfs_end_dio_bio;
8396 btrfs_io_bio(bio)->logical = file_offset;
8398 map_length = orig_bio->bi_iter.bi_size;
8399 ret = btrfs_map_block(fs_info, btrfs_op(orig_bio),
8401 &map_length, NULL, 0);
8409 submit_len += blocksize;
8418 ret = __btrfs_submit_dio_bio(bio, inode, file_offset, skip_sum,
8427 * before atomic variable goto zero, we must
8428 * make sure dip->errors is perceived to be set.
8430 smp_mb__before_atomic();
8431 if (atomic_dec_and_test(&dip->pending_bios))
8432 bio_io_error(dip->orig_bio);
8434 /* bio_end_io() will handle error, so we needn't return it */
8438 static void btrfs_submit_direct(struct bio *dio_bio, struct inode *inode,
8441 struct btrfs_dio_private *dip = NULL;
8442 struct bio *io_bio = NULL;
8443 struct btrfs_io_bio *btrfs_bio;
8445 bool write = (bio_op(dio_bio) == REQ_OP_WRITE);
8448 skip_sum = BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM;
8450 io_bio = btrfs_bio_clone(dio_bio, GFP_NOFS);
8456 dip = kzalloc(sizeof(*dip), GFP_NOFS);
8462 dip->private = dio_bio->bi_private;
8464 dip->logical_offset = file_offset;
8465 dip->bytes = dio_bio->bi_iter.bi_size;
8466 dip->disk_bytenr = (u64)dio_bio->bi_iter.bi_sector << 9;
8467 io_bio->bi_private = dip;
8468 dip->orig_bio = io_bio;
8469 dip->dio_bio = dio_bio;
8470 atomic_set(&dip->pending_bios, 0);
8471 btrfs_bio = btrfs_io_bio(io_bio);
8472 btrfs_bio->logical = file_offset;
8475 io_bio->bi_end_io = btrfs_endio_direct_write;
8477 io_bio->bi_end_io = btrfs_endio_direct_read;
8478 dip->subio_endio = btrfs_subio_endio_read;
8482 * Reset the range for unsubmitted ordered extents (to a 0 length range)
8483 * even if we fail to submit a bio, because in such case we do the
8484 * corresponding error handling below and it must not be done a second
8485 * time by btrfs_direct_IO().
8488 struct btrfs_dio_data *dio_data = current->journal_info;
8490 dio_data->unsubmitted_oe_range_end = dip->logical_offset +
8492 dio_data->unsubmitted_oe_range_start =
8493 dio_data->unsubmitted_oe_range_end;
8496 ret = btrfs_submit_direct_hook(dip, skip_sum);
8500 if (btrfs_bio->end_io)
8501 btrfs_bio->end_io(btrfs_bio, ret);
8505 * If we arrived here it means either we failed to submit the dip
8506 * or we either failed to clone the dio_bio or failed to allocate the
8507 * dip. If we cloned the dio_bio and allocated the dip, we can just
8508 * call bio_endio against our io_bio so that we get proper resource
8509 * cleanup if we fail to submit the dip, otherwise, we must do the
8510 * same as btrfs_endio_direct_[write|read] because we can't call these
8511 * callbacks - they require an allocated dip and a clone of dio_bio.
8513 if (io_bio && dip) {
8514 io_bio->bi_error = -EIO;
8517 * The end io callbacks free our dip, do the final put on io_bio
8518 * and all the cleanup and final put for dio_bio (through
8525 btrfs_endio_direct_write_update_ordered(inode,
8527 dio_bio->bi_iter.bi_size,
8530 unlock_extent(&BTRFS_I(inode)->io_tree, file_offset,
8531 file_offset + dio_bio->bi_iter.bi_size - 1);
8533 dio_bio->bi_error = -EIO;
8535 * Releases and cleans up our dio_bio, no need to bio_put()
8536 * nor bio_endio()/bio_io_error() against dio_bio.
8538 dio_end_io(dio_bio, ret);
8545 static ssize_t check_direct_IO(struct btrfs_fs_info *fs_info,
8547 const struct iov_iter *iter, loff_t offset)
8551 unsigned int blocksize_mask = fs_info->sectorsize - 1;
8552 ssize_t retval = -EINVAL;
8554 if (offset & blocksize_mask)
8557 if (iov_iter_alignment(iter) & blocksize_mask)
8560 /* If this is a write we don't need to check anymore */
8561 if (iov_iter_rw(iter) != READ || !iter_is_iovec(iter))
8564 * Check to make sure we don't have duplicate iov_base's in this
8565 * iovec, if so return EINVAL, otherwise we'll get csum errors
8566 * when reading back.
8568 for (seg = 0; seg < iter->nr_segs; seg++) {
8569 for (i = seg + 1; i < iter->nr_segs; i++) {
8570 if (iter->iov[seg].iov_base == iter->iov[i].iov_base)
8579 static ssize_t btrfs_direct_IO(struct kiocb *iocb, struct iov_iter *iter)
8581 struct file *file = iocb->ki_filp;
8582 struct inode *inode = file->f_mapping->host;
8583 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
8584 struct btrfs_dio_data dio_data = { 0 };
8585 loff_t offset = iocb->ki_pos;
8589 bool relock = false;
8592 if (check_direct_IO(fs_info, iocb, iter, offset))
8595 inode_dio_begin(inode);
8596 smp_mb__after_atomic();
8599 * The generic stuff only does filemap_write_and_wait_range, which
8600 * isn't enough if we've written compressed pages to this area, so
8601 * we need to flush the dirty pages again to make absolutely sure
8602 * that any outstanding dirty pages are on disk.
8604 count = iov_iter_count(iter);
8605 if (test_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
8606 &BTRFS_I(inode)->runtime_flags))
8607 filemap_fdatawrite_range(inode->i_mapping, offset,
8608 offset + count - 1);
8610 if (iov_iter_rw(iter) == WRITE) {
8612 * If the write DIO is beyond the EOF, we need update
8613 * the isize, but it is protected by i_mutex. So we can
8614 * not unlock the i_mutex at this case.
8616 if (offset + count <= inode->i_size) {
8617 dio_data.overwrite = 1;
8618 inode_unlock(inode);
8621 ret = btrfs_delalloc_reserve_space(inode, offset, count);
8624 dio_data.outstanding_extents = count_max_extents(count);
8627 * We need to know how many extents we reserved so that we can
8628 * do the accounting properly if we go over the number we
8629 * originally calculated. Abuse current->journal_info for this.
8631 dio_data.reserve = round_up(count,
8632 fs_info->sectorsize);
8633 dio_data.unsubmitted_oe_range_start = (u64)offset;
8634 dio_data.unsubmitted_oe_range_end = (u64)offset;
8635 current->journal_info = &dio_data;
8636 down_read(&BTRFS_I(inode)->dio_sem);
8637 } else if (test_bit(BTRFS_INODE_READDIO_NEED_LOCK,
8638 &BTRFS_I(inode)->runtime_flags)) {
8639 inode_dio_end(inode);
8640 flags = DIO_LOCKING | DIO_SKIP_HOLES;
8644 ret = __blockdev_direct_IO(iocb, inode,
8645 fs_info->fs_devices->latest_bdev,
8646 iter, btrfs_get_blocks_direct, NULL,
8647 btrfs_submit_direct, flags);
8648 if (iov_iter_rw(iter) == WRITE) {
8649 up_read(&BTRFS_I(inode)->dio_sem);
8650 current->journal_info = NULL;
8651 if (ret < 0 && ret != -EIOCBQUEUED) {
8652 if (dio_data.reserve)
8653 btrfs_delalloc_release_space(inode, offset,
8656 * On error we might have left some ordered extents
8657 * without submitting corresponding bios for them, so
8658 * cleanup them up to avoid other tasks getting them
8659 * and waiting for them to complete forever.
8661 if (dio_data.unsubmitted_oe_range_start <
8662 dio_data.unsubmitted_oe_range_end)
8663 btrfs_endio_direct_write_update_ordered(inode,
8664 dio_data.unsubmitted_oe_range_start,
8665 dio_data.unsubmitted_oe_range_end -
8666 dio_data.unsubmitted_oe_range_start,
8668 } else if (ret >= 0 && (size_t)ret < count)
8669 btrfs_delalloc_release_space(inode, offset,
8670 count - (size_t)ret);
8674 inode_dio_end(inode);
8681 #define BTRFS_FIEMAP_FLAGS (FIEMAP_FLAG_SYNC)
8683 static int btrfs_fiemap(struct inode *inode, struct fiemap_extent_info *fieinfo,
8684 __u64 start, __u64 len)
8688 ret = fiemap_check_flags(fieinfo, BTRFS_FIEMAP_FLAGS);
8692 return extent_fiemap(inode, fieinfo, start, len, btrfs_get_extent_fiemap);
8695 int btrfs_readpage(struct file *file, struct page *page)
8697 struct extent_io_tree *tree;
8698 tree = &BTRFS_I(page->mapping->host)->io_tree;
8699 return extent_read_full_page(tree, page, btrfs_get_extent, 0);
8702 static int btrfs_writepage(struct page *page, struct writeback_control *wbc)
8704 struct extent_io_tree *tree;
8705 struct inode *inode = page->mapping->host;
8708 if (current->flags & PF_MEMALLOC) {
8709 redirty_page_for_writepage(wbc, page);
8715 * If we are under memory pressure we will call this directly from the
8716 * VM, we need to make sure we have the inode referenced for the ordered
8717 * extent. If not just return like we didn't do anything.
8719 if (!igrab(inode)) {
8720 redirty_page_for_writepage(wbc, page);
8721 return AOP_WRITEPAGE_ACTIVATE;
8723 tree = &BTRFS_I(page->mapping->host)->io_tree;
8724 ret = extent_write_full_page(tree, page, btrfs_get_extent, wbc);
8725 btrfs_add_delayed_iput(inode);
8729 static int btrfs_writepages(struct address_space *mapping,
8730 struct writeback_control *wbc)
8732 struct extent_io_tree *tree;
8734 tree = &BTRFS_I(mapping->host)->io_tree;
8735 return extent_writepages(tree, mapping, btrfs_get_extent, wbc);
8739 btrfs_readpages(struct file *file, struct address_space *mapping,
8740 struct list_head *pages, unsigned nr_pages)
8742 struct extent_io_tree *tree;
8743 tree = &BTRFS_I(mapping->host)->io_tree;
8744 return extent_readpages(tree, mapping, pages, nr_pages,
8747 static int __btrfs_releasepage(struct page *page, gfp_t gfp_flags)
8749 struct extent_io_tree *tree;
8750 struct extent_map_tree *map;
8753 tree = &BTRFS_I(page->mapping->host)->io_tree;
8754 map = &BTRFS_I(page->mapping->host)->extent_tree;
8755 ret = try_release_extent_mapping(map, tree, page, gfp_flags);
8757 ClearPagePrivate(page);
8758 set_page_private(page, 0);
8764 static int btrfs_releasepage(struct page *page, gfp_t gfp_flags)
8766 if (PageWriteback(page) || PageDirty(page))
8768 return __btrfs_releasepage(page, gfp_flags);
8771 static void btrfs_invalidatepage(struct page *page, unsigned int offset,
8772 unsigned int length)
8774 struct inode *inode = page->mapping->host;
8775 struct extent_io_tree *tree;
8776 struct btrfs_ordered_extent *ordered;
8777 struct extent_state *cached_state = NULL;
8778 u64 page_start = page_offset(page);
8779 u64 page_end = page_start + PAGE_SIZE - 1;
8782 int inode_evicting = inode->i_state & I_FREEING;
8785 * we have the page locked, so new writeback can't start,
8786 * and the dirty bit won't be cleared while we are here.
8788 * Wait for IO on this page so that we can safely clear
8789 * the PagePrivate2 bit and do ordered accounting
8791 wait_on_page_writeback(page);
8793 tree = &BTRFS_I(inode)->io_tree;
8795 btrfs_releasepage(page, GFP_NOFS);
8799 if (!inode_evicting)
8800 lock_extent_bits(tree, page_start, page_end, &cached_state);
8803 ordered = btrfs_lookup_ordered_range(BTRFS_I(inode), start,
8804 page_end - start + 1);
8806 end = min(page_end, ordered->file_offset + ordered->len - 1);
8808 * IO on this page will never be started, so we need
8809 * to account for any ordered extents now
8811 if (!inode_evicting)
8812 clear_extent_bit(tree, start, end,
8813 EXTENT_DIRTY | EXTENT_DELALLOC |
8814 EXTENT_LOCKED | EXTENT_DO_ACCOUNTING |
8815 EXTENT_DEFRAG, 1, 0, &cached_state,
8818 * whoever cleared the private bit is responsible
8819 * for the finish_ordered_io
8821 if (TestClearPagePrivate2(page)) {
8822 struct btrfs_ordered_inode_tree *tree;
8825 tree = &BTRFS_I(inode)->ordered_tree;
8827 spin_lock_irq(&tree->lock);
8828 set_bit(BTRFS_ORDERED_TRUNCATED, &ordered->flags);
8829 new_len = start - ordered->file_offset;
8830 if (new_len < ordered->truncated_len)
8831 ordered->truncated_len = new_len;
8832 spin_unlock_irq(&tree->lock);
8834 if (btrfs_dec_test_ordered_pending(inode, &ordered,
8836 end - start + 1, 1))
8837 btrfs_finish_ordered_io(ordered);
8839 btrfs_put_ordered_extent(ordered);
8840 if (!inode_evicting) {
8841 cached_state = NULL;
8842 lock_extent_bits(tree, start, end,
8847 if (start < page_end)
8852 * Qgroup reserved space handler
8853 * Page here will be either
8854 * 1) Already written to disk
8855 * In this case, its reserved space is released from data rsv map
8856 * and will be freed by delayed_ref handler finally.
8857 * So even we call qgroup_free_data(), it won't decrease reserved
8859 * 2) Not written to disk
8860 * This means the reserved space should be freed here. However,
8861 * if a truncate invalidates the page (by clearing PageDirty)
8862 * and the page is accounted for while allocating extent
8863 * in btrfs_check_data_free_space() we let delayed_ref to
8864 * free the entire extent.
8866 if (PageDirty(page))
8867 btrfs_qgroup_free_data(inode, page_start, PAGE_SIZE);
8868 if (!inode_evicting) {
8869 clear_extent_bit(tree, page_start, page_end,
8870 EXTENT_LOCKED | EXTENT_DIRTY |
8871 EXTENT_DELALLOC | EXTENT_DO_ACCOUNTING |
8872 EXTENT_DEFRAG, 1, 1,
8873 &cached_state, GFP_NOFS);
8875 __btrfs_releasepage(page, GFP_NOFS);
8878 ClearPageChecked(page);
8879 if (PagePrivate(page)) {
8880 ClearPagePrivate(page);
8881 set_page_private(page, 0);
8887 * btrfs_page_mkwrite() is not allowed to change the file size as it gets
8888 * called from a page fault handler when a page is first dirtied. Hence we must
8889 * be careful to check for EOF conditions here. We set the page up correctly
8890 * for a written page which means we get ENOSPC checking when writing into
8891 * holes and correct delalloc and unwritten extent mapping on filesystems that
8892 * support these features.
8894 * We are not allowed to take the i_mutex here so we have to play games to
8895 * protect against truncate races as the page could now be beyond EOF. Because
8896 * vmtruncate() writes the inode size before removing pages, once we have the
8897 * page lock we can determine safely if the page is beyond EOF. If it is not
8898 * beyond EOF, then the page is guaranteed safe against truncation until we
8901 int btrfs_page_mkwrite(struct vm_area_struct *vma, struct vm_fault *vmf)
8903 struct page *page = vmf->page;
8904 struct inode *inode = file_inode(vma->vm_file);
8905 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
8906 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
8907 struct btrfs_ordered_extent *ordered;
8908 struct extent_state *cached_state = NULL;
8910 unsigned long zero_start;
8919 reserved_space = PAGE_SIZE;
8921 sb_start_pagefault(inode->i_sb);
8922 page_start = page_offset(page);
8923 page_end = page_start + PAGE_SIZE - 1;
8927 * Reserving delalloc space after obtaining the page lock can lead to
8928 * deadlock. For example, if a dirty page is locked by this function
8929 * and the call to btrfs_delalloc_reserve_space() ends up triggering
8930 * dirty page write out, then the btrfs_writepage() function could
8931 * end up waiting indefinitely to get a lock on the page currently
8932 * being processed by btrfs_page_mkwrite() function.
8934 ret = btrfs_delalloc_reserve_space(inode, page_start,
8937 ret = file_update_time(vma->vm_file);
8943 else /* -ENOSPC, -EIO, etc */
8944 ret = VM_FAULT_SIGBUS;
8950 ret = VM_FAULT_NOPAGE; /* make the VM retry the fault */
8953 size = i_size_read(inode);
8955 if ((page->mapping != inode->i_mapping) ||
8956 (page_start >= size)) {
8957 /* page got truncated out from underneath us */
8960 wait_on_page_writeback(page);
8962 lock_extent_bits(io_tree, page_start, page_end, &cached_state);
8963 set_page_extent_mapped(page);
8966 * we can't set the delalloc bits if there are pending ordered
8967 * extents. Drop our locks and wait for them to finish
8969 ordered = btrfs_lookup_ordered_range(BTRFS_I(inode), page_start,
8972 unlock_extent_cached(io_tree, page_start, page_end,
8973 &cached_state, GFP_NOFS);
8975 btrfs_start_ordered_extent(inode, ordered, 1);
8976 btrfs_put_ordered_extent(ordered);
8980 if (page->index == ((size - 1) >> PAGE_SHIFT)) {
8981 reserved_space = round_up(size - page_start,
8982 fs_info->sectorsize);
8983 if (reserved_space < PAGE_SIZE) {
8984 end = page_start + reserved_space - 1;
8985 spin_lock(&BTRFS_I(inode)->lock);
8986 BTRFS_I(inode)->outstanding_extents++;
8987 spin_unlock(&BTRFS_I(inode)->lock);
8988 btrfs_delalloc_release_space(inode, page_start,
8989 PAGE_SIZE - reserved_space);
8994 * page_mkwrite gets called when the page is firstly dirtied after it's
8995 * faulted in, but write(2) could also dirty a page and set delalloc
8996 * bits, thus in this case for space account reason, we still need to
8997 * clear any delalloc bits within this page range since we have to
8998 * reserve data&meta space before lock_page() (see above comments).
9000 clear_extent_bit(&BTRFS_I(inode)->io_tree, page_start, end,
9001 EXTENT_DIRTY | EXTENT_DELALLOC |
9002 EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG,
9003 0, 0, &cached_state, GFP_NOFS);
9005 ret = btrfs_set_extent_delalloc(inode, page_start, end,
9008 unlock_extent_cached(io_tree, page_start, page_end,
9009 &cached_state, GFP_NOFS);
9010 ret = VM_FAULT_SIGBUS;
9015 /* page is wholly or partially inside EOF */
9016 if (page_start + PAGE_SIZE > size)
9017 zero_start = size & ~PAGE_MASK;
9019 zero_start = PAGE_SIZE;
9021 if (zero_start != PAGE_SIZE) {
9023 memset(kaddr + zero_start, 0, PAGE_SIZE - zero_start);
9024 flush_dcache_page(page);
9027 ClearPageChecked(page);
9028 set_page_dirty(page);
9029 SetPageUptodate(page);
9031 BTRFS_I(inode)->last_trans = fs_info->generation;
9032 BTRFS_I(inode)->last_sub_trans = BTRFS_I(inode)->root->log_transid;
9033 BTRFS_I(inode)->last_log_commit = BTRFS_I(inode)->root->last_log_commit;
9035 unlock_extent_cached(io_tree, page_start, page_end, &cached_state, GFP_NOFS);
9039 sb_end_pagefault(inode->i_sb);
9040 return VM_FAULT_LOCKED;
9044 btrfs_delalloc_release_space(inode, page_start, reserved_space);
9046 sb_end_pagefault(inode->i_sb);
9050 static int btrfs_truncate(struct inode *inode)
9052 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
9053 struct btrfs_root *root = BTRFS_I(inode)->root;
9054 struct btrfs_block_rsv *rsv;
9057 struct btrfs_trans_handle *trans;
9058 u64 mask = fs_info->sectorsize - 1;
9059 u64 min_size = btrfs_calc_trunc_metadata_size(fs_info, 1);
9061 ret = btrfs_wait_ordered_range(inode, inode->i_size & (~mask),
9067 * Yes ladies and gentlemen, this is indeed ugly. The fact is we have
9068 * 3 things going on here
9070 * 1) We need to reserve space for our orphan item and the space to
9071 * delete our orphan item. Lord knows we don't want to have a dangling
9072 * orphan item because we didn't reserve space to remove it.
9074 * 2) We need to reserve space to update our inode.
9076 * 3) We need to have something to cache all the space that is going to
9077 * be free'd up by the truncate operation, but also have some slack
9078 * space reserved in case it uses space during the truncate (thank you
9079 * very much snapshotting).
9081 * And we need these to all be separate. The fact is we can use a lot of
9082 * space doing the truncate, and we have no earthly idea how much space
9083 * we will use, so we need the truncate reservation to be separate so it
9084 * doesn't end up using space reserved for updating the inode or
9085 * removing the orphan item. We also need to be able to stop the
9086 * transaction and start a new one, which means we need to be able to
9087 * update the inode several times, and we have no idea of knowing how
9088 * many times that will be, so we can't just reserve 1 item for the
9089 * entirety of the operation, so that has to be done separately as well.
9090 * Then there is the orphan item, which does indeed need to be held on
9091 * to for the whole operation, and we need nobody to touch this reserved
9092 * space except the orphan code.
9094 * So that leaves us with
9096 * 1) root->orphan_block_rsv - for the orphan deletion.
9097 * 2) rsv - for the truncate reservation, which we will steal from the
9098 * transaction reservation.
9099 * 3) fs_info->trans_block_rsv - this will have 1 items worth left for
9100 * updating the inode.
9102 rsv = btrfs_alloc_block_rsv(fs_info, BTRFS_BLOCK_RSV_TEMP);
9105 rsv->size = min_size;
9109 * 1 for the truncate slack space
9110 * 1 for updating the inode.
9112 trans = btrfs_start_transaction(root, 2);
9113 if (IS_ERR(trans)) {
9114 err = PTR_ERR(trans);
9118 /* Migrate the slack space for the truncate to our reserve */
9119 ret = btrfs_block_rsv_migrate(&fs_info->trans_block_rsv, rsv,
9124 * So if we truncate and then write and fsync we normally would just
9125 * write the extents that changed, which is a problem if we need to
9126 * first truncate that entire inode. So set this flag so we write out
9127 * all of the extents in the inode to the sync log so we're completely
9130 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &BTRFS_I(inode)->runtime_flags);
9131 trans->block_rsv = rsv;
9134 ret = btrfs_truncate_inode_items(trans, root, inode,
9136 BTRFS_EXTENT_DATA_KEY);
9137 if (ret != -ENOSPC && ret != -EAGAIN) {
9142 trans->block_rsv = &fs_info->trans_block_rsv;
9143 ret = btrfs_update_inode(trans, root, inode);
9149 btrfs_end_transaction(trans);
9150 btrfs_btree_balance_dirty(fs_info);
9152 trans = btrfs_start_transaction(root, 2);
9153 if (IS_ERR(trans)) {
9154 ret = err = PTR_ERR(trans);
9159 btrfs_block_rsv_release(fs_info, rsv, -1);
9160 ret = btrfs_block_rsv_migrate(&fs_info->trans_block_rsv,
9162 BUG_ON(ret); /* shouldn't happen */
9163 trans->block_rsv = rsv;
9166 if (ret == 0 && inode->i_nlink > 0) {
9167 trans->block_rsv = root->orphan_block_rsv;
9168 ret = btrfs_orphan_del(trans, BTRFS_I(inode));
9174 trans->block_rsv = &fs_info->trans_block_rsv;
9175 ret = btrfs_update_inode(trans, root, inode);
9179 ret = btrfs_end_transaction(trans);
9180 btrfs_btree_balance_dirty(fs_info);
9183 btrfs_free_block_rsv(fs_info, rsv);
9192 * create a new subvolume directory/inode (helper for the ioctl).
9194 int btrfs_create_subvol_root(struct btrfs_trans_handle *trans,
9195 struct btrfs_root *new_root,
9196 struct btrfs_root *parent_root,
9199 struct inode *inode;
9203 inode = btrfs_new_inode(trans, new_root, NULL, "..", 2,
9204 new_dirid, new_dirid,
9205 S_IFDIR | (~current_umask() & S_IRWXUGO),
9208 return PTR_ERR(inode);
9209 inode->i_op = &btrfs_dir_inode_operations;
9210 inode->i_fop = &btrfs_dir_file_operations;
9212 set_nlink(inode, 1);
9213 btrfs_i_size_write(BTRFS_I(inode), 0);
9214 unlock_new_inode(inode);
9216 err = btrfs_subvol_inherit_props(trans, new_root, parent_root);
9218 btrfs_err(new_root->fs_info,
9219 "error inheriting subvolume %llu properties: %d",
9220 new_root->root_key.objectid, err);
9222 err = btrfs_update_inode(trans, new_root, inode);
9228 struct inode *btrfs_alloc_inode(struct super_block *sb)
9230 struct btrfs_inode *ei;
9231 struct inode *inode;
9233 ei = kmem_cache_alloc(btrfs_inode_cachep, GFP_NOFS);
9240 ei->last_sub_trans = 0;
9241 ei->logged_trans = 0;
9242 ei->delalloc_bytes = 0;
9243 ei->defrag_bytes = 0;
9244 ei->disk_i_size = 0;
9247 ei->index_cnt = (u64)-1;
9249 ei->last_unlink_trans = 0;
9250 ei->last_log_commit = 0;
9251 ei->delayed_iput_count = 0;
9253 spin_lock_init(&ei->lock);
9254 ei->outstanding_extents = 0;
9255 ei->reserved_extents = 0;
9257 ei->runtime_flags = 0;
9258 ei->force_compress = BTRFS_COMPRESS_NONE;
9260 ei->delayed_node = NULL;
9262 ei->i_otime.tv_sec = 0;
9263 ei->i_otime.tv_nsec = 0;
9265 inode = &ei->vfs_inode;
9266 extent_map_tree_init(&ei->extent_tree);
9267 extent_io_tree_init(&ei->io_tree, &inode->i_data);
9268 extent_io_tree_init(&ei->io_failure_tree, &inode->i_data);
9269 ei->io_tree.track_uptodate = 1;
9270 ei->io_failure_tree.track_uptodate = 1;
9271 atomic_set(&ei->sync_writers, 0);
9272 mutex_init(&ei->log_mutex);
9273 mutex_init(&ei->delalloc_mutex);
9274 btrfs_ordered_inode_tree_init(&ei->ordered_tree);
9275 INIT_LIST_HEAD(&ei->delalloc_inodes);
9276 INIT_LIST_HEAD(&ei->delayed_iput);
9277 RB_CLEAR_NODE(&ei->rb_node);
9278 init_rwsem(&ei->dio_sem);
9283 #ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
9284 void btrfs_test_destroy_inode(struct inode *inode)
9286 btrfs_drop_extent_cache(BTRFS_I(inode), 0, (u64)-1, 0);
9287 kmem_cache_free(btrfs_inode_cachep, BTRFS_I(inode));
9291 static void btrfs_i_callback(struct rcu_head *head)
9293 struct inode *inode = container_of(head, struct inode, i_rcu);
9294 kmem_cache_free(btrfs_inode_cachep, BTRFS_I(inode));
9297 void btrfs_destroy_inode(struct inode *inode)
9299 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
9300 struct btrfs_ordered_extent *ordered;
9301 struct btrfs_root *root = BTRFS_I(inode)->root;
9303 WARN_ON(!hlist_empty(&inode->i_dentry));
9304 WARN_ON(inode->i_data.nrpages);
9305 WARN_ON(BTRFS_I(inode)->outstanding_extents);
9306 WARN_ON(BTRFS_I(inode)->reserved_extents);
9307 WARN_ON(BTRFS_I(inode)->delalloc_bytes);
9308 WARN_ON(BTRFS_I(inode)->csum_bytes);
9309 WARN_ON(BTRFS_I(inode)->defrag_bytes);
9312 * This can happen where we create an inode, but somebody else also
9313 * created the same inode and we need to destroy the one we already
9319 if (test_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
9320 &BTRFS_I(inode)->runtime_flags)) {
9321 btrfs_info(fs_info, "inode %llu still on the orphan list",
9322 btrfs_ino(BTRFS_I(inode)));
9323 atomic_dec(&root->orphan_inodes);
9327 ordered = btrfs_lookup_first_ordered_extent(inode, (u64)-1);
9332 "found ordered extent %llu %llu on inode cleanup",
9333 ordered->file_offset, ordered->len);
9334 btrfs_remove_ordered_extent(inode, ordered);
9335 btrfs_put_ordered_extent(ordered);
9336 btrfs_put_ordered_extent(ordered);
9339 btrfs_qgroup_check_reserved_leak(inode);
9340 inode_tree_del(inode);
9341 btrfs_drop_extent_cache(BTRFS_I(inode), 0, (u64)-1, 0);
9343 call_rcu(&inode->i_rcu, btrfs_i_callback);
9346 int btrfs_drop_inode(struct inode *inode)
9348 struct btrfs_root *root = BTRFS_I(inode)->root;
9353 /* the snap/subvol tree is on deleting */
9354 if (btrfs_root_refs(&root->root_item) == 0)
9357 return generic_drop_inode(inode);
9360 static void init_once(void *foo)
9362 struct btrfs_inode *ei = (struct btrfs_inode *) foo;
9364 inode_init_once(&ei->vfs_inode);
9367 void btrfs_destroy_cachep(void)
9370 * Make sure all delayed rcu free inodes are flushed before we
9374 kmem_cache_destroy(btrfs_inode_cachep);
9375 kmem_cache_destroy(btrfs_trans_handle_cachep);
9376 kmem_cache_destroy(btrfs_transaction_cachep);
9377 kmem_cache_destroy(btrfs_path_cachep);
9378 kmem_cache_destroy(btrfs_free_space_cachep);
9381 int btrfs_init_cachep(void)
9383 btrfs_inode_cachep = kmem_cache_create("btrfs_inode",
9384 sizeof(struct btrfs_inode), 0,
9385 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD | SLAB_ACCOUNT,
9387 if (!btrfs_inode_cachep)
9390 btrfs_trans_handle_cachep = kmem_cache_create("btrfs_trans_handle",
9391 sizeof(struct btrfs_trans_handle), 0,
9392 SLAB_TEMPORARY | SLAB_MEM_SPREAD, NULL);
9393 if (!btrfs_trans_handle_cachep)
9396 btrfs_transaction_cachep = kmem_cache_create("btrfs_transaction",
9397 sizeof(struct btrfs_transaction), 0,
9398 SLAB_TEMPORARY | SLAB_MEM_SPREAD, NULL);
9399 if (!btrfs_transaction_cachep)
9402 btrfs_path_cachep = kmem_cache_create("btrfs_path",
9403 sizeof(struct btrfs_path), 0,
9404 SLAB_MEM_SPREAD, NULL);
9405 if (!btrfs_path_cachep)
9408 btrfs_free_space_cachep = kmem_cache_create("btrfs_free_space",
9409 sizeof(struct btrfs_free_space), 0,
9410 SLAB_MEM_SPREAD, NULL);
9411 if (!btrfs_free_space_cachep)
9416 btrfs_destroy_cachep();
9420 static int btrfs_getattr(struct vfsmount *mnt,
9421 struct dentry *dentry, struct kstat *stat)
9424 struct inode *inode = d_inode(dentry);
9425 u32 blocksize = inode->i_sb->s_blocksize;
9427 generic_fillattr(inode, stat);
9428 stat->dev = BTRFS_I(inode)->root->anon_dev;
9430 spin_lock(&BTRFS_I(inode)->lock);
9431 delalloc_bytes = BTRFS_I(inode)->delalloc_bytes;
9432 spin_unlock(&BTRFS_I(inode)->lock);
9433 stat->blocks = (ALIGN(inode_get_bytes(inode), blocksize) +
9434 ALIGN(delalloc_bytes, blocksize)) >> 9;
9438 static int btrfs_rename_exchange(struct inode *old_dir,
9439 struct dentry *old_dentry,
9440 struct inode *new_dir,
9441 struct dentry *new_dentry)
9443 struct btrfs_fs_info *fs_info = btrfs_sb(old_dir->i_sb);
9444 struct btrfs_trans_handle *trans;
9445 struct btrfs_root *root = BTRFS_I(old_dir)->root;
9446 struct btrfs_root *dest = BTRFS_I(new_dir)->root;
9447 struct inode *new_inode = new_dentry->d_inode;
9448 struct inode *old_inode = old_dentry->d_inode;
9449 struct timespec ctime = current_time(old_inode);
9450 struct dentry *parent;
9451 u64 old_ino = btrfs_ino(BTRFS_I(old_inode));
9452 u64 new_ino = btrfs_ino(BTRFS_I(new_inode));
9457 bool root_log_pinned = false;
9458 bool dest_log_pinned = false;
9460 /* we only allow rename subvolume link between subvolumes */
9461 if (old_ino != BTRFS_FIRST_FREE_OBJECTID && root != dest)
9464 /* close the race window with snapshot create/destroy ioctl */
9465 if (old_ino == BTRFS_FIRST_FREE_OBJECTID)
9466 down_read(&fs_info->subvol_sem);
9467 if (new_ino == BTRFS_FIRST_FREE_OBJECTID)
9468 down_read(&fs_info->subvol_sem);
9471 * We want to reserve the absolute worst case amount of items. So if
9472 * both inodes are subvols and we need to unlink them then that would
9473 * require 4 item modifications, but if they are both normal inodes it
9474 * would require 5 item modifications, so we'll assume their normal
9475 * inodes. So 5 * 2 is 10, plus 2 for the new links, so 12 total items
9476 * should cover the worst case number of items we'll modify.
9478 trans = btrfs_start_transaction(root, 12);
9479 if (IS_ERR(trans)) {
9480 ret = PTR_ERR(trans);
9485 * We need to find a free sequence number both in the source and
9486 * in the destination directory for the exchange.
9488 ret = btrfs_set_inode_index(BTRFS_I(new_dir), &old_idx);
9491 ret = btrfs_set_inode_index(BTRFS_I(old_dir), &new_idx);
9495 BTRFS_I(old_inode)->dir_index = 0ULL;
9496 BTRFS_I(new_inode)->dir_index = 0ULL;
9498 /* Reference for the source. */
9499 if (old_ino == BTRFS_FIRST_FREE_OBJECTID) {
9500 /* force full log commit if subvolume involved. */
9501 btrfs_set_log_full_commit(fs_info, trans);
9503 btrfs_pin_log_trans(root);
9504 root_log_pinned = true;
9505 ret = btrfs_insert_inode_ref(trans, dest,
9506 new_dentry->d_name.name,
9507 new_dentry->d_name.len,
9509 btrfs_ino(BTRFS_I(new_dir)),
9515 /* And now for the dest. */
9516 if (new_ino == BTRFS_FIRST_FREE_OBJECTID) {
9517 /* force full log commit if subvolume involved. */
9518 btrfs_set_log_full_commit(fs_info, trans);
9520 btrfs_pin_log_trans(dest);
9521 dest_log_pinned = true;
9522 ret = btrfs_insert_inode_ref(trans, root,
9523 old_dentry->d_name.name,
9524 old_dentry->d_name.len,
9526 btrfs_ino(BTRFS_I(old_dir)),
9532 /* Update inode version and ctime/mtime. */
9533 inode_inc_iversion(old_dir);
9534 inode_inc_iversion(new_dir);
9535 inode_inc_iversion(old_inode);
9536 inode_inc_iversion(new_inode);
9537 old_dir->i_ctime = old_dir->i_mtime = ctime;
9538 new_dir->i_ctime = new_dir->i_mtime = ctime;
9539 old_inode->i_ctime = ctime;
9540 new_inode->i_ctime = ctime;
9542 if (old_dentry->d_parent != new_dentry->d_parent) {
9543 btrfs_record_unlink_dir(trans, BTRFS_I(old_dir),
9544 BTRFS_I(old_inode), 1);
9545 btrfs_record_unlink_dir(trans, BTRFS_I(new_dir),
9546 BTRFS_I(new_inode), 1);
9549 /* src is a subvolume */
9550 if (old_ino == BTRFS_FIRST_FREE_OBJECTID) {
9551 root_objectid = BTRFS_I(old_inode)->root->root_key.objectid;
9552 ret = btrfs_unlink_subvol(trans, root, old_dir,
9554 old_dentry->d_name.name,
9555 old_dentry->d_name.len);
9556 } else { /* src is an inode */
9557 ret = __btrfs_unlink_inode(trans, root, BTRFS_I(old_dir),
9558 BTRFS_I(old_dentry->d_inode),
9559 old_dentry->d_name.name,
9560 old_dentry->d_name.len);
9562 ret = btrfs_update_inode(trans, root, old_inode);
9565 btrfs_abort_transaction(trans, ret);
9569 /* dest is a subvolume */
9570 if (new_ino == BTRFS_FIRST_FREE_OBJECTID) {
9571 root_objectid = BTRFS_I(new_inode)->root->root_key.objectid;
9572 ret = btrfs_unlink_subvol(trans, dest, new_dir,
9574 new_dentry->d_name.name,
9575 new_dentry->d_name.len);
9576 } else { /* dest is an inode */
9577 ret = __btrfs_unlink_inode(trans, dest, BTRFS_I(new_dir),
9578 BTRFS_I(new_dentry->d_inode),
9579 new_dentry->d_name.name,
9580 new_dentry->d_name.len);
9582 ret = btrfs_update_inode(trans, dest, new_inode);
9585 btrfs_abort_transaction(trans, ret);
9589 ret = btrfs_add_link(trans, BTRFS_I(new_dir), BTRFS_I(old_inode),
9590 new_dentry->d_name.name,
9591 new_dentry->d_name.len, 0, old_idx);
9593 btrfs_abort_transaction(trans, ret);
9597 ret = btrfs_add_link(trans, BTRFS_I(old_dir), BTRFS_I(new_inode),
9598 old_dentry->d_name.name,
9599 old_dentry->d_name.len, 0, new_idx);
9601 btrfs_abort_transaction(trans, ret);
9605 if (old_inode->i_nlink == 1)
9606 BTRFS_I(old_inode)->dir_index = old_idx;
9607 if (new_inode->i_nlink == 1)
9608 BTRFS_I(new_inode)->dir_index = new_idx;
9610 if (root_log_pinned) {
9611 parent = new_dentry->d_parent;
9612 btrfs_log_new_name(trans, BTRFS_I(old_inode), BTRFS_I(old_dir),
9614 btrfs_end_log_trans(root);
9615 root_log_pinned = false;
9617 if (dest_log_pinned) {
9618 parent = old_dentry->d_parent;
9619 btrfs_log_new_name(trans, BTRFS_I(new_inode), BTRFS_I(new_dir),
9621 btrfs_end_log_trans(dest);
9622 dest_log_pinned = false;
9626 * If we have pinned a log and an error happened, we unpin tasks
9627 * trying to sync the log and force them to fallback to a transaction
9628 * commit if the log currently contains any of the inodes involved in
9629 * this rename operation (to ensure we do not persist a log with an
9630 * inconsistent state for any of these inodes or leading to any
9631 * inconsistencies when replayed). If the transaction was aborted, the
9632 * abortion reason is propagated to userspace when attempting to commit
9633 * the transaction. If the log does not contain any of these inodes, we
9634 * allow the tasks to sync it.
9636 if (ret && (root_log_pinned || dest_log_pinned)) {
9637 if (btrfs_inode_in_log(BTRFS_I(old_dir), fs_info->generation) ||
9638 btrfs_inode_in_log(BTRFS_I(new_dir), fs_info->generation) ||
9639 btrfs_inode_in_log(BTRFS_I(old_inode), fs_info->generation) ||
9641 btrfs_inode_in_log(BTRFS_I(new_inode), fs_info->generation)))
9642 btrfs_set_log_full_commit(fs_info, trans);
9644 if (root_log_pinned) {
9645 btrfs_end_log_trans(root);
9646 root_log_pinned = false;
9648 if (dest_log_pinned) {
9649 btrfs_end_log_trans(dest);
9650 dest_log_pinned = false;
9653 ret = btrfs_end_transaction(trans);
9655 if (new_ino == BTRFS_FIRST_FREE_OBJECTID)
9656 up_read(&fs_info->subvol_sem);
9657 if (old_ino == BTRFS_FIRST_FREE_OBJECTID)
9658 up_read(&fs_info->subvol_sem);
9663 static int btrfs_whiteout_for_rename(struct btrfs_trans_handle *trans,
9664 struct btrfs_root *root,
9666 struct dentry *dentry)
9669 struct inode *inode;
9673 ret = btrfs_find_free_ino(root, &objectid);
9677 inode = btrfs_new_inode(trans, root, dir,
9678 dentry->d_name.name,
9680 btrfs_ino(BTRFS_I(dir)),
9682 S_IFCHR | WHITEOUT_MODE,
9685 if (IS_ERR(inode)) {
9686 ret = PTR_ERR(inode);
9690 inode->i_op = &btrfs_special_inode_operations;
9691 init_special_inode(inode, inode->i_mode,
9694 ret = btrfs_init_inode_security(trans, inode, dir,
9699 ret = btrfs_add_nondir(trans, BTRFS_I(dir), dentry,
9700 BTRFS_I(inode), 0, index);
9704 ret = btrfs_update_inode(trans, root, inode);
9706 unlock_new_inode(inode);
9708 inode_dec_link_count(inode);
9714 static int btrfs_rename(struct inode *old_dir, struct dentry *old_dentry,
9715 struct inode *new_dir, struct dentry *new_dentry,
9718 struct btrfs_fs_info *fs_info = btrfs_sb(old_dir->i_sb);
9719 struct btrfs_trans_handle *trans;
9720 unsigned int trans_num_items;
9721 struct btrfs_root *root = BTRFS_I(old_dir)->root;
9722 struct btrfs_root *dest = BTRFS_I(new_dir)->root;
9723 struct inode *new_inode = d_inode(new_dentry);
9724 struct inode *old_inode = d_inode(old_dentry);
9728 u64 old_ino = btrfs_ino(BTRFS_I(old_inode));
9729 bool log_pinned = false;
9731 if (btrfs_ino(BTRFS_I(new_dir)) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)
9734 /* we only allow rename subvolume link between subvolumes */
9735 if (old_ino != BTRFS_FIRST_FREE_OBJECTID && root != dest)
9738 if (old_ino == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID ||
9739 (new_inode && btrfs_ino(BTRFS_I(new_inode)) == BTRFS_FIRST_FREE_OBJECTID))
9742 if (S_ISDIR(old_inode->i_mode) && new_inode &&
9743 new_inode->i_size > BTRFS_EMPTY_DIR_SIZE)
9747 /* check for collisions, even if the name isn't there */
9748 ret = btrfs_check_dir_item_collision(dest, new_dir->i_ino,
9749 new_dentry->d_name.name,
9750 new_dentry->d_name.len);
9753 if (ret == -EEXIST) {
9755 * eexist without a new_inode */
9756 if (WARN_ON(!new_inode)) {
9760 /* maybe -EOVERFLOW */
9767 * we're using rename to replace one file with another. Start IO on it
9768 * now so we don't add too much work to the end of the transaction
9770 if (new_inode && S_ISREG(old_inode->i_mode) && new_inode->i_size)
9771 filemap_flush(old_inode->i_mapping);
9773 /* close the racy window with snapshot create/destroy ioctl */
9774 if (old_ino == BTRFS_FIRST_FREE_OBJECTID)
9775 down_read(&fs_info->subvol_sem);
9777 * We want to reserve the absolute worst case amount of items. So if
9778 * both inodes are subvols and we need to unlink them then that would
9779 * require 4 item modifications, but if they are both normal inodes it
9780 * would require 5 item modifications, so we'll assume they are normal
9781 * inodes. So 5 * 2 is 10, plus 1 for the new link, so 11 total items
9782 * should cover the worst case number of items we'll modify.
9783 * If our rename has the whiteout flag, we need more 5 units for the
9784 * new inode (1 inode item, 1 inode ref, 2 dir items and 1 xattr item
9785 * when selinux is enabled).
9787 trans_num_items = 11;
9788 if (flags & RENAME_WHITEOUT)
9789 trans_num_items += 5;
9790 trans = btrfs_start_transaction(root, trans_num_items);
9791 if (IS_ERR(trans)) {
9792 ret = PTR_ERR(trans);
9797 btrfs_record_root_in_trans(trans, dest);
9799 ret = btrfs_set_inode_index(BTRFS_I(new_dir), &index);
9803 BTRFS_I(old_inode)->dir_index = 0ULL;
9804 if (unlikely(old_ino == BTRFS_FIRST_FREE_OBJECTID)) {
9805 /* force full log commit if subvolume involved. */
9806 btrfs_set_log_full_commit(fs_info, trans);
9808 btrfs_pin_log_trans(root);
9810 ret = btrfs_insert_inode_ref(trans, dest,
9811 new_dentry->d_name.name,
9812 new_dentry->d_name.len,
9814 btrfs_ino(BTRFS_I(new_dir)), index);
9819 inode_inc_iversion(old_dir);
9820 inode_inc_iversion(new_dir);
9821 inode_inc_iversion(old_inode);
9822 old_dir->i_ctime = old_dir->i_mtime =
9823 new_dir->i_ctime = new_dir->i_mtime =
9824 old_inode->i_ctime = current_time(old_dir);
9826 if (old_dentry->d_parent != new_dentry->d_parent)
9827 btrfs_record_unlink_dir(trans, BTRFS_I(old_dir),
9828 BTRFS_I(old_inode), 1);
9830 if (unlikely(old_ino == BTRFS_FIRST_FREE_OBJECTID)) {
9831 root_objectid = BTRFS_I(old_inode)->root->root_key.objectid;
9832 ret = btrfs_unlink_subvol(trans, root, old_dir, root_objectid,
9833 old_dentry->d_name.name,
9834 old_dentry->d_name.len);
9836 ret = __btrfs_unlink_inode(trans, root, BTRFS_I(old_dir),
9837 BTRFS_I(d_inode(old_dentry)),
9838 old_dentry->d_name.name,
9839 old_dentry->d_name.len);
9841 ret = btrfs_update_inode(trans, root, old_inode);
9844 btrfs_abort_transaction(trans, ret);
9849 inode_inc_iversion(new_inode);
9850 new_inode->i_ctime = current_time(new_inode);
9851 if (unlikely(btrfs_ino(BTRFS_I(new_inode)) ==
9852 BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)) {
9853 root_objectid = BTRFS_I(new_inode)->location.objectid;
9854 ret = btrfs_unlink_subvol(trans, dest, new_dir,
9856 new_dentry->d_name.name,
9857 new_dentry->d_name.len);
9858 BUG_ON(new_inode->i_nlink == 0);
9860 ret = btrfs_unlink_inode(trans, dest, BTRFS_I(new_dir),
9861 BTRFS_I(d_inode(new_dentry)),
9862 new_dentry->d_name.name,
9863 new_dentry->d_name.len);
9865 if (!ret && new_inode->i_nlink == 0)
9866 ret = btrfs_orphan_add(trans,
9867 BTRFS_I(d_inode(new_dentry)));
9869 btrfs_abort_transaction(trans, ret);
9874 ret = btrfs_add_link(trans, BTRFS_I(new_dir), BTRFS_I(old_inode),
9875 new_dentry->d_name.name,
9876 new_dentry->d_name.len, 0, index);
9878 btrfs_abort_transaction(trans, ret);
9882 if (old_inode->i_nlink == 1)
9883 BTRFS_I(old_inode)->dir_index = index;
9886 struct dentry *parent = new_dentry->d_parent;
9888 btrfs_log_new_name(trans, BTRFS_I(old_inode), BTRFS_I(old_dir),
9890 btrfs_end_log_trans(root);
9894 if (flags & RENAME_WHITEOUT) {
9895 ret = btrfs_whiteout_for_rename(trans, root, old_dir,
9899 btrfs_abort_transaction(trans, ret);
9905 * If we have pinned the log and an error happened, we unpin tasks
9906 * trying to sync the log and force them to fallback to a transaction
9907 * commit if the log currently contains any of the inodes involved in
9908 * this rename operation (to ensure we do not persist a log with an
9909 * inconsistent state for any of these inodes or leading to any
9910 * inconsistencies when replayed). If the transaction was aborted, the
9911 * abortion reason is propagated to userspace when attempting to commit
9912 * the transaction. If the log does not contain any of these inodes, we
9913 * allow the tasks to sync it.
9915 if (ret && log_pinned) {
9916 if (btrfs_inode_in_log(BTRFS_I(old_dir), fs_info->generation) ||
9917 btrfs_inode_in_log(BTRFS_I(new_dir), fs_info->generation) ||
9918 btrfs_inode_in_log(BTRFS_I(old_inode), fs_info->generation) ||
9920 btrfs_inode_in_log(BTRFS_I(new_inode), fs_info->generation)))
9921 btrfs_set_log_full_commit(fs_info, trans);
9923 btrfs_end_log_trans(root);
9926 btrfs_end_transaction(trans);
9928 if (old_ino == BTRFS_FIRST_FREE_OBJECTID)
9929 up_read(&fs_info->subvol_sem);
9934 static int btrfs_rename2(struct inode *old_dir, struct dentry *old_dentry,
9935 struct inode *new_dir, struct dentry *new_dentry,
9938 if (flags & ~(RENAME_NOREPLACE | RENAME_EXCHANGE | RENAME_WHITEOUT))
9941 if (flags & RENAME_EXCHANGE)
9942 return btrfs_rename_exchange(old_dir, old_dentry, new_dir,
9945 return btrfs_rename(old_dir, old_dentry, new_dir, new_dentry, flags);
9948 static void btrfs_run_delalloc_work(struct btrfs_work *work)
9950 struct btrfs_delalloc_work *delalloc_work;
9951 struct inode *inode;
9953 delalloc_work = container_of(work, struct btrfs_delalloc_work,
9955 inode = delalloc_work->inode;
9956 filemap_flush(inode->i_mapping);
9957 if (test_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
9958 &BTRFS_I(inode)->runtime_flags))
9959 filemap_flush(inode->i_mapping);
9961 if (delalloc_work->delay_iput)
9962 btrfs_add_delayed_iput(inode);
9965 complete(&delalloc_work->completion);
9968 struct btrfs_delalloc_work *btrfs_alloc_delalloc_work(struct inode *inode,
9971 struct btrfs_delalloc_work *work;
9973 work = kmalloc(sizeof(*work), GFP_NOFS);
9977 init_completion(&work->completion);
9978 INIT_LIST_HEAD(&work->list);
9979 work->inode = inode;
9980 work->delay_iput = delay_iput;
9981 WARN_ON_ONCE(!inode);
9982 btrfs_init_work(&work->work, btrfs_flush_delalloc_helper,
9983 btrfs_run_delalloc_work, NULL, NULL);
9988 void btrfs_wait_and_free_delalloc_work(struct btrfs_delalloc_work *work)
9990 wait_for_completion(&work->completion);
9995 * some fairly slow code that needs optimization. This walks the list
9996 * of all the inodes with pending delalloc and forces them to disk.
9998 static int __start_delalloc_inodes(struct btrfs_root *root, int delay_iput,
10001 struct btrfs_inode *binode;
10002 struct inode *inode;
10003 struct btrfs_delalloc_work *work, *next;
10004 struct list_head works;
10005 struct list_head splice;
10008 INIT_LIST_HEAD(&works);
10009 INIT_LIST_HEAD(&splice);
10011 mutex_lock(&root->delalloc_mutex);
10012 spin_lock(&root->delalloc_lock);
10013 list_splice_init(&root->delalloc_inodes, &splice);
10014 while (!list_empty(&splice)) {
10015 binode = list_entry(splice.next, struct btrfs_inode,
10018 list_move_tail(&binode->delalloc_inodes,
10019 &root->delalloc_inodes);
10020 inode = igrab(&binode->vfs_inode);
10022 cond_resched_lock(&root->delalloc_lock);
10025 spin_unlock(&root->delalloc_lock);
10027 work = btrfs_alloc_delalloc_work(inode, delay_iput);
10030 btrfs_add_delayed_iput(inode);
10036 list_add_tail(&work->list, &works);
10037 btrfs_queue_work(root->fs_info->flush_workers,
10040 if (nr != -1 && ret >= nr)
10043 spin_lock(&root->delalloc_lock);
10045 spin_unlock(&root->delalloc_lock);
10048 list_for_each_entry_safe(work, next, &works, list) {
10049 list_del_init(&work->list);
10050 btrfs_wait_and_free_delalloc_work(work);
10053 if (!list_empty_careful(&splice)) {
10054 spin_lock(&root->delalloc_lock);
10055 list_splice_tail(&splice, &root->delalloc_inodes);
10056 spin_unlock(&root->delalloc_lock);
10058 mutex_unlock(&root->delalloc_mutex);
10062 int btrfs_start_delalloc_inodes(struct btrfs_root *root, int delay_iput)
10064 struct btrfs_fs_info *fs_info = root->fs_info;
10067 if (test_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state))
10070 ret = __start_delalloc_inodes(root, delay_iput, -1);
10074 * the filemap_flush will queue IO into the worker threads, but
10075 * we have to make sure the IO is actually started and that
10076 * ordered extents get created before we return
10078 atomic_inc(&fs_info->async_submit_draining);
10079 while (atomic_read(&fs_info->nr_async_submits) ||
10080 atomic_read(&fs_info->async_delalloc_pages)) {
10081 wait_event(fs_info->async_submit_wait,
10082 (atomic_read(&fs_info->nr_async_submits) == 0 &&
10083 atomic_read(&fs_info->async_delalloc_pages) == 0));
10085 atomic_dec(&fs_info->async_submit_draining);
10089 int btrfs_start_delalloc_roots(struct btrfs_fs_info *fs_info, int delay_iput,
10092 struct btrfs_root *root;
10093 struct list_head splice;
10096 if (test_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state))
10099 INIT_LIST_HEAD(&splice);
10101 mutex_lock(&fs_info->delalloc_root_mutex);
10102 spin_lock(&fs_info->delalloc_root_lock);
10103 list_splice_init(&fs_info->delalloc_roots, &splice);
10104 while (!list_empty(&splice) && nr) {
10105 root = list_first_entry(&splice, struct btrfs_root,
10107 root = btrfs_grab_fs_root(root);
10109 list_move_tail(&root->delalloc_root,
10110 &fs_info->delalloc_roots);
10111 spin_unlock(&fs_info->delalloc_root_lock);
10113 ret = __start_delalloc_inodes(root, delay_iput, nr);
10114 btrfs_put_fs_root(root);
10122 spin_lock(&fs_info->delalloc_root_lock);
10124 spin_unlock(&fs_info->delalloc_root_lock);
10127 atomic_inc(&fs_info->async_submit_draining);
10128 while (atomic_read(&fs_info->nr_async_submits) ||
10129 atomic_read(&fs_info->async_delalloc_pages)) {
10130 wait_event(fs_info->async_submit_wait,
10131 (atomic_read(&fs_info->nr_async_submits) == 0 &&
10132 atomic_read(&fs_info->async_delalloc_pages) == 0));
10134 atomic_dec(&fs_info->async_submit_draining);
10136 if (!list_empty_careful(&splice)) {
10137 spin_lock(&fs_info->delalloc_root_lock);
10138 list_splice_tail(&splice, &fs_info->delalloc_roots);
10139 spin_unlock(&fs_info->delalloc_root_lock);
10141 mutex_unlock(&fs_info->delalloc_root_mutex);
10145 static int btrfs_symlink(struct inode *dir, struct dentry *dentry,
10146 const char *symname)
10148 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
10149 struct btrfs_trans_handle *trans;
10150 struct btrfs_root *root = BTRFS_I(dir)->root;
10151 struct btrfs_path *path;
10152 struct btrfs_key key;
10153 struct inode *inode = NULL;
10155 int drop_inode = 0;
10161 struct btrfs_file_extent_item *ei;
10162 struct extent_buffer *leaf;
10164 name_len = strlen(symname);
10165 if (name_len > BTRFS_MAX_INLINE_DATA_SIZE(fs_info))
10166 return -ENAMETOOLONG;
10169 * 2 items for inode item and ref
10170 * 2 items for dir items
10171 * 1 item for updating parent inode item
10172 * 1 item for the inline extent item
10173 * 1 item for xattr if selinux is on
10175 trans = btrfs_start_transaction(root, 7);
10177 return PTR_ERR(trans);
10179 err = btrfs_find_free_ino(root, &objectid);
10183 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
10184 dentry->d_name.len, btrfs_ino(BTRFS_I(dir)),
10185 objectid, S_IFLNK|S_IRWXUGO, &index);
10186 if (IS_ERR(inode)) {
10187 err = PTR_ERR(inode);
10192 * If the active LSM wants to access the inode during
10193 * d_instantiate it needs these. Smack checks to see
10194 * if the filesystem supports xattrs by looking at the
10197 inode->i_fop = &btrfs_file_operations;
10198 inode->i_op = &btrfs_file_inode_operations;
10199 inode->i_mapping->a_ops = &btrfs_aops;
10200 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
10202 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
10204 goto out_unlock_inode;
10206 path = btrfs_alloc_path();
10209 goto out_unlock_inode;
10211 key.objectid = btrfs_ino(BTRFS_I(inode));
10213 key.type = BTRFS_EXTENT_DATA_KEY;
10214 datasize = btrfs_file_extent_calc_inline_size(name_len);
10215 err = btrfs_insert_empty_item(trans, root, path, &key,
10218 btrfs_free_path(path);
10219 goto out_unlock_inode;
10221 leaf = path->nodes[0];
10222 ei = btrfs_item_ptr(leaf, path->slots[0],
10223 struct btrfs_file_extent_item);
10224 btrfs_set_file_extent_generation(leaf, ei, trans->transid);
10225 btrfs_set_file_extent_type(leaf, ei,
10226 BTRFS_FILE_EXTENT_INLINE);
10227 btrfs_set_file_extent_encryption(leaf, ei, 0);
10228 btrfs_set_file_extent_compression(leaf, ei, 0);
10229 btrfs_set_file_extent_other_encoding(leaf, ei, 0);
10230 btrfs_set_file_extent_ram_bytes(leaf, ei, name_len);
10232 ptr = btrfs_file_extent_inline_start(ei);
10233 write_extent_buffer(leaf, symname, ptr, name_len);
10234 btrfs_mark_buffer_dirty(leaf);
10235 btrfs_free_path(path);
10237 inode->i_op = &btrfs_symlink_inode_operations;
10238 inode_nohighmem(inode);
10239 inode->i_mapping->a_ops = &btrfs_symlink_aops;
10240 inode_set_bytes(inode, name_len);
10241 btrfs_i_size_write(BTRFS_I(inode), name_len);
10242 err = btrfs_update_inode(trans, root, inode);
10244 * Last step, add directory indexes for our symlink inode. This is the
10245 * last step to avoid extra cleanup of these indexes if an error happens
10249 err = btrfs_add_nondir(trans, BTRFS_I(dir), dentry,
10250 BTRFS_I(inode), 0, index);
10253 goto out_unlock_inode;
10256 unlock_new_inode(inode);
10257 d_instantiate(dentry, inode);
10260 btrfs_end_transaction(trans);
10262 inode_dec_link_count(inode);
10265 btrfs_btree_balance_dirty(fs_info);
10270 unlock_new_inode(inode);
10274 static int __btrfs_prealloc_file_range(struct inode *inode, int mode,
10275 u64 start, u64 num_bytes, u64 min_size,
10276 loff_t actual_len, u64 *alloc_hint,
10277 struct btrfs_trans_handle *trans)
10279 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
10280 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
10281 struct extent_map *em;
10282 struct btrfs_root *root = BTRFS_I(inode)->root;
10283 struct btrfs_key ins;
10284 u64 cur_offset = start;
10287 u64 last_alloc = (u64)-1;
10289 bool own_trans = true;
10290 u64 end = start + num_bytes - 1;
10294 while (num_bytes > 0) {
10296 trans = btrfs_start_transaction(root, 3);
10297 if (IS_ERR(trans)) {
10298 ret = PTR_ERR(trans);
10303 cur_bytes = min_t(u64, num_bytes, SZ_256M);
10304 cur_bytes = max(cur_bytes, min_size);
10306 * If we are severely fragmented we could end up with really
10307 * small allocations, so if the allocator is returning small
10308 * chunks lets make its job easier by only searching for those
10311 cur_bytes = min(cur_bytes, last_alloc);
10312 ret = btrfs_reserve_extent(root, cur_bytes, cur_bytes,
10313 min_size, 0, *alloc_hint, &ins, 1, 0);
10316 btrfs_end_transaction(trans);
10319 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
10321 last_alloc = ins.offset;
10322 ret = insert_reserved_file_extent(trans, inode,
10323 cur_offset, ins.objectid,
10324 ins.offset, ins.offset,
10325 ins.offset, 0, 0, 0,
10326 BTRFS_FILE_EXTENT_PREALLOC);
10328 btrfs_free_reserved_extent(fs_info, ins.objectid,
10330 btrfs_abort_transaction(trans, ret);
10332 btrfs_end_transaction(trans);
10336 btrfs_drop_extent_cache(BTRFS_I(inode), cur_offset,
10337 cur_offset + ins.offset -1, 0);
10339 em = alloc_extent_map();
10341 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
10342 &BTRFS_I(inode)->runtime_flags);
10346 em->start = cur_offset;
10347 em->orig_start = cur_offset;
10348 em->len = ins.offset;
10349 em->block_start = ins.objectid;
10350 em->block_len = ins.offset;
10351 em->orig_block_len = ins.offset;
10352 em->ram_bytes = ins.offset;
10353 em->bdev = fs_info->fs_devices->latest_bdev;
10354 set_bit(EXTENT_FLAG_PREALLOC, &em->flags);
10355 em->generation = trans->transid;
10358 write_lock(&em_tree->lock);
10359 ret = add_extent_mapping(em_tree, em, 1);
10360 write_unlock(&em_tree->lock);
10361 if (ret != -EEXIST)
10363 btrfs_drop_extent_cache(BTRFS_I(inode), cur_offset,
10364 cur_offset + ins.offset - 1,
10367 free_extent_map(em);
10369 num_bytes -= ins.offset;
10370 cur_offset += ins.offset;
10371 *alloc_hint = ins.objectid + ins.offset;
10373 inode_inc_iversion(inode);
10374 inode->i_ctime = current_time(inode);
10375 BTRFS_I(inode)->flags |= BTRFS_INODE_PREALLOC;
10376 if (!(mode & FALLOC_FL_KEEP_SIZE) &&
10377 (actual_len > inode->i_size) &&
10378 (cur_offset > inode->i_size)) {
10379 if (cur_offset > actual_len)
10380 i_size = actual_len;
10382 i_size = cur_offset;
10383 i_size_write(inode, i_size);
10384 btrfs_ordered_update_i_size(inode, i_size, NULL);
10387 ret = btrfs_update_inode(trans, root, inode);
10390 btrfs_abort_transaction(trans, ret);
10392 btrfs_end_transaction(trans);
10397 btrfs_end_transaction(trans);
10399 if (cur_offset < end)
10400 btrfs_free_reserved_data_space(inode, cur_offset,
10401 end - cur_offset + 1);
10405 int btrfs_prealloc_file_range(struct inode *inode, int mode,
10406 u64 start, u64 num_bytes, u64 min_size,
10407 loff_t actual_len, u64 *alloc_hint)
10409 return __btrfs_prealloc_file_range(inode, mode, start, num_bytes,
10410 min_size, actual_len, alloc_hint,
10414 int btrfs_prealloc_file_range_trans(struct inode *inode,
10415 struct btrfs_trans_handle *trans, int mode,
10416 u64 start, u64 num_bytes, u64 min_size,
10417 loff_t actual_len, u64 *alloc_hint)
10419 return __btrfs_prealloc_file_range(inode, mode, start, num_bytes,
10420 min_size, actual_len, alloc_hint, trans);
10423 static int btrfs_set_page_dirty(struct page *page)
10425 return __set_page_dirty_nobuffers(page);
10428 static int btrfs_permission(struct inode *inode, int mask)
10430 struct btrfs_root *root = BTRFS_I(inode)->root;
10431 umode_t mode = inode->i_mode;
10433 if (mask & MAY_WRITE &&
10434 (S_ISREG(mode) || S_ISDIR(mode) || S_ISLNK(mode))) {
10435 if (btrfs_root_readonly(root))
10437 if (BTRFS_I(inode)->flags & BTRFS_INODE_READONLY)
10440 return generic_permission(inode, mask);
10443 static int btrfs_tmpfile(struct inode *dir, struct dentry *dentry, umode_t mode)
10445 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
10446 struct btrfs_trans_handle *trans;
10447 struct btrfs_root *root = BTRFS_I(dir)->root;
10448 struct inode *inode = NULL;
10454 * 5 units required for adding orphan entry
10456 trans = btrfs_start_transaction(root, 5);
10458 return PTR_ERR(trans);
10460 ret = btrfs_find_free_ino(root, &objectid);
10464 inode = btrfs_new_inode(trans, root, dir, NULL, 0,
10465 btrfs_ino(BTRFS_I(dir)), objectid, mode, &index);
10466 if (IS_ERR(inode)) {
10467 ret = PTR_ERR(inode);
10472 inode->i_fop = &btrfs_file_operations;
10473 inode->i_op = &btrfs_file_inode_operations;
10475 inode->i_mapping->a_ops = &btrfs_aops;
10476 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
10478 ret = btrfs_init_inode_security(trans, inode, dir, NULL);
10482 ret = btrfs_update_inode(trans, root, inode);
10485 ret = btrfs_orphan_add(trans, BTRFS_I(inode));
10490 * We set number of links to 0 in btrfs_new_inode(), and here we set
10491 * it to 1 because d_tmpfile() will issue a warning if the count is 0,
10494 * d_tmpfile() -> inode_dec_link_count() -> drop_nlink()
10496 set_nlink(inode, 1);
10497 unlock_new_inode(inode);
10498 d_tmpfile(dentry, inode);
10499 mark_inode_dirty(inode);
10502 btrfs_end_transaction(trans);
10505 btrfs_balance_delayed_items(fs_info);
10506 btrfs_btree_balance_dirty(fs_info);
10510 unlock_new_inode(inode);
10515 static const struct inode_operations btrfs_dir_inode_operations = {
10516 .getattr = btrfs_getattr,
10517 .lookup = btrfs_lookup,
10518 .create = btrfs_create,
10519 .unlink = btrfs_unlink,
10520 .link = btrfs_link,
10521 .mkdir = btrfs_mkdir,
10522 .rmdir = btrfs_rmdir,
10523 .rename = btrfs_rename2,
10524 .symlink = btrfs_symlink,
10525 .setattr = btrfs_setattr,
10526 .mknod = btrfs_mknod,
10527 .listxattr = btrfs_listxattr,
10528 .permission = btrfs_permission,
10529 .get_acl = btrfs_get_acl,
10530 .set_acl = btrfs_set_acl,
10531 .update_time = btrfs_update_time,
10532 .tmpfile = btrfs_tmpfile,
10534 static const struct inode_operations btrfs_dir_ro_inode_operations = {
10535 .lookup = btrfs_lookup,
10536 .permission = btrfs_permission,
10537 .update_time = btrfs_update_time,
10540 static const struct file_operations btrfs_dir_file_operations = {
10541 .llseek = generic_file_llseek,
10542 .read = generic_read_dir,
10543 .iterate_shared = btrfs_real_readdir,
10544 .unlocked_ioctl = btrfs_ioctl,
10545 #ifdef CONFIG_COMPAT
10546 .compat_ioctl = btrfs_compat_ioctl,
10548 .release = btrfs_release_file,
10549 .fsync = btrfs_sync_file,
10552 static const struct extent_io_ops btrfs_extent_io_ops = {
10553 .fill_delalloc = run_delalloc_range,
10554 .submit_bio_hook = btrfs_submit_bio_hook,
10555 .merge_bio_hook = btrfs_merge_bio_hook,
10556 .readpage_end_io_hook = btrfs_readpage_end_io_hook,
10557 .writepage_end_io_hook = btrfs_writepage_end_io_hook,
10558 .writepage_start_hook = btrfs_writepage_start_hook,
10559 .set_bit_hook = btrfs_set_bit_hook,
10560 .clear_bit_hook = btrfs_clear_bit_hook,
10561 .merge_extent_hook = btrfs_merge_extent_hook,
10562 .split_extent_hook = btrfs_split_extent_hook,
10566 * btrfs doesn't support the bmap operation because swapfiles
10567 * use bmap to make a mapping of extents in the file. They assume
10568 * these extents won't change over the life of the file and they
10569 * use the bmap result to do IO directly to the drive.
10571 * the btrfs bmap call would return logical addresses that aren't
10572 * suitable for IO and they also will change frequently as COW
10573 * operations happen. So, swapfile + btrfs == corruption.
10575 * For now we're avoiding this by dropping bmap.
10577 static const struct address_space_operations btrfs_aops = {
10578 .readpage = btrfs_readpage,
10579 .writepage = btrfs_writepage,
10580 .writepages = btrfs_writepages,
10581 .readpages = btrfs_readpages,
10582 .direct_IO = btrfs_direct_IO,
10583 .invalidatepage = btrfs_invalidatepage,
10584 .releasepage = btrfs_releasepage,
10585 .set_page_dirty = btrfs_set_page_dirty,
10586 .error_remove_page = generic_error_remove_page,
10589 static const struct address_space_operations btrfs_symlink_aops = {
10590 .readpage = btrfs_readpage,
10591 .writepage = btrfs_writepage,
10592 .invalidatepage = btrfs_invalidatepage,
10593 .releasepage = btrfs_releasepage,
10596 static const struct inode_operations btrfs_file_inode_operations = {
10597 .getattr = btrfs_getattr,
10598 .setattr = btrfs_setattr,
10599 .listxattr = btrfs_listxattr,
10600 .permission = btrfs_permission,
10601 .fiemap = btrfs_fiemap,
10602 .get_acl = btrfs_get_acl,
10603 .set_acl = btrfs_set_acl,
10604 .update_time = btrfs_update_time,
10606 static const struct inode_operations btrfs_special_inode_operations = {
10607 .getattr = btrfs_getattr,
10608 .setattr = btrfs_setattr,
10609 .permission = btrfs_permission,
10610 .listxattr = btrfs_listxattr,
10611 .get_acl = btrfs_get_acl,
10612 .set_acl = btrfs_set_acl,
10613 .update_time = btrfs_update_time,
10615 static const struct inode_operations btrfs_symlink_inode_operations = {
10616 .get_link = page_get_link,
10617 .getattr = btrfs_getattr,
10618 .setattr = btrfs_setattr,
10619 .permission = btrfs_permission,
10620 .listxattr = btrfs_listxattr,
10621 .update_time = btrfs_update_time,
10624 const struct dentry_operations btrfs_dentry_operations = {
10625 .d_delete = btrfs_dentry_delete,
10626 .d_release = btrfs_dentry_release,