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>
45 #include <linux/magic.h>
46 #include <linux/iversion.h>
49 #include "transaction.h"
50 #include "btrfs_inode.h"
51 #include "print-tree.h"
52 #include "ordered-data.h"
56 #include "compression.h"
58 #include "free-space-cache.h"
59 #include "inode-map.h"
66 struct btrfs_iget_args {
67 struct btrfs_key *location;
68 struct btrfs_root *root;
71 struct btrfs_dio_data {
73 u64 unsubmitted_oe_range_start;
74 u64 unsubmitted_oe_range_end;
78 static const struct inode_operations btrfs_dir_inode_operations;
79 static const struct inode_operations btrfs_symlink_inode_operations;
80 static const struct inode_operations btrfs_dir_ro_inode_operations;
81 static const struct inode_operations btrfs_special_inode_operations;
82 static const struct inode_operations btrfs_file_inode_operations;
83 static const struct address_space_operations btrfs_aops;
84 static const struct address_space_operations btrfs_symlink_aops;
85 static const struct file_operations btrfs_dir_file_operations;
86 static const struct extent_io_ops btrfs_extent_io_ops;
88 static struct kmem_cache *btrfs_inode_cachep;
89 struct kmem_cache *btrfs_trans_handle_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 void __endio_write_update_ordered(struct inode *inode,
119 const u64 offset, const u64 bytes,
120 const bool uptodate);
123 * Cleanup all submitted ordered extents in specified range to handle errors
124 * from the fill_dellaloc() callback.
126 * NOTE: caller must ensure that when an error happens, it can not call
127 * extent_clear_unlock_delalloc() to clear both the bits EXTENT_DO_ACCOUNTING
128 * and EXTENT_DELALLOC simultaneously, because that causes the reserved metadata
129 * to be released, which we want to happen only when finishing the ordered
130 * extent (btrfs_finish_ordered_io()). Also note that the caller of the
131 * fill_delalloc() callback already does proper cleanup for the first page of
132 * the range, that is, it invokes the callback writepage_end_io_hook() for the
133 * range of the first page.
135 static inline void btrfs_cleanup_ordered_extents(struct inode *inode,
139 unsigned long index = offset >> PAGE_SHIFT;
140 unsigned long end_index = (offset + bytes - 1) >> PAGE_SHIFT;
143 while (index <= end_index) {
144 page = find_get_page(inode->i_mapping, index);
148 ClearPagePrivate2(page);
151 return __endio_write_update_ordered(inode, offset + PAGE_SIZE,
152 bytes - PAGE_SIZE, false);
155 static int btrfs_dirty_inode(struct inode *inode);
157 #ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
158 void btrfs_test_inode_set_ops(struct inode *inode)
160 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
164 static int btrfs_init_inode_security(struct btrfs_trans_handle *trans,
165 struct inode *inode, struct inode *dir,
166 const struct qstr *qstr)
170 err = btrfs_init_acl(trans, inode, dir);
172 err = btrfs_xattr_security_init(trans, inode, dir, qstr);
177 * this does all the hard work for inserting an inline extent into
178 * the btree. The caller should have done a btrfs_drop_extents so that
179 * no overlapping inline items exist in the btree
181 static int insert_inline_extent(struct btrfs_trans_handle *trans,
182 struct btrfs_path *path, int extent_inserted,
183 struct btrfs_root *root, struct inode *inode,
184 u64 start, size_t size, size_t compressed_size,
186 struct page **compressed_pages)
188 struct extent_buffer *leaf;
189 struct page *page = NULL;
192 struct btrfs_file_extent_item *ei;
194 size_t cur_size = size;
195 unsigned long offset;
197 if (compressed_size && compressed_pages)
198 cur_size = compressed_size;
200 inode_add_bytes(inode, size);
202 if (!extent_inserted) {
203 struct btrfs_key key;
206 key.objectid = btrfs_ino(BTRFS_I(inode));
208 key.type = BTRFS_EXTENT_DATA_KEY;
210 datasize = btrfs_file_extent_calc_inline_size(cur_size);
211 path->leave_spinning = 1;
212 ret = btrfs_insert_empty_item(trans, root, path, &key,
217 leaf = path->nodes[0];
218 ei = btrfs_item_ptr(leaf, path->slots[0],
219 struct btrfs_file_extent_item);
220 btrfs_set_file_extent_generation(leaf, ei, trans->transid);
221 btrfs_set_file_extent_type(leaf, ei, BTRFS_FILE_EXTENT_INLINE);
222 btrfs_set_file_extent_encryption(leaf, ei, 0);
223 btrfs_set_file_extent_other_encoding(leaf, ei, 0);
224 btrfs_set_file_extent_ram_bytes(leaf, ei, size);
225 ptr = btrfs_file_extent_inline_start(ei);
227 if (compress_type != BTRFS_COMPRESS_NONE) {
230 while (compressed_size > 0) {
231 cpage = compressed_pages[i];
232 cur_size = min_t(unsigned long, compressed_size,
235 kaddr = kmap_atomic(cpage);
236 write_extent_buffer(leaf, kaddr, ptr, cur_size);
237 kunmap_atomic(kaddr);
241 compressed_size -= cur_size;
243 btrfs_set_file_extent_compression(leaf, ei,
246 page = find_get_page(inode->i_mapping,
247 start >> PAGE_SHIFT);
248 btrfs_set_file_extent_compression(leaf, ei, 0);
249 kaddr = kmap_atomic(page);
250 offset = start & (PAGE_SIZE - 1);
251 write_extent_buffer(leaf, kaddr + offset, ptr, size);
252 kunmap_atomic(kaddr);
255 btrfs_mark_buffer_dirty(leaf);
256 btrfs_release_path(path);
259 * we're an inline extent, so nobody can
260 * extend the file past i_size without locking
261 * a page we already have locked.
263 * We must do any isize and inode updates
264 * before we unlock the pages. Otherwise we
265 * could end up racing with unlink.
267 BTRFS_I(inode)->disk_i_size = inode->i_size;
268 ret = btrfs_update_inode(trans, root, inode);
276 * conditionally insert an inline extent into the file. This
277 * does the checks required to make sure the data is small enough
278 * to fit as an inline extent.
280 static noinline int cow_file_range_inline(struct btrfs_root *root,
281 struct inode *inode, u64 start,
282 u64 end, size_t compressed_size,
284 struct page **compressed_pages)
286 struct btrfs_fs_info *fs_info = root->fs_info;
287 struct btrfs_trans_handle *trans;
288 u64 isize = i_size_read(inode);
289 u64 actual_end = min(end + 1, isize);
290 u64 inline_len = actual_end - start;
291 u64 aligned_end = ALIGN(end, fs_info->sectorsize);
292 u64 data_len = inline_len;
294 struct btrfs_path *path;
295 int extent_inserted = 0;
296 u32 extent_item_size;
299 data_len = compressed_size;
302 actual_end > fs_info->sectorsize ||
303 data_len > BTRFS_MAX_INLINE_DATA_SIZE(fs_info) ||
305 (actual_end & (fs_info->sectorsize - 1)) == 0) ||
307 data_len > fs_info->max_inline) {
311 path = btrfs_alloc_path();
315 trans = btrfs_join_transaction(root);
317 btrfs_free_path(path);
318 return PTR_ERR(trans);
320 trans->block_rsv = &BTRFS_I(inode)->block_rsv;
322 if (compressed_size && compressed_pages)
323 extent_item_size = btrfs_file_extent_calc_inline_size(
326 extent_item_size = btrfs_file_extent_calc_inline_size(
329 ret = __btrfs_drop_extents(trans, root, inode, path,
330 start, aligned_end, NULL,
331 1, 1, extent_item_size, &extent_inserted);
333 btrfs_abort_transaction(trans, ret);
337 if (isize > actual_end)
338 inline_len = min_t(u64, isize, actual_end);
339 ret = insert_inline_extent(trans, path, extent_inserted,
341 inline_len, compressed_size,
342 compress_type, compressed_pages);
343 if (ret && ret != -ENOSPC) {
344 btrfs_abort_transaction(trans, ret);
346 } else if (ret == -ENOSPC) {
351 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &BTRFS_I(inode)->runtime_flags);
352 btrfs_drop_extent_cache(BTRFS_I(inode), start, aligned_end - 1, 0);
355 * Don't forget to free the reserved space, as for inlined extent
356 * it won't count as data extent, free them directly here.
357 * And at reserve time, it's always aligned to page size, so
358 * just free one page here.
360 btrfs_qgroup_free_data(inode, NULL, 0, PAGE_SIZE);
361 btrfs_free_path(path);
362 btrfs_end_transaction(trans);
366 struct async_extent {
371 unsigned long nr_pages;
373 struct list_head list;
378 struct btrfs_root *root;
379 struct page *locked_page;
382 unsigned int write_flags;
383 struct list_head extents;
384 struct btrfs_work work;
387 static noinline int add_async_extent(struct async_cow *cow,
388 u64 start, u64 ram_size,
391 unsigned long nr_pages,
394 struct async_extent *async_extent;
396 async_extent = kmalloc(sizeof(*async_extent), GFP_NOFS);
397 BUG_ON(!async_extent); /* -ENOMEM */
398 async_extent->start = start;
399 async_extent->ram_size = ram_size;
400 async_extent->compressed_size = compressed_size;
401 async_extent->pages = pages;
402 async_extent->nr_pages = nr_pages;
403 async_extent->compress_type = compress_type;
404 list_add_tail(&async_extent->list, &cow->extents);
408 static inline int inode_need_compress(struct inode *inode, u64 start, u64 end)
410 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
413 if (btrfs_test_opt(fs_info, FORCE_COMPRESS))
416 if (BTRFS_I(inode)->defrag_compress)
418 /* bad compression ratios */
419 if (BTRFS_I(inode)->flags & BTRFS_INODE_NOCOMPRESS)
421 if (btrfs_test_opt(fs_info, COMPRESS) ||
422 BTRFS_I(inode)->flags & BTRFS_INODE_COMPRESS ||
423 BTRFS_I(inode)->prop_compress)
424 return btrfs_compress_heuristic(inode, start, end);
428 static inline void inode_should_defrag(struct btrfs_inode *inode,
429 u64 start, u64 end, u64 num_bytes, u64 small_write)
431 /* If this is a small write inside eof, kick off a defrag */
432 if (num_bytes < small_write &&
433 (start > 0 || end + 1 < inode->disk_i_size))
434 btrfs_add_inode_defrag(NULL, inode);
438 * we create compressed extents in two phases. The first
439 * phase compresses a range of pages that have already been
440 * locked (both pages and state bits are locked).
442 * This is done inside an ordered work queue, and the compression
443 * is spread across many cpus. The actual IO submission is step
444 * two, and the ordered work queue takes care of making sure that
445 * happens in the same order things were put onto the queue by
446 * writepages and friends.
448 * If this code finds it can't get good compression, it puts an
449 * entry onto the work queue to write the uncompressed bytes. This
450 * makes sure that both compressed inodes and uncompressed inodes
451 * are written in the same order that the flusher thread sent them
454 static noinline void compress_file_range(struct inode *inode,
455 struct page *locked_page,
457 struct async_cow *async_cow,
460 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
461 struct btrfs_root *root = BTRFS_I(inode)->root;
462 u64 blocksize = fs_info->sectorsize;
464 u64 isize = i_size_read(inode);
466 struct page **pages = NULL;
467 unsigned long nr_pages;
468 unsigned long total_compressed = 0;
469 unsigned long total_in = 0;
472 int compress_type = fs_info->compress_type;
475 inode_should_defrag(BTRFS_I(inode), start, end, end - start + 1,
478 actual_end = min_t(u64, isize, end + 1);
481 nr_pages = (end >> PAGE_SHIFT) - (start >> PAGE_SHIFT) + 1;
482 BUILD_BUG_ON((BTRFS_MAX_COMPRESSED % PAGE_SIZE) != 0);
483 nr_pages = min_t(unsigned long, nr_pages,
484 BTRFS_MAX_COMPRESSED / PAGE_SIZE);
487 * we don't want to send crud past the end of i_size through
488 * compression, that's just a waste of CPU time. So, if the
489 * end of the file is before the start of our current
490 * requested range of bytes, we bail out to the uncompressed
491 * cleanup code that can deal with all of this.
493 * It isn't really the fastest way to fix things, but this is a
494 * very uncommon corner.
496 if (actual_end <= start)
497 goto cleanup_and_bail_uncompressed;
499 total_compressed = actual_end - start;
502 * skip compression for a small file range(<=blocksize) that
503 * isn't an inline extent, since it doesn't save disk space at all.
505 if (total_compressed <= blocksize &&
506 (start > 0 || end + 1 < BTRFS_I(inode)->disk_i_size))
507 goto cleanup_and_bail_uncompressed;
509 total_compressed = min_t(unsigned long, total_compressed,
510 BTRFS_MAX_UNCOMPRESSED);
515 * we do compression for mount -o compress and when the
516 * inode has not been flagged as nocompress. This flag can
517 * change at any time if we discover bad compression ratios.
519 if (inode_need_compress(inode, start, end)) {
521 pages = kcalloc(nr_pages, sizeof(struct page *), GFP_NOFS);
523 /* just bail out to the uncompressed code */
527 if (BTRFS_I(inode)->defrag_compress)
528 compress_type = BTRFS_I(inode)->defrag_compress;
529 else if (BTRFS_I(inode)->prop_compress)
530 compress_type = BTRFS_I(inode)->prop_compress;
533 * we need to call clear_page_dirty_for_io on each
534 * page in the range. Otherwise applications with the file
535 * mmap'd can wander in and change the page contents while
536 * we are compressing them.
538 * If the compression fails for any reason, we set the pages
539 * dirty again later on.
541 * Note that the remaining part is redirtied, the start pointer
542 * has moved, the end is the original one.
545 extent_range_clear_dirty_for_io(inode, start, end);
549 /* Compression level is applied here and only here */
550 ret = btrfs_compress_pages(
551 compress_type | (fs_info->compress_level << 4),
552 inode->i_mapping, start,
559 unsigned long offset = total_compressed &
561 struct page *page = pages[nr_pages - 1];
564 /* zero the tail end of the last page, we might be
565 * sending it down to disk
568 kaddr = kmap_atomic(page);
569 memset(kaddr + offset, 0,
571 kunmap_atomic(kaddr);
578 /* lets try to make an inline extent */
579 if (ret || total_in < actual_end) {
580 /* we didn't compress the entire range, try
581 * to make an uncompressed inline extent.
583 ret = cow_file_range_inline(root, inode, start, end,
584 0, BTRFS_COMPRESS_NONE, NULL);
586 /* try making a compressed inline extent */
587 ret = cow_file_range_inline(root, inode, start, end,
589 compress_type, pages);
592 unsigned long clear_flags = EXTENT_DELALLOC |
593 EXTENT_DELALLOC_NEW | EXTENT_DEFRAG |
594 EXTENT_DO_ACCOUNTING;
595 unsigned long page_error_op;
597 page_error_op = ret < 0 ? PAGE_SET_ERROR : 0;
600 * inline extent creation worked or returned error,
601 * we don't need to create any more async work items.
602 * Unlock and free up our temp pages.
604 * We use DO_ACCOUNTING here because we need the
605 * delalloc_release_metadata to be done _after_ we drop
606 * our outstanding extent for clearing delalloc for this
609 extent_clear_unlock_delalloc(inode, start, end, end,
622 * we aren't doing an inline extent round the compressed size
623 * up to a block size boundary so the allocator does sane
626 total_compressed = ALIGN(total_compressed, blocksize);
629 * one last check to make sure the compression is really a
630 * win, compare the page count read with the blocks on disk,
631 * compression must free at least one sector size
633 total_in = ALIGN(total_in, PAGE_SIZE);
634 if (total_compressed + blocksize <= total_in) {
638 * The async work queues will take care of doing actual
639 * allocation on disk for these compressed pages, and
640 * will submit them to the elevator.
642 add_async_extent(async_cow, start, total_in,
643 total_compressed, pages, nr_pages,
646 if (start + total_in < end) {
657 * the compression code ran but failed to make things smaller,
658 * free any pages it allocated and our page pointer array
660 for (i = 0; i < nr_pages; i++) {
661 WARN_ON(pages[i]->mapping);
666 total_compressed = 0;
669 /* flag the file so we don't compress in the future */
670 if (!btrfs_test_opt(fs_info, FORCE_COMPRESS) &&
671 !(BTRFS_I(inode)->prop_compress)) {
672 BTRFS_I(inode)->flags |= BTRFS_INODE_NOCOMPRESS;
675 cleanup_and_bail_uncompressed:
677 * No compression, but we still need to write the pages in the file
678 * we've been given so far. redirty the locked page if it corresponds
679 * to our extent and set things up for the async work queue to run
680 * cow_file_range to do the normal delalloc dance.
682 if (page_offset(locked_page) >= start &&
683 page_offset(locked_page) <= end)
684 __set_page_dirty_nobuffers(locked_page);
685 /* unlocked later on in the async handlers */
688 extent_range_redirty_for_io(inode, start, end);
689 add_async_extent(async_cow, start, end - start + 1, 0, NULL, 0,
690 BTRFS_COMPRESS_NONE);
696 for (i = 0; i < nr_pages; i++) {
697 WARN_ON(pages[i]->mapping);
703 static void free_async_extent_pages(struct async_extent *async_extent)
707 if (!async_extent->pages)
710 for (i = 0; i < async_extent->nr_pages; i++) {
711 WARN_ON(async_extent->pages[i]->mapping);
712 put_page(async_extent->pages[i]);
714 kfree(async_extent->pages);
715 async_extent->nr_pages = 0;
716 async_extent->pages = NULL;
720 * phase two of compressed writeback. This is the ordered portion
721 * of the code, which only gets called in the order the work was
722 * queued. We walk all the async extents created by compress_file_range
723 * and send them down to the disk.
725 static noinline void submit_compressed_extents(struct inode *inode,
726 struct async_cow *async_cow)
728 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
729 struct async_extent *async_extent;
731 struct btrfs_key ins;
732 struct extent_map *em;
733 struct btrfs_root *root = BTRFS_I(inode)->root;
734 struct extent_io_tree *io_tree;
738 while (!list_empty(&async_cow->extents)) {
739 async_extent = list_entry(async_cow->extents.next,
740 struct async_extent, list);
741 list_del(&async_extent->list);
743 io_tree = &BTRFS_I(inode)->io_tree;
746 /* did the compression code fall back to uncompressed IO? */
747 if (!async_extent->pages) {
748 int page_started = 0;
749 unsigned long nr_written = 0;
751 lock_extent(io_tree, async_extent->start,
752 async_extent->start +
753 async_extent->ram_size - 1);
755 /* allocate blocks */
756 ret = cow_file_range(inode, async_cow->locked_page,
758 async_extent->start +
759 async_extent->ram_size - 1,
760 async_extent->start +
761 async_extent->ram_size - 1,
762 &page_started, &nr_written, 0,
768 * if page_started, cow_file_range inserted an
769 * inline extent and took care of all the unlocking
770 * and IO for us. Otherwise, we need to submit
771 * all those pages down to the drive.
773 if (!page_started && !ret)
774 extent_write_locked_range(inode,
776 async_extent->start +
777 async_extent->ram_size - 1,
780 unlock_page(async_cow->locked_page);
786 lock_extent(io_tree, async_extent->start,
787 async_extent->start + async_extent->ram_size - 1);
789 ret = btrfs_reserve_extent(root, async_extent->ram_size,
790 async_extent->compressed_size,
791 async_extent->compressed_size,
792 0, alloc_hint, &ins, 1, 1);
794 free_async_extent_pages(async_extent);
796 if (ret == -ENOSPC) {
797 unlock_extent(io_tree, async_extent->start,
798 async_extent->start +
799 async_extent->ram_size - 1);
802 * we need to redirty the pages if we decide to
803 * fallback to uncompressed IO, otherwise we
804 * will not submit these pages down to lower
807 extent_range_redirty_for_io(inode,
809 async_extent->start +
810 async_extent->ram_size - 1);
817 * here we're doing allocation and writeback of the
820 em = create_io_em(inode, async_extent->start,
821 async_extent->ram_size, /* len */
822 async_extent->start, /* orig_start */
823 ins.objectid, /* block_start */
824 ins.offset, /* block_len */
825 ins.offset, /* orig_block_len */
826 async_extent->ram_size, /* ram_bytes */
827 async_extent->compress_type,
828 BTRFS_ORDERED_COMPRESSED);
830 /* ret value is not necessary due to void function */
831 goto out_free_reserve;
834 ret = btrfs_add_ordered_extent_compress(inode,
837 async_extent->ram_size,
839 BTRFS_ORDERED_COMPRESSED,
840 async_extent->compress_type);
842 btrfs_drop_extent_cache(BTRFS_I(inode),
844 async_extent->start +
845 async_extent->ram_size - 1, 0);
846 goto out_free_reserve;
848 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
851 * clear dirty, set writeback and unlock the pages.
853 extent_clear_unlock_delalloc(inode, async_extent->start,
854 async_extent->start +
855 async_extent->ram_size - 1,
856 async_extent->start +
857 async_extent->ram_size - 1,
858 NULL, EXTENT_LOCKED | EXTENT_DELALLOC,
859 PAGE_UNLOCK | PAGE_CLEAR_DIRTY |
861 if (btrfs_submit_compressed_write(inode,
863 async_extent->ram_size,
865 ins.offset, async_extent->pages,
866 async_extent->nr_pages,
867 async_cow->write_flags)) {
868 struct extent_io_tree *tree = &BTRFS_I(inode)->io_tree;
869 struct page *p = async_extent->pages[0];
870 const u64 start = async_extent->start;
871 const u64 end = start + async_extent->ram_size - 1;
873 p->mapping = inode->i_mapping;
874 tree->ops->writepage_end_io_hook(p, start, end,
877 extent_clear_unlock_delalloc(inode, start, end, end,
881 free_async_extent_pages(async_extent);
883 alloc_hint = ins.objectid + ins.offset;
889 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
890 btrfs_free_reserved_extent(fs_info, ins.objectid, ins.offset, 1);
892 extent_clear_unlock_delalloc(inode, async_extent->start,
893 async_extent->start +
894 async_extent->ram_size - 1,
895 async_extent->start +
896 async_extent->ram_size - 1,
897 NULL, EXTENT_LOCKED | EXTENT_DELALLOC |
898 EXTENT_DELALLOC_NEW |
899 EXTENT_DEFRAG | EXTENT_DO_ACCOUNTING,
900 PAGE_UNLOCK | PAGE_CLEAR_DIRTY |
901 PAGE_SET_WRITEBACK | PAGE_END_WRITEBACK |
903 free_async_extent_pages(async_extent);
908 static u64 get_extent_allocation_hint(struct inode *inode, u64 start,
911 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
912 struct extent_map *em;
915 read_lock(&em_tree->lock);
916 em = search_extent_mapping(em_tree, start, num_bytes);
919 * if block start isn't an actual block number then find the
920 * first block in this inode and use that as a hint. If that
921 * block is also bogus then just don't worry about it.
923 if (em->block_start >= EXTENT_MAP_LAST_BYTE) {
925 em = search_extent_mapping(em_tree, 0, 0);
926 if (em && em->block_start < EXTENT_MAP_LAST_BYTE)
927 alloc_hint = em->block_start;
931 alloc_hint = em->block_start;
935 read_unlock(&em_tree->lock);
941 * when extent_io.c finds a delayed allocation range in the file,
942 * the call backs end up in this code. The basic idea is to
943 * allocate extents on disk for the range, and create ordered data structs
944 * in ram to track those extents.
946 * locked_page is the page that writepage had locked already. We use
947 * it to make sure we don't do extra locks or unlocks.
949 * *page_started is set to one if we unlock locked_page and do everything
950 * required to start IO on it. It may be clean and already done with
953 static noinline int cow_file_range(struct inode *inode,
954 struct page *locked_page,
955 u64 start, u64 end, u64 delalloc_end,
956 int *page_started, unsigned long *nr_written,
957 int unlock, struct btrfs_dedupe_hash *hash)
959 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
960 struct btrfs_root *root = BTRFS_I(inode)->root;
963 unsigned long ram_size;
965 u64 cur_alloc_size = 0;
966 u64 blocksize = fs_info->sectorsize;
967 struct btrfs_key ins;
968 struct extent_map *em;
970 unsigned long page_ops;
971 bool extent_reserved = false;
974 if (btrfs_is_free_space_inode(BTRFS_I(inode))) {
980 num_bytes = ALIGN(end - start + 1, blocksize);
981 num_bytes = max(blocksize, num_bytes);
982 disk_num_bytes = num_bytes;
984 inode_should_defrag(BTRFS_I(inode), start, end, num_bytes, SZ_64K);
987 /* lets try to make an inline extent */
988 ret = cow_file_range_inline(root, inode, start, end, 0,
989 BTRFS_COMPRESS_NONE, NULL);
992 * We use DO_ACCOUNTING here because we need the
993 * delalloc_release_metadata to be run _after_ we drop
994 * our outstanding extent for clearing delalloc for this
997 extent_clear_unlock_delalloc(inode, start, end,
999 EXTENT_LOCKED | EXTENT_DELALLOC |
1000 EXTENT_DELALLOC_NEW | EXTENT_DEFRAG |
1001 EXTENT_DO_ACCOUNTING, PAGE_UNLOCK |
1002 PAGE_CLEAR_DIRTY | PAGE_SET_WRITEBACK |
1003 PAGE_END_WRITEBACK);
1004 *nr_written = *nr_written +
1005 (end - start + PAGE_SIZE) / PAGE_SIZE;
1008 } else if (ret < 0) {
1013 BUG_ON(disk_num_bytes >
1014 btrfs_super_total_bytes(fs_info->super_copy));
1016 alloc_hint = get_extent_allocation_hint(inode, start, num_bytes);
1017 btrfs_drop_extent_cache(BTRFS_I(inode), start,
1018 start + num_bytes - 1, 0);
1020 while (disk_num_bytes > 0) {
1021 cur_alloc_size = disk_num_bytes;
1022 ret = btrfs_reserve_extent(root, cur_alloc_size, cur_alloc_size,
1023 fs_info->sectorsize, 0, alloc_hint,
1027 cur_alloc_size = ins.offset;
1028 extent_reserved = true;
1030 ram_size = ins.offset;
1031 em = create_io_em(inode, start, ins.offset, /* len */
1032 start, /* orig_start */
1033 ins.objectid, /* block_start */
1034 ins.offset, /* block_len */
1035 ins.offset, /* orig_block_len */
1036 ram_size, /* ram_bytes */
1037 BTRFS_COMPRESS_NONE, /* compress_type */
1038 BTRFS_ORDERED_REGULAR /* type */);
1041 free_extent_map(em);
1043 ret = btrfs_add_ordered_extent(inode, start, ins.objectid,
1044 ram_size, cur_alloc_size, 0);
1046 goto out_drop_extent_cache;
1048 if (root->root_key.objectid ==
1049 BTRFS_DATA_RELOC_TREE_OBJECTID) {
1050 ret = btrfs_reloc_clone_csums(inode, start,
1053 * Only drop cache here, and process as normal.
1055 * We must not allow extent_clear_unlock_delalloc()
1056 * at out_unlock label to free meta of this ordered
1057 * extent, as its meta should be freed by
1058 * btrfs_finish_ordered_io().
1060 * So we must continue until @start is increased to
1061 * skip current ordered extent.
1064 btrfs_drop_extent_cache(BTRFS_I(inode), start,
1065 start + ram_size - 1, 0);
1068 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
1070 /* we're not doing compressed IO, don't unlock the first
1071 * page (which the caller expects to stay locked), don't
1072 * clear any dirty bits and don't set any writeback bits
1074 * Do set the Private2 bit so we know this page was properly
1075 * setup for writepage
1077 page_ops = unlock ? PAGE_UNLOCK : 0;
1078 page_ops |= PAGE_SET_PRIVATE2;
1080 extent_clear_unlock_delalloc(inode, start,
1081 start + ram_size - 1,
1082 delalloc_end, locked_page,
1083 EXTENT_LOCKED | EXTENT_DELALLOC,
1085 if (disk_num_bytes < cur_alloc_size)
1088 disk_num_bytes -= cur_alloc_size;
1089 num_bytes -= cur_alloc_size;
1090 alloc_hint = ins.objectid + ins.offset;
1091 start += cur_alloc_size;
1092 extent_reserved = false;
1095 * btrfs_reloc_clone_csums() error, since start is increased
1096 * extent_clear_unlock_delalloc() at out_unlock label won't
1097 * free metadata of current ordered extent, we're OK to exit.
1105 out_drop_extent_cache:
1106 btrfs_drop_extent_cache(BTRFS_I(inode), start, start + ram_size - 1, 0);
1108 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
1109 btrfs_free_reserved_extent(fs_info, ins.objectid, ins.offset, 1);
1111 clear_bits = EXTENT_LOCKED | EXTENT_DELALLOC | EXTENT_DELALLOC_NEW |
1112 EXTENT_DEFRAG | EXTENT_CLEAR_META_RESV;
1113 page_ops = PAGE_UNLOCK | PAGE_CLEAR_DIRTY | PAGE_SET_WRITEBACK |
1116 * If we reserved an extent for our delalloc range (or a subrange) and
1117 * failed to create the respective ordered extent, then it means that
1118 * when we reserved the extent we decremented the extent's size from
1119 * the data space_info's bytes_may_use counter and incremented the
1120 * space_info's bytes_reserved counter by the same amount. We must make
1121 * sure extent_clear_unlock_delalloc() does not try to decrement again
1122 * the data space_info's bytes_may_use counter, therefore we do not pass
1123 * it the flag EXTENT_CLEAR_DATA_RESV.
1125 if (extent_reserved) {
1126 extent_clear_unlock_delalloc(inode, start,
1127 start + cur_alloc_size,
1128 start + cur_alloc_size,
1132 start += cur_alloc_size;
1136 extent_clear_unlock_delalloc(inode, start, end, delalloc_end,
1138 clear_bits | EXTENT_CLEAR_DATA_RESV,
1144 * work queue call back to started compression on a file and pages
1146 static noinline void async_cow_start(struct btrfs_work *work)
1148 struct async_cow *async_cow;
1150 async_cow = container_of(work, struct async_cow, work);
1152 compress_file_range(async_cow->inode, async_cow->locked_page,
1153 async_cow->start, async_cow->end, async_cow,
1155 if (num_added == 0) {
1156 btrfs_add_delayed_iput(async_cow->inode);
1157 async_cow->inode = NULL;
1162 * work queue call back to submit previously compressed pages
1164 static noinline void async_cow_submit(struct btrfs_work *work)
1166 struct btrfs_fs_info *fs_info;
1167 struct async_cow *async_cow;
1168 struct btrfs_root *root;
1169 unsigned long nr_pages;
1171 async_cow = container_of(work, struct async_cow, work);
1173 root = async_cow->root;
1174 fs_info = root->fs_info;
1175 nr_pages = (async_cow->end - async_cow->start + PAGE_SIZE) >>
1179 * atomic_sub_return implies a barrier for waitqueue_active
1181 if (atomic_sub_return(nr_pages, &fs_info->async_delalloc_pages) <
1183 waitqueue_active(&fs_info->async_submit_wait))
1184 wake_up(&fs_info->async_submit_wait);
1186 if (async_cow->inode)
1187 submit_compressed_extents(async_cow->inode, async_cow);
1190 static noinline void async_cow_free(struct btrfs_work *work)
1192 struct async_cow *async_cow;
1193 async_cow = container_of(work, struct async_cow, work);
1194 if (async_cow->inode)
1195 btrfs_add_delayed_iput(async_cow->inode);
1199 static int cow_file_range_async(struct inode *inode, struct page *locked_page,
1200 u64 start, u64 end, int *page_started,
1201 unsigned long *nr_written,
1202 unsigned int write_flags)
1204 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1205 struct async_cow *async_cow;
1206 struct btrfs_root *root = BTRFS_I(inode)->root;
1207 unsigned long nr_pages;
1210 clear_extent_bit(&BTRFS_I(inode)->io_tree, start, end, EXTENT_LOCKED,
1212 while (start < end) {
1213 async_cow = kmalloc(sizeof(*async_cow), GFP_NOFS);
1214 BUG_ON(!async_cow); /* -ENOMEM */
1215 async_cow->inode = igrab(inode);
1216 async_cow->root = root;
1217 async_cow->locked_page = locked_page;
1218 async_cow->start = start;
1219 async_cow->write_flags = write_flags;
1221 if (BTRFS_I(inode)->flags & BTRFS_INODE_NOCOMPRESS &&
1222 !btrfs_test_opt(fs_info, FORCE_COMPRESS))
1225 cur_end = min(end, start + SZ_512K - 1);
1227 async_cow->end = cur_end;
1228 INIT_LIST_HEAD(&async_cow->extents);
1230 btrfs_init_work(&async_cow->work,
1231 btrfs_delalloc_helper,
1232 async_cow_start, async_cow_submit,
1235 nr_pages = (cur_end - start + PAGE_SIZE) >>
1237 atomic_add(nr_pages, &fs_info->async_delalloc_pages);
1239 btrfs_queue_work(fs_info->delalloc_workers, &async_cow->work);
1241 *nr_written += nr_pages;
1242 start = cur_end + 1;
1248 static noinline int csum_exist_in_range(struct btrfs_fs_info *fs_info,
1249 u64 bytenr, u64 num_bytes)
1252 struct btrfs_ordered_sum *sums;
1255 ret = btrfs_lookup_csums_range(fs_info->csum_root, bytenr,
1256 bytenr + num_bytes - 1, &list, 0);
1257 if (ret == 0 && list_empty(&list))
1260 while (!list_empty(&list)) {
1261 sums = list_entry(list.next, struct btrfs_ordered_sum, list);
1262 list_del(&sums->list);
1269 * when nowcow writeback call back. This checks for snapshots or COW copies
1270 * of the extents that exist in the file, and COWs the file as required.
1272 * If no cow copies or snapshots exist, we write directly to the existing
1275 static noinline int run_delalloc_nocow(struct inode *inode,
1276 struct page *locked_page,
1277 u64 start, u64 end, int *page_started, int force,
1278 unsigned long *nr_written)
1280 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1281 struct btrfs_root *root = BTRFS_I(inode)->root;
1282 struct extent_buffer *leaf;
1283 struct btrfs_path *path;
1284 struct btrfs_file_extent_item *fi;
1285 struct btrfs_key found_key;
1286 struct extent_map *em;
1301 u64 ino = btrfs_ino(BTRFS_I(inode));
1303 path = btrfs_alloc_path();
1305 extent_clear_unlock_delalloc(inode, start, end, end,
1307 EXTENT_LOCKED | EXTENT_DELALLOC |
1308 EXTENT_DO_ACCOUNTING |
1309 EXTENT_DEFRAG, PAGE_UNLOCK |
1311 PAGE_SET_WRITEBACK |
1312 PAGE_END_WRITEBACK);
1316 nolock = btrfs_is_free_space_inode(BTRFS_I(inode));
1318 cow_start = (u64)-1;
1321 ret = btrfs_lookup_file_extent(NULL, root, path, ino,
1325 if (ret > 0 && path->slots[0] > 0 && check_prev) {
1326 leaf = path->nodes[0];
1327 btrfs_item_key_to_cpu(leaf, &found_key,
1328 path->slots[0] - 1);
1329 if (found_key.objectid == ino &&
1330 found_key.type == BTRFS_EXTENT_DATA_KEY)
1335 leaf = path->nodes[0];
1336 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
1337 ret = btrfs_next_leaf(root, path);
1339 if (cow_start != (u64)-1)
1340 cur_offset = cow_start;
1345 leaf = path->nodes[0];
1351 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
1353 if (found_key.objectid > ino)
1355 if (WARN_ON_ONCE(found_key.objectid < ino) ||
1356 found_key.type < BTRFS_EXTENT_DATA_KEY) {
1360 if (found_key.type > BTRFS_EXTENT_DATA_KEY ||
1361 found_key.offset > end)
1364 if (found_key.offset > cur_offset) {
1365 extent_end = found_key.offset;
1370 fi = btrfs_item_ptr(leaf, path->slots[0],
1371 struct btrfs_file_extent_item);
1372 extent_type = btrfs_file_extent_type(leaf, fi);
1374 ram_bytes = btrfs_file_extent_ram_bytes(leaf, fi);
1375 if (extent_type == BTRFS_FILE_EXTENT_REG ||
1376 extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
1377 disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
1378 extent_offset = btrfs_file_extent_offset(leaf, fi);
1379 extent_end = found_key.offset +
1380 btrfs_file_extent_num_bytes(leaf, fi);
1382 btrfs_file_extent_disk_num_bytes(leaf, fi);
1383 if (extent_end <= start) {
1387 if (disk_bytenr == 0)
1389 if (btrfs_file_extent_compression(leaf, fi) ||
1390 btrfs_file_extent_encryption(leaf, fi) ||
1391 btrfs_file_extent_other_encoding(leaf, fi))
1393 if (extent_type == BTRFS_FILE_EXTENT_REG && !force)
1395 if (btrfs_extent_readonly(fs_info, disk_bytenr))
1397 if (btrfs_cross_ref_exist(root, ino,
1399 extent_offset, disk_bytenr))
1401 disk_bytenr += extent_offset;
1402 disk_bytenr += cur_offset - found_key.offset;
1403 num_bytes = min(end + 1, extent_end) - cur_offset;
1405 * if there are pending snapshots for this root,
1406 * we fall into common COW way.
1409 err = btrfs_start_write_no_snapshotting(root);
1414 * force cow if csum exists in the range.
1415 * this ensure that csum for a given extent are
1416 * either valid or do not exist.
1418 if (csum_exist_in_range(fs_info, disk_bytenr,
1421 btrfs_end_write_no_snapshotting(root);
1424 if (!btrfs_inc_nocow_writers(fs_info, disk_bytenr)) {
1426 btrfs_end_write_no_snapshotting(root);
1430 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
1431 extent_end = found_key.offset +
1432 btrfs_file_extent_inline_len(leaf,
1433 path->slots[0], fi);
1434 extent_end = ALIGN(extent_end,
1435 fs_info->sectorsize);
1440 if (extent_end <= start) {
1442 if (!nolock && nocow)
1443 btrfs_end_write_no_snapshotting(root);
1445 btrfs_dec_nocow_writers(fs_info, disk_bytenr);
1449 if (cow_start == (u64)-1)
1450 cow_start = cur_offset;
1451 cur_offset = extent_end;
1452 if (cur_offset > end)
1458 btrfs_release_path(path);
1459 if (cow_start != (u64)-1) {
1460 ret = cow_file_range(inode, locked_page,
1461 cow_start, found_key.offset - 1,
1462 end, page_started, nr_written, 1,
1465 if (!nolock && nocow)
1466 btrfs_end_write_no_snapshotting(root);
1468 btrfs_dec_nocow_writers(fs_info,
1472 cow_start = (u64)-1;
1475 if (extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
1476 u64 orig_start = found_key.offset - extent_offset;
1478 em = create_io_em(inode, cur_offset, num_bytes,
1480 disk_bytenr, /* block_start */
1481 num_bytes, /* block_len */
1482 disk_num_bytes, /* orig_block_len */
1483 ram_bytes, BTRFS_COMPRESS_NONE,
1484 BTRFS_ORDERED_PREALLOC);
1486 if (!nolock && nocow)
1487 btrfs_end_write_no_snapshotting(root);
1489 btrfs_dec_nocow_writers(fs_info,
1494 free_extent_map(em);
1497 if (extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
1498 type = BTRFS_ORDERED_PREALLOC;
1500 type = BTRFS_ORDERED_NOCOW;
1503 ret = btrfs_add_ordered_extent(inode, cur_offset, disk_bytenr,
1504 num_bytes, num_bytes, type);
1506 btrfs_dec_nocow_writers(fs_info, disk_bytenr);
1507 BUG_ON(ret); /* -ENOMEM */
1509 if (root->root_key.objectid ==
1510 BTRFS_DATA_RELOC_TREE_OBJECTID)
1512 * Error handled later, as we must prevent
1513 * extent_clear_unlock_delalloc() in error handler
1514 * from freeing metadata of created ordered extent.
1516 ret = btrfs_reloc_clone_csums(inode, cur_offset,
1519 extent_clear_unlock_delalloc(inode, cur_offset,
1520 cur_offset + num_bytes - 1, end,
1521 locked_page, EXTENT_LOCKED |
1523 EXTENT_CLEAR_DATA_RESV,
1524 PAGE_UNLOCK | PAGE_SET_PRIVATE2);
1526 if (!nolock && nocow)
1527 btrfs_end_write_no_snapshotting(root);
1528 cur_offset = extent_end;
1531 * btrfs_reloc_clone_csums() error, now we're OK to call error
1532 * handler, as metadata for created ordered extent will only
1533 * be freed by btrfs_finish_ordered_io().
1537 if (cur_offset > end)
1540 btrfs_release_path(path);
1542 if (cur_offset <= end && cow_start == (u64)-1) {
1543 cow_start = cur_offset;
1547 if (cow_start != (u64)-1) {
1548 ret = cow_file_range(inode, locked_page, cow_start, end, end,
1549 page_started, nr_written, 1, NULL);
1555 if (ret && cur_offset < end)
1556 extent_clear_unlock_delalloc(inode, cur_offset, end, end,
1557 locked_page, EXTENT_LOCKED |
1558 EXTENT_DELALLOC | EXTENT_DEFRAG |
1559 EXTENT_DO_ACCOUNTING, PAGE_UNLOCK |
1561 PAGE_SET_WRITEBACK |
1562 PAGE_END_WRITEBACK);
1563 btrfs_free_path(path);
1567 static inline int need_force_cow(struct inode *inode, u64 start, u64 end)
1570 if (!(BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW) &&
1571 !(BTRFS_I(inode)->flags & BTRFS_INODE_PREALLOC))
1575 * @defrag_bytes is a hint value, no spinlock held here,
1576 * if is not zero, it means the file is defragging.
1577 * Force cow if given extent needs to be defragged.
1579 if (BTRFS_I(inode)->defrag_bytes &&
1580 test_range_bit(&BTRFS_I(inode)->io_tree, start, end,
1581 EXTENT_DEFRAG, 0, NULL))
1588 * extent_io.c call back to do delayed allocation processing
1590 static int run_delalloc_range(void *private_data, struct page *locked_page,
1591 u64 start, u64 end, int *page_started,
1592 unsigned long *nr_written,
1593 struct writeback_control *wbc)
1595 struct inode *inode = private_data;
1597 int force_cow = need_force_cow(inode, start, end);
1598 unsigned int write_flags = wbc_to_write_flags(wbc);
1600 if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW && !force_cow) {
1601 ret = run_delalloc_nocow(inode, locked_page, start, end,
1602 page_started, 1, nr_written);
1603 } else if (BTRFS_I(inode)->flags & BTRFS_INODE_PREALLOC && !force_cow) {
1604 ret = run_delalloc_nocow(inode, locked_page, start, end,
1605 page_started, 0, nr_written);
1606 } else if (!inode_need_compress(inode, start, end)) {
1607 ret = cow_file_range(inode, locked_page, start, end, end,
1608 page_started, nr_written, 1, NULL);
1610 set_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
1611 &BTRFS_I(inode)->runtime_flags);
1612 ret = cow_file_range_async(inode, locked_page, start, end,
1613 page_started, nr_written,
1617 btrfs_cleanup_ordered_extents(inode, start, end - start + 1);
1621 static void btrfs_split_extent_hook(void *private_data,
1622 struct extent_state *orig, u64 split)
1624 struct inode *inode = private_data;
1627 /* not delalloc, ignore it */
1628 if (!(orig->state & EXTENT_DELALLOC))
1631 size = orig->end - orig->start + 1;
1632 if (size > BTRFS_MAX_EXTENT_SIZE) {
1637 * See the explanation in btrfs_merge_extent_hook, the same
1638 * applies here, just in reverse.
1640 new_size = orig->end - split + 1;
1641 num_extents = count_max_extents(new_size);
1642 new_size = split - orig->start;
1643 num_extents += count_max_extents(new_size);
1644 if (count_max_extents(size) >= num_extents)
1648 spin_lock(&BTRFS_I(inode)->lock);
1649 btrfs_mod_outstanding_extents(BTRFS_I(inode), 1);
1650 spin_unlock(&BTRFS_I(inode)->lock);
1654 * extent_io.c merge_extent_hook, used to track merged delayed allocation
1655 * extents so we can keep track of new extents that are just merged onto old
1656 * extents, such as when we are doing sequential writes, so we can properly
1657 * account for the metadata space we'll need.
1659 static void btrfs_merge_extent_hook(void *private_data,
1660 struct extent_state *new,
1661 struct extent_state *other)
1663 struct inode *inode = private_data;
1664 u64 new_size, old_size;
1667 /* not delalloc, ignore it */
1668 if (!(other->state & EXTENT_DELALLOC))
1671 if (new->start > other->start)
1672 new_size = new->end - other->start + 1;
1674 new_size = other->end - new->start + 1;
1676 /* we're not bigger than the max, unreserve the space and go */
1677 if (new_size <= BTRFS_MAX_EXTENT_SIZE) {
1678 spin_lock(&BTRFS_I(inode)->lock);
1679 btrfs_mod_outstanding_extents(BTRFS_I(inode), -1);
1680 spin_unlock(&BTRFS_I(inode)->lock);
1685 * We have to add up either side to figure out how many extents were
1686 * accounted for before we merged into one big extent. If the number of
1687 * extents we accounted for is <= the amount we need for the new range
1688 * then we can return, otherwise drop. Think of it like this
1692 * So we've grown the extent by a MAX_SIZE extent, this would mean we
1693 * need 2 outstanding extents, on one side we have 1 and the other side
1694 * we have 1 so they are == and we can return. But in this case
1696 * [MAX_SIZE+4k][MAX_SIZE+4k]
1698 * Each range on their own accounts for 2 extents, but merged together
1699 * they are only 3 extents worth of accounting, so we need to drop in
1702 old_size = other->end - other->start + 1;
1703 num_extents = count_max_extents(old_size);
1704 old_size = new->end - new->start + 1;
1705 num_extents += count_max_extents(old_size);
1706 if (count_max_extents(new_size) >= num_extents)
1709 spin_lock(&BTRFS_I(inode)->lock);
1710 btrfs_mod_outstanding_extents(BTRFS_I(inode), -1);
1711 spin_unlock(&BTRFS_I(inode)->lock);
1714 static void btrfs_add_delalloc_inodes(struct btrfs_root *root,
1715 struct inode *inode)
1717 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1719 spin_lock(&root->delalloc_lock);
1720 if (list_empty(&BTRFS_I(inode)->delalloc_inodes)) {
1721 list_add_tail(&BTRFS_I(inode)->delalloc_inodes,
1722 &root->delalloc_inodes);
1723 set_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1724 &BTRFS_I(inode)->runtime_flags);
1725 root->nr_delalloc_inodes++;
1726 if (root->nr_delalloc_inodes == 1) {
1727 spin_lock(&fs_info->delalloc_root_lock);
1728 BUG_ON(!list_empty(&root->delalloc_root));
1729 list_add_tail(&root->delalloc_root,
1730 &fs_info->delalloc_roots);
1731 spin_unlock(&fs_info->delalloc_root_lock);
1734 spin_unlock(&root->delalloc_lock);
1737 static void btrfs_del_delalloc_inode(struct btrfs_root *root,
1738 struct btrfs_inode *inode)
1740 struct btrfs_fs_info *fs_info = btrfs_sb(inode->vfs_inode.i_sb);
1742 spin_lock(&root->delalloc_lock);
1743 if (!list_empty(&inode->delalloc_inodes)) {
1744 list_del_init(&inode->delalloc_inodes);
1745 clear_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1746 &inode->runtime_flags);
1747 root->nr_delalloc_inodes--;
1748 if (!root->nr_delalloc_inodes) {
1749 spin_lock(&fs_info->delalloc_root_lock);
1750 BUG_ON(list_empty(&root->delalloc_root));
1751 list_del_init(&root->delalloc_root);
1752 spin_unlock(&fs_info->delalloc_root_lock);
1755 spin_unlock(&root->delalloc_lock);
1759 * extent_io.c set_bit_hook, used to track delayed allocation
1760 * bytes in this file, and to maintain the list of inodes that
1761 * have pending delalloc work to be done.
1763 static void btrfs_set_bit_hook(void *private_data,
1764 struct extent_state *state, unsigned *bits)
1766 struct inode *inode = private_data;
1768 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1770 if ((*bits & EXTENT_DEFRAG) && !(*bits & EXTENT_DELALLOC))
1773 * set_bit and clear bit hooks normally require _irqsave/restore
1774 * but in this case, we are only testing for the DELALLOC
1775 * bit, which is only set or cleared with irqs on
1777 if (!(state->state & EXTENT_DELALLOC) && (*bits & EXTENT_DELALLOC)) {
1778 struct btrfs_root *root = BTRFS_I(inode)->root;
1779 u64 len = state->end + 1 - state->start;
1780 u32 num_extents = count_max_extents(len);
1781 bool do_list = !btrfs_is_free_space_inode(BTRFS_I(inode));
1783 spin_lock(&BTRFS_I(inode)->lock);
1784 btrfs_mod_outstanding_extents(BTRFS_I(inode), num_extents);
1785 spin_unlock(&BTRFS_I(inode)->lock);
1787 /* For sanity tests */
1788 if (btrfs_is_testing(fs_info))
1791 percpu_counter_add_batch(&fs_info->delalloc_bytes, len,
1792 fs_info->delalloc_batch);
1793 spin_lock(&BTRFS_I(inode)->lock);
1794 BTRFS_I(inode)->delalloc_bytes += len;
1795 if (*bits & EXTENT_DEFRAG)
1796 BTRFS_I(inode)->defrag_bytes += len;
1797 if (do_list && !test_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1798 &BTRFS_I(inode)->runtime_flags))
1799 btrfs_add_delalloc_inodes(root, inode);
1800 spin_unlock(&BTRFS_I(inode)->lock);
1803 if (!(state->state & EXTENT_DELALLOC_NEW) &&
1804 (*bits & EXTENT_DELALLOC_NEW)) {
1805 spin_lock(&BTRFS_I(inode)->lock);
1806 BTRFS_I(inode)->new_delalloc_bytes += state->end + 1 -
1808 spin_unlock(&BTRFS_I(inode)->lock);
1813 * extent_io.c clear_bit_hook, see set_bit_hook for why
1815 static void btrfs_clear_bit_hook(void *private_data,
1816 struct extent_state *state,
1819 struct btrfs_inode *inode = BTRFS_I((struct inode *)private_data);
1820 struct btrfs_fs_info *fs_info = btrfs_sb(inode->vfs_inode.i_sb);
1821 u64 len = state->end + 1 - state->start;
1822 u32 num_extents = count_max_extents(len);
1824 if ((state->state & EXTENT_DEFRAG) && (*bits & EXTENT_DEFRAG)) {
1825 spin_lock(&inode->lock);
1826 inode->defrag_bytes -= len;
1827 spin_unlock(&inode->lock);
1831 * set_bit and clear bit hooks normally require _irqsave/restore
1832 * but in this case, we are only testing for the DELALLOC
1833 * bit, which is only set or cleared with irqs on
1835 if ((state->state & EXTENT_DELALLOC) && (*bits & EXTENT_DELALLOC)) {
1836 struct btrfs_root *root = inode->root;
1837 bool do_list = !btrfs_is_free_space_inode(inode);
1839 spin_lock(&inode->lock);
1840 btrfs_mod_outstanding_extents(inode, -num_extents);
1841 spin_unlock(&inode->lock);
1844 * We don't reserve metadata space for space cache inodes so we
1845 * don't need to call dellalloc_release_metadata if there is an
1848 if (*bits & EXTENT_CLEAR_META_RESV &&
1849 root != fs_info->tree_root)
1850 btrfs_delalloc_release_metadata(inode, len);
1852 /* For sanity tests. */
1853 if (btrfs_is_testing(fs_info))
1856 if (root->root_key.objectid != BTRFS_DATA_RELOC_TREE_OBJECTID &&
1857 do_list && !(state->state & EXTENT_NORESERVE) &&
1858 (*bits & EXTENT_CLEAR_DATA_RESV))
1859 btrfs_free_reserved_data_space_noquota(
1863 percpu_counter_add_batch(&fs_info->delalloc_bytes, -len,
1864 fs_info->delalloc_batch);
1865 spin_lock(&inode->lock);
1866 inode->delalloc_bytes -= len;
1867 if (do_list && inode->delalloc_bytes == 0 &&
1868 test_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1869 &inode->runtime_flags))
1870 btrfs_del_delalloc_inode(root, inode);
1871 spin_unlock(&inode->lock);
1874 if ((state->state & EXTENT_DELALLOC_NEW) &&
1875 (*bits & EXTENT_DELALLOC_NEW)) {
1876 spin_lock(&inode->lock);
1877 ASSERT(inode->new_delalloc_bytes >= len);
1878 inode->new_delalloc_bytes -= len;
1879 spin_unlock(&inode->lock);
1884 * extent_io.c merge_bio_hook, this must check the chunk tree to make sure
1885 * we don't create bios that span stripes or chunks
1887 * return 1 if page cannot be merged to bio
1888 * return 0 if page can be merged to bio
1889 * return error otherwise
1891 int btrfs_merge_bio_hook(struct page *page, unsigned long offset,
1892 size_t size, struct bio *bio,
1893 unsigned long bio_flags)
1895 struct inode *inode = page->mapping->host;
1896 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1897 u64 logical = (u64)bio->bi_iter.bi_sector << 9;
1902 if (bio_flags & EXTENT_BIO_COMPRESSED)
1905 length = bio->bi_iter.bi_size;
1906 map_length = length;
1907 ret = btrfs_map_block(fs_info, btrfs_op(bio), logical, &map_length,
1911 if (map_length < length + size)
1917 * in order to insert checksums into the metadata in large chunks,
1918 * we wait until bio submission time. All the pages in the bio are
1919 * checksummed and sums are attached onto the ordered extent record.
1921 * At IO completion time the cums attached on the ordered extent record
1922 * are inserted into the btree
1924 static blk_status_t __btrfs_submit_bio_start(void *private_data, struct bio *bio,
1925 int mirror_num, unsigned long bio_flags,
1928 struct inode *inode = private_data;
1929 blk_status_t ret = 0;
1931 ret = btrfs_csum_one_bio(inode, bio, 0, 0);
1932 BUG_ON(ret); /* -ENOMEM */
1937 * in order to insert checksums into the metadata in large chunks,
1938 * we wait until bio submission time. All the pages in the bio are
1939 * checksummed and sums are attached onto the ordered extent record.
1941 * At IO completion time the cums attached on the ordered extent record
1942 * are inserted into the btree
1944 static blk_status_t __btrfs_submit_bio_done(void *private_data, struct bio *bio,
1945 int mirror_num, unsigned long bio_flags,
1948 struct inode *inode = private_data;
1949 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1952 ret = btrfs_map_bio(fs_info, bio, mirror_num, 1);
1954 bio->bi_status = ret;
1961 * extent_io.c submission hook. This does the right thing for csum calculation
1962 * on write, or reading the csums from the tree before a read.
1964 * Rules about async/sync submit,
1965 * a) read: sync submit
1967 * b) write without checksum: sync submit
1969 * c) write with checksum:
1970 * c-1) if bio is issued by fsync: sync submit
1971 * (sync_writers != 0)
1973 * c-2) if root is reloc root: sync submit
1974 * (only in case of buffered IO)
1976 * c-3) otherwise: async submit
1978 static blk_status_t btrfs_submit_bio_hook(void *private_data, struct bio *bio,
1979 int mirror_num, unsigned long bio_flags,
1982 struct inode *inode = private_data;
1983 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1984 struct btrfs_root *root = BTRFS_I(inode)->root;
1985 enum btrfs_wq_endio_type metadata = BTRFS_WQ_ENDIO_DATA;
1986 blk_status_t ret = 0;
1988 int async = !atomic_read(&BTRFS_I(inode)->sync_writers);
1990 skip_sum = BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM;
1992 if (btrfs_is_free_space_inode(BTRFS_I(inode)))
1993 metadata = BTRFS_WQ_ENDIO_FREE_SPACE;
1995 if (bio_op(bio) != REQ_OP_WRITE) {
1996 ret = btrfs_bio_wq_end_io(fs_info, bio, metadata);
2000 if (bio_flags & EXTENT_BIO_COMPRESSED) {
2001 ret = btrfs_submit_compressed_read(inode, bio,
2005 } else if (!skip_sum) {
2006 ret = btrfs_lookup_bio_sums(inode, bio, NULL);
2011 } else if (async && !skip_sum) {
2012 /* csum items have already been cloned */
2013 if (root->root_key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID)
2015 /* we're doing a write, do the async checksumming */
2016 ret = btrfs_wq_submit_bio(fs_info, bio, mirror_num, bio_flags,
2018 __btrfs_submit_bio_start,
2019 __btrfs_submit_bio_done);
2021 } else if (!skip_sum) {
2022 ret = btrfs_csum_one_bio(inode, bio, 0, 0);
2028 ret = btrfs_map_bio(fs_info, bio, mirror_num, 0);
2032 bio->bi_status = ret;
2039 * given a list of ordered sums record them in the inode. This happens
2040 * at IO completion time based on sums calculated at bio submission time.
2042 static noinline int add_pending_csums(struct btrfs_trans_handle *trans,
2043 struct inode *inode, struct list_head *list)
2045 struct btrfs_ordered_sum *sum;
2048 list_for_each_entry(sum, list, list) {
2049 trans->adding_csums = true;
2050 ret = btrfs_csum_file_blocks(trans,
2051 BTRFS_I(inode)->root->fs_info->csum_root, sum);
2052 trans->adding_csums = false;
2059 int btrfs_set_extent_delalloc(struct inode *inode, u64 start, u64 end,
2060 unsigned int extra_bits,
2061 struct extent_state **cached_state, int dedupe)
2063 WARN_ON((end & (PAGE_SIZE - 1)) == 0);
2064 return set_extent_delalloc(&BTRFS_I(inode)->io_tree, start, end,
2065 extra_bits, cached_state);
2068 /* see btrfs_writepage_start_hook for details on why this is required */
2069 struct btrfs_writepage_fixup {
2071 struct btrfs_work work;
2074 static void btrfs_writepage_fixup_worker(struct btrfs_work *work)
2076 struct btrfs_writepage_fixup *fixup;
2077 struct btrfs_ordered_extent *ordered;
2078 struct extent_state *cached_state = NULL;
2079 struct extent_changeset *data_reserved = NULL;
2081 struct inode *inode;
2086 fixup = container_of(work, struct btrfs_writepage_fixup, work);
2090 if (!page->mapping || !PageDirty(page) || !PageChecked(page)) {
2091 ClearPageChecked(page);
2095 inode = page->mapping->host;
2096 page_start = page_offset(page);
2097 page_end = page_offset(page) + PAGE_SIZE - 1;
2099 lock_extent_bits(&BTRFS_I(inode)->io_tree, page_start, page_end,
2102 /* already ordered? We're done */
2103 if (PagePrivate2(page))
2106 ordered = btrfs_lookup_ordered_range(BTRFS_I(inode), page_start,
2109 unlock_extent_cached(&BTRFS_I(inode)->io_tree, page_start,
2110 page_end, &cached_state);
2112 btrfs_start_ordered_extent(inode, ordered, 1);
2113 btrfs_put_ordered_extent(ordered);
2117 ret = btrfs_delalloc_reserve_space(inode, &data_reserved, page_start,
2120 mapping_set_error(page->mapping, ret);
2121 end_extent_writepage(page, ret, page_start, page_end);
2122 ClearPageChecked(page);
2126 ret = btrfs_set_extent_delalloc(inode, page_start, page_end, 0,
2129 mapping_set_error(page->mapping, ret);
2130 end_extent_writepage(page, ret, page_start, page_end);
2131 ClearPageChecked(page);
2135 ClearPageChecked(page);
2136 set_page_dirty(page);
2137 btrfs_delalloc_release_extents(BTRFS_I(inode), PAGE_SIZE);
2139 unlock_extent_cached(&BTRFS_I(inode)->io_tree, page_start, page_end,
2145 extent_changeset_free(data_reserved);
2149 * There are a few paths in the higher layers of the kernel that directly
2150 * set the page dirty bit without asking the filesystem if it is a
2151 * good idea. This causes problems because we want to make sure COW
2152 * properly happens and the data=ordered rules are followed.
2154 * In our case any range that doesn't have the ORDERED bit set
2155 * hasn't been properly setup for IO. We kick off an async process
2156 * to fix it up. The async helper will wait for ordered extents, set
2157 * the delalloc bit and make it safe to write the page.
2159 static int btrfs_writepage_start_hook(struct page *page, u64 start, u64 end)
2161 struct inode *inode = page->mapping->host;
2162 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2163 struct btrfs_writepage_fixup *fixup;
2165 /* this page is properly in the ordered list */
2166 if (TestClearPagePrivate2(page))
2169 if (PageChecked(page))
2172 fixup = kzalloc(sizeof(*fixup), GFP_NOFS);
2176 SetPageChecked(page);
2178 btrfs_init_work(&fixup->work, btrfs_fixup_helper,
2179 btrfs_writepage_fixup_worker, NULL, NULL);
2181 btrfs_queue_work(fs_info->fixup_workers, &fixup->work);
2185 static int insert_reserved_file_extent(struct btrfs_trans_handle *trans,
2186 struct inode *inode, u64 file_pos,
2187 u64 disk_bytenr, u64 disk_num_bytes,
2188 u64 num_bytes, u64 ram_bytes,
2189 u8 compression, u8 encryption,
2190 u16 other_encoding, int extent_type)
2192 struct btrfs_root *root = BTRFS_I(inode)->root;
2193 struct btrfs_file_extent_item *fi;
2194 struct btrfs_path *path;
2195 struct extent_buffer *leaf;
2196 struct btrfs_key ins;
2198 int extent_inserted = 0;
2201 path = btrfs_alloc_path();
2206 * we may be replacing one extent in the tree with another.
2207 * The new extent is pinned in the extent map, and we don't want
2208 * to drop it from the cache until it is completely in the btree.
2210 * So, tell btrfs_drop_extents to leave this extent in the cache.
2211 * the caller is expected to unpin it and allow it to be merged
2214 ret = __btrfs_drop_extents(trans, root, inode, path, file_pos,
2215 file_pos + num_bytes, NULL, 0,
2216 1, sizeof(*fi), &extent_inserted);
2220 if (!extent_inserted) {
2221 ins.objectid = btrfs_ino(BTRFS_I(inode));
2222 ins.offset = file_pos;
2223 ins.type = BTRFS_EXTENT_DATA_KEY;
2225 path->leave_spinning = 1;
2226 ret = btrfs_insert_empty_item(trans, root, path, &ins,
2231 leaf = path->nodes[0];
2232 fi = btrfs_item_ptr(leaf, path->slots[0],
2233 struct btrfs_file_extent_item);
2234 btrfs_set_file_extent_generation(leaf, fi, trans->transid);
2235 btrfs_set_file_extent_type(leaf, fi, extent_type);
2236 btrfs_set_file_extent_disk_bytenr(leaf, fi, disk_bytenr);
2237 btrfs_set_file_extent_disk_num_bytes(leaf, fi, disk_num_bytes);
2238 btrfs_set_file_extent_offset(leaf, fi, 0);
2239 btrfs_set_file_extent_num_bytes(leaf, fi, num_bytes);
2240 btrfs_set_file_extent_ram_bytes(leaf, fi, ram_bytes);
2241 btrfs_set_file_extent_compression(leaf, fi, compression);
2242 btrfs_set_file_extent_encryption(leaf, fi, encryption);
2243 btrfs_set_file_extent_other_encoding(leaf, fi, other_encoding);
2245 btrfs_mark_buffer_dirty(leaf);
2246 btrfs_release_path(path);
2248 inode_add_bytes(inode, num_bytes);
2250 ins.objectid = disk_bytenr;
2251 ins.offset = disk_num_bytes;
2252 ins.type = BTRFS_EXTENT_ITEM_KEY;
2255 * Release the reserved range from inode dirty range map, as it is
2256 * already moved into delayed_ref_head
2258 ret = btrfs_qgroup_release_data(inode, file_pos, ram_bytes);
2262 ret = btrfs_alloc_reserved_file_extent(trans, root,
2263 btrfs_ino(BTRFS_I(inode)),
2264 file_pos, qg_released, &ins);
2266 btrfs_free_path(path);
2271 /* snapshot-aware defrag */
2272 struct sa_defrag_extent_backref {
2273 struct rb_node node;
2274 struct old_sa_defrag_extent *old;
2283 struct old_sa_defrag_extent {
2284 struct list_head list;
2285 struct new_sa_defrag_extent *new;
2294 struct new_sa_defrag_extent {
2295 struct rb_root root;
2296 struct list_head head;
2297 struct btrfs_path *path;
2298 struct inode *inode;
2306 static int backref_comp(struct sa_defrag_extent_backref *b1,
2307 struct sa_defrag_extent_backref *b2)
2309 if (b1->root_id < b2->root_id)
2311 else if (b1->root_id > b2->root_id)
2314 if (b1->inum < b2->inum)
2316 else if (b1->inum > b2->inum)
2319 if (b1->file_pos < b2->file_pos)
2321 else if (b1->file_pos > b2->file_pos)
2325 * [------------------------------] ===> (a range of space)
2326 * |<--->| |<---->| =============> (fs/file tree A)
2327 * |<---------------------------->| ===> (fs/file tree B)
2329 * A range of space can refer to two file extents in one tree while
2330 * refer to only one file extent in another tree.
2332 * So we may process a disk offset more than one time(two extents in A)
2333 * and locate at the same extent(one extent in B), then insert two same
2334 * backrefs(both refer to the extent in B).
2339 static void backref_insert(struct rb_root *root,
2340 struct sa_defrag_extent_backref *backref)
2342 struct rb_node **p = &root->rb_node;
2343 struct rb_node *parent = NULL;
2344 struct sa_defrag_extent_backref *entry;
2349 entry = rb_entry(parent, struct sa_defrag_extent_backref, node);
2351 ret = backref_comp(backref, entry);
2355 p = &(*p)->rb_right;
2358 rb_link_node(&backref->node, parent, p);
2359 rb_insert_color(&backref->node, root);
2363 * Note the backref might has changed, and in this case we just return 0.
2365 static noinline int record_one_backref(u64 inum, u64 offset, u64 root_id,
2368 struct btrfs_file_extent_item *extent;
2369 struct old_sa_defrag_extent *old = ctx;
2370 struct new_sa_defrag_extent *new = old->new;
2371 struct btrfs_path *path = new->path;
2372 struct btrfs_key key;
2373 struct btrfs_root *root;
2374 struct sa_defrag_extent_backref *backref;
2375 struct extent_buffer *leaf;
2376 struct inode *inode = new->inode;
2377 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2383 if (BTRFS_I(inode)->root->root_key.objectid == root_id &&
2384 inum == btrfs_ino(BTRFS_I(inode)))
2387 key.objectid = root_id;
2388 key.type = BTRFS_ROOT_ITEM_KEY;
2389 key.offset = (u64)-1;
2391 root = btrfs_read_fs_root_no_name(fs_info, &key);
2393 if (PTR_ERR(root) == -ENOENT)
2396 btrfs_debug(fs_info, "inum=%llu, offset=%llu, root_id=%llu",
2397 inum, offset, root_id);
2398 return PTR_ERR(root);
2401 key.objectid = inum;
2402 key.type = BTRFS_EXTENT_DATA_KEY;
2403 if (offset > (u64)-1 << 32)
2406 key.offset = offset;
2408 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2409 if (WARN_ON(ret < 0))
2416 leaf = path->nodes[0];
2417 slot = path->slots[0];
2419 if (slot >= btrfs_header_nritems(leaf)) {
2420 ret = btrfs_next_leaf(root, path);
2423 } else if (ret > 0) {
2432 btrfs_item_key_to_cpu(leaf, &key, slot);
2434 if (key.objectid > inum)
2437 if (key.objectid < inum || key.type != BTRFS_EXTENT_DATA_KEY)
2440 extent = btrfs_item_ptr(leaf, slot,
2441 struct btrfs_file_extent_item);
2443 if (btrfs_file_extent_disk_bytenr(leaf, extent) != old->bytenr)
2447 * 'offset' refers to the exact key.offset,
2448 * NOT the 'offset' field in btrfs_extent_data_ref, ie.
2449 * (key.offset - extent_offset).
2451 if (key.offset != offset)
2454 extent_offset = btrfs_file_extent_offset(leaf, extent);
2455 num_bytes = btrfs_file_extent_num_bytes(leaf, extent);
2457 if (extent_offset >= old->extent_offset + old->offset +
2458 old->len || extent_offset + num_bytes <=
2459 old->extent_offset + old->offset)
2464 backref = kmalloc(sizeof(*backref), GFP_NOFS);
2470 backref->root_id = root_id;
2471 backref->inum = inum;
2472 backref->file_pos = offset;
2473 backref->num_bytes = num_bytes;
2474 backref->extent_offset = extent_offset;
2475 backref->generation = btrfs_file_extent_generation(leaf, extent);
2477 backref_insert(&new->root, backref);
2480 btrfs_release_path(path);
2485 static noinline bool record_extent_backrefs(struct btrfs_path *path,
2486 struct new_sa_defrag_extent *new)
2488 struct btrfs_fs_info *fs_info = btrfs_sb(new->inode->i_sb);
2489 struct old_sa_defrag_extent *old, *tmp;
2494 list_for_each_entry_safe(old, tmp, &new->head, list) {
2495 ret = iterate_inodes_from_logical(old->bytenr +
2496 old->extent_offset, fs_info,
2497 path, record_one_backref,
2499 if (ret < 0 && ret != -ENOENT)
2502 /* no backref to be processed for this extent */
2504 list_del(&old->list);
2509 if (list_empty(&new->head))
2515 static int relink_is_mergable(struct extent_buffer *leaf,
2516 struct btrfs_file_extent_item *fi,
2517 struct new_sa_defrag_extent *new)
2519 if (btrfs_file_extent_disk_bytenr(leaf, fi) != new->bytenr)
2522 if (btrfs_file_extent_type(leaf, fi) != BTRFS_FILE_EXTENT_REG)
2525 if (btrfs_file_extent_compression(leaf, fi) != new->compress_type)
2528 if (btrfs_file_extent_encryption(leaf, fi) ||
2529 btrfs_file_extent_other_encoding(leaf, fi))
2536 * Note the backref might has changed, and in this case we just return 0.
2538 static noinline int relink_extent_backref(struct btrfs_path *path,
2539 struct sa_defrag_extent_backref *prev,
2540 struct sa_defrag_extent_backref *backref)
2542 struct btrfs_file_extent_item *extent;
2543 struct btrfs_file_extent_item *item;
2544 struct btrfs_ordered_extent *ordered;
2545 struct btrfs_trans_handle *trans;
2546 struct btrfs_root *root;
2547 struct btrfs_key key;
2548 struct extent_buffer *leaf;
2549 struct old_sa_defrag_extent *old = backref->old;
2550 struct new_sa_defrag_extent *new = old->new;
2551 struct btrfs_fs_info *fs_info = btrfs_sb(new->inode->i_sb);
2552 struct inode *inode;
2553 struct extent_state *cached = NULL;
2562 if (prev && prev->root_id == backref->root_id &&
2563 prev->inum == backref->inum &&
2564 prev->file_pos + prev->num_bytes == backref->file_pos)
2567 /* step 1: get root */
2568 key.objectid = backref->root_id;
2569 key.type = BTRFS_ROOT_ITEM_KEY;
2570 key.offset = (u64)-1;
2572 index = srcu_read_lock(&fs_info->subvol_srcu);
2574 root = btrfs_read_fs_root_no_name(fs_info, &key);
2576 srcu_read_unlock(&fs_info->subvol_srcu, index);
2577 if (PTR_ERR(root) == -ENOENT)
2579 return PTR_ERR(root);
2582 if (btrfs_root_readonly(root)) {
2583 srcu_read_unlock(&fs_info->subvol_srcu, index);
2587 /* step 2: get inode */
2588 key.objectid = backref->inum;
2589 key.type = BTRFS_INODE_ITEM_KEY;
2592 inode = btrfs_iget(fs_info->sb, &key, root, NULL);
2593 if (IS_ERR(inode)) {
2594 srcu_read_unlock(&fs_info->subvol_srcu, index);
2598 srcu_read_unlock(&fs_info->subvol_srcu, index);
2600 /* step 3: relink backref */
2601 lock_start = backref->file_pos;
2602 lock_end = backref->file_pos + backref->num_bytes - 1;
2603 lock_extent_bits(&BTRFS_I(inode)->io_tree, lock_start, lock_end,
2606 ordered = btrfs_lookup_first_ordered_extent(inode, lock_end);
2608 btrfs_put_ordered_extent(ordered);
2612 trans = btrfs_join_transaction(root);
2613 if (IS_ERR(trans)) {
2614 ret = PTR_ERR(trans);
2618 key.objectid = backref->inum;
2619 key.type = BTRFS_EXTENT_DATA_KEY;
2620 key.offset = backref->file_pos;
2622 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2625 } else if (ret > 0) {
2630 extent = btrfs_item_ptr(path->nodes[0], path->slots[0],
2631 struct btrfs_file_extent_item);
2633 if (btrfs_file_extent_generation(path->nodes[0], extent) !=
2634 backref->generation)
2637 btrfs_release_path(path);
2639 start = backref->file_pos;
2640 if (backref->extent_offset < old->extent_offset + old->offset)
2641 start += old->extent_offset + old->offset -
2642 backref->extent_offset;
2644 len = min(backref->extent_offset + backref->num_bytes,
2645 old->extent_offset + old->offset + old->len);
2646 len -= max(backref->extent_offset, old->extent_offset + old->offset);
2648 ret = btrfs_drop_extents(trans, root, inode, start,
2653 key.objectid = btrfs_ino(BTRFS_I(inode));
2654 key.type = BTRFS_EXTENT_DATA_KEY;
2657 path->leave_spinning = 1;
2659 struct btrfs_file_extent_item *fi;
2661 struct btrfs_key found_key;
2663 ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
2668 leaf = path->nodes[0];
2669 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
2671 fi = btrfs_item_ptr(leaf, path->slots[0],
2672 struct btrfs_file_extent_item);
2673 extent_len = btrfs_file_extent_num_bytes(leaf, fi);
2675 if (extent_len + found_key.offset == start &&
2676 relink_is_mergable(leaf, fi, new)) {
2677 btrfs_set_file_extent_num_bytes(leaf, fi,
2679 btrfs_mark_buffer_dirty(leaf);
2680 inode_add_bytes(inode, len);
2686 btrfs_release_path(path);
2691 ret = btrfs_insert_empty_item(trans, root, path, &key,
2694 btrfs_abort_transaction(trans, ret);
2698 leaf = path->nodes[0];
2699 item = btrfs_item_ptr(leaf, path->slots[0],
2700 struct btrfs_file_extent_item);
2701 btrfs_set_file_extent_disk_bytenr(leaf, item, new->bytenr);
2702 btrfs_set_file_extent_disk_num_bytes(leaf, item, new->disk_len);
2703 btrfs_set_file_extent_offset(leaf, item, start - new->file_pos);
2704 btrfs_set_file_extent_num_bytes(leaf, item, len);
2705 btrfs_set_file_extent_ram_bytes(leaf, item, new->len);
2706 btrfs_set_file_extent_generation(leaf, item, trans->transid);
2707 btrfs_set_file_extent_type(leaf, item, BTRFS_FILE_EXTENT_REG);
2708 btrfs_set_file_extent_compression(leaf, item, new->compress_type);
2709 btrfs_set_file_extent_encryption(leaf, item, 0);
2710 btrfs_set_file_extent_other_encoding(leaf, item, 0);
2712 btrfs_mark_buffer_dirty(leaf);
2713 inode_add_bytes(inode, len);
2714 btrfs_release_path(path);
2716 ret = btrfs_inc_extent_ref(trans, root, new->bytenr,
2718 backref->root_id, backref->inum,
2719 new->file_pos); /* start - extent_offset */
2721 btrfs_abort_transaction(trans, ret);
2727 btrfs_release_path(path);
2728 path->leave_spinning = 0;
2729 btrfs_end_transaction(trans);
2731 unlock_extent_cached(&BTRFS_I(inode)->io_tree, lock_start, lock_end,
2737 static void free_sa_defrag_extent(struct new_sa_defrag_extent *new)
2739 struct old_sa_defrag_extent *old, *tmp;
2744 list_for_each_entry_safe(old, tmp, &new->head, list) {
2750 static void relink_file_extents(struct new_sa_defrag_extent *new)
2752 struct btrfs_fs_info *fs_info = btrfs_sb(new->inode->i_sb);
2753 struct btrfs_path *path;
2754 struct sa_defrag_extent_backref *backref;
2755 struct sa_defrag_extent_backref *prev = NULL;
2756 struct inode *inode;
2757 struct btrfs_root *root;
2758 struct rb_node *node;
2762 root = BTRFS_I(inode)->root;
2764 path = btrfs_alloc_path();
2768 if (!record_extent_backrefs(path, new)) {
2769 btrfs_free_path(path);
2772 btrfs_release_path(path);
2775 node = rb_first(&new->root);
2778 rb_erase(node, &new->root);
2780 backref = rb_entry(node, struct sa_defrag_extent_backref, node);
2782 ret = relink_extent_backref(path, prev, backref);
2795 btrfs_free_path(path);
2797 free_sa_defrag_extent(new);
2799 atomic_dec(&fs_info->defrag_running);
2800 wake_up(&fs_info->transaction_wait);
2803 static struct new_sa_defrag_extent *
2804 record_old_file_extents(struct inode *inode,
2805 struct btrfs_ordered_extent *ordered)
2807 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2808 struct btrfs_root *root = BTRFS_I(inode)->root;
2809 struct btrfs_path *path;
2810 struct btrfs_key key;
2811 struct old_sa_defrag_extent *old;
2812 struct new_sa_defrag_extent *new;
2815 new = kmalloc(sizeof(*new), GFP_NOFS);
2820 new->file_pos = ordered->file_offset;
2821 new->len = ordered->len;
2822 new->bytenr = ordered->start;
2823 new->disk_len = ordered->disk_len;
2824 new->compress_type = ordered->compress_type;
2825 new->root = RB_ROOT;
2826 INIT_LIST_HEAD(&new->head);
2828 path = btrfs_alloc_path();
2832 key.objectid = btrfs_ino(BTRFS_I(inode));
2833 key.type = BTRFS_EXTENT_DATA_KEY;
2834 key.offset = new->file_pos;
2836 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2839 if (ret > 0 && path->slots[0] > 0)
2842 /* find out all the old extents for the file range */
2844 struct btrfs_file_extent_item *extent;
2845 struct extent_buffer *l;
2854 slot = path->slots[0];
2856 if (slot >= btrfs_header_nritems(l)) {
2857 ret = btrfs_next_leaf(root, path);
2865 btrfs_item_key_to_cpu(l, &key, slot);
2867 if (key.objectid != btrfs_ino(BTRFS_I(inode)))
2869 if (key.type != BTRFS_EXTENT_DATA_KEY)
2871 if (key.offset >= new->file_pos + new->len)
2874 extent = btrfs_item_ptr(l, slot, struct btrfs_file_extent_item);
2876 num_bytes = btrfs_file_extent_num_bytes(l, extent);
2877 if (key.offset + num_bytes < new->file_pos)
2880 disk_bytenr = btrfs_file_extent_disk_bytenr(l, extent);
2884 extent_offset = btrfs_file_extent_offset(l, extent);
2886 old = kmalloc(sizeof(*old), GFP_NOFS);
2890 offset = max(new->file_pos, key.offset);
2891 end = min(new->file_pos + new->len, key.offset + num_bytes);
2893 old->bytenr = disk_bytenr;
2894 old->extent_offset = extent_offset;
2895 old->offset = offset - key.offset;
2896 old->len = end - offset;
2899 list_add_tail(&old->list, &new->head);
2905 btrfs_free_path(path);
2906 atomic_inc(&fs_info->defrag_running);
2911 btrfs_free_path(path);
2913 free_sa_defrag_extent(new);
2917 static void btrfs_release_delalloc_bytes(struct btrfs_fs_info *fs_info,
2920 struct btrfs_block_group_cache *cache;
2922 cache = btrfs_lookup_block_group(fs_info, start);
2925 spin_lock(&cache->lock);
2926 cache->delalloc_bytes -= len;
2927 spin_unlock(&cache->lock);
2929 btrfs_put_block_group(cache);
2932 /* as ordered data IO finishes, this gets called so we can finish
2933 * an ordered extent if the range of bytes in the file it covers are
2936 static int btrfs_finish_ordered_io(struct btrfs_ordered_extent *ordered_extent)
2938 struct inode *inode = ordered_extent->inode;
2939 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2940 struct btrfs_root *root = BTRFS_I(inode)->root;
2941 struct btrfs_trans_handle *trans = NULL;
2942 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
2943 struct extent_state *cached_state = NULL;
2944 struct new_sa_defrag_extent *new = NULL;
2945 int compress_type = 0;
2947 u64 logical_len = ordered_extent->len;
2949 bool truncated = false;
2950 bool range_locked = false;
2951 bool clear_new_delalloc_bytes = false;
2953 if (!test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags) &&
2954 !test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags) &&
2955 !test_bit(BTRFS_ORDERED_DIRECT, &ordered_extent->flags))
2956 clear_new_delalloc_bytes = true;
2958 nolock = btrfs_is_free_space_inode(BTRFS_I(inode));
2960 if (test_bit(BTRFS_ORDERED_IOERR, &ordered_extent->flags)) {
2965 btrfs_free_io_failure_record(BTRFS_I(inode),
2966 ordered_extent->file_offset,
2967 ordered_extent->file_offset +
2968 ordered_extent->len - 1);
2970 if (test_bit(BTRFS_ORDERED_TRUNCATED, &ordered_extent->flags)) {
2972 logical_len = ordered_extent->truncated_len;
2973 /* Truncated the entire extent, don't bother adding */
2978 if (test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags)) {
2979 BUG_ON(!list_empty(&ordered_extent->list)); /* Logic error */
2982 * For mwrite(mmap + memset to write) case, we still reserve
2983 * space for NOCOW range.
2984 * As NOCOW won't cause a new delayed ref, just free the space
2986 btrfs_qgroup_free_data(inode, NULL, ordered_extent->file_offset,
2987 ordered_extent->len);
2988 btrfs_ordered_update_i_size(inode, 0, ordered_extent);
2990 trans = btrfs_join_transaction_nolock(root);
2992 trans = btrfs_join_transaction(root);
2993 if (IS_ERR(trans)) {
2994 ret = PTR_ERR(trans);
2998 trans->block_rsv = &BTRFS_I(inode)->block_rsv;
2999 ret = btrfs_update_inode_fallback(trans, root, inode);
3000 if (ret) /* -ENOMEM or corruption */
3001 btrfs_abort_transaction(trans, ret);
3005 range_locked = true;
3006 lock_extent_bits(io_tree, ordered_extent->file_offset,
3007 ordered_extent->file_offset + ordered_extent->len - 1,
3010 ret = test_range_bit(io_tree, ordered_extent->file_offset,
3011 ordered_extent->file_offset + ordered_extent->len - 1,
3012 EXTENT_DEFRAG, 0, cached_state);
3014 u64 last_snapshot = btrfs_root_last_snapshot(&root->root_item);
3015 if (0 && last_snapshot >= BTRFS_I(inode)->generation)
3016 /* the inode is shared */
3017 new = record_old_file_extents(inode, ordered_extent);
3019 clear_extent_bit(io_tree, ordered_extent->file_offset,
3020 ordered_extent->file_offset + ordered_extent->len - 1,
3021 EXTENT_DEFRAG, 0, 0, &cached_state);
3025 trans = btrfs_join_transaction_nolock(root);
3027 trans = btrfs_join_transaction(root);
3028 if (IS_ERR(trans)) {
3029 ret = PTR_ERR(trans);
3034 trans->block_rsv = &BTRFS_I(inode)->block_rsv;
3036 if (test_bit(BTRFS_ORDERED_COMPRESSED, &ordered_extent->flags))
3037 compress_type = ordered_extent->compress_type;
3038 if (test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags)) {
3039 BUG_ON(compress_type);
3040 btrfs_qgroup_free_data(inode, NULL, ordered_extent->file_offset,
3041 ordered_extent->len);
3042 ret = btrfs_mark_extent_written(trans, BTRFS_I(inode),
3043 ordered_extent->file_offset,
3044 ordered_extent->file_offset +
3047 BUG_ON(root == fs_info->tree_root);
3048 ret = insert_reserved_file_extent(trans, inode,
3049 ordered_extent->file_offset,
3050 ordered_extent->start,
3051 ordered_extent->disk_len,
3052 logical_len, logical_len,
3053 compress_type, 0, 0,
3054 BTRFS_FILE_EXTENT_REG);
3056 btrfs_release_delalloc_bytes(fs_info,
3057 ordered_extent->start,
3058 ordered_extent->disk_len);
3060 unpin_extent_cache(&BTRFS_I(inode)->extent_tree,
3061 ordered_extent->file_offset, ordered_extent->len,
3064 btrfs_abort_transaction(trans, ret);
3068 ret = add_pending_csums(trans, inode, &ordered_extent->list);
3070 btrfs_abort_transaction(trans, ret);
3074 btrfs_ordered_update_i_size(inode, 0, ordered_extent);
3075 ret = btrfs_update_inode_fallback(trans, root, inode);
3076 if (ret) { /* -ENOMEM or corruption */
3077 btrfs_abort_transaction(trans, ret);
3082 if (range_locked || clear_new_delalloc_bytes) {
3083 unsigned int clear_bits = 0;
3086 clear_bits |= EXTENT_LOCKED;
3087 if (clear_new_delalloc_bytes)
3088 clear_bits |= EXTENT_DELALLOC_NEW;
3089 clear_extent_bit(&BTRFS_I(inode)->io_tree,
3090 ordered_extent->file_offset,
3091 ordered_extent->file_offset +
3092 ordered_extent->len - 1,
3094 (clear_bits & EXTENT_LOCKED) ? 1 : 0,
3099 btrfs_end_transaction(trans);
3101 if (ret || truncated) {
3105 start = ordered_extent->file_offset + logical_len;
3107 start = ordered_extent->file_offset;
3108 end = ordered_extent->file_offset + ordered_extent->len - 1;
3109 clear_extent_uptodate(io_tree, start, end, NULL);
3111 /* Drop the cache for the part of the extent we didn't write. */
3112 btrfs_drop_extent_cache(BTRFS_I(inode), start, end, 0);
3115 * If the ordered extent had an IOERR or something else went
3116 * wrong we need to return the space for this ordered extent
3117 * back to the allocator. We only free the extent in the
3118 * truncated case if we didn't write out the extent at all.
3120 if ((ret || !logical_len) &&
3121 !test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags) &&
3122 !test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags))
3123 btrfs_free_reserved_extent(fs_info,
3124 ordered_extent->start,
3125 ordered_extent->disk_len, 1);
3130 * This needs to be done to make sure anybody waiting knows we are done
3131 * updating everything for this ordered extent.
3133 btrfs_remove_ordered_extent(inode, ordered_extent);
3135 /* for snapshot-aware defrag */
3138 free_sa_defrag_extent(new);
3139 atomic_dec(&fs_info->defrag_running);
3141 relink_file_extents(new);
3146 btrfs_put_ordered_extent(ordered_extent);
3147 /* once for the tree */
3148 btrfs_put_ordered_extent(ordered_extent);
3153 static void finish_ordered_fn(struct btrfs_work *work)
3155 struct btrfs_ordered_extent *ordered_extent;
3156 ordered_extent = container_of(work, struct btrfs_ordered_extent, work);
3157 btrfs_finish_ordered_io(ordered_extent);
3160 static void btrfs_writepage_end_io_hook(struct page *page, u64 start, u64 end,
3161 struct extent_state *state, int uptodate)
3163 struct inode *inode = page->mapping->host;
3164 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
3165 struct btrfs_ordered_extent *ordered_extent = NULL;
3166 struct btrfs_workqueue *wq;
3167 btrfs_work_func_t func;
3169 trace_btrfs_writepage_end_io_hook(page, start, end, uptodate);
3171 ClearPagePrivate2(page);
3172 if (!btrfs_dec_test_ordered_pending(inode, &ordered_extent, start,
3173 end - start + 1, uptodate))
3176 if (btrfs_is_free_space_inode(BTRFS_I(inode))) {
3177 wq = fs_info->endio_freespace_worker;
3178 func = btrfs_freespace_write_helper;
3180 wq = fs_info->endio_write_workers;
3181 func = btrfs_endio_write_helper;
3184 btrfs_init_work(&ordered_extent->work, func, finish_ordered_fn, NULL,
3186 btrfs_queue_work(wq, &ordered_extent->work);
3189 static int __readpage_endio_check(struct inode *inode,
3190 struct btrfs_io_bio *io_bio,
3191 int icsum, struct page *page,
3192 int pgoff, u64 start, size_t len)
3198 csum_expected = *(((u32 *)io_bio->csum) + icsum);
3200 kaddr = kmap_atomic(page);
3201 csum = btrfs_csum_data(kaddr + pgoff, csum, len);
3202 btrfs_csum_final(csum, (u8 *)&csum);
3203 if (csum != csum_expected)
3206 kunmap_atomic(kaddr);
3209 btrfs_print_data_csum_error(BTRFS_I(inode), start, csum, csum_expected,
3210 io_bio->mirror_num);
3211 memset(kaddr + pgoff, 1, len);
3212 flush_dcache_page(page);
3213 kunmap_atomic(kaddr);
3218 * when reads are done, we need to check csums to verify the data is correct
3219 * if there's a match, we allow the bio to finish. If not, the code in
3220 * extent_io.c will try to find good copies for us.
3222 static int btrfs_readpage_end_io_hook(struct btrfs_io_bio *io_bio,
3223 u64 phy_offset, struct page *page,
3224 u64 start, u64 end, int mirror)
3226 size_t offset = start - page_offset(page);
3227 struct inode *inode = page->mapping->host;
3228 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
3229 struct btrfs_root *root = BTRFS_I(inode)->root;
3231 if (PageChecked(page)) {
3232 ClearPageChecked(page);
3236 if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)
3239 if (root->root_key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID &&
3240 test_range_bit(io_tree, start, end, EXTENT_NODATASUM, 1, NULL)) {
3241 clear_extent_bits(io_tree, start, end, EXTENT_NODATASUM);
3245 phy_offset >>= inode->i_sb->s_blocksize_bits;
3246 return __readpage_endio_check(inode, io_bio, phy_offset, page, offset,
3247 start, (size_t)(end - start + 1));
3250 void btrfs_add_delayed_iput(struct inode *inode)
3252 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
3253 struct btrfs_inode *binode = BTRFS_I(inode);
3255 if (atomic_add_unless(&inode->i_count, -1, 1))
3258 spin_lock(&fs_info->delayed_iput_lock);
3259 if (binode->delayed_iput_count == 0) {
3260 ASSERT(list_empty(&binode->delayed_iput));
3261 list_add_tail(&binode->delayed_iput, &fs_info->delayed_iputs);
3263 binode->delayed_iput_count++;
3265 spin_unlock(&fs_info->delayed_iput_lock);
3268 void btrfs_run_delayed_iputs(struct btrfs_fs_info *fs_info)
3271 spin_lock(&fs_info->delayed_iput_lock);
3272 while (!list_empty(&fs_info->delayed_iputs)) {
3273 struct btrfs_inode *inode;
3275 inode = list_first_entry(&fs_info->delayed_iputs,
3276 struct btrfs_inode, delayed_iput);
3277 if (inode->delayed_iput_count) {
3278 inode->delayed_iput_count--;
3279 list_move_tail(&inode->delayed_iput,
3280 &fs_info->delayed_iputs);
3282 list_del_init(&inode->delayed_iput);
3284 spin_unlock(&fs_info->delayed_iput_lock);
3285 iput(&inode->vfs_inode);
3286 spin_lock(&fs_info->delayed_iput_lock);
3288 spin_unlock(&fs_info->delayed_iput_lock);
3292 * This is called in transaction commit time. If there are no orphan
3293 * files in the subvolume, it removes orphan item and frees block_rsv
3296 void btrfs_orphan_commit_root(struct btrfs_trans_handle *trans,
3297 struct btrfs_root *root)
3299 struct btrfs_fs_info *fs_info = root->fs_info;
3300 struct btrfs_block_rsv *block_rsv;
3303 if (atomic_read(&root->orphan_inodes) ||
3304 root->orphan_cleanup_state != ORPHAN_CLEANUP_DONE)
3307 spin_lock(&root->orphan_lock);
3308 if (atomic_read(&root->orphan_inodes)) {
3309 spin_unlock(&root->orphan_lock);
3313 if (root->orphan_cleanup_state != ORPHAN_CLEANUP_DONE) {
3314 spin_unlock(&root->orphan_lock);
3318 block_rsv = root->orphan_block_rsv;
3319 root->orphan_block_rsv = NULL;
3320 spin_unlock(&root->orphan_lock);
3322 if (test_bit(BTRFS_ROOT_ORPHAN_ITEM_INSERTED, &root->state) &&
3323 btrfs_root_refs(&root->root_item) > 0) {
3324 ret = btrfs_del_orphan_item(trans, fs_info->tree_root,
3325 root->root_key.objectid);
3327 btrfs_abort_transaction(trans, ret);
3329 clear_bit(BTRFS_ROOT_ORPHAN_ITEM_INSERTED,
3334 WARN_ON(block_rsv->size > 0);
3335 btrfs_free_block_rsv(fs_info, block_rsv);
3340 * This creates an orphan entry for the given inode in case something goes
3341 * wrong in the middle of an unlink/truncate.
3343 * NOTE: caller of this function should reserve 5 units of metadata for
3346 int btrfs_orphan_add(struct btrfs_trans_handle *trans,
3347 struct btrfs_inode *inode)
3349 struct btrfs_fs_info *fs_info = btrfs_sb(inode->vfs_inode.i_sb);
3350 struct btrfs_root *root = inode->root;
3351 struct btrfs_block_rsv *block_rsv = NULL;
3356 if (!root->orphan_block_rsv) {
3357 block_rsv = btrfs_alloc_block_rsv(fs_info,
3358 BTRFS_BLOCK_RSV_TEMP);
3363 spin_lock(&root->orphan_lock);
3364 if (!root->orphan_block_rsv) {
3365 root->orphan_block_rsv = block_rsv;
3366 } else if (block_rsv) {
3367 btrfs_free_block_rsv(fs_info, block_rsv);
3371 if (!test_and_set_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
3372 &inode->runtime_flags)) {
3375 * For proper ENOSPC handling, we should do orphan
3376 * cleanup when mounting. But this introduces backward
3377 * compatibility issue.
3379 if (!xchg(&root->orphan_item_inserted, 1))
3385 atomic_inc(&root->orphan_inodes);
3388 if (!test_and_set_bit(BTRFS_INODE_ORPHAN_META_RESERVED,
3389 &inode->runtime_flags))
3391 spin_unlock(&root->orphan_lock);
3393 /* grab metadata reservation from transaction handle */
3395 ret = btrfs_orphan_reserve_metadata(trans, inode);
3399 * dec doesn't need spin_lock as ->orphan_block_rsv
3400 * would be released only if ->orphan_inodes is
3403 atomic_dec(&root->orphan_inodes);
3404 clear_bit(BTRFS_INODE_ORPHAN_META_RESERVED,
3405 &inode->runtime_flags);
3407 clear_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
3408 &inode->runtime_flags);
3413 /* insert an orphan item to track this unlinked/truncated file */
3415 ret = btrfs_insert_orphan_item(trans, root, btrfs_ino(inode));
3418 clear_bit(BTRFS_INODE_ORPHAN_META_RESERVED,
3419 &inode->runtime_flags);
3420 btrfs_orphan_release_metadata(inode);
3423 * btrfs_orphan_commit_root may race with us and set
3424 * ->orphan_block_rsv to zero, in order to avoid that,
3425 * decrease ->orphan_inodes after everything is done.
3427 atomic_dec(&root->orphan_inodes);
3428 if (ret != -EEXIST) {
3429 clear_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
3430 &inode->runtime_flags);
3431 btrfs_abort_transaction(trans, ret);
3438 /* insert an orphan item to track subvolume contains orphan files */
3440 ret = btrfs_insert_orphan_item(trans, fs_info->tree_root,
3441 root->root_key.objectid);
3442 if (ret && ret != -EEXIST) {
3443 btrfs_abort_transaction(trans, ret);
3451 * We have done the truncate/delete so we can go ahead and remove the orphan
3452 * item for this particular inode.
3454 static int btrfs_orphan_del(struct btrfs_trans_handle *trans,
3455 struct btrfs_inode *inode)
3457 struct btrfs_root *root = inode->root;
3458 int delete_item = 0;
3461 if (test_and_clear_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
3462 &inode->runtime_flags))
3465 if (delete_item && trans)
3466 ret = btrfs_del_orphan_item(trans, root, btrfs_ino(inode));
3468 if (test_and_clear_bit(BTRFS_INODE_ORPHAN_META_RESERVED,
3469 &inode->runtime_flags))
3470 btrfs_orphan_release_metadata(inode);
3473 * btrfs_orphan_commit_root may race with us and set ->orphan_block_rsv
3474 * to zero, in order to avoid that, decrease ->orphan_inodes after
3475 * everything is done.
3478 atomic_dec(&root->orphan_inodes);
3484 * this cleans up any orphans that may be left on the list from the last use
3487 int btrfs_orphan_cleanup(struct btrfs_root *root)
3489 struct btrfs_fs_info *fs_info = root->fs_info;
3490 struct btrfs_path *path;
3491 struct extent_buffer *leaf;
3492 struct btrfs_key key, found_key;
3493 struct btrfs_trans_handle *trans;
3494 struct inode *inode;
3495 u64 last_objectid = 0;
3496 int ret = 0, nr_unlink = 0, nr_truncate = 0;
3498 if (cmpxchg(&root->orphan_cleanup_state, 0, ORPHAN_CLEANUP_STARTED))
3501 path = btrfs_alloc_path();
3506 path->reada = READA_BACK;
3508 key.objectid = BTRFS_ORPHAN_OBJECTID;
3509 key.type = BTRFS_ORPHAN_ITEM_KEY;
3510 key.offset = (u64)-1;
3513 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
3518 * if ret == 0 means we found what we were searching for, which
3519 * is weird, but possible, so only screw with path if we didn't
3520 * find the key and see if we have stuff that matches
3524 if (path->slots[0] == 0)
3529 /* pull out the item */
3530 leaf = path->nodes[0];
3531 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
3533 /* make sure the item matches what we want */
3534 if (found_key.objectid != BTRFS_ORPHAN_OBJECTID)
3536 if (found_key.type != BTRFS_ORPHAN_ITEM_KEY)
3539 /* release the path since we're done with it */
3540 btrfs_release_path(path);
3543 * this is where we are basically btrfs_lookup, without the
3544 * crossing root thing. we store the inode number in the
3545 * offset of the orphan item.
3548 if (found_key.offset == last_objectid) {
3550 "Error removing orphan entry, stopping orphan cleanup");
3555 last_objectid = found_key.offset;
3557 found_key.objectid = found_key.offset;
3558 found_key.type = BTRFS_INODE_ITEM_KEY;
3559 found_key.offset = 0;
3560 inode = btrfs_iget(fs_info->sb, &found_key, root, NULL);
3561 ret = PTR_ERR_OR_ZERO(inode);
3562 if (ret && ret != -ENOENT)
3565 if (ret == -ENOENT && root == fs_info->tree_root) {
3566 struct btrfs_root *dead_root;
3567 struct btrfs_fs_info *fs_info = root->fs_info;
3568 int is_dead_root = 0;
3571 * this is an orphan in the tree root. Currently these
3572 * could come from 2 sources:
3573 * a) a snapshot deletion in progress
3574 * b) a free space cache inode
3575 * We need to distinguish those two, as the snapshot
3576 * orphan must not get deleted.
3577 * find_dead_roots already ran before us, so if this
3578 * is a snapshot deletion, we should find the root
3579 * in the dead_roots list
3581 spin_lock(&fs_info->trans_lock);
3582 list_for_each_entry(dead_root, &fs_info->dead_roots,
3584 if (dead_root->root_key.objectid ==
3585 found_key.objectid) {
3590 spin_unlock(&fs_info->trans_lock);
3592 /* prevent this orphan from being found again */
3593 key.offset = found_key.objectid - 1;
3598 * Inode is already gone but the orphan item is still there,
3599 * kill the orphan item.
3601 if (ret == -ENOENT) {
3602 trans = btrfs_start_transaction(root, 1);
3603 if (IS_ERR(trans)) {
3604 ret = PTR_ERR(trans);
3607 btrfs_debug(fs_info, "auto deleting %Lu",
3608 found_key.objectid);
3609 ret = btrfs_del_orphan_item(trans, root,
3610 found_key.objectid);
3611 btrfs_end_transaction(trans);
3618 * add this inode to the orphan list so btrfs_orphan_del does
3619 * the proper thing when we hit it
3621 set_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
3622 &BTRFS_I(inode)->runtime_flags);
3623 atomic_inc(&root->orphan_inodes);
3625 /* if we have links, this was a truncate, lets do that */
3626 if (inode->i_nlink) {
3627 if (WARN_ON(!S_ISREG(inode->i_mode))) {
3633 /* 1 for the orphan item deletion. */
3634 trans = btrfs_start_transaction(root, 1);
3635 if (IS_ERR(trans)) {
3637 ret = PTR_ERR(trans);
3640 ret = btrfs_orphan_add(trans, BTRFS_I(inode));
3641 btrfs_end_transaction(trans);
3647 ret = btrfs_truncate(inode);
3649 btrfs_orphan_del(NULL, BTRFS_I(inode));
3654 /* this will do delete_inode and everything for us */
3659 /* release the path since we're done with it */
3660 btrfs_release_path(path);
3662 root->orphan_cleanup_state = ORPHAN_CLEANUP_DONE;
3664 if (root->orphan_block_rsv)
3665 btrfs_block_rsv_release(fs_info, root->orphan_block_rsv,
3668 if (root->orphan_block_rsv ||
3669 test_bit(BTRFS_ROOT_ORPHAN_ITEM_INSERTED, &root->state)) {
3670 trans = btrfs_join_transaction(root);
3672 btrfs_end_transaction(trans);
3676 btrfs_debug(fs_info, "unlinked %d orphans", nr_unlink);
3678 btrfs_debug(fs_info, "truncated %d orphans", nr_truncate);
3682 btrfs_err(fs_info, "could not do orphan cleanup %d", ret);
3683 btrfs_free_path(path);
3688 * very simple check to peek ahead in the leaf looking for xattrs. If we
3689 * don't find any xattrs, we know there can't be any acls.
3691 * slot is the slot the inode is in, objectid is the objectid of the inode
3693 static noinline int acls_after_inode_item(struct extent_buffer *leaf,
3694 int slot, u64 objectid,
3695 int *first_xattr_slot)
3697 u32 nritems = btrfs_header_nritems(leaf);
3698 struct btrfs_key found_key;
3699 static u64 xattr_access = 0;
3700 static u64 xattr_default = 0;
3703 if (!xattr_access) {
3704 xattr_access = btrfs_name_hash(XATTR_NAME_POSIX_ACL_ACCESS,
3705 strlen(XATTR_NAME_POSIX_ACL_ACCESS));
3706 xattr_default = btrfs_name_hash(XATTR_NAME_POSIX_ACL_DEFAULT,
3707 strlen(XATTR_NAME_POSIX_ACL_DEFAULT));
3711 *first_xattr_slot = -1;
3712 while (slot < nritems) {
3713 btrfs_item_key_to_cpu(leaf, &found_key, slot);
3715 /* we found a different objectid, there must not be acls */
3716 if (found_key.objectid != objectid)
3719 /* we found an xattr, assume we've got an acl */
3720 if (found_key.type == BTRFS_XATTR_ITEM_KEY) {
3721 if (*first_xattr_slot == -1)
3722 *first_xattr_slot = slot;
3723 if (found_key.offset == xattr_access ||
3724 found_key.offset == xattr_default)
3729 * we found a key greater than an xattr key, there can't
3730 * be any acls later on
3732 if (found_key.type > BTRFS_XATTR_ITEM_KEY)
3739 * it goes inode, inode backrefs, xattrs, extents,
3740 * so if there are a ton of hard links to an inode there can
3741 * be a lot of backrefs. Don't waste time searching too hard,
3742 * this is just an optimization
3747 /* we hit the end of the leaf before we found an xattr or
3748 * something larger than an xattr. We have to assume the inode
3751 if (*first_xattr_slot == -1)
3752 *first_xattr_slot = slot;
3757 * read an inode from the btree into the in-memory inode
3759 static int btrfs_read_locked_inode(struct inode *inode)
3761 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
3762 struct btrfs_path *path;
3763 struct extent_buffer *leaf;
3764 struct btrfs_inode_item *inode_item;
3765 struct btrfs_root *root = BTRFS_I(inode)->root;
3766 struct btrfs_key location;
3771 bool filled = false;
3772 int first_xattr_slot;
3774 ret = btrfs_fill_inode(inode, &rdev);
3778 path = btrfs_alloc_path();
3784 memcpy(&location, &BTRFS_I(inode)->location, sizeof(location));
3786 ret = btrfs_lookup_inode(NULL, root, path, &location, 0);
3793 leaf = path->nodes[0];
3798 inode_item = btrfs_item_ptr(leaf, path->slots[0],
3799 struct btrfs_inode_item);
3800 inode->i_mode = btrfs_inode_mode(leaf, inode_item);
3801 set_nlink(inode, btrfs_inode_nlink(leaf, inode_item));
3802 i_uid_write(inode, btrfs_inode_uid(leaf, inode_item));
3803 i_gid_write(inode, btrfs_inode_gid(leaf, inode_item));
3804 btrfs_i_size_write(BTRFS_I(inode), btrfs_inode_size(leaf, inode_item));
3806 inode->i_atime.tv_sec = btrfs_timespec_sec(leaf, &inode_item->atime);
3807 inode->i_atime.tv_nsec = btrfs_timespec_nsec(leaf, &inode_item->atime);
3809 inode->i_mtime.tv_sec = btrfs_timespec_sec(leaf, &inode_item->mtime);
3810 inode->i_mtime.tv_nsec = btrfs_timespec_nsec(leaf, &inode_item->mtime);
3812 inode->i_ctime.tv_sec = btrfs_timespec_sec(leaf, &inode_item->ctime);
3813 inode->i_ctime.tv_nsec = btrfs_timespec_nsec(leaf, &inode_item->ctime);
3815 BTRFS_I(inode)->i_otime.tv_sec =
3816 btrfs_timespec_sec(leaf, &inode_item->otime);
3817 BTRFS_I(inode)->i_otime.tv_nsec =
3818 btrfs_timespec_nsec(leaf, &inode_item->otime);
3820 inode_set_bytes(inode, btrfs_inode_nbytes(leaf, inode_item));
3821 BTRFS_I(inode)->generation = btrfs_inode_generation(leaf, inode_item);
3822 BTRFS_I(inode)->last_trans = btrfs_inode_transid(leaf, inode_item);
3824 inode_set_iversion_queried(inode,
3825 btrfs_inode_sequence(leaf, inode_item));
3826 inode->i_generation = BTRFS_I(inode)->generation;
3828 rdev = btrfs_inode_rdev(leaf, inode_item);
3830 BTRFS_I(inode)->index_cnt = (u64)-1;
3831 BTRFS_I(inode)->flags = btrfs_inode_flags(leaf, inode_item);
3835 * If we were modified in the current generation and evicted from memory
3836 * and then re-read we need to do a full sync since we don't have any
3837 * idea about which extents were modified before we were evicted from
3840 * This is required for both inode re-read from disk and delayed inode
3841 * in delayed_nodes_tree.
3843 if (BTRFS_I(inode)->last_trans == fs_info->generation)
3844 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
3845 &BTRFS_I(inode)->runtime_flags);
3848 * We don't persist the id of the transaction where an unlink operation
3849 * against the inode was last made. So here we assume the inode might
3850 * have been evicted, and therefore the exact value of last_unlink_trans
3851 * lost, and set it to last_trans to avoid metadata inconsistencies
3852 * between the inode and its parent if the inode is fsync'ed and the log
3853 * replayed. For example, in the scenario:
3856 * ln mydir/foo mydir/bar
3859 * echo 2 > /proc/sys/vm/drop_caches # evicts inode
3860 * xfs_io -c fsync mydir/foo
3862 * mount fs, triggers fsync log replay
3864 * We must make sure that when we fsync our inode foo we also log its
3865 * parent inode, otherwise after log replay the parent still has the
3866 * dentry with the "bar" name but our inode foo has a link count of 1
3867 * and doesn't have an inode ref with the name "bar" anymore.
3869 * Setting last_unlink_trans to last_trans is a pessimistic approach,
3870 * but it guarantees correctness at the expense of occasional full
3871 * transaction commits on fsync if our inode is a directory, or if our
3872 * inode is not a directory, logging its parent unnecessarily.
3874 BTRFS_I(inode)->last_unlink_trans = BTRFS_I(inode)->last_trans;
3877 if (inode->i_nlink != 1 ||
3878 path->slots[0] >= btrfs_header_nritems(leaf))
3881 btrfs_item_key_to_cpu(leaf, &location, path->slots[0]);
3882 if (location.objectid != btrfs_ino(BTRFS_I(inode)))
3885 ptr = btrfs_item_ptr_offset(leaf, path->slots[0]);
3886 if (location.type == BTRFS_INODE_REF_KEY) {
3887 struct btrfs_inode_ref *ref;
3889 ref = (struct btrfs_inode_ref *)ptr;
3890 BTRFS_I(inode)->dir_index = btrfs_inode_ref_index(leaf, ref);
3891 } else if (location.type == BTRFS_INODE_EXTREF_KEY) {
3892 struct btrfs_inode_extref *extref;
3894 extref = (struct btrfs_inode_extref *)ptr;
3895 BTRFS_I(inode)->dir_index = btrfs_inode_extref_index(leaf,
3900 * try to precache a NULL acl entry for files that don't have
3901 * any xattrs or acls
3903 maybe_acls = acls_after_inode_item(leaf, path->slots[0],
3904 btrfs_ino(BTRFS_I(inode)), &first_xattr_slot);
3905 if (first_xattr_slot != -1) {
3906 path->slots[0] = first_xattr_slot;
3907 ret = btrfs_load_inode_props(inode, path);
3910 "error loading props for ino %llu (root %llu): %d",
3911 btrfs_ino(BTRFS_I(inode)),
3912 root->root_key.objectid, ret);
3914 btrfs_free_path(path);
3917 cache_no_acl(inode);
3919 switch (inode->i_mode & S_IFMT) {
3921 inode->i_mapping->a_ops = &btrfs_aops;
3922 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
3923 inode->i_fop = &btrfs_file_operations;
3924 inode->i_op = &btrfs_file_inode_operations;
3927 inode->i_fop = &btrfs_dir_file_operations;
3928 inode->i_op = &btrfs_dir_inode_operations;
3931 inode->i_op = &btrfs_symlink_inode_operations;
3932 inode_nohighmem(inode);
3933 inode->i_mapping->a_ops = &btrfs_symlink_aops;
3936 inode->i_op = &btrfs_special_inode_operations;
3937 init_special_inode(inode, inode->i_mode, rdev);
3941 btrfs_update_iflags(inode);
3945 btrfs_free_path(path);
3946 make_bad_inode(inode);
3951 * given a leaf and an inode, copy the inode fields into the leaf
3953 static void fill_inode_item(struct btrfs_trans_handle *trans,
3954 struct extent_buffer *leaf,
3955 struct btrfs_inode_item *item,
3956 struct inode *inode)
3958 struct btrfs_map_token token;
3960 btrfs_init_map_token(&token);
3962 btrfs_set_token_inode_uid(leaf, item, i_uid_read(inode), &token);
3963 btrfs_set_token_inode_gid(leaf, item, i_gid_read(inode), &token);
3964 btrfs_set_token_inode_size(leaf, item, BTRFS_I(inode)->disk_i_size,
3966 btrfs_set_token_inode_mode(leaf, item, inode->i_mode, &token);
3967 btrfs_set_token_inode_nlink(leaf, item, inode->i_nlink, &token);
3969 btrfs_set_token_timespec_sec(leaf, &item->atime,
3970 inode->i_atime.tv_sec, &token);
3971 btrfs_set_token_timespec_nsec(leaf, &item->atime,
3972 inode->i_atime.tv_nsec, &token);
3974 btrfs_set_token_timespec_sec(leaf, &item->mtime,
3975 inode->i_mtime.tv_sec, &token);
3976 btrfs_set_token_timespec_nsec(leaf, &item->mtime,
3977 inode->i_mtime.tv_nsec, &token);
3979 btrfs_set_token_timespec_sec(leaf, &item->ctime,
3980 inode->i_ctime.tv_sec, &token);
3981 btrfs_set_token_timespec_nsec(leaf, &item->ctime,
3982 inode->i_ctime.tv_nsec, &token);
3984 btrfs_set_token_timespec_sec(leaf, &item->otime,
3985 BTRFS_I(inode)->i_otime.tv_sec, &token);
3986 btrfs_set_token_timespec_nsec(leaf, &item->otime,
3987 BTRFS_I(inode)->i_otime.tv_nsec, &token);
3989 btrfs_set_token_inode_nbytes(leaf, item, inode_get_bytes(inode),
3991 btrfs_set_token_inode_generation(leaf, item, BTRFS_I(inode)->generation,
3993 btrfs_set_token_inode_sequence(leaf, item, inode_peek_iversion(inode),
3995 btrfs_set_token_inode_transid(leaf, item, trans->transid, &token);
3996 btrfs_set_token_inode_rdev(leaf, item, inode->i_rdev, &token);
3997 btrfs_set_token_inode_flags(leaf, item, BTRFS_I(inode)->flags, &token);
3998 btrfs_set_token_inode_block_group(leaf, item, 0, &token);
4002 * copy everything in the in-memory inode into the btree.
4004 static noinline int btrfs_update_inode_item(struct btrfs_trans_handle *trans,
4005 struct btrfs_root *root, struct inode *inode)
4007 struct btrfs_inode_item *inode_item;
4008 struct btrfs_path *path;
4009 struct extent_buffer *leaf;
4012 path = btrfs_alloc_path();
4016 path->leave_spinning = 1;
4017 ret = btrfs_lookup_inode(trans, root, path, &BTRFS_I(inode)->location,
4025 leaf = path->nodes[0];
4026 inode_item = btrfs_item_ptr(leaf, path->slots[0],
4027 struct btrfs_inode_item);
4029 fill_inode_item(trans, leaf, inode_item, inode);
4030 btrfs_mark_buffer_dirty(leaf);
4031 btrfs_set_inode_last_trans(trans, inode);
4034 btrfs_free_path(path);
4039 * copy everything in the in-memory inode into the btree.
4041 noinline int btrfs_update_inode(struct btrfs_trans_handle *trans,
4042 struct btrfs_root *root, struct inode *inode)
4044 struct btrfs_fs_info *fs_info = root->fs_info;
4048 * If the inode is a free space inode, we can deadlock during commit
4049 * if we put it into the delayed code.
4051 * The data relocation inode should also be directly updated
4054 if (!btrfs_is_free_space_inode(BTRFS_I(inode))
4055 && root->root_key.objectid != BTRFS_DATA_RELOC_TREE_OBJECTID
4056 && !test_bit(BTRFS_FS_LOG_RECOVERING, &fs_info->flags)) {
4057 btrfs_update_root_times(trans, root);
4059 ret = btrfs_delayed_update_inode(trans, root, inode);
4061 btrfs_set_inode_last_trans(trans, inode);
4065 return btrfs_update_inode_item(trans, root, inode);
4068 noinline int btrfs_update_inode_fallback(struct btrfs_trans_handle *trans,
4069 struct btrfs_root *root,
4070 struct inode *inode)
4074 ret = btrfs_update_inode(trans, root, inode);
4076 return btrfs_update_inode_item(trans, root, inode);
4081 * unlink helper that gets used here in inode.c and in the tree logging
4082 * recovery code. It remove a link in a directory with a given name, and
4083 * also drops the back refs in the inode to the directory
4085 static int __btrfs_unlink_inode(struct btrfs_trans_handle *trans,
4086 struct btrfs_root *root,
4087 struct btrfs_inode *dir,
4088 struct btrfs_inode *inode,
4089 const char *name, int name_len)
4091 struct btrfs_fs_info *fs_info = root->fs_info;
4092 struct btrfs_path *path;
4094 struct extent_buffer *leaf;
4095 struct btrfs_dir_item *di;
4096 struct btrfs_key key;
4098 u64 ino = btrfs_ino(inode);
4099 u64 dir_ino = btrfs_ino(dir);
4101 path = btrfs_alloc_path();
4107 path->leave_spinning = 1;
4108 di = btrfs_lookup_dir_item(trans, root, path, dir_ino,
4109 name, name_len, -1);
4118 leaf = path->nodes[0];
4119 btrfs_dir_item_key_to_cpu(leaf, di, &key);
4120 ret = btrfs_delete_one_dir_name(trans, root, path, di);
4123 btrfs_release_path(path);
4126 * If we don't have dir index, we have to get it by looking up
4127 * the inode ref, since we get the inode ref, remove it directly,
4128 * it is unnecessary to do delayed deletion.
4130 * But if we have dir index, needn't search inode ref to get it.
4131 * Since the inode ref is close to the inode item, it is better
4132 * that we delay to delete it, and just do this deletion when
4133 * we update the inode item.
4135 if (inode->dir_index) {
4136 ret = btrfs_delayed_delete_inode_ref(inode);
4138 index = inode->dir_index;
4143 ret = btrfs_del_inode_ref(trans, root, name, name_len, ino,
4147 "failed to delete reference to %.*s, inode %llu parent %llu",
4148 name_len, name, ino, dir_ino);
4149 btrfs_abort_transaction(trans, ret);
4153 ret = btrfs_delete_delayed_dir_index(trans, fs_info, dir, index);
4155 btrfs_abort_transaction(trans, ret);
4159 ret = btrfs_del_inode_ref_in_log(trans, root, name, name_len, inode,
4161 if (ret != 0 && ret != -ENOENT) {
4162 btrfs_abort_transaction(trans, ret);
4166 ret = btrfs_del_dir_entries_in_log(trans, root, name, name_len, dir,
4171 btrfs_abort_transaction(trans, ret);
4173 btrfs_free_path(path);
4177 btrfs_i_size_write(dir, dir->vfs_inode.i_size - name_len * 2);
4178 inode_inc_iversion(&inode->vfs_inode);
4179 inode_inc_iversion(&dir->vfs_inode);
4180 inode->vfs_inode.i_ctime = dir->vfs_inode.i_mtime =
4181 dir->vfs_inode.i_ctime = current_time(&inode->vfs_inode);
4182 ret = btrfs_update_inode(trans, root, &dir->vfs_inode);
4187 int btrfs_unlink_inode(struct btrfs_trans_handle *trans,
4188 struct btrfs_root *root,
4189 struct btrfs_inode *dir, struct btrfs_inode *inode,
4190 const char *name, int name_len)
4193 ret = __btrfs_unlink_inode(trans, root, dir, inode, name, name_len);
4195 drop_nlink(&inode->vfs_inode);
4196 ret = btrfs_update_inode(trans, root, &inode->vfs_inode);
4202 * helper to start transaction for unlink and rmdir.
4204 * unlink and rmdir are special in btrfs, they do not always free space, so
4205 * if we cannot make our reservations the normal way try and see if there is
4206 * plenty of slack room in the global reserve to migrate, otherwise we cannot
4207 * allow the unlink to occur.
4209 static struct btrfs_trans_handle *__unlink_start_trans(struct inode *dir)
4211 struct btrfs_root *root = BTRFS_I(dir)->root;
4214 * 1 for the possible orphan item
4215 * 1 for the dir item
4216 * 1 for the dir index
4217 * 1 for the inode ref
4220 return btrfs_start_transaction_fallback_global_rsv(root, 5, 5);
4223 static int btrfs_unlink(struct inode *dir, struct dentry *dentry)
4225 struct btrfs_root *root = BTRFS_I(dir)->root;
4226 struct btrfs_trans_handle *trans;
4227 struct inode *inode = d_inode(dentry);
4230 trans = __unlink_start_trans(dir);
4232 return PTR_ERR(trans);
4234 btrfs_record_unlink_dir(trans, BTRFS_I(dir), BTRFS_I(d_inode(dentry)),
4237 ret = btrfs_unlink_inode(trans, root, BTRFS_I(dir),
4238 BTRFS_I(d_inode(dentry)), dentry->d_name.name,
4239 dentry->d_name.len);
4243 if (inode->i_nlink == 0) {
4244 ret = btrfs_orphan_add(trans, BTRFS_I(inode));
4250 btrfs_end_transaction(trans);
4251 btrfs_btree_balance_dirty(root->fs_info);
4255 int btrfs_unlink_subvol(struct btrfs_trans_handle *trans,
4256 struct btrfs_root *root,
4257 struct inode *dir, u64 objectid,
4258 const char *name, int name_len)
4260 struct btrfs_fs_info *fs_info = root->fs_info;
4261 struct btrfs_path *path;
4262 struct extent_buffer *leaf;
4263 struct btrfs_dir_item *di;
4264 struct btrfs_key key;
4267 u64 dir_ino = btrfs_ino(BTRFS_I(dir));
4269 path = btrfs_alloc_path();
4273 di = btrfs_lookup_dir_item(trans, root, path, dir_ino,
4274 name, name_len, -1);
4275 if (IS_ERR_OR_NULL(di)) {
4283 leaf = path->nodes[0];
4284 btrfs_dir_item_key_to_cpu(leaf, di, &key);
4285 WARN_ON(key.type != BTRFS_ROOT_ITEM_KEY || key.objectid != objectid);
4286 ret = btrfs_delete_one_dir_name(trans, root, path, di);
4288 btrfs_abort_transaction(trans, ret);
4291 btrfs_release_path(path);
4293 ret = btrfs_del_root_ref(trans, fs_info, objectid,
4294 root->root_key.objectid, dir_ino,
4295 &index, name, name_len);
4297 if (ret != -ENOENT) {
4298 btrfs_abort_transaction(trans, ret);
4301 di = btrfs_search_dir_index_item(root, path, dir_ino,
4303 if (IS_ERR_OR_NULL(di)) {
4308 btrfs_abort_transaction(trans, ret);
4312 leaf = path->nodes[0];
4313 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
4314 btrfs_release_path(path);
4317 btrfs_release_path(path);
4319 ret = btrfs_delete_delayed_dir_index(trans, fs_info, BTRFS_I(dir), index);
4321 btrfs_abort_transaction(trans, ret);
4325 btrfs_i_size_write(BTRFS_I(dir), dir->i_size - name_len * 2);
4326 inode_inc_iversion(dir);
4327 dir->i_mtime = dir->i_ctime = current_time(dir);
4328 ret = btrfs_update_inode_fallback(trans, root, dir);
4330 btrfs_abort_transaction(trans, ret);
4332 btrfs_free_path(path);
4336 static int btrfs_rmdir(struct inode *dir, struct dentry *dentry)
4338 struct inode *inode = d_inode(dentry);
4340 struct btrfs_root *root = BTRFS_I(dir)->root;
4341 struct btrfs_trans_handle *trans;
4342 u64 last_unlink_trans;
4344 if (inode->i_size > BTRFS_EMPTY_DIR_SIZE)
4346 if (btrfs_ino(BTRFS_I(inode)) == BTRFS_FIRST_FREE_OBJECTID)
4349 trans = __unlink_start_trans(dir);
4351 return PTR_ERR(trans);
4353 if (unlikely(btrfs_ino(BTRFS_I(inode)) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)) {
4354 err = btrfs_unlink_subvol(trans, root, dir,
4355 BTRFS_I(inode)->location.objectid,
4356 dentry->d_name.name,
4357 dentry->d_name.len);
4361 err = btrfs_orphan_add(trans, BTRFS_I(inode));
4365 last_unlink_trans = BTRFS_I(inode)->last_unlink_trans;
4367 /* now the directory is empty */
4368 err = btrfs_unlink_inode(trans, root, BTRFS_I(dir),
4369 BTRFS_I(d_inode(dentry)), dentry->d_name.name,
4370 dentry->d_name.len);
4372 btrfs_i_size_write(BTRFS_I(inode), 0);
4374 * Propagate the last_unlink_trans value of the deleted dir to
4375 * its parent directory. This is to prevent an unrecoverable
4376 * log tree in the case we do something like this:
4378 * 2) create snapshot under dir foo
4379 * 3) delete the snapshot
4382 * 6) fsync foo or some file inside foo
4384 if (last_unlink_trans >= trans->transid)
4385 BTRFS_I(dir)->last_unlink_trans = last_unlink_trans;
4388 btrfs_end_transaction(trans);
4389 btrfs_btree_balance_dirty(root->fs_info);
4394 static int truncate_space_check(struct btrfs_trans_handle *trans,
4395 struct btrfs_root *root,
4398 struct btrfs_fs_info *fs_info = root->fs_info;
4402 * This is only used to apply pressure to the enospc system, we don't
4403 * intend to use this reservation at all.
4405 bytes_deleted = btrfs_csum_bytes_to_leaves(fs_info, bytes_deleted);
4406 bytes_deleted *= fs_info->nodesize;
4407 ret = btrfs_block_rsv_add(root, &fs_info->trans_block_rsv,
4408 bytes_deleted, BTRFS_RESERVE_NO_FLUSH);
4410 trace_btrfs_space_reservation(fs_info, "transaction",
4413 trans->bytes_reserved += bytes_deleted;
4420 * Return this if we need to call truncate_block for the last bit of the
4423 #define NEED_TRUNCATE_BLOCK 1
4426 * this can truncate away extent items, csum items and directory items.
4427 * It starts at a high offset and removes keys until it can't find
4428 * any higher than new_size
4430 * csum items that cross the new i_size are truncated to the new size
4433 * min_type is the minimum key type to truncate down to. If set to 0, this
4434 * will kill all the items on this inode, including the INODE_ITEM_KEY.
4436 int btrfs_truncate_inode_items(struct btrfs_trans_handle *trans,
4437 struct btrfs_root *root,
4438 struct inode *inode,
4439 u64 new_size, u32 min_type)
4441 struct btrfs_fs_info *fs_info = root->fs_info;
4442 struct btrfs_path *path;
4443 struct extent_buffer *leaf;
4444 struct btrfs_file_extent_item *fi;
4445 struct btrfs_key key;
4446 struct btrfs_key found_key;
4447 u64 extent_start = 0;
4448 u64 extent_num_bytes = 0;
4449 u64 extent_offset = 0;
4451 u64 last_size = new_size;
4452 u32 found_type = (u8)-1;
4455 int pending_del_nr = 0;
4456 int pending_del_slot = 0;
4457 int extent_type = -1;
4460 u64 ino = btrfs_ino(BTRFS_I(inode));
4461 u64 bytes_deleted = 0;
4462 bool be_nice = false;
4463 bool should_throttle = false;
4464 bool should_end = false;
4466 BUG_ON(new_size > 0 && min_type != BTRFS_EXTENT_DATA_KEY);
4469 * for non-free space inodes and ref cows, we want to back off from
4472 if (!btrfs_is_free_space_inode(BTRFS_I(inode)) &&
4473 test_bit(BTRFS_ROOT_REF_COWS, &root->state))
4476 path = btrfs_alloc_path();
4479 path->reada = READA_BACK;
4482 * We want to drop from the next block forward in case this new size is
4483 * not block aligned since we will be keeping the last block of the
4484 * extent just the way it is.
4486 if (test_bit(BTRFS_ROOT_REF_COWS, &root->state) ||
4487 root == fs_info->tree_root)
4488 btrfs_drop_extent_cache(BTRFS_I(inode), ALIGN(new_size,
4489 fs_info->sectorsize),
4493 * This function is also used to drop the items in the log tree before
4494 * we relog the inode, so if root != BTRFS_I(inode)->root, it means
4495 * it is used to drop the loged items. So we shouldn't kill the delayed
4498 if (min_type == 0 && root == BTRFS_I(inode)->root)
4499 btrfs_kill_delayed_inode_items(BTRFS_I(inode));
4502 key.offset = (u64)-1;
4507 * with a 16K leaf size and 128MB extents, you can actually queue
4508 * up a huge file in a single leaf. Most of the time that
4509 * bytes_deleted is > 0, it will be huge by the time we get here
4511 if (be_nice && bytes_deleted > SZ_32M) {
4512 if (btrfs_should_end_transaction(trans)) {
4519 path->leave_spinning = 1;
4520 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
4527 /* there are no items in the tree for us to truncate, we're
4530 if (path->slots[0] == 0)
4537 leaf = path->nodes[0];
4538 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
4539 found_type = found_key.type;
4541 if (found_key.objectid != ino)
4544 if (found_type < min_type)
4547 item_end = found_key.offset;
4548 if (found_type == BTRFS_EXTENT_DATA_KEY) {
4549 fi = btrfs_item_ptr(leaf, path->slots[0],
4550 struct btrfs_file_extent_item);
4551 extent_type = btrfs_file_extent_type(leaf, fi);
4552 if (extent_type != BTRFS_FILE_EXTENT_INLINE) {
4554 btrfs_file_extent_num_bytes(leaf, fi);
4556 trace_btrfs_truncate_show_fi_regular(
4557 BTRFS_I(inode), leaf, fi,
4559 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
4560 item_end += btrfs_file_extent_inline_len(leaf,
4561 path->slots[0], fi);
4563 trace_btrfs_truncate_show_fi_inline(
4564 BTRFS_I(inode), leaf, fi, path->slots[0],
4569 if (found_type > min_type) {
4572 if (item_end < new_size)
4574 if (found_key.offset >= new_size)
4580 /* FIXME, shrink the extent if the ref count is only 1 */
4581 if (found_type != BTRFS_EXTENT_DATA_KEY)
4584 if (extent_type != BTRFS_FILE_EXTENT_INLINE) {
4586 extent_start = btrfs_file_extent_disk_bytenr(leaf, fi);
4588 u64 orig_num_bytes =
4589 btrfs_file_extent_num_bytes(leaf, fi);
4590 extent_num_bytes = ALIGN(new_size -
4592 fs_info->sectorsize);
4593 btrfs_set_file_extent_num_bytes(leaf, fi,
4595 num_dec = (orig_num_bytes -
4597 if (test_bit(BTRFS_ROOT_REF_COWS,
4600 inode_sub_bytes(inode, num_dec);
4601 btrfs_mark_buffer_dirty(leaf);
4604 btrfs_file_extent_disk_num_bytes(leaf,
4606 extent_offset = found_key.offset -
4607 btrfs_file_extent_offset(leaf, fi);
4609 /* FIXME blocksize != 4096 */
4610 num_dec = btrfs_file_extent_num_bytes(leaf, fi);
4611 if (extent_start != 0) {
4613 if (test_bit(BTRFS_ROOT_REF_COWS,
4615 inode_sub_bytes(inode, num_dec);
4618 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
4620 * we can't truncate inline items that have had
4624 btrfs_file_extent_encryption(leaf, fi) == 0 &&
4625 btrfs_file_extent_other_encoding(leaf, fi) == 0 &&
4626 btrfs_file_extent_compression(leaf, fi) == 0) {
4627 u32 size = (u32)(new_size - found_key.offset);
4629 btrfs_set_file_extent_ram_bytes(leaf, fi, size);
4630 size = btrfs_file_extent_calc_inline_size(size);
4631 btrfs_truncate_item(root->fs_info, path, size, 1);
4632 } else if (!del_item) {
4634 * We have to bail so the last_size is set to
4635 * just before this extent.
4637 err = NEED_TRUNCATE_BLOCK;
4641 if (test_bit(BTRFS_ROOT_REF_COWS, &root->state))
4642 inode_sub_bytes(inode, item_end + 1 - new_size);
4646 last_size = found_key.offset;
4648 last_size = new_size;
4650 if (!pending_del_nr) {
4651 /* no pending yet, add ourselves */
4652 pending_del_slot = path->slots[0];
4654 } else if (pending_del_nr &&
4655 path->slots[0] + 1 == pending_del_slot) {
4656 /* hop on the pending chunk */
4658 pending_del_slot = path->slots[0];
4665 should_throttle = false;
4668 (test_bit(BTRFS_ROOT_REF_COWS, &root->state) ||
4669 root == fs_info->tree_root)) {
4670 btrfs_set_path_blocking(path);
4671 bytes_deleted += extent_num_bytes;
4672 ret = btrfs_free_extent(trans, root, extent_start,
4673 extent_num_bytes, 0,
4674 btrfs_header_owner(leaf),
4675 ino, extent_offset);
4677 if (btrfs_should_throttle_delayed_refs(trans, fs_info))
4678 btrfs_async_run_delayed_refs(fs_info,
4679 trans->delayed_ref_updates * 2,
4682 if (truncate_space_check(trans, root,
4683 extent_num_bytes)) {
4686 if (btrfs_should_throttle_delayed_refs(trans,
4688 should_throttle = true;
4692 if (found_type == BTRFS_INODE_ITEM_KEY)
4695 if (path->slots[0] == 0 ||
4696 path->slots[0] != pending_del_slot ||
4697 should_throttle || should_end) {
4698 if (pending_del_nr) {
4699 ret = btrfs_del_items(trans, root, path,
4703 btrfs_abort_transaction(trans, ret);
4708 btrfs_release_path(path);
4709 if (should_throttle) {
4710 unsigned long updates = trans->delayed_ref_updates;
4712 trans->delayed_ref_updates = 0;
4713 ret = btrfs_run_delayed_refs(trans,
4721 * if we failed to refill our space rsv, bail out
4722 * and let the transaction restart
4734 if (pending_del_nr) {
4735 ret = btrfs_del_items(trans, root, path, pending_del_slot,
4738 btrfs_abort_transaction(trans, ret);
4741 if (root->root_key.objectid != BTRFS_TREE_LOG_OBJECTID) {
4742 ASSERT(last_size >= new_size);
4743 if (!err && last_size > new_size)
4744 last_size = new_size;
4745 btrfs_ordered_update_i_size(inode, last_size, NULL);
4748 btrfs_free_path(path);
4750 if (be_nice && bytes_deleted > SZ_32M) {
4751 unsigned long updates = trans->delayed_ref_updates;
4753 trans->delayed_ref_updates = 0;
4754 ret = btrfs_run_delayed_refs(trans, fs_info,
4764 * btrfs_truncate_block - read, zero a chunk and write a block
4765 * @inode - inode that we're zeroing
4766 * @from - the offset to start zeroing
4767 * @len - the length to zero, 0 to zero the entire range respective to the
4769 * @front - zero up to the offset instead of from the offset on
4771 * This will find the block for the "from" offset and cow the block and zero the
4772 * part we want to zero. This is used with truncate and hole punching.
4774 int btrfs_truncate_block(struct inode *inode, loff_t from, loff_t len,
4777 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
4778 struct address_space *mapping = inode->i_mapping;
4779 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
4780 struct btrfs_ordered_extent *ordered;
4781 struct extent_state *cached_state = NULL;
4782 struct extent_changeset *data_reserved = NULL;
4784 u32 blocksize = fs_info->sectorsize;
4785 pgoff_t index = from >> PAGE_SHIFT;
4786 unsigned offset = from & (blocksize - 1);
4788 gfp_t mask = btrfs_alloc_write_mask(mapping);
4793 if (IS_ALIGNED(offset, blocksize) &&
4794 (!len || IS_ALIGNED(len, blocksize)))
4797 block_start = round_down(from, blocksize);
4798 block_end = block_start + blocksize - 1;
4800 ret = btrfs_delalloc_reserve_space(inode, &data_reserved,
4801 block_start, blocksize);
4806 page = find_or_create_page(mapping, index, mask);
4808 btrfs_delalloc_release_space(inode, data_reserved,
4809 block_start, blocksize);
4810 btrfs_delalloc_release_extents(BTRFS_I(inode), blocksize);
4815 if (!PageUptodate(page)) {
4816 ret = btrfs_readpage(NULL, page);
4818 if (page->mapping != mapping) {
4823 if (!PageUptodate(page)) {
4828 wait_on_page_writeback(page);
4830 lock_extent_bits(io_tree, block_start, block_end, &cached_state);
4831 set_page_extent_mapped(page);
4833 ordered = btrfs_lookup_ordered_extent(inode, block_start);
4835 unlock_extent_cached(io_tree, block_start, block_end,
4839 btrfs_start_ordered_extent(inode, ordered, 1);
4840 btrfs_put_ordered_extent(ordered);
4844 clear_extent_bit(&BTRFS_I(inode)->io_tree, block_start, block_end,
4845 EXTENT_DIRTY | EXTENT_DELALLOC |
4846 EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG,
4847 0, 0, &cached_state);
4849 ret = btrfs_set_extent_delalloc(inode, block_start, block_end, 0,
4852 unlock_extent_cached(io_tree, block_start, block_end,
4857 if (offset != blocksize) {
4859 len = blocksize - offset;
4862 memset(kaddr + (block_start - page_offset(page)),
4865 memset(kaddr + (block_start - page_offset(page)) + offset,
4867 flush_dcache_page(page);
4870 ClearPageChecked(page);
4871 set_page_dirty(page);
4872 unlock_extent_cached(io_tree, block_start, block_end, &cached_state);
4876 btrfs_delalloc_release_space(inode, data_reserved, block_start,
4878 btrfs_delalloc_release_extents(BTRFS_I(inode), blocksize);
4882 extent_changeset_free(data_reserved);
4886 static int maybe_insert_hole(struct btrfs_root *root, struct inode *inode,
4887 u64 offset, u64 len)
4889 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
4890 struct btrfs_trans_handle *trans;
4894 * Still need to make sure the inode looks like it's been updated so
4895 * that any holes get logged if we fsync.
4897 if (btrfs_fs_incompat(fs_info, NO_HOLES)) {
4898 BTRFS_I(inode)->last_trans = fs_info->generation;
4899 BTRFS_I(inode)->last_sub_trans = root->log_transid;
4900 BTRFS_I(inode)->last_log_commit = root->last_log_commit;
4905 * 1 - for the one we're dropping
4906 * 1 - for the one we're adding
4907 * 1 - for updating the inode.
4909 trans = btrfs_start_transaction(root, 3);
4911 return PTR_ERR(trans);
4913 ret = btrfs_drop_extents(trans, root, inode, offset, offset + len, 1);
4915 btrfs_abort_transaction(trans, ret);
4916 btrfs_end_transaction(trans);
4920 ret = btrfs_insert_file_extent(trans, root, btrfs_ino(BTRFS_I(inode)),
4921 offset, 0, 0, len, 0, len, 0, 0, 0);
4923 btrfs_abort_transaction(trans, ret);
4925 btrfs_update_inode(trans, root, inode);
4926 btrfs_end_transaction(trans);
4931 * This function puts in dummy file extents for the area we're creating a hole
4932 * for. So if we are truncating this file to a larger size we need to insert
4933 * these file extents so that btrfs_get_extent will return a EXTENT_MAP_HOLE for
4934 * the range between oldsize and size
4936 int btrfs_cont_expand(struct inode *inode, loff_t oldsize, loff_t size)
4938 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
4939 struct btrfs_root *root = BTRFS_I(inode)->root;
4940 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
4941 struct extent_map *em = NULL;
4942 struct extent_state *cached_state = NULL;
4943 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
4944 u64 hole_start = ALIGN(oldsize, fs_info->sectorsize);
4945 u64 block_end = ALIGN(size, fs_info->sectorsize);
4952 * If our size started in the middle of a block we need to zero out the
4953 * rest of the block before we expand the i_size, otherwise we could
4954 * expose stale data.
4956 err = btrfs_truncate_block(inode, oldsize, 0, 0);
4960 if (size <= hole_start)
4964 struct btrfs_ordered_extent *ordered;
4966 lock_extent_bits(io_tree, hole_start, block_end - 1,
4968 ordered = btrfs_lookup_ordered_range(BTRFS_I(inode), hole_start,
4969 block_end - hole_start);
4972 unlock_extent_cached(io_tree, hole_start, block_end - 1,
4974 btrfs_start_ordered_extent(inode, ordered, 1);
4975 btrfs_put_ordered_extent(ordered);
4978 cur_offset = hole_start;
4980 em = btrfs_get_extent(BTRFS_I(inode), NULL, 0, cur_offset,
4981 block_end - cur_offset, 0);
4987 last_byte = min(extent_map_end(em), block_end);
4988 last_byte = ALIGN(last_byte, fs_info->sectorsize);
4989 if (!test_bit(EXTENT_FLAG_PREALLOC, &em->flags)) {
4990 struct extent_map *hole_em;
4991 hole_size = last_byte - cur_offset;
4993 err = maybe_insert_hole(root, inode, cur_offset,
4997 btrfs_drop_extent_cache(BTRFS_I(inode), cur_offset,
4998 cur_offset + hole_size - 1, 0);
4999 hole_em = alloc_extent_map();
5001 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
5002 &BTRFS_I(inode)->runtime_flags);
5005 hole_em->start = cur_offset;
5006 hole_em->len = hole_size;
5007 hole_em->orig_start = cur_offset;
5009 hole_em->block_start = EXTENT_MAP_HOLE;
5010 hole_em->block_len = 0;
5011 hole_em->orig_block_len = 0;
5012 hole_em->ram_bytes = hole_size;
5013 hole_em->bdev = fs_info->fs_devices->latest_bdev;
5014 hole_em->compress_type = BTRFS_COMPRESS_NONE;
5015 hole_em->generation = fs_info->generation;
5018 write_lock(&em_tree->lock);
5019 err = add_extent_mapping(em_tree, hole_em, 1);
5020 write_unlock(&em_tree->lock);
5023 btrfs_drop_extent_cache(BTRFS_I(inode),
5028 free_extent_map(hole_em);
5031 free_extent_map(em);
5033 cur_offset = last_byte;
5034 if (cur_offset >= block_end)
5037 free_extent_map(em);
5038 unlock_extent_cached(io_tree, hole_start, block_end - 1, &cached_state);
5042 static int btrfs_setsize(struct inode *inode, struct iattr *attr)
5044 struct btrfs_root *root = BTRFS_I(inode)->root;
5045 struct btrfs_trans_handle *trans;
5046 loff_t oldsize = i_size_read(inode);
5047 loff_t newsize = attr->ia_size;
5048 int mask = attr->ia_valid;
5052 * The regular truncate() case without ATTR_CTIME and ATTR_MTIME is a
5053 * special case where we need to update the times despite not having
5054 * these flags set. For all other operations the VFS set these flags
5055 * explicitly if it wants a timestamp update.
5057 if (newsize != oldsize) {
5058 inode_inc_iversion(inode);
5059 if (!(mask & (ATTR_CTIME | ATTR_MTIME)))
5060 inode->i_ctime = inode->i_mtime =
5061 current_time(inode);
5064 if (newsize > oldsize) {
5066 * Don't do an expanding truncate while snapshotting is ongoing.
5067 * This is to ensure the snapshot captures a fully consistent
5068 * state of this file - if the snapshot captures this expanding
5069 * truncation, it must capture all writes that happened before
5072 btrfs_wait_for_snapshot_creation(root);
5073 ret = btrfs_cont_expand(inode, oldsize, newsize);
5075 btrfs_end_write_no_snapshotting(root);
5079 trans = btrfs_start_transaction(root, 1);
5080 if (IS_ERR(trans)) {
5081 btrfs_end_write_no_snapshotting(root);
5082 return PTR_ERR(trans);
5085 i_size_write(inode, newsize);
5086 btrfs_ordered_update_i_size(inode, i_size_read(inode), NULL);
5087 pagecache_isize_extended(inode, oldsize, newsize);
5088 ret = btrfs_update_inode(trans, root, inode);
5089 btrfs_end_write_no_snapshotting(root);
5090 btrfs_end_transaction(trans);
5094 * We're truncating a file that used to have good data down to
5095 * zero. Make sure it gets into the ordered flush list so that
5096 * any new writes get down to disk quickly.
5099 set_bit(BTRFS_INODE_ORDERED_DATA_CLOSE,
5100 &BTRFS_I(inode)->runtime_flags);
5103 * 1 for the orphan item we're going to add
5104 * 1 for the orphan item deletion.
5106 trans = btrfs_start_transaction(root, 2);
5108 return PTR_ERR(trans);
5111 * We need to do this in case we fail at _any_ point during the
5112 * actual truncate. Once we do the truncate_setsize we could
5113 * invalidate pages which forces any outstanding ordered io to
5114 * be instantly completed which will give us extents that need
5115 * to be truncated. If we fail to get an orphan inode down we
5116 * could have left over extents that were never meant to live,
5117 * so we need to guarantee from this point on that everything
5118 * will be consistent.
5120 ret = btrfs_orphan_add(trans, BTRFS_I(inode));
5121 btrfs_end_transaction(trans);
5125 /* we don't support swapfiles, so vmtruncate shouldn't fail */
5126 truncate_setsize(inode, newsize);
5128 /* Disable nonlocked read DIO to avoid the end less truncate */
5129 btrfs_inode_block_unlocked_dio(BTRFS_I(inode));
5130 inode_dio_wait(inode);
5131 btrfs_inode_resume_unlocked_dio(BTRFS_I(inode));
5133 ret = btrfs_truncate(inode);
5134 if (ret && inode->i_nlink) {
5137 /* To get a stable disk_i_size */
5138 err = btrfs_wait_ordered_range(inode, 0, (u64)-1);
5140 btrfs_orphan_del(NULL, BTRFS_I(inode));
5145 * failed to truncate, disk_i_size is only adjusted down
5146 * as we remove extents, so it should represent the true
5147 * size of the inode, so reset the in memory size and
5148 * delete our orphan entry.
5150 trans = btrfs_join_transaction(root);
5151 if (IS_ERR(trans)) {
5152 btrfs_orphan_del(NULL, BTRFS_I(inode));
5155 i_size_write(inode, BTRFS_I(inode)->disk_i_size);
5156 err = btrfs_orphan_del(trans, BTRFS_I(inode));
5158 btrfs_abort_transaction(trans, err);
5159 btrfs_end_transaction(trans);
5166 static int btrfs_setattr(struct dentry *dentry, struct iattr *attr)
5168 struct inode *inode = d_inode(dentry);
5169 struct btrfs_root *root = BTRFS_I(inode)->root;
5172 if (btrfs_root_readonly(root))
5175 err = setattr_prepare(dentry, attr);
5179 if (S_ISREG(inode->i_mode) && (attr->ia_valid & ATTR_SIZE)) {
5180 err = btrfs_setsize(inode, attr);
5185 if (attr->ia_valid) {
5186 setattr_copy(inode, attr);
5187 inode_inc_iversion(inode);
5188 err = btrfs_dirty_inode(inode);
5190 if (!err && attr->ia_valid & ATTR_MODE)
5191 err = posix_acl_chmod(inode, inode->i_mode);
5198 * While truncating the inode pages during eviction, we get the VFS calling
5199 * btrfs_invalidatepage() against each page of the inode. This is slow because
5200 * the calls to btrfs_invalidatepage() result in a huge amount of calls to
5201 * lock_extent_bits() and clear_extent_bit(), which keep merging and splitting
5202 * extent_state structures over and over, wasting lots of time.
5204 * Therefore if the inode is being evicted, let btrfs_invalidatepage() skip all
5205 * those expensive operations on a per page basis and do only the ordered io
5206 * finishing, while we release here the extent_map and extent_state structures,
5207 * without the excessive merging and splitting.
5209 static void evict_inode_truncate_pages(struct inode *inode)
5211 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
5212 struct extent_map_tree *map_tree = &BTRFS_I(inode)->extent_tree;
5213 struct rb_node *node;
5215 ASSERT(inode->i_state & I_FREEING);
5216 truncate_inode_pages_final(&inode->i_data);
5218 write_lock(&map_tree->lock);
5219 while (!RB_EMPTY_ROOT(&map_tree->map)) {
5220 struct extent_map *em;
5222 node = rb_first(&map_tree->map);
5223 em = rb_entry(node, struct extent_map, rb_node);
5224 clear_bit(EXTENT_FLAG_PINNED, &em->flags);
5225 clear_bit(EXTENT_FLAG_LOGGING, &em->flags);
5226 remove_extent_mapping(map_tree, em);
5227 free_extent_map(em);
5228 if (need_resched()) {
5229 write_unlock(&map_tree->lock);
5231 write_lock(&map_tree->lock);
5234 write_unlock(&map_tree->lock);
5237 * Keep looping until we have no more ranges in the io tree.
5238 * We can have ongoing bios started by readpages (called from readahead)
5239 * that have their endio callback (extent_io.c:end_bio_extent_readpage)
5240 * still in progress (unlocked the pages in the bio but did not yet
5241 * unlocked the ranges in the io tree). Therefore this means some
5242 * ranges can still be locked and eviction started because before
5243 * submitting those bios, which are executed by a separate task (work
5244 * queue kthread), inode references (inode->i_count) were not taken
5245 * (which would be dropped in the end io callback of each bio).
5246 * Therefore here we effectively end up waiting for those bios and
5247 * anyone else holding locked ranges without having bumped the inode's
5248 * reference count - if we don't do it, when they access the inode's
5249 * io_tree to unlock a range it may be too late, leading to an
5250 * use-after-free issue.
5252 spin_lock(&io_tree->lock);
5253 while (!RB_EMPTY_ROOT(&io_tree->state)) {
5254 struct extent_state *state;
5255 struct extent_state *cached_state = NULL;
5259 node = rb_first(&io_tree->state);
5260 state = rb_entry(node, struct extent_state, rb_node);
5261 start = state->start;
5263 spin_unlock(&io_tree->lock);
5265 lock_extent_bits(io_tree, start, end, &cached_state);
5268 * If still has DELALLOC flag, the extent didn't reach disk,
5269 * and its reserved space won't be freed by delayed_ref.
5270 * So we need to free its reserved space here.
5271 * (Refer to comment in btrfs_invalidatepage, case 2)
5273 * Note, end is the bytenr of last byte, so we need + 1 here.
5275 if (state->state & EXTENT_DELALLOC)
5276 btrfs_qgroup_free_data(inode, NULL, start, end - start + 1);
5278 clear_extent_bit(io_tree, start, end,
5279 EXTENT_LOCKED | EXTENT_DIRTY |
5280 EXTENT_DELALLOC | EXTENT_DO_ACCOUNTING |
5281 EXTENT_DEFRAG, 1, 1, &cached_state);
5284 spin_lock(&io_tree->lock);
5286 spin_unlock(&io_tree->lock);
5289 void btrfs_evict_inode(struct inode *inode)
5291 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
5292 struct btrfs_trans_handle *trans;
5293 struct btrfs_root *root = BTRFS_I(inode)->root;
5294 struct btrfs_block_rsv *rsv, *global_rsv;
5295 int steal_from_global = 0;
5299 trace_btrfs_inode_evict(inode);
5306 min_size = btrfs_calc_trunc_metadata_size(fs_info, 1);
5308 evict_inode_truncate_pages(inode);
5310 if (inode->i_nlink &&
5311 ((btrfs_root_refs(&root->root_item) != 0 &&
5312 root->root_key.objectid != BTRFS_ROOT_TREE_OBJECTID) ||
5313 btrfs_is_free_space_inode(BTRFS_I(inode))))
5316 if (is_bad_inode(inode)) {
5317 btrfs_orphan_del(NULL, BTRFS_I(inode));
5320 /* do we really want it for ->i_nlink > 0 and zero btrfs_root_refs? */
5321 if (!special_file(inode->i_mode))
5322 btrfs_wait_ordered_range(inode, 0, (u64)-1);
5324 btrfs_free_io_failure_record(BTRFS_I(inode), 0, (u64)-1);
5326 if (test_bit(BTRFS_FS_LOG_RECOVERING, &fs_info->flags)) {
5327 BUG_ON(test_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
5328 &BTRFS_I(inode)->runtime_flags));
5332 if (inode->i_nlink > 0) {
5333 BUG_ON(btrfs_root_refs(&root->root_item) != 0 &&
5334 root->root_key.objectid != BTRFS_ROOT_TREE_OBJECTID);
5338 ret = btrfs_commit_inode_delayed_inode(BTRFS_I(inode));
5340 btrfs_orphan_del(NULL, BTRFS_I(inode));
5344 rsv = btrfs_alloc_block_rsv(fs_info, BTRFS_BLOCK_RSV_TEMP);
5346 btrfs_orphan_del(NULL, BTRFS_I(inode));
5349 rsv->size = min_size;
5351 global_rsv = &fs_info->global_block_rsv;
5353 btrfs_i_size_write(BTRFS_I(inode), 0);
5356 * This is a bit simpler than btrfs_truncate since we've already
5357 * reserved our space for our orphan item in the unlink, so we just
5358 * need to reserve some slack space in case we add bytes and update
5359 * inode item when doing the truncate.
5362 ret = btrfs_block_rsv_refill(root, rsv, min_size,
5363 BTRFS_RESERVE_FLUSH_LIMIT);
5366 * Try and steal from the global reserve since we will
5367 * likely not use this space anyway, we want to try as
5368 * hard as possible to get this to work.
5371 steal_from_global++;
5373 steal_from_global = 0;
5377 * steal_from_global == 0: we reserved stuff, hooray!
5378 * steal_from_global == 1: we didn't reserve stuff, boo!
5379 * steal_from_global == 2: we've committed, still not a lot of
5380 * room but maybe we'll have room in the global reserve this
5382 * steal_from_global == 3: abandon all hope!
5384 if (steal_from_global > 2) {
5386 "Could not get space for a delete, will truncate on mount %d",
5388 btrfs_orphan_del(NULL, BTRFS_I(inode));
5389 btrfs_free_block_rsv(fs_info, rsv);
5393 trans = btrfs_join_transaction(root);
5394 if (IS_ERR(trans)) {
5395 btrfs_orphan_del(NULL, BTRFS_I(inode));
5396 btrfs_free_block_rsv(fs_info, rsv);
5401 * We can't just steal from the global reserve, we need to make
5402 * sure there is room to do it, if not we need to commit and try
5405 if (steal_from_global) {
5406 if (!btrfs_check_space_for_delayed_refs(trans, fs_info))
5407 ret = btrfs_block_rsv_migrate(global_rsv, rsv,
5414 * Couldn't steal from the global reserve, we have too much
5415 * pending stuff built up, commit the transaction and try it
5419 ret = btrfs_commit_transaction(trans);
5421 btrfs_orphan_del(NULL, BTRFS_I(inode));
5422 btrfs_free_block_rsv(fs_info, rsv);
5427 steal_from_global = 0;
5430 trans->block_rsv = rsv;
5432 ret = btrfs_truncate_inode_items(trans, root, inode, 0, 0);
5433 if (ret != -ENOSPC && ret != -EAGAIN)
5436 trans->block_rsv = &fs_info->trans_block_rsv;
5437 btrfs_end_transaction(trans);
5439 btrfs_btree_balance_dirty(fs_info);
5442 btrfs_free_block_rsv(fs_info, rsv);
5445 * Errors here aren't a big deal, it just means we leave orphan items
5446 * in the tree. They will be cleaned up on the next mount.
5449 trans->block_rsv = root->orphan_block_rsv;
5450 btrfs_orphan_del(trans, BTRFS_I(inode));
5452 btrfs_orphan_del(NULL, BTRFS_I(inode));
5455 trans->block_rsv = &fs_info->trans_block_rsv;
5456 if (!(root == fs_info->tree_root ||
5457 root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID))
5458 btrfs_return_ino(root, btrfs_ino(BTRFS_I(inode)));
5460 btrfs_end_transaction(trans);
5461 btrfs_btree_balance_dirty(fs_info);
5463 btrfs_remove_delayed_node(BTRFS_I(inode));
5468 * this returns the key found in the dir entry in the location pointer.
5469 * If no dir entries were found, location->objectid is 0.
5471 static int btrfs_inode_by_name(struct inode *dir, struct dentry *dentry,
5472 struct btrfs_key *location)
5474 const char *name = dentry->d_name.name;
5475 int namelen = dentry->d_name.len;
5476 struct btrfs_dir_item *di;
5477 struct btrfs_path *path;
5478 struct btrfs_root *root = BTRFS_I(dir)->root;
5481 path = btrfs_alloc_path();
5485 di = btrfs_lookup_dir_item(NULL, root, path, btrfs_ino(BTRFS_I(dir)),
5490 if (IS_ERR_OR_NULL(di))
5493 btrfs_dir_item_key_to_cpu(path->nodes[0], di, location);
5494 if (location->type != BTRFS_INODE_ITEM_KEY &&
5495 location->type != BTRFS_ROOT_ITEM_KEY) {
5496 btrfs_warn(root->fs_info,
5497 "%s gets something invalid in DIR_ITEM (name %s, directory ino %llu, location(%llu %u %llu))",
5498 __func__, name, btrfs_ino(BTRFS_I(dir)),
5499 location->objectid, location->type, location->offset);
5503 btrfs_free_path(path);
5506 location->objectid = 0;
5511 * when we hit a tree root in a directory, the btrfs part of the inode
5512 * needs to be changed to reflect the root directory of the tree root. This
5513 * is kind of like crossing a mount point.
5515 static int fixup_tree_root_location(struct btrfs_fs_info *fs_info,
5517 struct dentry *dentry,
5518 struct btrfs_key *location,
5519 struct btrfs_root **sub_root)
5521 struct btrfs_path *path;
5522 struct btrfs_root *new_root;
5523 struct btrfs_root_ref *ref;
5524 struct extent_buffer *leaf;
5525 struct btrfs_key key;
5529 path = btrfs_alloc_path();
5536 key.objectid = BTRFS_I(dir)->root->root_key.objectid;
5537 key.type = BTRFS_ROOT_REF_KEY;
5538 key.offset = location->objectid;
5540 ret = btrfs_search_slot(NULL, fs_info->tree_root, &key, path, 0, 0);
5547 leaf = path->nodes[0];
5548 ref = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_root_ref);
5549 if (btrfs_root_ref_dirid(leaf, ref) != btrfs_ino(BTRFS_I(dir)) ||
5550 btrfs_root_ref_name_len(leaf, ref) != dentry->d_name.len)
5553 ret = memcmp_extent_buffer(leaf, dentry->d_name.name,
5554 (unsigned long)(ref + 1),
5555 dentry->d_name.len);
5559 btrfs_release_path(path);
5561 new_root = btrfs_read_fs_root_no_name(fs_info, location);
5562 if (IS_ERR(new_root)) {
5563 err = PTR_ERR(new_root);
5567 *sub_root = new_root;
5568 location->objectid = btrfs_root_dirid(&new_root->root_item);
5569 location->type = BTRFS_INODE_ITEM_KEY;
5570 location->offset = 0;
5573 btrfs_free_path(path);
5577 static void inode_tree_add(struct inode *inode)
5579 struct btrfs_root *root = BTRFS_I(inode)->root;
5580 struct btrfs_inode *entry;
5582 struct rb_node *parent;
5583 struct rb_node *new = &BTRFS_I(inode)->rb_node;
5584 u64 ino = btrfs_ino(BTRFS_I(inode));
5586 if (inode_unhashed(inode))
5589 spin_lock(&root->inode_lock);
5590 p = &root->inode_tree.rb_node;
5593 entry = rb_entry(parent, struct btrfs_inode, rb_node);
5595 if (ino < btrfs_ino(BTRFS_I(&entry->vfs_inode)))
5596 p = &parent->rb_left;
5597 else if (ino > btrfs_ino(BTRFS_I(&entry->vfs_inode)))
5598 p = &parent->rb_right;
5600 WARN_ON(!(entry->vfs_inode.i_state &
5601 (I_WILL_FREE | I_FREEING)));
5602 rb_replace_node(parent, new, &root->inode_tree);
5603 RB_CLEAR_NODE(parent);
5604 spin_unlock(&root->inode_lock);
5608 rb_link_node(new, parent, p);
5609 rb_insert_color(new, &root->inode_tree);
5610 spin_unlock(&root->inode_lock);
5613 static void inode_tree_del(struct inode *inode)
5615 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
5616 struct btrfs_root *root = BTRFS_I(inode)->root;
5619 spin_lock(&root->inode_lock);
5620 if (!RB_EMPTY_NODE(&BTRFS_I(inode)->rb_node)) {
5621 rb_erase(&BTRFS_I(inode)->rb_node, &root->inode_tree);
5622 RB_CLEAR_NODE(&BTRFS_I(inode)->rb_node);
5623 empty = RB_EMPTY_ROOT(&root->inode_tree);
5625 spin_unlock(&root->inode_lock);
5627 if (empty && btrfs_root_refs(&root->root_item) == 0) {
5628 synchronize_srcu(&fs_info->subvol_srcu);
5629 spin_lock(&root->inode_lock);
5630 empty = RB_EMPTY_ROOT(&root->inode_tree);
5631 spin_unlock(&root->inode_lock);
5633 btrfs_add_dead_root(root);
5637 void btrfs_invalidate_inodes(struct btrfs_root *root)
5639 struct btrfs_fs_info *fs_info = root->fs_info;
5640 struct rb_node *node;
5641 struct rb_node *prev;
5642 struct btrfs_inode *entry;
5643 struct inode *inode;
5646 if (!test_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state))
5647 WARN_ON(btrfs_root_refs(&root->root_item) != 0);
5649 spin_lock(&root->inode_lock);
5651 node = root->inode_tree.rb_node;
5655 entry = rb_entry(node, struct btrfs_inode, rb_node);
5657 if (objectid < btrfs_ino(BTRFS_I(&entry->vfs_inode)))
5658 node = node->rb_left;
5659 else if (objectid > btrfs_ino(BTRFS_I(&entry->vfs_inode)))
5660 node = node->rb_right;
5666 entry = rb_entry(prev, struct btrfs_inode, rb_node);
5667 if (objectid <= btrfs_ino(BTRFS_I(&entry->vfs_inode))) {
5671 prev = rb_next(prev);
5675 entry = rb_entry(node, struct btrfs_inode, rb_node);
5676 objectid = btrfs_ino(BTRFS_I(&entry->vfs_inode)) + 1;
5677 inode = igrab(&entry->vfs_inode);
5679 spin_unlock(&root->inode_lock);
5680 if (atomic_read(&inode->i_count) > 1)
5681 d_prune_aliases(inode);
5683 * btrfs_drop_inode will have it removed from
5684 * the inode cache when its usage count
5689 spin_lock(&root->inode_lock);
5693 if (cond_resched_lock(&root->inode_lock))
5696 node = rb_next(node);
5698 spin_unlock(&root->inode_lock);
5701 static int btrfs_init_locked_inode(struct inode *inode, void *p)
5703 struct btrfs_iget_args *args = p;
5704 inode->i_ino = args->location->objectid;
5705 memcpy(&BTRFS_I(inode)->location, args->location,
5706 sizeof(*args->location));
5707 BTRFS_I(inode)->root = args->root;
5711 static int btrfs_find_actor(struct inode *inode, void *opaque)
5713 struct btrfs_iget_args *args = opaque;
5714 return args->location->objectid == BTRFS_I(inode)->location.objectid &&
5715 args->root == BTRFS_I(inode)->root;
5718 static struct inode *btrfs_iget_locked(struct super_block *s,
5719 struct btrfs_key *location,
5720 struct btrfs_root *root)
5722 struct inode *inode;
5723 struct btrfs_iget_args args;
5724 unsigned long hashval = btrfs_inode_hash(location->objectid, root);
5726 args.location = location;
5729 inode = iget5_locked(s, hashval, btrfs_find_actor,
5730 btrfs_init_locked_inode,
5735 /* Get an inode object given its location and corresponding root.
5736 * Returns in *is_new if the inode was read from disk
5738 struct inode *btrfs_iget(struct super_block *s, struct btrfs_key *location,
5739 struct btrfs_root *root, int *new)
5741 struct inode *inode;
5743 inode = btrfs_iget_locked(s, location, root);
5745 return ERR_PTR(-ENOMEM);
5747 if (inode->i_state & I_NEW) {
5750 ret = btrfs_read_locked_inode(inode);
5751 if (!is_bad_inode(inode)) {
5752 inode_tree_add(inode);
5753 unlock_new_inode(inode);
5757 unlock_new_inode(inode);
5760 inode = ERR_PTR(ret < 0 ? ret : -ESTALE);
5767 static struct inode *new_simple_dir(struct super_block *s,
5768 struct btrfs_key *key,
5769 struct btrfs_root *root)
5771 struct inode *inode = new_inode(s);
5774 return ERR_PTR(-ENOMEM);
5776 BTRFS_I(inode)->root = root;
5777 memcpy(&BTRFS_I(inode)->location, key, sizeof(*key));
5778 set_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags);
5780 inode->i_ino = BTRFS_EMPTY_SUBVOL_DIR_OBJECTID;
5781 inode->i_op = &btrfs_dir_ro_inode_operations;
5782 inode->i_opflags &= ~IOP_XATTR;
5783 inode->i_fop = &simple_dir_operations;
5784 inode->i_mode = S_IFDIR | S_IRUGO | S_IWUSR | S_IXUGO;
5785 inode->i_mtime = current_time(inode);
5786 inode->i_atime = inode->i_mtime;
5787 inode->i_ctime = inode->i_mtime;
5788 BTRFS_I(inode)->i_otime = inode->i_mtime;
5793 struct inode *btrfs_lookup_dentry(struct inode *dir, struct dentry *dentry)
5795 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
5796 struct inode *inode;
5797 struct btrfs_root *root = BTRFS_I(dir)->root;
5798 struct btrfs_root *sub_root = root;
5799 struct btrfs_key location;
5803 if (dentry->d_name.len > BTRFS_NAME_LEN)
5804 return ERR_PTR(-ENAMETOOLONG);
5806 ret = btrfs_inode_by_name(dir, dentry, &location);
5808 return ERR_PTR(ret);
5810 if (location.objectid == 0)
5811 return ERR_PTR(-ENOENT);
5813 if (location.type == BTRFS_INODE_ITEM_KEY) {
5814 inode = btrfs_iget(dir->i_sb, &location, root, NULL);
5818 index = srcu_read_lock(&fs_info->subvol_srcu);
5819 ret = fixup_tree_root_location(fs_info, dir, dentry,
5820 &location, &sub_root);
5823 inode = ERR_PTR(ret);
5825 inode = new_simple_dir(dir->i_sb, &location, sub_root);
5827 inode = btrfs_iget(dir->i_sb, &location, sub_root, NULL);
5829 srcu_read_unlock(&fs_info->subvol_srcu, index);
5831 if (!IS_ERR(inode) && root != sub_root) {
5832 down_read(&fs_info->cleanup_work_sem);
5833 if (!sb_rdonly(inode->i_sb))
5834 ret = btrfs_orphan_cleanup(sub_root);
5835 up_read(&fs_info->cleanup_work_sem);
5838 inode = ERR_PTR(ret);
5845 static int btrfs_dentry_delete(const struct dentry *dentry)
5847 struct btrfs_root *root;
5848 struct inode *inode = d_inode(dentry);
5850 if (!inode && !IS_ROOT(dentry))
5851 inode = d_inode(dentry->d_parent);
5854 root = BTRFS_I(inode)->root;
5855 if (btrfs_root_refs(&root->root_item) == 0)
5858 if (btrfs_ino(BTRFS_I(inode)) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)
5864 static void btrfs_dentry_release(struct dentry *dentry)
5866 kfree(dentry->d_fsdata);
5869 static struct dentry *btrfs_lookup(struct inode *dir, struct dentry *dentry,
5872 struct inode *inode;
5874 inode = btrfs_lookup_dentry(dir, dentry);
5875 if (IS_ERR(inode)) {
5876 if (PTR_ERR(inode) == -ENOENT)
5879 return ERR_CAST(inode);
5882 return d_splice_alias(inode, dentry);
5885 unsigned char btrfs_filetype_table[] = {
5886 DT_UNKNOWN, DT_REG, DT_DIR, DT_CHR, DT_BLK, DT_FIFO, DT_SOCK, DT_LNK
5890 * All this infrastructure exists because dir_emit can fault, and we are holding
5891 * the tree lock when doing readdir. For now just allocate a buffer and copy
5892 * our information into that, and then dir_emit from the buffer. This is
5893 * similar to what NFS does, only we don't keep the buffer around in pagecache
5894 * because I'm afraid I'll mess that up. Long term we need to make filldir do
5895 * copy_to_user_inatomic so we don't have to worry about page faulting under the
5898 static int btrfs_opendir(struct inode *inode, struct file *file)
5900 struct btrfs_file_private *private;
5902 private = kzalloc(sizeof(struct btrfs_file_private), GFP_KERNEL);
5905 private->filldir_buf = kzalloc(PAGE_SIZE, GFP_KERNEL);
5906 if (!private->filldir_buf) {
5910 file->private_data = private;
5921 static int btrfs_filldir(void *addr, int entries, struct dir_context *ctx)
5924 struct dir_entry *entry = addr;
5925 char *name = (char *)(entry + 1);
5927 ctx->pos = entry->offset;
5928 if (!dir_emit(ctx, name, entry->name_len, entry->ino,
5931 addr += sizeof(struct dir_entry) + entry->name_len;
5937 static int btrfs_real_readdir(struct file *file, struct dir_context *ctx)
5939 struct inode *inode = file_inode(file);
5940 struct btrfs_root *root = BTRFS_I(inode)->root;
5941 struct btrfs_file_private *private = file->private_data;
5942 struct btrfs_dir_item *di;
5943 struct btrfs_key key;
5944 struct btrfs_key found_key;
5945 struct btrfs_path *path;
5947 struct list_head ins_list;
5948 struct list_head del_list;
5950 struct extent_buffer *leaf;
5957 struct btrfs_key location;
5959 if (!dir_emit_dots(file, ctx))
5962 path = btrfs_alloc_path();
5966 addr = private->filldir_buf;
5967 path->reada = READA_FORWARD;
5969 INIT_LIST_HEAD(&ins_list);
5970 INIT_LIST_HEAD(&del_list);
5971 put = btrfs_readdir_get_delayed_items(inode, &ins_list, &del_list);
5974 key.type = BTRFS_DIR_INDEX_KEY;
5975 key.offset = ctx->pos;
5976 key.objectid = btrfs_ino(BTRFS_I(inode));
5978 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
5983 struct dir_entry *entry;
5985 leaf = path->nodes[0];
5986 slot = path->slots[0];
5987 if (slot >= btrfs_header_nritems(leaf)) {
5988 ret = btrfs_next_leaf(root, path);
5996 btrfs_item_key_to_cpu(leaf, &found_key, slot);
5998 if (found_key.objectid != key.objectid)
6000 if (found_key.type != BTRFS_DIR_INDEX_KEY)
6002 if (found_key.offset < ctx->pos)
6004 if (btrfs_should_delete_dir_index(&del_list, found_key.offset))
6006 di = btrfs_item_ptr(leaf, slot, struct btrfs_dir_item);
6007 name_len = btrfs_dir_name_len(leaf, di);
6008 if ((total_len + sizeof(struct dir_entry) + name_len) >=
6010 btrfs_release_path(path);
6011 ret = btrfs_filldir(private->filldir_buf, entries, ctx);
6014 addr = private->filldir_buf;
6021 entry->name_len = name_len;
6022 name_ptr = (char *)(entry + 1);
6023 read_extent_buffer(leaf, name_ptr, (unsigned long)(di + 1),
6025 entry->type = btrfs_filetype_table[btrfs_dir_type(leaf, di)];
6026 btrfs_dir_item_key_to_cpu(leaf, di, &location);
6027 entry->ino = location.objectid;
6028 entry->offset = found_key.offset;
6030 addr += sizeof(struct dir_entry) + name_len;
6031 total_len += sizeof(struct dir_entry) + name_len;
6035 btrfs_release_path(path);
6037 ret = btrfs_filldir(private->filldir_buf, entries, ctx);
6041 ret = btrfs_readdir_delayed_dir_index(ctx, &ins_list);
6046 * Stop new entries from being returned after we return the last
6049 * New directory entries are assigned a strictly increasing
6050 * offset. This means that new entries created during readdir
6051 * are *guaranteed* to be seen in the future by that readdir.
6052 * This has broken buggy programs which operate on names as
6053 * they're returned by readdir. Until we re-use freed offsets
6054 * we have this hack to stop new entries from being returned
6055 * under the assumption that they'll never reach this huge
6058 * This is being careful not to overflow 32bit loff_t unless the
6059 * last entry requires it because doing so has broken 32bit apps
6062 if (ctx->pos >= INT_MAX)
6063 ctx->pos = LLONG_MAX;
6070 btrfs_readdir_put_delayed_items(inode, &ins_list, &del_list);
6071 btrfs_free_path(path);
6075 int btrfs_write_inode(struct inode *inode, struct writeback_control *wbc)
6077 struct btrfs_root *root = BTRFS_I(inode)->root;
6078 struct btrfs_trans_handle *trans;
6080 bool nolock = false;
6082 if (test_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags))
6085 if (btrfs_fs_closing(root->fs_info) &&
6086 btrfs_is_free_space_inode(BTRFS_I(inode)))
6089 if (wbc->sync_mode == WB_SYNC_ALL) {
6091 trans = btrfs_join_transaction_nolock(root);
6093 trans = btrfs_join_transaction(root);
6095 return PTR_ERR(trans);
6096 ret = btrfs_commit_transaction(trans);
6102 * This is somewhat expensive, updating the tree every time the
6103 * inode changes. But, it is most likely to find the inode in cache.
6104 * FIXME, needs more benchmarking...there are no reasons other than performance
6105 * to keep or drop this code.
6107 static int btrfs_dirty_inode(struct inode *inode)
6109 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
6110 struct btrfs_root *root = BTRFS_I(inode)->root;
6111 struct btrfs_trans_handle *trans;
6114 if (test_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags))
6117 trans = btrfs_join_transaction(root);
6119 return PTR_ERR(trans);
6121 ret = btrfs_update_inode(trans, root, inode);
6122 if (ret && ret == -ENOSPC) {
6123 /* whoops, lets try again with the full transaction */
6124 btrfs_end_transaction(trans);
6125 trans = btrfs_start_transaction(root, 1);
6127 return PTR_ERR(trans);
6129 ret = btrfs_update_inode(trans, root, inode);
6131 btrfs_end_transaction(trans);
6132 if (BTRFS_I(inode)->delayed_node)
6133 btrfs_balance_delayed_items(fs_info);
6139 * This is a copy of file_update_time. We need this so we can return error on
6140 * ENOSPC for updating the inode in the case of file write and mmap writes.
6142 static int btrfs_update_time(struct inode *inode, struct timespec *now,
6145 struct btrfs_root *root = BTRFS_I(inode)->root;
6146 bool dirty = flags & ~S_VERSION;
6148 if (btrfs_root_readonly(root))
6151 if (flags & S_VERSION)
6152 dirty |= inode_maybe_inc_iversion(inode, dirty);
6153 if (flags & S_CTIME)
6154 inode->i_ctime = *now;
6155 if (flags & S_MTIME)
6156 inode->i_mtime = *now;
6157 if (flags & S_ATIME)
6158 inode->i_atime = *now;
6159 return dirty ? btrfs_dirty_inode(inode) : 0;
6163 * find the highest existing sequence number in a directory
6164 * and then set the in-memory index_cnt variable to reflect
6165 * free sequence numbers
6167 static int btrfs_set_inode_index_count(struct btrfs_inode *inode)
6169 struct btrfs_root *root = inode->root;
6170 struct btrfs_key key, found_key;
6171 struct btrfs_path *path;
6172 struct extent_buffer *leaf;
6175 key.objectid = btrfs_ino(inode);
6176 key.type = BTRFS_DIR_INDEX_KEY;
6177 key.offset = (u64)-1;
6179 path = btrfs_alloc_path();
6183 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
6186 /* FIXME: we should be able to handle this */
6192 * MAGIC NUMBER EXPLANATION:
6193 * since we search a directory based on f_pos we have to start at 2
6194 * since '.' and '..' have f_pos of 0 and 1 respectively, so everybody
6195 * else has to start at 2
6197 if (path->slots[0] == 0) {
6198 inode->index_cnt = 2;
6204 leaf = path->nodes[0];
6205 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
6207 if (found_key.objectid != btrfs_ino(inode) ||
6208 found_key.type != BTRFS_DIR_INDEX_KEY) {
6209 inode->index_cnt = 2;
6213 inode->index_cnt = found_key.offset + 1;
6215 btrfs_free_path(path);
6220 * helper to find a free sequence number in a given directory. This current
6221 * code is very simple, later versions will do smarter things in the btree
6223 int btrfs_set_inode_index(struct btrfs_inode *dir, u64 *index)
6227 if (dir->index_cnt == (u64)-1) {
6228 ret = btrfs_inode_delayed_dir_index_count(dir);
6230 ret = btrfs_set_inode_index_count(dir);
6236 *index = dir->index_cnt;
6242 static int btrfs_insert_inode_locked(struct inode *inode)
6244 struct btrfs_iget_args args;
6245 args.location = &BTRFS_I(inode)->location;
6246 args.root = BTRFS_I(inode)->root;
6248 return insert_inode_locked4(inode,
6249 btrfs_inode_hash(inode->i_ino, BTRFS_I(inode)->root),
6250 btrfs_find_actor, &args);
6254 * Inherit flags from the parent inode.
6256 * Currently only the compression flags and the cow flags are inherited.
6258 static void btrfs_inherit_iflags(struct inode *inode, struct inode *dir)
6265 flags = BTRFS_I(dir)->flags;
6267 if (flags & BTRFS_INODE_NOCOMPRESS) {
6268 BTRFS_I(inode)->flags &= ~BTRFS_INODE_COMPRESS;
6269 BTRFS_I(inode)->flags |= BTRFS_INODE_NOCOMPRESS;
6270 } else if (flags & BTRFS_INODE_COMPRESS) {
6271 BTRFS_I(inode)->flags &= ~BTRFS_INODE_NOCOMPRESS;
6272 BTRFS_I(inode)->flags |= BTRFS_INODE_COMPRESS;
6275 if (flags & BTRFS_INODE_NODATACOW) {
6276 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATACOW;
6277 if (S_ISREG(inode->i_mode))
6278 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATASUM;
6281 btrfs_update_iflags(inode);
6284 static struct inode *btrfs_new_inode(struct btrfs_trans_handle *trans,
6285 struct btrfs_root *root,
6287 const char *name, int name_len,
6288 u64 ref_objectid, u64 objectid,
6289 umode_t mode, u64 *index)
6291 struct btrfs_fs_info *fs_info = root->fs_info;
6292 struct inode *inode;
6293 struct btrfs_inode_item *inode_item;
6294 struct btrfs_key *location;
6295 struct btrfs_path *path;
6296 struct btrfs_inode_ref *ref;
6297 struct btrfs_key key[2];
6299 int nitems = name ? 2 : 1;
6303 path = btrfs_alloc_path();
6305 return ERR_PTR(-ENOMEM);
6307 inode = new_inode(fs_info->sb);
6309 btrfs_free_path(path);
6310 return ERR_PTR(-ENOMEM);
6314 * O_TMPFILE, set link count to 0, so that after this point,
6315 * we fill in an inode item with the correct link count.
6318 set_nlink(inode, 0);
6321 * we have to initialize this early, so we can reclaim the inode
6322 * number if we fail afterwards in this function.
6324 inode->i_ino = objectid;
6327 trace_btrfs_inode_request(dir);
6329 ret = btrfs_set_inode_index(BTRFS_I(dir), index);
6331 btrfs_free_path(path);
6333 return ERR_PTR(ret);
6339 * index_cnt is ignored for everything but a dir,
6340 * btrfs_set_inode_index_count has an explanation for the magic
6343 BTRFS_I(inode)->index_cnt = 2;
6344 BTRFS_I(inode)->dir_index = *index;
6345 BTRFS_I(inode)->root = root;
6346 BTRFS_I(inode)->generation = trans->transid;
6347 inode->i_generation = BTRFS_I(inode)->generation;
6350 * We could have gotten an inode number from somebody who was fsynced
6351 * and then removed in this same transaction, so let's just set full
6352 * sync since it will be a full sync anyway and this will blow away the
6353 * old info in the log.
6355 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &BTRFS_I(inode)->runtime_flags);
6357 key[0].objectid = objectid;
6358 key[0].type = BTRFS_INODE_ITEM_KEY;
6361 sizes[0] = sizeof(struct btrfs_inode_item);
6365 * Start new inodes with an inode_ref. This is slightly more
6366 * efficient for small numbers of hard links since they will
6367 * be packed into one item. Extended refs will kick in if we
6368 * add more hard links than can fit in the ref item.
6370 key[1].objectid = objectid;
6371 key[1].type = BTRFS_INODE_REF_KEY;
6372 key[1].offset = ref_objectid;
6374 sizes[1] = name_len + sizeof(*ref);
6377 location = &BTRFS_I(inode)->location;
6378 location->objectid = objectid;
6379 location->offset = 0;
6380 location->type = BTRFS_INODE_ITEM_KEY;
6382 ret = btrfs_insert_inode_locked(inode);
6386 path->leave_spinning = 1;
6387 ret = btrfs_insert_empty_items(trans, root, path, key, sizes, nitems);
6391 inode_init_owner(inode, dir, mode);
6392 inode_set_bytes(inode, 0);
6394 inode->i_mtime = current_time(inode);
6395 inode->i_atime = inode->i_mtime;
6396 inode->i_ctime = inode->i_mtime;
6397 BTRFS_I(inode)->i_otime = inode->i_mtime;
6399 inode_item = btrfs_item_ptr(path->nodes[0], path->slots[0],
6400 struct btrfs_inode_item);
6401 memzero_extent_buffer(path->nodes[0], (unsigned long)inode_item,
6402 sizeof(*inode_item));
6403 fill_inode_item(trans, path->nodes[0], inode_item, inode);
6406 ref = btrfs_item_ptr(path->nodes[0], path->slots[0] + 1,
6407 struct btrfs_inode_ref);
6408 btrfs_set_inode_ref_name_len(path->nodes[0], ref, name_len);
6409 btrfs_set_inode_ref_index(path->nodes[0], ref, *index);
6410 ptr = (unsigned long)(ref + 1);
6411 write_extent_buffer(path->nodes[0], name, ptr, name_len);
6414 btrfs_mark_buffer_dirty(path->nodes[0]);
6415 btrfs_free_path(path);
6417 btrfs_inherit_iflags(inode, dir);
6419 if (S_ISREG(mode)) {
6420 if (btrfs_test_opt(fs_info, NODATASUM))
6421 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATASUM;
6422 if (btrfs_test_opt(fs_info, NODATACOW))
6423 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATACOW |
6424 BTRFS_INODE_NODATASUM;
6427 inode_tree_add(inode);
6429 trace_btrfs_inode_new(inode);
6430 btrfs_set_inode_last_trans(trans, inode);
6432 btrfs_update_root_times(trans, root);
6434 ret = btrfs_inode_inherit_props(trans, inode, dir);
6437 "error inheriting props for ino %llu (root %llu): %d",
6438 btrfs_ino(BTRFS_I(inode)), root->root_key.objectid, ret);
6443 unlock_new_inode(inode);
6446 BTRFS_I(dir)->index_cnt--;
6447 btrfs_free_path(path);
6449 return ERR_PTR(ret);
6452 static inline u8 btrfs_inode_type(struct inode *inode)
6454 return btrfs_type_by_mode[(inode->i_mode & S_IFMT) >> S_SHIFT];
6458 * utility function to add 'inode' into 'parent_inode' with
6459 * a give name and a given sequence number.
6460 * if 'add_backref' is true, also insert a backref from the
6461 * inode to the parent directory.
6463 int btrfs_add_link(struct btrfs_trans_handle *trans,
6464 struct btrfs_inode *parent_inode, struct btrfs_inode *inode,
6465 const char *name, int name_len, int add_backref, u64 index)
6467 struct btrfs_fs_info *fs_info = btrfs_sb(inode->vfs_inode.i_sb);
6469 struct btrfs_key key;
6470 struct btrfs_root *root = parent_inode->root;
6471 u64 ino = btrfs_ino(inode);
6472 u64 parent_ino = btrfs_ino(parent_inode);
6474 if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
6475 memcpy(&key, &inode->root->root_key, sizeof(key));
6478 key.type = BTRFS_INODE_ITEM_KEY;
6482 if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
6483 ret = btrfs_add_root_ref(trans, fs_info, key.objectid,
6484 root->root_key.objectid, parent_ino,
6485 index, name, name_len);
6486 } else if (add_backref) {
6487 ret = btrfs_insert_inode_ref(trans, root, name, name_len, ino,
6491 /* Nothing to clean up yet */
6495 ret = btrfs_insert_dir_item(trans, root, name, name_len,
6497 btrfs_inode_type(&inode->vfs_inode), index);
6498 if (ret == -EEXIST || ret == -EOVERFLOW)
6501 btrfs_abort_transaction(trans, ret);
6505 btrfs_i_size_write(parent_inode, parent_inode->vfs_inode.i_size +
6507 inode_inc_iversion(&parent_inode->vfs_inode);
6508 parent_inode->vfs_inode.i_mtime = parent_inode->vfs_inode.i_ctime =
6509 current_time(&parent_inode->vfs_inode);
6510 ret = btrfs_update_inode(trans, root, &parent_inode->vfs_inode);
6512 btrfs_abort_transaction(trans, ret);
6516 if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
6519 err = btrfs_del_root_ref(trans, fs_info, key.objectid,
6520 root->root_key.objectid, parent_ino,
6521 &local_index, name, name_len);
6523 } else if (add_backref) {
6527 err = btrfs_del_inode_ref(trans, root, name, name_len,
6528 ino, parent_ino, &local_index);
6533 static int btrfs_add_nondir(struct btrfs_trans_handle *trans,
6534 struct btrfs_inode *dir, struct dentry *dentry,
6535 struct btrfs_inode *inode, int backref, u64 index)
6537 int err = btrfs_add_link(trans, dir, inode,
6538 dentry->d_name.name, dentry->d_name.len,
6545 static int btrfs_mknod(struct inode *dir, struct dentry *dentry,
6546 umode_t mode, dev_t rdev)
6548 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
6549 struct btrfs_trans_handle *trans;
6550 struct btrfs_root *root = BTRFS_I(dir)->root;
6551 struct inode *inode = NULL;
6558 * 2 for inode item and ref
6560 * 1 for xattr if selinux is on
6562 trans = btrfs_start_transaction(root, 5);
6564 return PTR_ERR(trans);
6566 err = btrfs_find_free_ino(root, &objectid);
6570 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
6571 dentry->d_name.len, btrfs_ino(BTRFS_I(dir)), objectid,
6573 if (IS_ERR(inode)) {
6574 err = PTR_ERR(inode);
6579 * If the active LSM wants to access the inode during
6580 * d_instantiate it needs these. Smack checks to see
6581 * if the filesystem supports xattrs by looking at the
6584 inode->i_op = &btrfs_special_inode_operations;
6585 init_special_inode(inode, inode->i_mode, rdev);
6587 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
6589 goto out_unlock_inode;
6591 err = btrfs_add_nondir(trans, BTRFS_I(dir), dentry, BTRFS_I(inode),
6594 goto out_unlock_inode;
6596 btrfs_update_inode(trans, root, inode);
6597 unlock_new_inode(inode);
6598 d_instantiate(dentry, inode);
6602 btrfs_end_transaction(trans);
6603 btrfs_btree_balance_dirty(fs_info);
6605 inode_dec_link_count(inode);
6612 unlock_new_inode(inode);
6617 static int btrfs_create(struct inode *dir, struct dentry *dentry,
6618 umode_t mode, bool excl)
6620 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
6621 struct btrfs_trans_handle *trans;
6622 struct btrfs_root *root = BTRFS_I(dir)->root;
6623 struct inode *inode = NULL;
6624 int drop_inode_on_err = 0;
6630 * 2 for inode item and ref
6632 * 1 for xattr if selinux is on
6634 trans = btrfs_start_transaction(root, 5);
6636 return PTR_ERR(trans);
6638 err = btrfs_find_free_ino(root, &objectid);
6642 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
6643 dentry->d_name.len, btrfs_ino(BTRFS_I(dir)), objectid,
6645 if (IS_ERR(inode)) {
6646 err = PTR_ERR(inode);
6649 drop_inode_on_err = 1;
6651 * If the active LSM wants to access the inode during
6652 * d_instantiate it needs these. Smack checks to see
6653 * if the filesystem supports xattrs by looking at the
6656 inode->i_fop = &btrfs_file_operations;
6657 inode->i_op = &btrfs_file_inode_operations;
6658 inode->i_mapping->a_ops = &btrfs_aops;
6660 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
6662 goto out_unlock_inode;
6664 err = btrfs_update_inode(trans, root, inode);
6666 goto out_unlock_inode;
6668 err = btrfs_add_nondir(trans, BTRFS_I(dir), dentry, BTRFS_I(inode),
6671 goto out_unlock_inode;
6673 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
6674 unlock_new_inode(inode);
6675 d_instantiate(dentry, inode);
6678 btrfs_end_transaction(trans);
6679 if (err && drop_inode_on_err) {
6680 inode_dec_link_count(inode);
6683 btrfs_btree_balance_dirty(fs_info);
6687 unlock_new_inode(inode);
6692 static int btrfs_link(struct dentry *old_dentry, struct inode *dir,
6693 struct dentry *dentry)
6695 struct btrfs_trans_handle *trans = NULL;
6696 struct btrfs_root *root = BTRFS_I(dir)->root;
6697 struct inode *inode = d_inode(old_dentry);
6698 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
6703 /* do not allow sys_link's with other subvols of the same device */
6704 if (root->objectid != BTRFS_I(inode)->root->objectid)
6707 if (inode->i_nlink >= BTRFS_LINK_MAX)
6710 err = btrfs_set_inode_index(BTRFS_I(dir), &index);
6715 * 2 items for inode and inode ref
6716 * 2 items for dir items
6717 * 1 item for parent inode
6719 trans = btrfs_start_transaction(root, 5);
6720 if (IS_ERR(trans)) {
6721 err = PTR_ERR(trans);
6726 /* There are several dir indexes for this inode, clear the cache. */
6727 BTRFS_I(inode)->dir_index = 0ULL;
6729 inode_inc_iversion(inode);
6730 inode->i_ctime = current_time(inode);
6732 set_bit(BTRFS_INODE_COPY_EVERYTHING, &BTRFS_I(inode)->runtime_flags);
6734 err = btrfs_add_nondir(trans, BTRFS_I(dir), dentry, BTRFS_I(inode),
6740 struct dentry *parent = dentry->d_parent;
6741 err = btrfs_update_inode(trans, root, inode);
6744 if (inode->i_nlink == 1) {
6746 * If new hard link count is 1, it's a file created
6747 * with open(2) O_TMPFILE flag.
6749 err = btrfs_orphan_del(trans, BTRFS_I(inode));
6753 d_instantiate(dentry, inode);
6754 btrfs_log_new_name(trans, BTRFS_I(inode), NULL, parent);
6759 btrfs_end_transaction(trans);
6761 inode_dec_link_count(inode);
6764 btrfs_btree_balance_dirty(fs_info);
6768 static int btrfs_mkdir(struct inode *dir, struct dentry *dentry, umode_t mode)
6770 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
6771 struct inode *inode = NULL;
6772 struct btrfs_trans_handle *trans;
6773 struct btrfs_root *root = BTRFS_I(dir)->root;
6775 int drop_on_err = 0;
6780 * 2 items for inode and ref
6781 * 2 items for dir items
6782 * 1 for xattr if selinux is on
6784 trans = btrfs_start_transaction(root, 5);
6786 return PTR_ERR(trans);
6788 err = btrfs_find_free_ino(root, &objectid);
6792 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
6793 dentry->d_name.len, btrfs_ino(BTRFS_I(dir)), objectid,
6794 S_IFDIR | mode, &index);
6795 if (IS_ERR(inode)) {
6796 err = PTR_ERR(inode);
6801 /* these must be set before we unlock the inode */
6802 inode->i_op = &btrfs_dir_inode_operations;
6803 inode->i_fop = &btrfs_dir_file_operations;
6805 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
6807 goto out_fail_inode;
6809 btrfs_i_size_write(BTRFS_I(inode), 0);
6810 err = btrfs_update_inode(trans, root, inode);
6812 goto out_fail_inode;
6814 err = btrfs_add_link(trans, BTRFS_I(dir), BTRFS_I(inode),
6815 dentry->d_name.name,
6816 dentry->d_name.len, 0, index);
6818 goto out_fail_inode;
6820 d_instantiate(dentry, inode);
6822 * mkdir is special. We're unlocking after we call d_instantiate
6823 * to avoid a race with nfsd calling d_instantiate.
6825 unlock_new_inode(inode);
6829 btrfs_end_transaction(trans);
6831 inode_dec_link_count(inode);
6834 btrfs_btree_balance_dirty(fs_info);
6838 unlock_new_inode(inode);
6842 static noinline int uncompress_inline(struct btrfs_path *path,
6844 size_t pg_offset, u64 extent_offset,
6845 struct btrfs_file_extent_item *item)
6848 struct extent_buffer *leaf = path->nodes[0];
6851 unsigned long inline_size;
6855 WARN_ON(pg_offset != 0);
6856 compress_type = btrfs_file_extent_compression(leaf, item);
6857 max_size = btrfs_file_extent_ram_bytes(leaf, item);
6858 inline_size = btrfs_file_extent_inline_item_len(leaf,
6859 btrfs_item_nr(path->slots[0]));
6860 tmp = kmalloc(inline_size, GFP_NOFS);
6863 ptr = btrfs_file_extent_inline_start(item);
6865 read_extent_buffer(leaf, tmp, ptr, inline_size);
6867 max_size = min_t(unsigned long, PAGE_SIZE, max_size);
6868 ret = btrfs_decompress(compress_type, tmp, page,
6869 extent_offset, inline_size, max_size);
6872 * decompression code contains a memset to fill in any space between the end
6873 * of the uncompressed data and the end of max_size in case the decompressed
6874 * data ends up shorter than ram_bytes. That doesn't cover the hole between
6875 * the end of an inline extent and the beginning of the next block, so we
6876 * cover that region here.
6879 if (max_size + pg_offset < PAGE_SIZE) {
6880 char *map = kmap(page);
6881 memset(map + pg_offset + max_size, 0, PAGE_SIZE - max_size - pg_offset);
6889 * a bit scary, this does extent mapping from logical file offset to the disk.
6890 * the ugly parts come from merging extents from the disk with the in-ram
6891 * representation. This gets more complex because of the data=ordered code,
6892 * where the in-ram extents might be locked pending data=ordered completion.
6894 * This also copies inline extents directly into the page.
6896 struct extent_map *btrfs_get_extent(struct btrfs_inode *inode,
6898 size_t pg_offset, u64 start, u64 len,
6901 struct btrfs_fs_info *fs_info = btrfs_sb(inode->vfs_inode.i_sb);
6904 u64 extent_start = 0;
6906 u64 objectid = btrfs_ino(inode);
6908 struct btrfs_path *path = NULL;
6909 struct btrfs_root *root = inode->root;
6910 struct btrfs_file_extent_item *item;
6911 struct extent_buffer *leaf;
6912 struct btrfs_key found_key;
6913 struct extent_map *em = NULL;
6914 struct extent_map_tree *em_tree = &inode->extent_tree;
6915 struct extent_io_tree *io_tree = &inode->io_tree;
6916 const bool new_inline = !page || create;
6918 read_lock(&em_tree->lock);
6919 em = lookup_extent_mapping(em_tree, start, len);
6921 em->bdev = fs_info->fs_devices->latest_bdev;
6922 read_unlock(&em_tree->lock);
6925 if (em->start > start || em->start + em->len <= start)
6926 free_extent_map(em);
6927 else if (em->block_start == EXTENT_MAP_INLINE && page)
6928 free_extent_map(em);
6932 em = alloc_extent_map();
6937 em->bdev = fs_info->fs_devices->latest_bdev;
6938 em->start = EXTENT_MAP_HOLE;
6939 em->orig_start = EXTENT_MAP_HOLE;
6941 em->block_len = (u64)-1;
6944 path = btrfs_alloc_path();
6950 * Chances are we'll be called again, so go ahead and do
6953 path->reada = READA_FORWARD;
6956 ret = btrfs_lookup_file_extent(NULL, root, path, objectid, start, 0);
6963 if (path->slots[0] == 0)
6968 leaf = path->nodes[0];
6969 item = btrfs_item_ptr(leaf, path->slots[0],
6970 struct btrfs_file_extent_item);
6971 /* are we inside the extent that was found? */
6972 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
6973 found_type = found_key.type;
6974 if (found_key.objectid != objectid ||
6975 found_type != BTRFS_EXTENT_DATA_KEY) {
6977 * If we backup past the first extent we want to move forward
6978 * and see if there is an extent in front of us, otherwise we'll
6979 * say there is a hole for our whole search range which can
6986 found_type = btrfs_file_extent_type(leaf, item);
6987 extent_start = found_key.offset;
6988 if (found_type == BTRFS_FILE_EXTENT_REG ||
6989 found_type == BTRFS_FILE_EXTENT_PREALLOC) {
6990 extent_end = extent_start +
6991 btrfs_file_extent_num_bytes(leaf, item);
6993 trace_btrfs_get_extent_show_fi_regular(inode, leaf, item,
6995 } else if (found_type == BTRFS_FILE_EXTENT_INLINE) {
6997 size = btrfs_file_extent_inline_len(leaf, path->slots[0], item);
6998 extent_end = ALIGN(extent_start + size,
6999 fs_info->sectorsize);
7001 trace_btrfs_get_extent_show_fi_inline(inode, leaf, item,
7006 if (start >= extent_end) {
7008 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
7009 ret = btrfs_next_leaf(root, path);
7016 leaf = path->nodes[0];
7018 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
7019 if (found_key.objectid != objectid ||
7020 found_key.type != BTRFS_EXTENT_DATA_KEY)
7022 if (start + len <= found_key.offset)
7024 if (start > found_key.offset)
7027 em->orig_start = start;
7028 em->len = found_key.offset - start;
7032 btrfs_extent_item_to_extent_map(inode, path, item,
7035 if (found_type == BTRFS_FILE_EXTENT_REG ||
7036 found_type == BTRFS_FILE_EXTENT_PREALLOC) {
7038 } else if (found_type == BTRFS_FILE_EXTENT_INLINE) {
7042 size_t extent_offset;
7048 size = btrfs_file_extent_inline_len(leaf, path->slots[0], item);
7049 extent_offset = page_offset(page) + pg_offset - extent_start;
7050 copy_size = min_t(u64, PAGE_SIZE - pg_offset,
7051 size - extent_offset);
7052 em->start = extent_start + extent_offset;
7053 em->len = ALIGN(copy_size, fs_info->sectorsize);
7054 em->orig_block_len = em->len;
7055 em->orig_start = em->start;
7056 ptr = btrfs_file_extent_inline_start(item) + extent_offset;
7057 if (!PageUptodate(page)) {
7058 if (btrfs_file_extent_compression(leaf, item) !=
7059 BTRFS_COMPRESS_NONE) {
7060 ret = uncompress_inline(path, page, pg_offset,
7061 extent_offset, item);
7068 read_extent_buffer(leaf, map + pg_offset, ptr,
7070 if (pg_offset + copy_size < PAGE_SIZE) {
7071 memset(map + pg_offset + copy_size, 0,
7072 PAGE_SIZE - pg_offset -
7077 flush_dcache_page(page);
7079 set_extent_uptodate(io_tree, em->start,
7080 extent_map_end(em) - 1, NULL, GFP_NOFS);
7085 em->orig_start = start;
7088 em->block_start = EXTENT_MAP_HOLE;
7090 btrfs_release_path(path);
7091 if (em->start > start || extent_map_end(em) <= start) {
7093 "bad extent! em: [%llu %llu] passed [%llu %llu]",
7094 em->start, em->len, start, len);
7100 write_lock(&em_tree->lock);
7101 err = btrfs_add_extent_mapping(em_tree, &em, start, len);
7102 write_unlock(&em_tree->lock);
7105 trace_btrfs_get_extent(root, inode, em);
7107 btrfs_free_path(path);
7109 free_extent_map(em);
7110 return ERR_PTR(err);
7112 BUG_ON(!em); /* Error is always set */
7116 struct extent_map *btrfs_get_extent_fiemap(struct btrfs_inode *inode,
7118 size_t pg_offset, u64 start, u64 len,
7121 struct extent_map *em;
7122 struct extent_map *hole_em = NULL;
7123 u64 range_start = start;
7129 em = btrfs_get_extent(inode, page, pg_offset, start, len, create);
7133 * If our em maps to:
7135 * - a pre-alloc extent,
7136 * there might actually be delalloc bytes behind it.
7138 if (em->block_start != EXTENT_MAP_HOLE &&
7139 !test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
7144 /* check to see if we've wrapped (len == -1 or similar) */
7153 /* ok, we didn't find anything, lets look for delalloc */
7154 found = count_range_bits(&inode->io_tree, &range_start,
7155 end, len, EXTENT_DELALLOC, 1);
7156 found_end = range_start + found;
7157 if (found_end < range_start)
7158 found_end = (u64)-1;
7161 * we didn't find anything useful, return
7162 * the original results from get_extent()
7164 if (range_start > end || found_end <= start) {
7170 /* adjust the range_start to make sure it doesn't
7171 * go backwards from the start they passed in
7173 range_start = max(start, range_start);
7174 found = found_end - range_start;
7177 u64 hole_start = start;
7180 em = alloc_extent_map();
7186 * when btrfs_get_extent can't find anything it
7187 * returns one huge hole
7189 * make sure what it found really fits our range, and
7190 * adjust to make sure it is based on the start from
7194 u64 calc_end = extent_map_end(hole_em);
7196 if (calc_end <= start || (hole_em->start > end)) {
7197 free_extent_map(hole_em);
7200 hole_start = max(hole_em->start, start);
7201 hole_len = calc_end - hole_start;
7205 if (hole_em && range_start > hole_start) {
7206 /* our hole starts before our delalloc, so we
7207 * have to return just the parts of the hole
7208 * that go until the delalloc starts
7210 em->len = min(hole_len,
7211 range_start - hole_start);
7212 em->start = hole_start;
7213 em->orig_start = hole_start;
7215 * don't adjust block start at all,
7216 * it is fixed at EXTENT_MAP_HOLE
7218 em->block_start = hole_em->block_start;
7219 em->block_len = hole_len;
7220 if (test_bit(EXTENT_FLAG_PREALLOC, &hole_em->flags))
7221 set_bit(EXTENT_FLAG_PREALLOC, &em->flags);
7223 em->start = range_start;
7225 em->orig_start = range_start;
7226 em->block_start = EXTENT_MAP_DELALLOC;
7227 em->block_len = found;
7234 free_extent_map(hole_em);
7236 free_extent_map(em);
7237 return ERR_PTR(err);
7242 static struct extent_map *btrfs_create_dio_extent(struct inode *inode,
7245 const u64 orig_start,
7246 const u64 block_start,
7247 const u64 block_len,
7248 const u64 orig_block_len,
7249 const u64 ram_bytes,
7252 struct extent_map *em = NULL;
7255 if (type != BTRFS_ORDERED_NOCOW) {
7256 em = create_io_em(inode, start, len, orig_start,
7257 block_start, block_len, orig_block_len,
7259 BTRFS_COMPRESS_NONE, /* compress_type */
7264 ret = btrfs_add_ordered_extent_dio(inode, start, block_start,
7265 len, block_len, type);
7268 free_extent_map(em);
7269 btrfs_drop_extent_cache(BTRFS_I(inode), start,
7270 start + len - 1, 0);
7279 static struct extent_map *btrfs_new_extent_direct(struct inode *inode,
7282 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7283 struct btrfs_root *root = BTRFS_I(inode)->root;
7284 struct extent_map *em;
7285 struct btrfs_key ins;
7289 alloc_hint = get_extent_allocation_hint(inode, start, len);
7290 ret = btrfs_reserve_extent(root, len, len, fs_info->sectorsize,
7291 0, alloc_hint, &ins, 1, 1);
7293 return ERR_PTR(ret);
7295 em = btrfs_create_dio_extent(inode, start, ins.offset, start,
7296 ins.objectid, ins.offset, ins.offset,
7297 ins.offset, BTRFS_ORDERED_REGULAR);
7298 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
7300 btrfs_free_reserved_extent(fs_info, ins.objectid,
7307 * returns 1 when the nocow is safe, < 1 on error, 0 if the
7308 * block must be cow'd
7310 noinline int can_nocow_extent(struct inode *inode, u64 offset, u64 *len,
7311 u64 *orig_start, u64 *orig_block_len,
7314 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7315 struct btrfs_path *path;
7317 struct extent_buffer *leaf;
7318 struct btrfs_root *root = BTRFS_I(inode)->root;
7319 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
7320 struct btrfs_file_extent_item *fi;
7321 struct btrfs_key key;
7328 bool nocow = (BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW);
7330 path = btrfs_alloc_path();
7334 ret = btrfs_lookup_file_extent(NULL, root, path,
7335 btrfs_ino(BTRFS_I(inode)), offset, 0);
7339 slot = path->slots[0];
7342 /* can't find the item, must cow */
7349 leaf = path->nodes[0];
7350 btrfs_item_key_to_cpu(leaf, &key, slot);
7351 if (key.objectid != btrfs_ino(BTRFS_I(inode)) ||
7352 key.type != BTRFS_EXTENT_DATA_KEY) {
7353 /* not our file or wrong item type, must cow */
7357 if (key.offset > offset) {
7358 /* Wrong offset, must cow */
7362 fi = btrfs_item_ptr(leaf, slot, struct btrfs_file_extent_item);
7363 found_type = btrfs_file_extent_type(leaf, fi);
7364 if (found_type != BTRFS_FILE_EXTENT_REG &&
7365 found_type != BTRFS_FILE_EXTENT_PREALLOC) {
7366 /* not a regular extent, must cow */
7370 if (!nocow && found_type == BTRFS_FILE_EXTENT_REG)
7373 extent_end = key.offset + btrfs_file_extent_num_bytes(leaf, fi);
7374 if (extent_end <= offset)
7377 disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
7378 if (disk_bytenr == 0)
7381 if (btrfs_file_extent_compression(leaf, fi) ||
7382 btrfs_file_extent_encryption(leaf, fi) ||
7383 btrfs_file_extent_other_encoding(leaf, fi))
7386 backref_offset = btrfs_file_extent_offset(leaf, fi);
7389 *orig_start = key.offset - backref_offset;
7390 *orig_block_len = btrfs_file_extent_disk_num_bytes(leaf, fi);
7391 *ram_bytes = btrfs_file_extent_ram_bytes(leaf, fi);
7394 if (btrfs_extent_readonly(fs_info, disk_bytenr))
7397 num_bytes = min(offset + *len, extent_end) - offset;
7398 if (!nocow && found_type == BTRFS_FILE_EXTENT_PREALLOC) {
7401 range_end = round_up(offset + num_bytes,
7402 root->fs_info->sectorsize) - 1;
7403 ret = test_range_bit(io_tree, offset, range_end,
7404 EXTENT_DELALLOC, 0, NULL);
7411 btrfs_release_path(path);
7414 * look for other files referencing this extent, if we
7415 * find any we must cow
7418 ret = btrfs_cross_ref_exist(root, btrfs_ino(BTRFS_I(inode)),
7419 key.offset - backref_offset, disk_bytenr);
7426 * adjust disk_bytenr and num_bytes to cover just the bytes
7427 * in this extent we are about to write. If there
7428 * are any csums in that range we have to cow in order
7429 * to keep the csums correct
7431 disk_bytenr += backref_offset;
7432 disk_bytenr += offset - key.offset;
7433 if (csum_exist_in_range(fs_info, disk_bytenr, num_bytes))
7436 * all of the above have passed, it is safe to overwrite this extent
7442 btrfs_free_path(path);
7446 bool btrfs_page_exists_in_range(struct inode *inode, loff_t start, loff_t end)
7448 struct radix_tree_root *root = &inode->i_mapping->page_tree;
7450 void **pagep = NULL;
7451 struct page *page = NULL;
7452 unsigned long start_idx;
7453 unsigned long end_idx;
7455 start_idx = start >> PAGE_SHIFT;
7458 * end is the last byte in the last page. end == start is legal
7460 end_idx = end >> PAGE_SHIFT;
7464 /* Most of the code in this while loop is lifted from
7465 * find_get_page. It's been modified to begin searching from a
7466 * page and return just the first page found in that range. If the
7467 * found idx is less than or equal to the end idx then we know that
7468 * a page exists. If no pages are found or if those pages are
7469 * outside of the range then we're fine (yay!) */
7470 while (page == NULL &&
7471 radix_tree_gang_lookup_slot(root, &pagep, NULL, start_idx, 1)) {
7472 page = radix_tree_deref_slot(pagep);
7473 if (unlikely(!page))
7476 if (radix_tree_exception(page)) {
7477 if (radix_tree_deref_retry(page)) {
7482 * Otherwise, shmem/tmpfs must be storing a swap entry
7483 * here as an exceptional entry: so return it without
7484 * attempting to raise page count.
7487 break; /* TODO: Is this relevant for this use case? */
7490 if (!page_cache_get_speculative(page)) {
7496 * Has the page moved?
7497 * This is part of the lockless pagecache protocol. See
7498 * include/linux/pagemap.h for details.
7500 if (unlikely(page != *pagep)) {
7507 if (page->index <= end_idx)
7516 static int lock_extent_direct(struct inode *inode, u64 lockstart, u64 lockend,
7517 struct extent_state **cached_state, int writing)
7519 struct btrfs_ordered_extent *ordered;
7523 lock_extent_bits(&BTRFS_I(inode)->io_tree, lockstart, lockend,
7526 * We're concerned with the entire range that we're going to be
7527 * doing DIO to, so we need to make sure there's no ordered
7528 * extents in this range.
7530 ordered = btrfs_lookup_ordered_range(BTRFS_I(inode), lockstart,
7531 lockend - lockstart + 1);
7534 * We need to make sure there are no buffered pages in this
7535 * range either, we could have raced between the invalidate in
7536 * generic_file_direct_write and locking the extent. The
7537 * invalidate needs to happen so that reads after a write do not
7542 !btrfs_page_exists_in_range(inode, lockstart, lockend)))
7545 unlock_extent_cached(&BTRFS_I(inode)->io_tree, lockstart, lockend,
7550 * If we are doing a DIO read and the ordered extent we
7551 * found is for a buffered write, we can not wait for it
7552 * to complete and retry, because if we do so we can
7553 * deadlock with concurrent buffered writes on page
7554 * locks. This happens only if our DIO read covers more
7555 * than one extent map, if at this point has already
7556 * created an ordered extent for a previous extent map
7557 * and locked its range in the inode's io tree, and a
7558 * concurrent write against that previous extent map's
7559 * range and this range started (we unlock the ranges
7560 * in the io tree only when the bios complete and
7561 * buffered writes always lock pages before attempting
7562 * to lock range in the io tree).
7565 test_bit(BTRFS_ORDERED_DIRECT, &ordered->flags))
7566 btrfs_start_ordered_extent(inode, ordered, 1);
7569 btrfs_put_ordered_extent(ordered);
7572 * We could trigger writeback for this range (and wait
7573 * for it to complete) and then invalidate the pages for
7574 * this range (through invalidate_inode_pages2_range()),
7575 * but that can lead us to a deadlock with a concurrent
7576 * call to readpages() (a buffered read or a defrag call
7577 * triggered a readahead) on a page lock due to an
7578 * ordered dio extent we created before but did not have
7579 * yet a corresponding bio submitted (whence it can not
7580 * complete), which makes readpages() wait for that
7581 * ordered extent to complete while holding a lock on
7596 /* The callers of this must take lock_extent() */
7597 static struct extent_map *create_io_em(struct inode *inode, u64 start, u64 len,
7598 u64 orig_start, u64 block_start,
7599 u64 block_len, u64 orig_block_len,
7600 u64 ram_bytes, int compress_type,
7603 struct extent_map_tree *em_tree;
7604 struct extent_map *em;
7605 struct btrfs_root *root = BTRFS_I(inode)->root;
7608 ASSERT(type == BTRFS_ORDERED_PREALLOC ||
7609 type == BTRFS_ORDERED_COMPRESSED ||
7610 type == BTRFS_ORDERED_NOCOW ||
7611 type == BTRFS_ORDERED_REGULAR);
7613 em_tree = &BTRFS_I(inode)->extent_tree;
7614 em = alloc_extent_map();
7616 return ERR_PTR(-ENOMEM);
7619 em->orig_start = orig_start;
7621 em->block_len = block_len;
7622 em->block_start = block_start;
7623 em->bdev = root->fs_info->fs_devices->latest_bdev;
7624 em->orig_block_len = orig_block_len;
7625 em->ram_bytes = ram_bytes;
7626 em->generation = -1;
7627 set_bit(EXTENT_FLAG_PINNED, &em->flags);
7628 if (type == BTRFS_ORDERED_PREALLOC) {
7629 set_bit(EXTENT_FLAG_FILLING, &em->flags);
7630 } else if (type == BTRFS_ORDERED_COMPRESSED) {
7631 set_bit(EXTENT_FLAG_COMPRESSED, &em->flags);
7632 em->compress_type = compress_type;
7636 btrfs_drop_extent_cache(BTRFS_I(inode), em->start,
7637 em->start + em->len - 1, 0);
7638 write_lock(&em_tree->lock);
7639 ret = add_extent_mapping(em_tree, em, 1);
7640 write_unlock(&em_tree->lock);
7642 * The caller has taken lock_extent(), who could race with us
7645 } while (ret == -EEXIST);
7648 free_extent_map(em);
7649 return ERR_PTR(ret);
7652 /* em got 2 refs now, callers needs to do free_extent_map once. */
7656 static int btrfs_get_blocks_direct(struct inode *inode, sector_t iblock,
7657 struct buffer_head *bh_result, int create)
7659 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7660 struct extent_map *em;
7661 struct extent_state *cached_state = NULL;
7662 struct btrfs_dio_data *dio_data = NULL;
7663 u64 start = iblock << inode->i_blkbits;
7664 u64 lockstart, lockend;
7665 u64 len = bh_result->b_size;
7666 int unlock_bits = EXTENT_LOCKED;
7670 unlock_bits |= EXTENT_DIRTY;
7672 len = min_t(u64, len, fs_info->sectorsize);
7675 lockend = start + len - 1;
7677 if (current->journal_info) {
7679 * Need to pull our outstanding extents and set journal_info to NULL so
7680 * that anything that needs to check if there's a transaction doesn't get
7683 dio_data = current->journal_info;
7684 current->journal_info = NULL;
7688 * If this errors out it's because we couldn't invalidate pagecache for
7689 * this range and we need to fallback to buffered.
7691 if (lock_extent_direct(inode, lockstart, lockend, &cached_state,
7697 em = btrfs_get_extent(BTRFS_I(inode), NULL, 0, start, len, 0);
7704 * Ok for INLINE and COMPRESSED extents we need to fallback on buffered
7705 * io. INLINE is special, and we could probably kludge it in here, but
7706 * it's still buffered so for safety lets just fall back to the generic
7709 * For COMPRESSED we _have_ to read the entire extent in so we can
7710 * decompress it, so there will be buffering required no matter what we
7711 * do, so go ahead and fallback to buffered.
7713 * We return -ENOTBLK because that's what makes DIO go ahead and go back
7714 * to buffered IO. Don't blame me, this is the price we pay for using
7717 if (test_bit(EXTENT_FLAG_COMPRESSED, &em->flags) ||
7718 em->block_start == EXTENT_MAP_INLINE) {
7719 free_extent_map(em);
7724 /* Just a good old fashioned hole, return */
7725 if (!create && (em->block_start == EXTENT_MAP_HOLE ||
7726 test_bit(EXTENT_FLAG_PREALLOC, &em->flags))) {
7727 free_extent_map(em);
7732 * We don't allocate a new extent in the following cases
7734 * 1) The inode is marked as NODATACOW. In this case we'll just use the
7736 * 2) The extent is marked as PREALLOC. We're good to go here and can
7737 * just use the extent.
7741 len = min(len, em->len - (start - em->start));
7742 lockstart = start + len;
7746 if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags) ||
7747 ((BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW) &&
7748 em->block_start != EXTENT_MAP_HOLE)) {
7750 u64 block_start, orig_start, orig_block_len, ram_bytes;
7752 if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
7753 type = BTRFS_ORDERED_PREALLOC;
7755 type = BTRFS_ORDERED_NOCOW;
7756 len = min(len, em->len - (start - em->start));
7757 block_start = em->block_start + (start - em->start);
7759 if (can_nocow_extent(inode, start, &len, &orig_start,
7760 &orig_block_len, &ram_bytes) == 1 &&
7761 btrfs_inc_nocow_writers(fs_info, block_start)) {
7762 struct extent_map *em2;
7764 em2 = btrfs_create_dio_extent(inode, start, len,
7765 orig_start, block_start,
7766 len, orig_block_len,
7768 btrfs_dec_nocow_writers(fs_info, block_start);
7769 if (type == BTRFS_ORDERED_PREALLOC) {
7770 free_extent_map(em);
7773 if (em2 && IS_ERR(em2)) {
7778 * For inode marked NODATACOW or extent marked PREALLOC,
7779 * use the existing or preallocated extent, so does not
7780 * need to adjust btrfs_space_info's bytes_may_use.
7782 btrfs_free_reserved_data_space_noquota(inode,
7789 * this will cow the extent, reset the len in case we changed
7792 len = bh_result->b_size;
7793 free_extent_map(em);
7794 em = btrfs_new_extent_direct(inode, start, len);
7799 len = min(len, em->len - (start - em->start));
7801 bh_result->b_blocknr = (em->block_start + (start - em->start)) >>
7803 bh_result->b_size = len;
7804 bh_result->b_bdev = em->bdev;
7805 set_buffer_mapped(bh_result);
7807 if (!test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
7808 set_buffer_new(bh_result);
7811 * Need to update the i_size under the extent lock so buffered
7812 * readers will get the updated i_size when we unlock.
7814 if (!dio_data->overwrite && start + len > i_size_read(inode))
7815 i_size_write(inode, start + len);
7817 WARN_ON(dio_data->reserve < len);
7818 dio_data->reserve -= len;
7819 dio_data->unsubmitted_oe_range_end = start + len;
7820 current->journal_info = dio_data;
7824 * In the case of write we need to clear and unlock the entire range,
7825 * in the case of read we need to unlock only the end area that we
7826 * aren't using if there is any left over space.
7828 if (lockstart < lockend) {
7829 clear_extent_bit(&BTRFS_I(inode)->io_tree, lockstart,
7830 lockend, unlock_bits, 1, 0,
7833 free_extent_state(cached_state);
7836 free_extent_map(em);
7841 clear_extent_bit(&BTRFS_I(inode)->io_tree, lockstart, lockend,
7842 unlock_bits, 1, 0, &cached_state);
7845 current->journal_info = dio_data;
7849 static inline blk_status_t submit_dio_repair_bio(struct inode *inode,
7853 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7856 BUG_ON(bio_op(bio) == REQ_OP_WRITE);
7858 ret = btrfs_bio_wq_end_io(fs_info, bio, BTRFS_WQ_ENDIO_DIO_REPAIR);
7862 ret = btrfs_map_bio(fs_info, bio, mirror_num, 0);
7867 static int btrfs_check_dio_repairable(struct inode *inode,
7868 struct bio *failed_bio,
7869 struct io_failure_record *failrec,
7872 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7875 num_copies = btrfs_num_copies(fs_info, failrec->logical, failrec->len);
7876 if (num_copies == 1) {
7878 * we only have a single copy of the data, so don't bother with
7879 * all the retry and error correction code that follows. no
7880 * matter what the error is, it is very likely to persist.
7882 btrfs_debug(fs_info,
7883 "Check DIO Repairable: cannot repair, num_copies=%d, next_mirror %d, failed_mirror %d",
7884 num_copies, failrec->this_mirror, failed_mirror);
7888 failrec->failed_mirror = failed_mirror;
7889 failrec->this_mirror++;
7890 if (failrec->this_mirror == failed_mirror)
7891 failrec->this_mirror++;
7893 if (failrec->this_mirror > num_copies) {
7894 btrfs_debug(fs_info,
7895 "Check DIO Repairable: (fail) num_copies=%d, next_mirror %d, failed_mirror %d",
7896 num_copies, failrec->this_mirror, failed_mirror);
7903 static blk_status_t dio_read_error(struct inode *inode, struct bio *failed_bio,
7904 struct page *page, unsigned int pgoff,
7905 u64 start, u64 end, int failed_mirror,
7906 bio_end_io_t *repair_endio, void *repair_arg)
7908 struct io_failure_record *failrec;
7909 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
7910 struct extent_io_tree *failure_tree = &BTRFS_I(inode)->io_failure_tree;
7913 unsigned int read_mode = 0;
7916 blk_status_t status;
7917 struct bio_vec bvec;
7919 BUG_ON(bio_op(failed_bio) == REQ_OP_WRITE);
7921 ret = btrfs_get_io_failure_record(inode, start, end, &failrec);
7923 return errno_to_blk_status(ret);
7925 ret = btrfs_check_dio_repairable(inode, failed_bio, failrec,
7928 free_io_failure(failure_tree, io_tree, failrec);
7929 return BLK_STS_IOERR;
7932 segs = bio_segments(failed_bio);
7933 bio_get_first_bvec(failed_bio, &bvec);
7935 (bvec.bv_len > btrfs_inode_sectorsize(inode)))
7936 read_mode |= REQ_FAILFAST_DEV;
7938 isector = start - btrfs_io_bio(failed_bio)->logical;
7939 isector >>= inode->i_sb->s_blocksize_bits;
7940 bio = btrfs_create_repair_bio(inode, failed_bio, failrec, page,
7941 pgoff, isector, repair_endio, repair_arg);
7942 bio_set_op_attrs(bio, REQ_OP_READ, read_mode);
7944 btrfs_debug(BTRFS_I(inode)->root->fs_info,
7945 "repair DIO read error: submitting new dio read[%#x] to this_mirror=%d, in_validation=%d",
7946 read_mode, failrec->this_mirror, failrec->in_validation);
7948 status = submit_dio_repair_bio(inode, bio, failrec->this_mirror);
7950 free_io_failure(failure_tree, io_tree, failrec);
7957 struct btrfs_retry_complete {
7958 struct completion done;
7959 struct inode *inode;
7964 static void btrfs_retry_endio_nocsum(struct bio *bio)
7966 struct btrfs_retry_complete *done = bio->bi_private;
7967 struct inode *inode = done->inode;
7968 struct bio_vec *bvec;
7969 struct extent_io_tree *io_tree, *failure_tree;
7975 ASSERT(bio->bi_vcnt == 1);
7976 io_tree = &BTRFS_I(inode)->io_tree;
7977 failure_tree = &BTRFS_I(inode)->io_failure_tree;
7978 ASSERT(bio_first_bvec_all(bio)->bv_len == btrfs_inode_sectorsize(inode));
7981 ASSERT(!bio_flagged(bio, BIO_CLONED));
7982 bio_for_each_segment_all(bvec, bio, i)
7983 clean_io_failure(BTRFS_I(inode)->root->fs_info, failure_tree,
7984 io_tree, done->start, bvec->bv_page,
7985 btrfs_ino(BTRFS_I(inode)), 0);
7987 complete(&done->done);
7991 static blk_status_t __btrfs_correct_data_nocsum(struct inode *inode,
7992 struct btrfs_io_bio *io_bio)
7994 struct btrfs_fs_info *fs_info;
7995 struct bio_vec bvec;
7996 struct bvec_iter iter;
7997 struct btrfs_retry_complete done;
8003 blk_status_t err = BLK_STS_OK;
8005 fs_info = BTRFS_I(inode)->root->fs_info;
8006 sectorsize = fs_info->sectorsize;
8008 start = io_bio->logical;
8010 io_bio->bio.bi_iter = io_bio->iter;
8012 bio_for_each_segment(bvec, &io_bio->bio, iter) {
8013 nr_sectors = BTRFS_BYTES_TO_BLKS(fs_info, bvec.bv_len);
8014 pgoff = bvec.bv_offset;
8016 next_block_or_try_again:
8019 init_completion(&done.done);
8021 ret = dio_read_error(inode, &io_bio->bio, bvec.bv_page,
8022 pgoff, start, start + sectorsize - 1,
8024 btrfs_retry_endio_nocsum, &done);
8030 wait_for_completion_io(&done.done);
8032 if (!done.uptodate) {
8033 /* We might have another mirror, so try again */
8034 goto next_block_or_try_again;
8038 start += sectorsize;
8042 pgoff += sectorsize;
8043 ASSERT(pgoff < PAGE_SIZE);
8044 goto next_block_or_try_again;
8051 static void btrfs_retry_endio(struct bio *bio)
8053 struct btrfs_retry_complete *done = bio->bi_private;
8054 struct btrfs_io_bio *io_bio = btrfs_io_bio(bio);
8055 struct extent_io_tree *io_tree, *failure_tree;
8056 struct inode *inode = done->inode;
8057 struct bio_vec *bvec;
8067 ASSERT(bio->bi_vcnt == 1);
8068 ASSERT(bio_first_bvec_all(bio)->bv_len == btrfs_inode_sectorsize(done->inode));
8070 io_tree = &BTRFS_I(inode)->io_tree;
8071 failure_tree = &BTRFS_I(inode)->io_failure_tree;
8073 ASSERT(!bio_flagged(bio, BIO_CLONED));
8074 bio_for_each_segment_all(bvec, bio, i) {
8075 ret = __readpage_endio_check(inode, io_bio, i, bvec->bv_page,
8076 bvec->bv_offset, done->start,
8079 clean_io_failure(BTRFS_I(inode)->root->fs_info,
8080 failure_tree, io_tree, done->start,
8082 btrfs_ino(BTRFS_I(inode)),
8088 done->uptodate = uptodate;
8090 complete(&done->done);
8094 static blk_status_t __btrfs_subio_endio_read(struct inode *inode,
8095 struct btrfs_io_bio *io_bio, blk_status_t err)
8097 struct btrfs_fs_info *fs_info;
8098 struct bio_vec bvec;
8099 struct bvec_iter iter;
8100 struct btrfs_retry_complete done;
8107 bool uptodate = (err == 0);
8109 blk_status_t status;
8111 fs_info = BTRFS_I(inode)->root->fs_info;
8112 sectorsize = fs_info->sectorsize;
8115 start = io_bio->logical;
8117 io_bio->bio.bi_iter = io_bio->iter;
8119 bio_for_each_segment(bvec, &io_bio->bio, iter) {
8120 nr_sectors = BTRFS_BYTES_TO_BLKS(fs_info, bvec.bv_len);
8122 pgoff = bvec.bv_offset;
8125 csum_pos = BTRFS_BYTES_TO_BLKS(fs_info, offset);
8126 ret = __readpage_endio_check(inode, io_bio, csum_pos,
8127 bvec.bv_page, pgoff, start, sectorsize);
8134 init_completion(&done.done);
8136 status = dio_read_error(inode, &io_bio->bio, bvec.bv_page,
8137 pgoff, start, start + sectorsize - 1,
8138 io_bio->mirror_num, btrfs_retry_endio,
8145 wait_for_completion_io(&done.done);
8147 if (!done.uptodate) {
8148 /* We might have another mirror, so try again */
8152 offset += sectorsize;
8153 start += sectorsize;
8159 pgoff += sectorsize;
8160 ASSERT(pgoff < PAGE_SIZE);
8168 static blk_status_t btrfs_subio_endio_read(struct inode *inode,
8169 struct btrfs_io_bio *io_bio, blk_status_t err)
8171 bool skip_csum = BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM;
8175 return __btrfs_correct_data_nocsum(inode, io_bio);
8179 return __btrfs_subio_endio_read(inode, io_bio, err);
8183 static void btrfs_endio_direct_read(struct bio *bio)
8185 struct btrfs_dio_private *dip = bio->bi_private;
8186 struct inode *inode = dip->inode;
8187 struct bio *dio_bio;
8188 struct btrfs_io_bio *io_bio = btrfs_io_bio(bio);
8189 blk_status_t err = bio->bi_status;
8191 if (dip->flags & BTRFS_DIO_ORIG_BIO_SUBMITTED)
8192 err = btrfs_subio_endio_read(inode, io_bio, err);
8194 unlock_extent(&BTRFS_I(inode)->io_tree, dip->logical_offset,
8195 dip->logical_offset + dip->bytes - 1);
8196 dio_bio = dip->dio_bio;
8200 dio_bio->bi_status = err;
8201 dio_end_io(dio_bio);
8204 io_bio->end_io(io_bio, blk_status_to_errno(err));
8208 static void __endio_write_update_ordered(struct inode *inode,
8209 const u64 offset, const u64 bytes,
8210 const bool uptodate)
8212 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
8213 struct btrfs_ordered_extent *ordered = NULL;
8214 struct btrfs_workqueue *wq;
8215 btrfs_work_func_t func;
8216 u64 ordered_offset = offset;
8217 u64 ordered_bytes = bytes;
8221 if (btrfs_is_free_space_inode(BTRFS_I(inode))) {
8222 wq = fs_info->endio_freespace_worker;
8223 func = btrfs_freespace_write_helper;
8225 wq = fs_info->endio_write_workers;
8226 func = btrfs_endio_write_helper;
8230 last_offset = ordered_offset;
8231 ret = btrfs_dec_test_first_ordered_pending(inode, &ordered,
8238 btrfs_init_work(&ordered->work, func, finish_ordered_fn, NULL, NULL);
8239 btrfs_queue_work(wq, &ordered->work);
8242 * If btrfs_dec_test_ordered_pending does not find any ordered extent
8243 * in the range, we can exit.
8245 if (ordered_offset == last_offset)
8248 * our bio might span multiple ordered extents. If we haven't
8249 * completed the accounting for the whole dio, go back and try again
8251 if (ordered_offset < offset + bytes) {
8252 ordered_bytes = offset + bytes - ordered_offset;
8258 static void btrfs_endio_direct_write(struct bio *bio)
8260 struct btrfs_dio_private *dip = bio->bi_private;
8261 struct bio *dio_bio = dip->dio_bio;
8263 __endio_write_update_ordered(dip->inode, dip->logical_offset,
8264 dip->bytes, !bio->bi_status);
8268 dio_bio->bi_status = bio->bi_status;
8269 dio_end_io(dio_bio);
8273 static blk_status_t __btrfs_submit_bio_start_direct_io(void *private_data,
8274 struct bio *bio, int mirror_num,
8275 unsigned long bio_flags, u64 offset)
8277 struct inode *inode = private_data;
8279 ret = btrfs_csum_one_bio(inode, bio, offset, 1);
8280 BUG_ON(ret); /* -ENOMEM */
8284 static void btrfs_end_dio_bio(struct bio *bio)
8286 struct btrfs_dio_private *dip = bio->bi_private;
8287 blk_status_t err = bio->bi_status;
8290 btrfs_warn(BTRFS_I(dip->inode)->root->fs_info,
8291 "direct IO failed ino %llu rw %d,%u sector %#Lx len %u err no %d",
8292 btrfs_ino(BTRFS_I(dip->inode)), bio_op(bio),
8294 (unsigned long long)bio->bi_iter.bi_sector,
8295 bio->bi_iter.bi_size, err);
8297 if (dip->subio_endio)
8298 err = dip->subio_endio(dip->inode, btrfs_io_bio(bio), err);
8304 * before atomic variable goto zero, we must make sure
8305 * dip->errors is perceived to be set.
8307 smp_mb__before_atomic();
8310 /* if there are more bios still pending for this dio, just exit */
8311 if (!atomic_dec_and_test(&dip->pending_bios))
8315 bio_io_error(dip->orig_bio);
8317 dip->dio_bio->bi_status = BLK_STS_OK;
8318 bio_endio(dip->orig_bio);
8324 static inline blk_status_t btrfs_lookup_and_bind_dio_csum(struct inode *inode,
8325 struct btrfs_dio_private *dip,
8329 struct btrfs_io_bio *io_bio = btrfs_io_bio(bio);
8330 struct btrfs_io_bio *orig_io_bio = btrfs_io_bio(dip->orig_bio);
8334 * We load all the csum data we need when we submit
8335 * the first bio to reduce the csum tree search and
8338 if (dip->logical_offset == file_offset) {
8339 ret = btrfs_lookup_bio_sums_dio(inode, dip->orig_bio,
8345 if (bio == dip->orig_bio)
8348 file_offset -= dip->logical_offset;
8349 file_offset >>= inode->i_sb->s_blocksize_bits;
8350 io_bio->csum = (u8 *)(((u32 *)orig_io_bio->csum) + file_offset);
8355 static inline blk_status_t
8356 __btrfs_submit_dio_bio(struct bio *bio, struct inode *inode, u64 file_offset,
8359 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
8360 struct btrfs_dio_private *dip = bio->bi_private;
8361 bool write = bio_op(bio) == REQ_OP_WRITE;
8364 /* Check btrfs_submit_bio_hook() for rules about async submit. */
8366 async_submit = !atomic_read(&BTRFS_I(inode)->sync_writers);
8369 ret = btrfs_bio_wq_end_io(fs_info, bio, BTRFS_WQ_ENDIO_DATA);
8374 if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)
8377 if (write && async_submit) {
8378 ret = btrfs_wq_submit_bio(fs_info, bio, 0, 0,
8380 __btrfs_submit_bio_start_direct_io,
8381 __btrfs_submit_bio_done);
8385 * If we aren't doing async submit, calculate the csum of the
8388 ret = btrfs_csum_one_bio(inode, bio, file_offset, 1);
8392 ret = btrfs_lookup_and_bind_dio_csum(inode, dip, bio,
8398 ret = btrfs_map_bio(fs_info, bio, 0, 0);
8403 static int btrfs_submit_direct_hook(struct btrfs_dio_private *dip)
8405 struct inode *inode = dip->inode;
8406 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
8408 struct bio *orig_bio = dip->orig_bio;
8409 u64 start_sector = orig_bio->bi_iter.bi_sector;
8410 u64 file_offset = dip->logical_offset;
8412 int async_submit = 0;
8414 int clone_offset = 0;
8417 blk_status_t status;
8419 map_length = orig_bio->bi_iter.bi_size;
8420 submit_len = map_length;
8421 ret = btrfs_map_block(fs_info, btrfs_op(orig_bio), start_sector << 9,
8422 &map_length, NULL, 0);
8426 if (map_length >= submit_len) {
8428 dip->flags |= BTRFS_DIO_ORIG_BIO_SUBMITTED;
8432 /* async crcs make it difficult to collect full stripe writes. */
8433 if (btrfs_data_alloc_profile(fs_info) & BTRFS_BLOCK_GROUP_RAID56_MASK)
8439 ASSERT(map_length <= INT_MAX);
8440 atomic_inc(&dip->pending_bios);
8442 clone_len = min_t(int, submit_len, map_length);
8445 * This will never fail as it's passing GPF_NOFS and
8446 * the allocation is backed by btrfs_bioset.
8448 bio = btrfs_bio_clone_partial(orig_bio, clone_offset,
8450 bio->bi_private = dip;
8451 bio->bi_end_io = btrfs_end_dio_bio;
8452 btrfs_io_bio(bio)->logical = file_offset;
8454 ASSERT(submit_len >= clone_len);
8455 submit_len -= clone_len;
8456 if (submit_len == 0)
8460 * Increase the count before we submit the bio so we know
8461 * the end IO handler won't happen before we increase the
8462 * count. Otherwise, the dip might get freed before we're
8463 * done setting it up.
8465 atomic_inc(&dip->pending_bios);
8467 status = __btrfs_submit_dio_bio(bio, inode, file_offset,
8471 atomic_dec(&dip->pending_bios);
8475 clone_offset += clone_len;
8476 start_sector += clone_len >> 9;
8477 file_offset += clone_len;
8479 map_length = submit_len;
8480 ret = btrfs_map_block(fs_info, btrfs_op(orig_bio),
8481 start_sector << 9, &map_length, NULL, 0);
8484 } while (submit_len > 0);
8487 status = __btrfs_submit_dio_bio(bio, inode, file_offset, async_submit);
8495 * before atomic variable goto zero, we must
8496 * make sure dip->errors is perceived to be set.
8498 smp_mb__before_atomic();
8499 if (atomic_dec_and_test(&dip->pending_bios))
8500 bio_io_error(dip->orig_bio);
8502 /* bio_end_io() will handle error, so we needn't return it */
8506 static void btrfs_submit_direct(struct bio *dio_bio, struct inode *inode,
8509 struct btrfs_dio_private *dip = NULL;
8510 struct bio *bio = NULL;
8511 struct btrfs_io_bio *io_bio;
8512 bool write = (bio_op(dio_bio) == REQ_OP_WRITE);
8515 bio = btrfs_bio_clone(dio_bio);
8517 dip = kzalloc(sizeof(*dip), GFP_NOFS);
8523 dip->private = dio_bio->bi_private;
8525 dip->logical_offset = file_offset;
8526 dip->bytes = dio_bio->bi_iter.bi_size;
8527 dip->disk_bytenr = (u64)dio_bio->bi_iter.bi_sector << 9;
8528 bio->bi_private = dip;
8529 dip->orig_bio = bio;
8530 dip->dio_bio = dio_bio;
8531 atomic_set(&dip->pending_bios, 0);
8532 io_bio = btrfs_io_bio(bio);
8533 io_bio->logical = file_offset;
8536 bio->bi_end_io = btrfs_endio_direct_write;
8538 bio->bi_end_io = btrfs_endio_direct_read;
8539 dip->subio_endio = btrfs_subio_endio_read;
8543 * Reset the range for unsubmitted ordered extents (to a 0 length range)
8544 * even if we fail to submit a bio, because in such case we do the
8545 * corresponding error handling below and it must not be done a second
8546 * time by btrfs_direct_IO().
8549 struct btrfs_dio_data *dio_data = current->journal_info;
8551 dio_data->unsubmitted_oe_range_end = dip->logical_offset +
8553 dio_data->unsubmitted_oe_range_start =
8554 dio_data->unsubmitted_oe_range_end;
8557 ret = btrfs_submit_direct_hook(dip);
8562 io_bio->end_io(io_bio, ret);
8566 * If we arrived here it means either we failed to submit the dip
8567 * or we either failed to clone the dio_bio or failed to allocate the
8568 * dip. If we cloned the dio_bio and allocated the dip, we can just
8569 * call bio_endio against our io_bio so that we get proper resource
8570 * cleanup if we fail to submit the dip, otherwise, we must do the
8571 * same as btrfs_endio_direct_[write|read] because we can't call these
8572 * callbacks - they require an allocated dip and a clone of dio_bio.
8577 * The end io callbacks free our dip, do the final put on bio
8578 * and all the cleanup and final put for dio_bio (through
8585 __endio_write_update_ordered(inode,
8587 dio_bio->bi_iter.bi_size,
8590 unlock_extent(&BTRFS_I(inode)->io_tree, file_offset,
8591 file_offset + dio_bio->bi_iter.bi_size - 1);
8593 dio_bio->bi_status = BLK_STS_IOERR;
8595 * Releases and cleans up our dio_bio, no need to bio_put()
8596 * nor bio_endio()/bio_io_error() against dio_bio.
8598 dio_end_io(dio_bio);
8605 static ssize_t check_direct_IO(struct btrfs_fs_info *fs_info,
8606 const struct iov_iter *iter, loff_t offset)
8610 unsigned int blocksize_mask = fs_info->sectorsize - 1;
8611 ssize_t retval = -EINVAL;
8613 if (offset & blocksize_mask)
8616 if (iov_iter_alignment(iter) & blocksize_mask)
8619 /* If this is a write we don't need to check anymore */
8620 if (iov_iter_rw(iter) != READ || !iter_is_iovec(iter))
8623 * Check to make sure we don't have duplicate iov_base's in this
8624 * iovec, if so return EINVAL, otherwise we'll get csum errors
8625 * when reading back.
8627 for (seg = 0; seg < iter->nr_segs; seg++) {
8628 for (i = seg + 1; i < iter->nr_segs; i++) {
8629 if (iter->iov[seg].iov_base == iter->iov[i].iov_base)
8638 static ssize_t btrfs_direct_IO(struct kiocb *iocb, struct iov_iter *iter)
8640 struct file *file = iocb->ki_filp;
8641 struct inode *inode = file->f_mapping->host;
8642 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
8643 struct btrfs_dio_data dio_data = { 0 };
8644 struct extent_changeset *data_reserved = NULL;
8645 loff_t offset = iocb->ki_pos;
8649 bool relock = false;
8652 if (check_direct_IO(fs_info, iter, offset))
8655 inode_dio_begin(inode);
8658 * The generic stuff only does filemap_write_and_wait_range, which
8659 * isn't enough if we've written compressed pages to this area, so
8660 * we need to flush the dirty pages again to make absolutely sure
8661 * that any outstanding dirty pages are on disk.
8663 count = iov_iter_count(iter);
8664 if (test_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
8665 &BTRFS_I(inode)->runtime_flags))
8666 filemap_fdatawrite_range(inode->i_mapping, offset,
8667 offset + count - 1);
8669 if (iov_iter_rw(iter) == WRITE) {
8671 * If the write DIO is beyond the EOF, we need update
8672 * the isize, but it is protected by i_mutex. So we can
8673 * not unlock the i_mutex at this case.
8675 if (offset + count <= inode->i_size) {
8676 dio_data.overwrite = 1;
8677 inode_unlock(inode);
8679 } else if (iocb->ki_flags & IOCB_NOWAIT) {
8683 ret = btrfs_delalloc_reserve_space(inode, &data_reserved,
8689 * We need to know how many extents we reserved so that we can
8690 * do the accounting properly if we go over the number we
8691 * originally calculated. Abuse current->journal_info for this.
8693 dio_data.reserve = round_up(count,
8694 fs_info->sectorsize);
8695 dio_data.unsubmitted_oe_range_start = (u64)offset;
8696 dio_data.unsubmitted_oe_range_end = (u64)offset;
8697 current->journal_info = &dio_data;
8698 down_read(&BTRFS_I(inode)->dio_sem);
8699 } else if (test_bit(BTRFS_INODE_READDIO_NEED_LOCK,
8700 &BTRFS_I(inode)->runtime_flags)) {
8701 inode_dio_end(inode);
8702 flags = DIO_LOCKING | DIO_SKIP_HOLES;
8706 ret = __blockdev_direct_IO(iocb, inode,
8707 fs_info->fs_devices->latest_bdev,
8708 iter, btrfs_get_blocks_direct, NULL,
8709 btrfs_submit_direct, flags);
8710 if (iov_iter_rw(iter) == WRITE) {
8711 up_read(&BTRFS_I(inode)->dio_sem);
8712 current->journal_info = NULL;
8713 if (ret < 0 && ret != -EIOCBQUEUED) {
8714 if (dio_data.reserve)
8715 btrfs_delalloc_release_space(inode, data_reserved,
8716 offset, dio_data.reserve);
8718 * On error we might have left some ordered extents
8719 * without submitting corresponding bios for them, so
8720 * cleanup them up to avoid other tasks getting them
8721 * and waiting for them to complete forever.
8723 if (dio_data.unsubmitted_oe_range_start <
8724 dio_data.unsubmitted_oe_range_end)
8725 __endio_write_update_ordered(inode,
8726 dio_data.unsubmitted_oe_range_start,
8727 dio_data.unsubmitted_oe_range_end -
8728 dio_data.unsubmitted_oe_range_start,
8730 } else if (ret >= 0 && (size_t)ret < count)
8731 btrfs_delalloc_release_space(inode, data_reserved,
8732 offset, count - (size_t)ret);
8733 btrfs_delalloc_release_extents(BTRFS_I(inode), count);
8737 inode_dio_end(inode);
8741 extent_changeset_free(data_reserved);
8745 #define BTRFS_FIEMAP_FLAGS (FIEMAP_FLAG_SYNC)
8747 static int btrfs_fiemap(struct inode *inode, struct fiemap_extent_info *fieinfo,
8748 __u64 start, __u64 len)
8752 ret = fiemap_check_flags(fieinfo, BTRFS_FIEMAP_FLAGS);
8756 return extent_fiemap(inode, fieinfo, start, len);
8759 int btrfs_readpage(struct file *file, struct page *page)
8761 struct extent_io_tree *tree;
8762 tree = &BTRFS_I(page->mapping->host)->io_tree;
8763 return extent_read_full_page(tree, page, btrfs_get_extent, 0);
8766 static int btrfs_writepage(struct page *page, struct writeback_control *wbc)
8768 struct inode *inode = page->mapping->host;
8771 if (current->flags & PF_MEMALLOC) {
8772 redirty_page_for_writepage(wbc, page);
8778 * If we are under memory pressure we will call this directly from the
8779 * VM, we need to make sure we have the inode referenced for the ordered
8780 * extent. If not just return like we didn't do anything.
8782 if (!igrab(inode)) {
8783 redirty_page_for_writepage(wbc, page);
8784 return AOP_WRITEPAGE_ACTIVATE;
8786 ret = extent_write_full_page(page, wbc);
8787 btrfs_add_delayed_iput(inode);
8791 static int btrfs_writepages(struct address_space *mapping,
8792 struct writeback_control *wbc)
8794 struct extent_io_tree *tree;
8796 tree = &BTRFS_I(mapping->host)->io_tree;
8797 return extent_writepages(tree, mapping, wbc);
8801 btrfs_readpages(struct file *file, struct address_space *mapping,
8802 struct list_head *pages, unsigned nr_pages)
8804 struct extent_io_tree *tree;
8805 tree = &BTRFS_I(mapping->host)->io_tree;
8806 return extent_readpages(tree, mapping, pages, nr_pages);
8808 static int __btrfs_releasepage(struct page *page, gfp_t gfp_flags)
8810 struct extent_io_tree *tree;
8811 struct extent_map_tree *map;
8814 tree = &BTRFS_I(page->mapping->host)->io_tree;
8815 map = &BTRFS_I(page->mapping->host)->extent_tree;
8816 ret = try_release_extent_mapping(map, tree, page, gfp_flags);
8818 ClearPagePrivate(page);
8819 set_page_private(page, 0);
8825 static int btrfs_releasepage(struct page *page, gfp_t gfp_flags)
8827 if (PageWriteback(page) || PageDirty(page))
8829 return __btrfs_releasepage(page, gfp_flags);
8832 static void btrfs_invalidatepage(struct page *page, unsigned int offset,
8833 unsigned int length)
8835 struct inode *inode = page->mapping->host;
8836 struct extent_io_tree *tree;
8837 struct btrfs_ordered_extent *ordered;
8838 struct extent_state *cached_state = NULL;
8839 u64 page_start = page_offset(page);
8840 u64 page_end = page_start + PAGE_SIZE - 1;
8843 int inode_evicting = inode->i_state & I_FREEING;
8846 * we have the page locked, so new writeback can't start,
8847 * and the dirty bit won't be cleared while we are here.
8849 * Wait for IO on this page so that we can safely clear
8850 * the PagePrivate2 bit and do ordered accounting
8852 wait_on_page_writeback(page);
8854 tree = &BTRFS_I(inode)->io_tree;
8856 btrfs_releasepage(page, GFP_NOFS);
8860 if (!inode_evicting)
8861 lock_extent_bits(tree, page_start, page_end, &cached_state);
8864 ordered = btrfs_lookup_ordered_range(BTRFS_I(inode), start,
8865 page_end - start + 1);
8867 end = min(page_end, ordered->file_offset + ordered->len - 1);
8869 * IO on this page will never be started, so we need
8870 * to account for any ordered extents now
8872 if (!inode_evicting)
8873 clear_extent_bit(tree, start, end,
8874 EXTENT_DIRTY | EXTENT_DELALLOC |
8875 EXTENT_DELALLOC_NEW |
8876 EXTENT_LOCKED | EXTENT_DO_ACCOUNTING |
8877 EXTENT_DEFRAG, 1, 0, &cached_state);
8879 * whoever cleared the private bit is responsible
8880 * for the finish_ordered_io
8882 if (TestClearPagePrivate2(page)) {
8883 struct btrfs_ordered_inode_tree *tree;
8886 tree = &BTRFS_I(inode)->ordered_tree;
8888 spin_lock_irq(&tree->lock);
8889 set_bit(BTRFS_ORDERED_TRUNCATED, &ordered->flags);
8890 new_len = start - ordered->file_offset;
8891 if (new_len < ordered->truncated_len)
8892 ordered->truncated_len = new_len;
8893 spin_unlock_irq(&tree->lock);
8895 if (btrfs_dec_test_ordered_pending(inode, &ordered,
8897 end - start + 1, 1))
8898 btrfs_finish_ordered_io(ordered);
8900 btrfs_put_ordered_extent(ordered);
8901 if (!inode_evicting) {
8902 cached_state = NULL;
8903 lock_extent_bits(tree, start, end,
8908 if (start < page_end)
8913 * Qgroup reserved space handler
8914 * Page here will be either
8915 * 1) Already written to disk
8916 * In this case, its reserved space is released from data rsv map
8917 * and will be freed by delayed_ref handler finally.
8918 * So even we call qgroup_free_data(), it won't decrease reserved
8920 * 2) Not written to disk
8921 * This means the reserved space should be freed here. However,
8922 * if a truncate invalidates the page (by clearing PageDirty)
8923 * and the page is accounted for while allocating extent
8924 * in btrfs_check_data_free_space() we let delayed_ref to
8925 * free the entire extent.
8927 if (PageDirty(page))
8928 btrfs_qgroup_free_data(inode, NULL, page_start, PAGE_SIZE);
8929 if (!inode_evicting) {
8930 clear_extent_bit(tree, page_start, page_end,
8931 EXTENT_LOCKED | EXTENT_DIRTY |
8932 EXTENT_DELALLOC | EXTENT_DELALLOC_NEW |
8933 EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG, 1, 1,
8936 __btrfs_releasepage(page, GFP_NOFS);
8939 ClearPageChecked(page);
8940 if (PagePrivate(page)) {
8941 ClearPagePrivate(page);
8942 set_page_private(page, 0);
8948 * btrfs_page_mkwrite() is not allowed to change the file size as it gets
8949 * called from a page fault handler when a page is first dirtied. Hence we must
8950 * be careful to check for EOF conditions here. We set the page up correctly
8951 * for a written page which means we get ENOSPC checking when writing into
8952 * holes and correct delalloc and unwritten extent mapping on filesystems that
8953 * support these features.
8955 * We are not allowed to take the i_mutex here so we have to play games to
8956 * protect against truncate races as the page could now be beyond EOF. Because
8957 * vmtruncate() writes the inode size before removing pages, once we have the
8958 * page lock we can determine safely if the page is beyond EOF. If it is not
8959 * beyond EOF, then the page is guaranteed safe against truncation until we
8962 int btrfs_page_mkwrite(struct vm_fault *vmf)
8964 struct page *page = vmf->page;
8965 struct inode *inode = file_inode(vmf->vma->vm_file);
8966 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
8967 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
8968 struct btrfs_ordered_extent *ordered;
8969 struct extent_state *cached_state = NULL;
8970 struct extent_changeset *data_reserved = NULL;
8972 unsigned long zero_start;
8981 reserved_space = PAGE_SIZE;
8983 sb_start_pagefault(inode->i_sb);
8984 page_start = page_offset(page);
8985 page_end = page_start + PAGE_SIZE - 1;
8989 * Reserving delalloc space after obtaining the page lock can lead to
8990 * deadlock. For example, if a dirty page is locked by this function
8991 * and the call to btrfs_delalloc_reserve_space() ends up triggering
8992 * dirty page write out, then the btrfs_writepage() function could
8993 * end up waiting indefinitely to get a lock on the page currently
8994 * being processed by btrfs_page_mkwrite() function.
8996 ret = btrfs_delalloc_reserve_space(inode, &data_reserved, page_start,
8999 ret = file_update_time(vmf->vma->vm_file);
9005 else /* -ENOSPC, -EIO, etc */
9006 ret = VM_FAULT_SIGBUS;
9012 ret = VM_FAULT_NOPAGE; /* make the VM retry the fault */
9015 size = i_size_read(inode);
9017 if ((page->mapping != inode->i_mapping) ||
9018 (page_start >= size)) {
9019 /* page got truncated out from underneath us */
9022 wait_on_page_writeback(page);
9024 lock_extent_bits(io_tree, page_start, page_end, &cached_state);
9025 set_page_extent_mapped(page);
9028 * we can't set the delalloc bits if there are pending ordered
9029 * extents. Drop our locks and wait for them to finish
9031 ordered = btrfs_lookup_ordered_range(BTRFS_I(inode), page_start,
9034 unlock_extent_cached(io_tree, page_start, page_end,
9037 btrfs_start_ordered_extent(inode, ordered, 1);
9038 btrfs_put_ordered_extent(ordered);
9042 if (page->index == ((size - 1) >> PAGE_SHIFT)) {
9043 reserved_space = round_up(size - page_start,
9044 fs_info->sectorsize);
9045 if (reserved_space < PAGE_SIZE) {
9046 end = page_start + reserved_space - 1;
9047 btrfs_delalloc_release_space(inode, data_reserved,
9048 page_start, PAGE_SIZE - reserved_space);
9053 * page_mkwrite gets called when the page is firstly dirtied after it's
9054 * faulted in, but write(2) could also dirty a page and set delalloc
9055 * bits, thus in this case for space account reason, we still need to
9056 * clear any delalloc bits within this page range since we have to
9057 * reserve data&meta space before lock_page() (see above comments).
9059 clear_extent_bit(&BTRFS_I(inode)->io_tree, page_start, end,
9060 EXTENT_DIRTY | EXTENT_DELALLOC |
9061 EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG,
9062 0, 0, &cached_state);
9064 ret = btrfs_set_extent_delalloc(inode, page_start, end, 0,
9067 unlock_extent_cached(io_tree, page_start, page_end,
9069 ret = VM_FAULT_SIGBUS;
9074 /* page is wholly or partially inside EOF */
9075 if (page_start + PAGE_SIZE > size)
9076 zero_start = size & ~PAGE_MASK;
9078 zero_start = PAGE_SIZE;
9080 if (zero_start != PAGE_SIZE) {
9082 memset(kaddr + zero_start, 0, PAGE_SIZE - zero_start);
9083 flush_dcache_page(page);
9086 ClearPageChecked(page);
9087 set_page_dirty(page);
9088 SetPageUptodate(page);
9090 BTRFS_I(inode)->last_trans = fs_info->generation;
9091 BTRFS_I(inode)->last_sub_trans = BTRFS_I(inode)->root->log_transid;
9092 BTRFS_I(inode)->last_log_commit = BTRFS_I(inode)->root->last_log_commit;
9094 unlock_extent_cached(io_tree, page_start, page_end, &cached_state);
9098 btrfs_delalloc_release_extents(BTRFS_I(inode), PAGE_SIZE);
9099 sb_end_pagefault(inode->i_sb);
9100 extent_changeset_free(data_reserved);
9101 return VM_FAULT_LOCKED;
9105 btrfs_delalloc_release_extents(BTRFS_I(inode), PAGE_SIZE);
9106 btrfs_delalloc_release_space(inode, data_reserved, page_start,
9109 sb_end_pagefault(inode->i_sb);
9110 extent_changeset_free(data_reserved);
9114 static int btrfs_truncate(struct inode *inode)
9116 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
9117 struct btrfs_root *root = BTRFS_I(inode)->root;
9118 struct btrfs_block_rsv *rsv;
9121 struct btrfs_trans_handle *trans;
9122 u64 mask = fs_info->sectorsize - 1;
9123 u64 min_size = btrfs_calc_trunc_metadata_size(fs_info, 1);
9125 ret = btrfs_wait_ordered_range(inode, inode->i_size & (~mask),
9131 * Yes ladies and gentlemen, this is indeed ugly. The fact is we have
9132 * 3 things going on here
9134 * 1) We need to reserve space for our orphan item and the space to
9135 * delete our orphan item. Lord knows we don't want to have a dangling
9136 * orphan item because we didn't reserve space to remove it.
9138 * 2) We need to reserve space to update our inode.
9140 * 3) We need to have something to cache all the space that is going to
9141 * be free'd up by the truncate operation, but also have some slack
9142 * space reserved in case it uses space during the truncate (thank you
9143 * very much snapshotting).
9145 * And we need these to all be separate. The fact is we can use a lot of
9146 * space doing the truncate, and we have no earthly idea how much space
9147 * we will use, so we need the truncate reservation to be separate so it
9148 * doesn't end up using space reserved for updating the inode or
9149 * removing the orphan item. We also need to be able to stop the
9150 * transaction and start a new one, which means we need to be able to
9151 * update the inode several times, and we have no idea of knowing how
9152 * many times that will be, so we can't just reserve 1 item for the
9153 * entirety of the operation, so that has to be done separately as well.
9154 * Then there is the orphan item, which does indeed need to be held on
9155 * to for the whole operation, and we need nobody to touch this reserved
9156 * space except the orphan code.
9158 * So that leaves us with
9160 * 1) root->orphan_block_rsv - for the orphan deletion.
9161 * 2) rsv - for the truncate reservation, which we will steal from the
9162 * transaction reservation.
9163 * 3) fs_info->trans_block_rsv - this will have 1 items worth left for
9164 * updating the inode.
9166 rsv = btrfs_alloc_block_rsv(fs_info, BTRFS_BLOCK_RSV_TEMP);
9169 rsv->size = min_size;
9173 * 1 for the truncate slack space
9174 * 1 for updating the inode.
9176 trans = btrfs_start_transaction(root, 2);
9177 if (IS_ERR(trans)) {
9178 err = PTR_ERR(trans);
9182 /* Migrate the slack space for the truncate to our reserve */
9183 ret = btrfs_block_rsv_migrate(&fs_info->trans_block_rsv, rsv,
9188 * So if we truncate and then write and fsync we normally would just
9189 * write the extents that changed, which is a problem if we need to
9190 * first truncate that entire inode. So set this flag so we write out
9191 * all of the extents in the inode to the sync log so we're completely
9194 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &BTRFS_I(inode)->runtime_flags);
9195 trans->block_rsv = rsv;
9198 ret = btrfs_truncate_inode_items(trans, root, inode,
9200 BTRFS_EXTENT_DATA_KEY);
9201 trans->block_rsv = &fs_info->trans_block_rsv;
9202 if (ret != -ENOSPC && ret != -EAGAIN) {
9207 ret = btrfs_update_inode(trans, root, inode);
9213 btrfs_end_transaction(trans);
9214 btrfs_btree_balance_dirty(fs_info);
9216 trans = btrfs_start_transaction(root, 2);
9217 if (IS_ERR(trans)) {
9218 ret = err = PTR_ERR(trans);
9223 btrfs_block_rsv_release(fs_info, rsv, -1);
9224 ret = btrfs_block_rsv_migrate(&fs_info->trans_block_rsv,
9226 BUG_ON(ret); /* shouldn't happen */
9227 trans->block_rsv = rsv;
9231 * We can't call btrfs_truncate_block inside a trans handle as we could
9232 * deadlock with freeze, if we got NEED_TRUNCATE_BLOCK then we know
9233 * we've truncated everything except the last little bit, and can do
9234 * btrfs_truncate_block and then update the disk_i_size.
9236 if (ret == NEED_TRUNCATE_BLOCK) {
9237 btrfs_end_transaction(trans);
9238 btrfs_btree_balance_dirty(fs_info);
9240 ret = btrfs_truncate_block(inode, inode->i_size, 0, 0);
9243 trans = btrfs_start_transaction(root, 1);
9244 if (IS_ERR(trans)) {
9245 ret = PTR_ERR(trans);
9248 btrfs_ordered_update_i_size(inode, inode->i_size, NULL);
9251 if (ret == 0 && inode->i_nlink > 0) {
9252 trans->block_rsv = root->orphan_block_rsv;
9253 ret = btrfs_orphan_del(trans, BTRFS_I(inode));
9259 trans->block_rsv = &fs_info->trans_block_rsv;
9260 ret = btrfs_update_inode(trans, root, inode);
9264 ret = btrfs_end_transaction(trans);
9265 btrfs_btree_balance_dirty(fs_info);
9268 btrfs_free_block_rsv(fs_info, rsv);
9277 * create a new subvolume directory/inode (helper for the ioctl).
9279 int btrfs_create_subvol_root(struct btrfs_trans_handle *trans,
9280 struct btrfs_root *new_root,
9281 struct btrfs_root *parent_root,
9284 struct inode *inode;
9288 inode = btrfs_new_inode(trans, new_root, NULL, "..", 2,
9289 new_dirid, new_dirid,
9290 S_IFDIR | (~current_umask() & S_IRWXUGO),
9293 return PTR_ERR(inode);
9294 inode->i_op = &btrfs_dir_inode_operations;
9295 inode->i_fop = &btrfs_dir_file_operations;
9297 set_nlink(inode, 1);
9298 btrfs_i_size_write(BTRFS_I(inode), 0);
9299 unlock_new_inode(inode);
9301 err = btrfs_subvol_inherit_props(trans, new_root, parent_root);
9303 btrfs_err(new_root->fs_info,
9304 "error inheriting subvolume %llu properties: %d",
9305 new_root->root_key.objectid, err);
9307 err = btrfs_update_inode(trans, new_root, inode);
9313 struct inode *btrfs_alloc_inode(struct super_block *sb)
9315 struct btrfs_fs_info *fs_info = btrfs_sb(sb);
9316 struct btrfs_inode *ei;
9317 struct inode *inode;
9319 ei = kmem_cache_alloc(btrfs_inode_cachep, GFP_KERNEL);
9326 ei->last_sub_trans = 0;
9327 ei->logged_trans = 0;
9328 ei->delalloc_bytes = 0;
9329 ei->new_delalloc_bytes = 0;
9330 ei->defrag_bytes = 0;
9331 ei->disk_i_size = 0;
9334 ei->index_cnt = (u64)-1;
9336 ei->last_unlink_trans = 0;
9337 ei->last_log_commit = 0;
9338 ei->delayed_iput_count = 0;
9340 spin_lock_init(&ei->lock);
9341 ei->outstanding_extents = 0;
9342 if (sb->s_magic != BTRFS_TEST_MAGIC)
9343 btrfs_init_metadata_block_rsv(fs_info, &ei->block_rsv,
9344 BTRFS_BLOCK_RSV_DELALLOC);
9345 ei->runtime_flags = 0;
9346 ei->prop_compress = BTRFS_COMPRESS_NONE;
9347 ei->defrag_compress = BTRFS_COMPRESS_NONE;
9349 ei->delayed_node = NULL;
9351 ei->i_otime.tv_sec = 0;
9352 ei->i_otime.tv_nsec = 0;
9354 inode = &ei->vfs_inode;
9355 extent_map_tree_init(&ei->extent_tree);
9356 extent_io_tree_init(&ei->io_tree, inode);
9357 extent_io_tree_init(&ei->io_failure_tree, inode);
9358 ei->io_tree.track_uptodate = 1;
9359 ei->io_failure_tree.track_uptodate = 1;
9360 atomic_set(&ei->sync_writers, 0);
9361 mutex_init(&ei->log_mutex);
9362 mutex_init(&ei->delalloc_mutex);
9363 btrfs_ordered_inode_tree_init(&ei->ordered_tree);
9364 INIT_LIST_HEAD(&ei->delalloc_inodes);
9365 INIT_LIST_HEAD(&ei->delayed_iput);
9366 RB_CLEAR_NODE(&ei->rb_node);
9367 init_rwsem(&ei->dio_sem);
9372 #ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
9373 void btrfs_test_destroy_inode(struct inode *inode)
9375 btrfs_drop_extent_cache(BTRFS_I(inode), 0, (u64)-1, 0);
9376 kmem_cache_free(btrfs_inode_cachep, BTRFS_I(inode));
9380 static void btrfs_i_callback(struct rcu_head *head)
9382 struct inode *inode = container_of(head, struct inode, i_rcu);
9383 kmem_cache_free(btrfs_inode_cachep, BTRFS_I(inode));
9386 void btrfs_destroy_inode(struct inode *inode)
9388 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
9389 struct btrfs_ordered_extent *ordered;
9390 struct btrfs_root *root = BTRFS_I(inode)->root;
9392 WARN_ON(!hlist_empty(&inode->i_dentry));
9393 WARN_ON(inode->i_data.nrpages);
9394 WARN_ON(BTRFS_I(inode)->block_rsv.reserved);
9395 WARN_ON(BTRFS_I(inode)->block_rsv.size);
9396 WARN_ON(BTRFS_I(inode)->outstanding_extents);
9397 WARN_ON(BTRFS_I(inode)->delalloc_bytes);
9398 WARN_ON(BTRFS_I(inode)->new_delalloc_bytes);
9399 WARN_ON(BTRFS_I(inode)->csum_bytes);
9400 WARN_ON(BTRFS_I(inode)->defrag_bytes);
9403 * This can happen where we create an inode, but somebody else also
9404 * created the same inode and we need to destroy the one we already
9410 if (test_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
9411 &BTRFS_I(inode)->runtime_flags)) {
9412 btrfs_info(fs_info, "inode %llu still on the orphan list",
9413 btrfs_ino(BTRFS_I(inode)));
9414 atomic_dec(&root->orphan_inodes);
9418 ordered = btrfs_lookup_first_ordered_extent(inode, (u64)-1);
9423 "found ordered extent %llu %llu on inode cleanup",
9424 ordered->file_offset, ordered->len);
9425 btrfs_remove_ordered_extent(inode, ordered);
9426 btrfs_put_ordered_extent(ordered);
9427 btrfs_put_ordered_extent(ordered);
9430 btrfs_qgroup_check_reserved_leak(inode);
9431 inode_tree_del(inode);
9432 btrfs_drop_extent_cache(BTRFS_I(inode), 0, (u64)-1, 0);
9434 call_rcu(&inode->i_rcu, btrfs_i_callback);
9437 int btrfs_drop_inode(struct inode *inode)
9439 struct btrfs_root *root = BTRFS_I(inode)->root;
9444 /* the snap/subvol tree is on deleting */
9445 if (btrfs_root_refs(&root->root_item) == 0)
9448 return generic_drop_inode(inode);
9451 static void init_once(void *foo)
9453 struct btrfs_inode *ei = (struct btrfs_inode *) foo;
9455 inode_init_once(&ei->vfs_inode);
9458 void btrfs_destroy_cachep(void)
9461 * Make sure all delayed rcu free inodes are flushed before we
9465 kmem_cache_destroy(btrfs_inode_cachep);
9466 kmem_cache_destroy(btrfs_trans_handle_cachep);
9467 kmem_cache_destroy(btrfs_path_cachep);
9468 kmem_cache_destroy(btrfs_free_space_cachep);
9471 int __init btrfs_init_cachep(void)
9473 btrfs_inode_cachep = kmem_cache_create("btrfs_inode",
9474 sizeof(struct btrfs_inode), 0,
9475 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD | SLAB_ACCOUNT,
9477 if (!btrfs_inode_cachep)
9480 btrfs_trans_handle_cachep = kmem_cache_create("btrfs_trans_handle",
9481 sizeof(struct btrfs_trans_handle), 0,
9482 SLAB_TEMPORARY | SLAB_MEM_SPREAD, NULL);
9483 if (!btrfs_trans_handle_cachep)
9486 btrfs_path_cachep = kmem_cache_create("btrfs_path",
9487 sizeof(struct btrfs_path), 0,
9488 SLAB_MEM_SPREAD, NULL);
9489 if (!btrfs_path_cachep)
9492 btrfs_free_space_cachep = kmem_cache_create("btrfs_free_space",
9493 sizeof(struct btrfs_free_space), 0,
9494 SLAB_MEM_SPREAD, NULL);
9495 if (!btrfs_free_space_cachep)
9500 btrfs_destroy_cachep();
9504 static int btrfs_getattr(const struct path *path, struct kstat *stat,
9505 u32 request_mask, unsigned int flags)
9508 struct inode *inode = d_inode(path->dentry);
9509 u32 blocksize = inode->i_sb->s_blocksize;
9510 u32 bi_flags = BTRFS_I(inode)->flags;
9512 stat->result_mask |= STATX_BTIME;
9513 stat->btime.tv_sec = BTRFS_I(inode)->i_otime.tv_sec;
9514 stat->btime.tv_nsec = BTRFS_I(inode)->i_otime.tv_nsec;
9515 if (bi_flags & BTRFS_INODE_APPEND)
9516 stat->attributes |= STATX_ATTR_APPEND;
9517 if (bi_flags & BTRFS_INODE_COMPRESS)
9518 stat->attributes |= STATX_ATTR_COMPRESSED;
9519 if (bi_flags & BTRFS_INODE_IMMUTABLE)
9520 stat->attributes |= STATX_ATTR_IMMUTABLE;
9521 if (bi_flags & BTRFS_INODE_NODUMP)
9522 stat->attributes |= STATX_ATTR_NODUMP;
9524 stat->attributes_mask |= (STATX_ATTR_APPEND |
9525 STATX_ATTR_COMPRESSED |
9526 STATX_ATTR_IMMUTABLE |
9529 generic_fillattr(inode, stat);
9530 stat->dev = BTRFS_I(inode)->root->anon_dev;
9532 spin_lock(&BTRFS_I(inode)->lock);
9533 delalloc_bytes = BTRFS_I(inode)->new_delalloc_bytes;
9534 spin_unlock(&BTRFS_I(inode)->lock);
9535 stat->blocks = (ALIGN(inode_get_bytes(inode), blocksize) +
9536 ALIGN(delalloc_bytes, blocksize)) >> 9;
9540 static int btrfs_rename_exchange(struct inode *old_dir,
9541 struct dentry *old_dentry,
9542 struct inode *new_dir,
9543 struct dentry *new_dentry)
9545 struct btrfs_fs_info *fs_info = btrfs_sb(old_dir->i_sb);
9546 struct btrfs_trans_handle *trans;
9547 struct btrfs_root *root = BTRFS_I(old_dir)->root;
9548 struct btrfs_root *dest = BTRFS_I(new_dir)->root;
9549 struct inode *new_inode = new_dentry->d_inode;
9550 struct inode *old_inode = old_dentry->d_inode;
9551 struct timespec ctime = current_time(old_inode);
9552 struct dentry *parent;
9553 u64 old_ino = btrfs_ino(BTRFS_I(old_inode));
9554 u64 new_ino = btrfs_ino(BTRFS_I(new_inode));
9559 bool root_log_pinned = false;
9560 bool dest_log_pinned = false;
9562 /* we only allow rename subvolume link between subvolumes */
9563 if (old_ino != BTRFS_FIRST_FREE_OBJECTID && root != dest)
9566 /* close the race window with snapshot create/destroy ioctl */
9567 if (old_ino == BTRFS_FIRST_FREE_OBJECTID)
9568 down_read(&fs_info->subvol_sem);
9569 if (new_ino == BTRFS_FIRST_FREE_OBJECTID)
9570 down_read(&fs_info->subvol_sem);
9573 * We want to reserve the absolute worst case amount of items. So if
9574 * both inodes are subvols and we need to unlink them then that would
9575 * require 4 item modifications, but if they are both normal inodes it
9576 * would require 5 item modifications, so we'll assume their normal
9577 * inodes. So 5 * 2 is 10, plus 2 for the new links, so 12 total items
9578 * should cover the worst case number of items we'll modify.
9580 trans = btrfs_start_transaction(root, 12);
9581 if (IS_ERR(trans)) {
9582 ret = PTR_ERR(trans);
9587 * We need to find a free sequence number both in the source and
9588 * in the destination directory for the exchange.
9590 ret = btrfs_set_inode_index(BTRFS_I(new_dir), &old_idx);
9593 ret = btrfs_set_inode_index(BTRFS_I(old_dir), &new_idx);
9597 BTRFS_I(old_inode)->dir_index = 0ULL;
9598 BTRFS_I(new_inode)->dir_index = 0ULL;
9600 /* Reference for the source. */
9601 if (old_ino == BTRFS_FIRST_FREE_OBJECTID) {
9602 /* force full log commit if subvolume involved. */
9603 btrfs_set_log_full_commit(fs_info, trans);
9605 btrfs_pin_log_trans(root);
9606 root_log_pinned = true;
9607 ret = btrfs_insert_inode_ref(trans, dest,
9608 new_dentry->d_name.name,
9609 new_dentry->d_name.len,
9611 btrfs_ino(BTRFS_I(new_dir)),
9617 /* And now for the dest. */
9618 if (new_ino == BTRFS_FIRST_FREE_OBJECTID) {
9619 /* force full log commit if subvolume involved. */
9620 btrfs_set_log_full_commit(fs_info, trans);
9622 btrfs_pin_log_trans(dest);
9623 dest_log_pinned = true;
9624 ret = btrfs_insert_inode_ref(trans, root,
9625 old_dentry->d_name.name,
9626 old_dentry->d_name.len,
9628 btrfs_ino(BTRFS_I(old_dir)),
9634 /* Update inode version and ctime/mtime. */
9635 inode_inc_iversion(old_dir);
9636 inode_inc_iversion(new_dir);
9637 inode_inc_iversion(old_inode);
9638 inode_inc_iversion(new_inode);
9639 old_dir->i_ctime = old_dir->i_mtime = ctime;
9640 new_dir->i_ctime = new_dir->i_mtime = ctime;
9641 old_inode->i_ctime = ctime;
9642 new_inode->i_ctime = ctime;
9644 if (old_dentry->d_parent != new_dentry->d_parent) {
9645 btrfs_record_unlink_dir(trans, BTRFS_I(old_dir),
9646 BTRFS_I(old_inode), 1);
9647 btrfs_record_unlink_dir(trans, BTRFS_I(new_dir),
9648 BTRFS_I(new_inode), 1);
9651 /* src is a subvolume */
9652 if (old_ino == BTRFS_FIRST_FREE_OBJECTID) {
9653 root_objectid = BTRFS_I(old_inode)->root->root_key.objectid;
9654 ret = btrfs_unlink_subvol(trans, root, old_dir,
9656 old_dentry->d_name.name,
9657 old_dentry->d_name.len);
9658 } else { /* src is an inode */
9659 ret = __btrfs_unlink_inode(trans, root, BTRFS_I(old_dir),
9660 BTRFS_I(old_dentry->d_inode),
9661 old_dentry->d_name.name,
9662 old_dentry->d_name.len);
9664 ret = btrfs_update_inode(trans, root, old_inode);
9667 btrfs_abort_transaction(trans, ret);
9671 /* dest is a subvolume */
9672 if (new_ino == BTRFS_FIRST_FREE_OBJECTID) {
9673 root_objectid = BTRFS_I(new_inode)->root->root_key.objectid;
9674 ret = btrfs_unlink_subvol(trans, dest, new_dir,
9676 new_dentry->d_name.name,
9677 new_dentry->d_name.len);
9678 } else { /* dest is an inode */
9679 ret = __btrfs_unlink_inode(trans, dest, BTRFS_I(new_dir),
9680 BTRFS_I(new_dentry->d_inode),
9681 new_dentry->d_name.name,
9682 new_dentry->d_name.len);
9684 ret = btrfs_update_inode(trans, dest, new_inode);
9687 btrfs_abort_transaction(trans, ret);
9691 ret = btrfs_add_link(trans, BTRFS_I(new_dir), BTRFS_I(old_inode),
9692 new_dentry->d_name.name,
9693 new_dentry->d_name.len, 0, old_idx);
9695 btrfs_abort_transaction(trans, ret);
9699 ret = btrfs_add_link(trans, BTRFS_I(old_dir), BTRFS_I(new_inode),
9700 old_dentry->d_name.name,
9701 old_dentry->d_name.len, 0, new_idx);
9703 btrfs_abort_transaction(trans, ret);
9707 if (old_inode->i_nlink == 1)
9708 BTRFS_I(old_inode)->dir_index = old_idx;
9709 if (new_inode->i_nlink == 1)
9710 BTRFS_I(new_inode)->dir_index = new_idx;
9712 if (root_log_pinned) {
9713 parent = new_dentry->d_parent;
9714 btrfs_log_new_name(trans, BTRFS_I(old_inode), BTRFS_I(old_dir),
9716 btrfs_end_log_trans(root);
9717 root_log_pinned = false;
9719 if (dest_log_pinned) {
9720 parent = old_dentry->d_parent;
9721 btrfs_log_new_name(trans, BTRFS_I(new_inode), BTRFS_I(new_dir),
9723 btrfs_end_log_trans(dest);
9724 dest_log_pinned = false;
9728 * If we have pinned a log and an error happened, we unpin tasks
9729 * trying to sync the log and force them to fallback to a transaction
9730 * commit if the log currently contains any of the inodes involved in
9731 * this rename operation (to ensure we do not persist a log with an
9732 * inconsistent state for any of these inodes or leading to any
9733 * inconsistencies when replayed). If the transaction was aborted, the
9734 * abortion reason is propagated to userspace when attempting to commit
9735 * the transaction. If the log does not contain any of these inodes, we
9736 * allow the tasks to sync it.
9738 if (ret && (root_log_pinned || dest_log_pinned)) {
9739 if (btrfs_inode_in_log(BTRFS_I(old_dir), fs_info->generation) ||
9740 btrfs_inode_in_log(BTRFS_I(new_dir), fs_info->generation) ||
9741 btrfs_inode_in_log(BTRFS_I(old_inode), fs_info->generation) ||
9743 btrfs_inode_in_log(BTRFS_I(new_inode), fs_info->generation)))
9744 btrfs_set_log_full_commit(fs_info, trans);
9746 if (root_log_pinned) {
9747 btrfs_end_log_trans(root);
9748 root_log_pinned = false;
9750 if (dest_log_pinned) {
9751 btrfs_end_log_trans(dest);
9752 dest_log_pinned = false;
9755 ret = btrfs_end_transaction(trans);
9757 if (new_ino == BTRFS_FIRST_FREE_OBJECTID)
9758 up_read(&fs_info->subvol_sem);
9759 if (old_ino == BTRFS_FIRST_FREE_OBJECTID)
9760 up_read(&fs_info->subvol_sem);
9765 static int btrfs_whiteout_for_rename(struct btrfs_trans_handle *trans,
9766 struct btrfs_root *root,
9768 struct dentry *dentry)
9771 struct inode *inode;
9775 ret = btrfs_find_free_ino(root, &objectid);
9779 inode = btrfs_new_inode(trans, root, dir,
9780 dentry->d_name.name,
9782 btrfs_ino(BTRFS_I(dir)),
9784 S_IFCHR | WHITEOUT_MODE,
9787 if (IS_ERR(inode)) {
9788 ret = PTR_ERR(inode);
9792 inode->i_op = &btrfs_special_inode_operations;
9793 init_special_inode(inode, inode->i_mode,
9796 ret = btrfs_init_inode_security(trans, inode, dir,
9801 ret = btrfs_add_nondir(trans, BTRFS_I(dir), dentry,
9802 BTRFS_I(inode), 0, index);
9806 ret = btrfs_update_inode(trans, root, inode);
9808 unlock_new_inode(inode);
9810 inode_dec_link_count(inode);
9816 static int btrfs_rename(struct inode *old_dir, struct dentry *old_dentry,
9817 struct inode *new_dir, struct dentry *new_dentry,
9820 struct btrfs_fs_info *fs_info = btrfs_sb(old_dir->i_sb);
9821 struct btrfs_trans_handle *trans;
9822 unsigned int trans_num_items;
9823 struct btrfs_root *root = BTRFS_I(old_dir)->root;
9824 struct btrfs_root *dest = BTRFS_I(new_dir)->root;
9825 struct inode *new_inode = d_inode(new_dentry);
9826 struct inode *old_inode = d_inode(old_dentry);
9830 u64 old_ino = btrfs_ino(BTRFS_I(old_inode));
9831 bool log_pinned = false;
9833 if (btrfs_ino(BTRFS_I(new_dir)) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)
9836 /* we only allow rename subvolume link between subvolumes */
9837 if (old_ino != BTRFS_FIRST_FREE_OBJECTID && root != dest)
9840 if (old_ino == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID ||
9841 (new_inode && btrfs_ino(BTRFS_I(new_inode)) == BTRFS_FIRST_FREE_OBJECTID))
9844 if (S_ISDIR(old_inode->i_mode) && new_inode &&
9845 new_inode->i_size > BTRFS_EMPTY_DIR_SIZE)
9849 /* check for collisions, even if the name isn't there */
9850 ret = btrfs_check_dir_item_collision(dest, new_dir->i_ino,
9851 new_dentry->d_name.name,
9852 new_dentry->d_name.len);
9855 if (ret == -EEXIST) {
9857 * eexist without a new_inode */
9858 if (WARN_ON(!new_inode)) {
9862 /* maybe -EOVERFLOW */
9869 * we're using rename to replace one file with another. Start IO on it
9870 * now so we don't add too much work to the end of the transaction
9872 if (new_inode && S_ISREG(old_inode->i_mode) && new_inode->i_size)
9873 filemap_flush(old_inode->i_mapping);
9875 /* close the racy window with snapshot create/destroy ioctl */
9876 if (old_ino == BTRFS_FIRST_FREE_OBJECTID)
9877 down_read(&fs_info->subvol_sem);
9879 * We want to reserve the absolute worst case amount of items. So if
9880 * both inodes are subvols and we need to unlink them then that would
9881 * require 4 item modifications, but if they are both normal inodes it
9882 * would require 5 item modifications, so we'll assume they are normal
9883 * inodes. So 5 * 2 is 10, plus 1 for the new link, so 11 total items
9884 * should cover the worst case number of items we'll modify.
9885 * If our rename has the whiteout flag, we need more 5 units for the
9886 * new inode (1 inode item, 1 inode ref, 2 dir items and 1 xattr item
9887 * when selinux is enabled).
9889 trans_num_items = 11;
9890 if (flags & RENAME_WHITEOUT)
9891 trans_num_items += 5;
9892 trans = btrfs_start_transaction(root, trans_num_items);
9893 if (IS_ERR(trans)) {
9894 ret = PTR_ERR(trans);
9899 btrfs_record_root_in_trans(trans, dest);
9901 ret = btrfs_set_inode_index(BTRFS_I(new_dir), &index);
9905 BTRFS_I(old_inode)->dir_index = 0ULL;
9906 if (unlikely(old_ino == BTRFS_FIRST_FREE_OBJECTID)) {
9907 /* force full log commit if subvolume involved. */
9908 btrfs_set_log_full_commit(fs_info, trans);
9910 btrfs_pin_log_trans(root);
9912 ret = btrfs_insert_inode_ref(trans, dest,
9913 new_dentry->d_name.name,
9914 new_dentry->d_name.len,
9916 btrfs_ino(BTRFS_I(new_dir)), index);
9921 inode_inc_iversion(old_dir);
9922 inode_inc_iversion(new_dir);
9923 inode_inc_iversion(old_inode);
9924 old_dir->i_ctime = old_dir->i_mtime =
9925 new_dir->i_ctime = new_dir->i_mtime =
9926 old_inode->i_ctime = current_time(old_dir);
9928 if (old_dentry->d_parent != new_dentry->d_parent)
9929 btrfs_record_unlink_dir(trans, BTRFS_I(old_dir),
9930 BTRFS_I(old_inode), 1);
9932 if (unlikely(old_ino == BTRFS_FIRST_FREE_OBJECTID)) {
9933 root_objectid = BTRFS_I(old_inode)->root->root_key.objectid;
9934 ret = btrfs_unlink_subvol(trans, root, old_dir, root_objectid,
9935 old_dentry->d_name.name,
9936 old_dentry->d_name.len);
9938 ret = __btrfs_unlink_inode(trans, root, BTRFS_I(old_dir),
9939 BTRFS_I(d_inode(old_dentry)),
9940 old_dentry->d_name.name,
9941 old_dentry->d_name.len);
9943 ret = btrfs_update_inode(trans, root, old_inode);
9946 btrfs_abort_transaction(trans, ret);
9951 inode_inc_iversion(new_inode);
9952 new_inode->i_ctime = current_time(new_inode);
9953 if (unlikely(btrfs_ino(BTRFS_I(new_inode)) ==
9954 BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)) {
9955 root_objectid = BTRFS_I(new_inode)->location.objectid;
9956 ret = btrfs_unlink_subvol(trans, dest, new_dir,
9958 new_dentry->d_name.name,
9959 new_dentry->d_name.len);
9960 BUG_ON(new_inode->i_nlink == 0);
9962 ret = btrfs_unlink_inode(trans, dest, BTRFS_I(new_dir),
9963 BTRFS_I(d_inode(new_dentry)),
9964 new_dentry->d_name.name,
9965 new_dentry->d_name.len);
9967 if (!ret && new_inode->i_nlink == 0)
9968 ret = btrfs_orphan_add(trans,
9969 BTRFS_I(d_inode(new_dentry)));
9971 btrfs_abort_transaction(trans, ret);
9976 ret = btrfs_add_link(trans, BTRFS_I(new_dir), BTRFS_I(old_inode),
9977 new_dentry->d_name.name,
9978 new_dentry->d_name.len, 0, index);
9980 btrfs_abort_transaction(trans, ret);
9984 if (old_inode->i_nlink == 1)
9985 BTRFS_I(old_inode)->dir_index = index;
9988 struct dentry *parent = new_dentry->d_parent;
9990 btrfs_log_new_name(trans, BTRFS_I(old_inode), BTRFS_I(old_dir),
9992 btrfs_end_log_trans(root);
9996 if (flags & RENAME_WHITEOUT) {
9997 ret = btrfs_whiteout_for_rename(trans, root, old_dir,
10001 btrfs_abort_transaction(trans, ret);
10007 * If we have pinned the log and an error happened, we unpin tasks
10008 * trying to sync the log and force them to fallback to a transaction
10009 * commit if the log currently contains any of the inodes involved in
10010 * this rename operation (to ensure we do not persist a log with an
10011 * inconsistent state for any of these inodes or leading to any
10012 * inconsistencies when replayed). If the transaction was aborted, the
10013 * abortion reason is propagated to userspace when attempting to commit
10014 * the transaction. If the log does not contain any of these inodes, we
10015 * allow the tasks to sync it.
10017 if (ret && log_pinned) {
10018 if (btrfs_inode_in_log(BTRFS_I(old_dir), fs_info->generation) ||
10019 btrfs_inode_in_log(BTRFS_I(new_dir), fs_info->generation) ||
10020 btrfs_inode_in_log(BTRFS_I(old_inode), fs_info->generation) ||
10022 btrfs_inode_in_log(BTRFS_I(new_inode), fs_info->generation)))
10023 btrfs_set_log_full_commit(fs_info, trans);
10025 btrfs_end_log_trans(root);
10026 log_pinned = false;
10028 btrfs_end_transaction(trans);
10030 if (old_ino == BTRFS_FIRST_FREE_OBJECTID)
10031 up_read(&fs_info->subvol_sem);
10036 static int btrfs_rename2(struct inode *old_dir, struct dentry *old_dentry,
10037 struct inode *new_dir, struct dentry *new_dentry,
10038 unsigned int flags)
10040 if (flags & ~(RENAME_NOREPLACE | RENAME_EXCHANGE | RENAME_WHITEOUT))
10043 if (flags & RENAME_EXCHANGE)
10044 return btrfs_rename_exchange(old_dir, old_dentry, new_dir,
10047 return btrfs_rename(old_dir, old_dentry, new_dir, new_dentry, flags);
10050 static void btrfs_run_delalloc_work(struct btrfs_work *work)
10052 struct btrfs_delalloc_work *delalloc_work;
10053 struct inode *inode;
10055 delalloc_work = container_of(work, struct btrfs_delalloc_work,
10057 inode = delalloc_work->inode;
10058 filemap_flush(inode->i_mapping);
10059 if (test_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
10060 &BTRFS_I(inode)->runtime_flags))
10061 filemap_flush(inode->i_mapping);
10063 if (delalloc_work->delay_iput)
10064 btrfs_add_delayed_iput(inode);
10067 complete(&delalloc_work->completion);
10070 struct btrfs_delalloc_work *btrfs_alloc_delalloc_work(struct inode *inode,
10073 struct btrfs_delalloc_work *work;
10075 work = kmalloc(sizeof(*work), GFP_NOFS);
10079 init_completion(&work->completion);
10080 INIT_LIST_HEAD(&work->list);
10081 work->inode = inode;
10082 work->delay_iput = delay_iput;
10083 WARN_ON_ONCE(!inode);
10084 btrfs_init_work(&work->work, btrfs_flush_delalloc_helper,
10085 btrfs_run_delalloc_work, NULL, NULL);
10090 void btrfs_wait_and_free_delalloc_work(struct btrfs_delalloc_work *work)
10092 wait_for_completion(&work->completion);
10097 * some fairly slow code that needs optimization. This walks the list
10098 * of all the inodes with pending delalloc and forces them to disk.
10100 static int __start_delalloc_inodes(struct btrfs_root *root, int delay_iput,
10103 struct btrfs_inode *binode;
10104 struct inode *inode;
10105 struct btrfs_delalloc_work *work, *next;
10106 struct list_head works;
10107 struct list_head splice;
10110 INIT_LIST_HEAD(&works);
10111 INIT_LIST_HEAD(&splice);
10113 mutex_lock(&root->delalloc_mutex);
10114 spin_lock(&root->delalloc_lock);
10115 list_splice_init(&root->delalloc_inodes, &splice);
10116 while (!list_empty(&splice)) {
10117 binode = list_entry(splice.next, struct btrfs_inode,
10120 list_move_tail(&binode->delalloc_inodes,
10121 &root->delalloc_inodes);
10122 inode = igrab(&binode->vfs_inode);
10124 cond_resched_lock(&root->delalloc_lock);
10127 spin_unlock(&root->delalloc_lock);
10129 work = btrfs_alloc_delalloc_work(inode, delay_iput);
10132 btrfs_add_delayed_iput(inode);
10138 list_add_tail(&work->list, &works);
10139 btrfs_queue_work(root->fs_info->flush_workers,
10142 if (nr != -1 && ret >= nr)
10145 spin_lock(&root->delalloc_lock);
10147 spin_unlock(&root->delalloc_lock);
10150 list_for_each_entry_safe(work, next, &works, list) {
10151 list_del_init(&work->list);
10152 btrfs_wait_and_free_delalloc_work(work);
10155 if (!list_empty_careful(&splice)) {
10156 spin_lock(&root->delalloc_lock);
10157 list_splice_tail(&splice, &root->delalloc_inodes);
10158 spin_unlock(&root->delalloc_lock);
10160 mutex_unlock(&root->delalloc_mutex);
10164 int btrfs_start_delalloc_inodes(struct btrfs_root *root, int delay_iput)
10166 struct btrfs_fs_info *fs_info = root->fs_info;
10169 if (test_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state))
10172 ret = __start_delalloc_inodes(root, delay_iput, -1);
10178 int btrfs_start_delalloc_roots(struct btrfs_fs_info *fs_info, int delay_iput,
10181 struct btrfs_root *root;
10182 struct list_head splice;
10185 if (test_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state))
10188 INIT_LIST_HEAD(&splice);
10190 mutex_lock(&fs_info->delalloc_root_mutex);
10191 spin_lock(&fs_info->delalloc_root_lock);
10192 list_splice_init(&fs_info->delalloc_roots, &splice);
10193 while (!list_empty(&splice) && nr) {
10194 root = list_first_entry(&splice, struct btrfs_root,
10196 root = btrfs_grab_fs_root(root);
10198 list_move_tail(&root->delalloc_root,
10199 &fs_info->delalloc_roots);
10200 spin_unlock(&fs_info->delalloc_root_lock);
10202 ret = __start_delalloc_inodes(root, delay_iput, nr);
10203 btrfs_put_fs_root(root);
10211 spin_lock(&fs_info->delalloc_root_lock);
10213 spin_unlock(&fs_info->delalloc_root_lock);
10217 if (!list_empty_careful(&splice)) {
10218 spin_lock(&fs_info->delalloc_root_lock);
10219 list_splice_tail(&splice, &fs_info->delalloc_roots);
10220 spin_unlock(&fs_info->delalloc_root_lock);
10222 mutex_unlock(&fs_info->delalloc_root_mutex);
10226 static int btrfs_symlink(struct inode *dir, struct dentry *dentry,
10227 const char *symname)
10229 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
10230 struct btrfs_trans_handle *trans;
10231 struct btrfs_root *root = BTRFS_I(dir)->root;
10232 struct btrfs_path *path;
10233 struct btrfs_key key;
10234 struct inode *inode = NULL;
10236 int drop_inode = 0;
10242 struct btrfs_file_extent_item *ei;
10243 struct extent_buffer *leaf;
10245 name_len = strlen(symname);
10246 if (name_len > BTRFS_MAX_INLINE_DATA_SIZE(fs_info))
10247 return -ENAMETOOLONG;
10250 * 2 items for inode item and ref
10251 * 2 items for dir items
10252 * 1 item for updating parent inode item
10253 * 1 item for the inline extent item
10254 * 1 item for xattr if selinux is on
10256 trans = btrfs_start_transaction(root, 7);
10258 return PTR_ERR(trans);
10260 err = btrfs_find_free_ino(root, &objectid);
10264 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
10265 dentry->d_name.len, btrfs_ino(BTRFS_I(dir)),
10266 objectid, S_IFLNK|S_IRWXUGO, &index);
10267 if (IS_ERR(inode)) {
10268 err = PTR_ERR(inode);
10273 * If the active LSM wants to access the inode during
10274 * d_instantiate it needs these. Smack checks to see
10275 * if the filesystem supports xattrs by looking at the
10278 inode->i_fop = &btrfs_file_operations;
10279 inode->i_op = &btrfs_file_inode_operations;
10280 inode->i_mapping->a_ops = &btrfs_aops;
10281 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
10283 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
10285 goto out_unlock_inode;
10287 path = btrfs_alloc_path();
10290 goto out_unlock_inode;
10292 key.objectid = btrfs_ino(BTRFS_I(inode));
10294 key.type = BTRFS_EXTENT_DATA_KEY;
10295 datasize = btrfs_file_extent_calc_inline_size(name_len);
10296 err = btrfs_insert_empty_item(trans, root, path, &key,
10299 btrfs_free_path(path);
10300 goto out_unlock_inode;
10302 leaf = path->nodes[0];
10303 ei = btrfs_item_ptr(leaf, path->slots[0],
10304 struct btrfs_file_extent_item);
10305 btrfs_set_file_extent_generation(leaf, ei, trans->transid);
10306 btrfs_set_file_extent_type(leaf, ei,
10307 BTRFS_FILE_EXTENT_INLINE);
10308 btrfs_set_file_extent_encryption(leaf, ei, 0);
10309 btrfs_set_file_extent_compression(leaf, ei, 0);
10310 btrfs_set_file_extent_other_encoding(leaf, ei, 0);
10311 btrfs_set_file_extent_ram_bytes(leaf, ei, name_len);
10313 ptr = btrfs_file_extent_inline_start(ei);
10314 write_extent_buffer(leaf, symname, ptr, name_len);
10315 btrfs_mark_buffer_dirty(leaf);
10316 btrfs_free_path(path);
10318 inode->i_op = &btrfs_symlink_inode_operations;
10319 inode_nohighmem(inode);
10320 inode->i_mapping->a_ops = &btrfs_symlink_aops;
10321 inode_set_bytes(inode, name_len);
10322 btrfs_i_size_write(BTRFS_I(inode), name_len);
10323 err = btrfs_update_inode(trans, root, inode);
10325 * Last step, add directory indexes for our symlink inode. This is the
10326 * last step to avoid extra cleanup of these indexes if an error happens
10330 err = btrfs_add_nondir(trans, BTRFS_I(dir), dentry,
10331 BTRFS_I(inode), 0, index);
10334 goto out_unlock_inode;
10337 unlock_new_inode(inode);
10338 d_instantiate(dentry, inode);
10341 btrfs_end_transaction(trans);
10343 inode_dec_link_count(inode);
10346 btrfs_btree_balance_dirty(fs_info);
10351 unlock_new_inode(inode);
10355 static int __btrfs_prealloc_file_range(struct inode *inode, int mode,
10356 u64 start, u64 num_bytes, u64 min_size,
10357 loff_t actual_len, u64 *alloc_hint,
10358 struct btrfs_trans_handle *trans)
10360 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
10361 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
10362 struct extent_map *em;
10363 struct btrfs_root *root = BTRFS_I(inode)->root;
10364 struct btrfs_key ins;
10365 u64 cur_offset = start;
10368 u64 last_alloc = (u64)-1;
10370 bool own_trans = true;
10371 u64 end = start + num_bytes - 1;
10375 while (num_bytes > 0) {
10377 trans = btrfs_start_transaction(root, 3);
10378 if (IS_ERR(trans)) {
10379 ret = PTR_ERR(trans);
10384 cur_bytes = min_t(u64, num_bytes, SZ_256M);
10385 cur_bytes = max(cur_bytes, min_size);
10387 * If we are severely fragmented we could end up with really
10388 * small allocations, so if the allocator is returning small
10389 * chunks lets make its job easier by only searching for those
10392 cur_bytes = min(cur_bytes, last_alloc);
10393 ret = btrfs_reserve_extent(root, cur_bytes, cur_bytes,
10394 min_size, 0, *alloc_hint, &ins, 1, 0);
10397 btrfs_end_transaction(trans);
10400 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
10402 last_alloc = ins.offset;
10403 ret = insert_reserved_file_extent(trans, inode,
10404 cur_offset, ins.objectid,
10405 ins.offset, ins.offset,
10406 ins.offset, 0, 0, 0,
10407 BTRFS_FILE_EXTENT_PREALLOC);
10409 btrfs_free_reserved_extent(fs_info, ins.objectid,
10411 btrfs_abort_transaction(trans, ret);
10413 btrfs_end_transaction(trans);
10417 btrfs_drop_extent_cache(BTRFS_I(inode), cur_offset,
10418 cur_offset + ins.offset -1, 0);
10420 em = alloc_extent_map();
10422 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
10423 &BTRFS_I(inode)->runtime_flags);
10427 em->start = cur_offset;
10428 em->orig_start = cur_offset;
10429 em->len = ins.offset;
10430 em->block_start = ins.objectid;
10431 em->block_len = ins.offset;
10432 em->orig_block_len = ins.offset;
10433 em->ram_bytes = ins.offset;
10434 em->bdev = fs_info->fs_devices->latest_bdev;
10435 set_bit(EXTENT_FLAG_PREALLOC, &em->flags);
10436 em->generation = trans->transid;
10439 write_lock(&em_tree->lock);
10440 ret = add_extent_mapping(em_tree, em, 1);
10441 write_unlock(&em_tree->lock);
10442 if (ret != -EEXIST)
10444 btrfs_drop_extent_cache(BTRFS_I(inode), cur_offset,
10445 cur_offset + ins.offset - 1,
10448 free_extent_map(em);
10450 num_bytes -= ins.offset;
10451 cur_offset += ins.offset;
10452 *alloc_hint = ins.objectid + ins.offset;
10454 inode_inc_iversion(inode);
10455 inode->i_ctime = current_time(inode);
10456 BTRFS_I(inode)->flags |= BTRFS_INODE_PREALLOC;
10457 if (!(mode & FALLOC_FL_KEEP_SIZE) &&
10458 (actual_len > inode->i_size) &&
10459 (cur_offset > inode->i_size)) {
10460 if (cur_offset > actual_len)
10461 i_size = actual_len;
10463 i_size = cur_offset;
10464 i_size_write(inode, i_size);
10465 btrfs_ordered_update_i_size(inode, i_size, NULL);
10468 ret = btrfs_update_inode(trans, root, inode);
10471 btrfs_abort_transaction(trans, ret);
10473 btrfs_end_transaction(trans);
10478 btrfs_end_transaction(trans);
10480 if (cur_offset < end)
10481 btrfs_free_reserved_data_space(inode, NULL, cur_offset,
10482 end - cur_offset + 1);
10486 int btrfs_prealloc_file_range(struct inode *inode, int mode,
10487 u64 start, u64 num_bytes, u64 min_size,
10488 loff_t actual_len, u64 *alloc_hint)
10490 return __btrfs_prealloc_file_range(inode, mode, start, num_bytes,
10491 min_size, actual_len, alloc_hint,
10495 int btrfs_prealloc_file_range_trans(struct inode *inode,
10496 struct btrfs_trans_handle *trans, int mode,
10497 u64 start, u64 num_bytes, u64 min_size,
10498 loff_t actual_len, u64 *alloc_hint)
10500 return __btrfs_prealloc_file_range(inode, mode, start, num_bytes,
10501 min_size, actual_len, alloc_hint, trans);
10504 static int btrfs_set_page_dirty(struct page *page)
10506 return __set_page_dirty_nobuffers(page);
10509 static int btrfs_permission(struct inode *inode, int mask)
10511 struct btrfs_root *root = BTRFS_I(inode)->root;
10512 umode_t mode = inode->i_mode;
10514 if (mask & MAY_WRITE &&
10515 (S_ISREG(mode) || S_ISDIR(mode) || S_ISLNK(mode))) {
10516 if (btrfs_root_readonly(root))
10518 if (BTRFS_I(inode)->flags & BTRFS_INODE_READONLY)
10521 return generic_permission(inode, mask);
10524 static int btrfs_tmpfile(struct inode *dir, struct dentry *dentry, umode_t mode)
10526 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
10527 struct btrfs_trans_handle *trans;
10528 struct btrfs_root *root = BTRFS_I(dir)->root;
10529 struct inode *inode = NULL;
10535 * 5 units required for adding orphan entry
10537 trans = btrfs_start_transaction(root, 5);
10539 return PTR_ERR(trans);
10541 ret = btrfs_find_free_ino(root, &objectid);
10545 inode = btrfs_new_inode(trans, root, dir, NULL, 0,
10546 btrfs_ino(BTRFS_I(dir)), objectid, mode, &index);
10547 if (IS_ERR(inode)) {
10548 ret = PTR_ERR(inode);
10553 inode->i_fop = &btrfs_file_operations;
10554 inode->i_op = &btrfs_file_inode_operations;
10556 inode->i_mapping->a_ops = &btrfs_aops;
10557 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
10559 ret = btrfs_init_inode_security(trans, inode, dir, NULL);
10563 ret = btrfs_update_inode(trans, root, inode);
10566 ret = btrfs_orphan_add(trans, BTRFS_I(inode));
10571 * We set number of links to 0 in btrfs_new_inode(), and here we set
10572 * it to 1 because d_tmpfile() will issue a warning if the count is 0,
10575 * d_tmpfile() -> inode_dec_link_count() -> drop_nlink()
10577 set_nlink(inode, 1);
10578 unlock_new_inode(inode);
10579 d_tmpfile(dentry, inode);
10580 mark_inode_dirty(inode);
10583 btrfs_end_transaction(trans);
10586 btrfs_btree_balance_dirty(fs_info);
10590 unlock_new_inode(inode);
10595 __attribute__((const))
10596 static int btrfs_readpage_io_failed_hook(struct page *page, int failed_mirror)
10601 static struct btrfs_fs_info *iotree_fs_info(void *private_data)
10603 struct inode *inode = private_data;
10604 return btrfs_sb(inode->i_sb);
10607 static void btrfs_check_extent_io_range(void *private_data, const char *caller,
10608 u64 start, u64 end)
10610 struct inode *inode = private_data;
10613 isize = i_size_read(inode);
10614 if (end >= PAGE_SIZE && (end % 2) == 0 && end != isize - 1) {
10615 btrfs_debug_rl(BTRFS_I(inode)->root->fs_info,
10616 "%s: ino %llu isize %llu odd range [%llu,%llu]",
10617 caller, btrfs_ino(BTRFS_I(inode)), isize, start, end);
10621 void btrfs_set_range_writeback(void *private_data, u64 start, u64 end)
10623 struct inode *inode = private_data;
10624 unsigned long index = start >> PAGE_SHIFT;
10625 unsigned long end_index = end >> PAGE_SHIFT;
10628 while (index <= end_index) {
10629 page = find_get_page(inode->i_mapping, index);
10630 ASSERT(page); /* Pages should be in the extent_io_tree */
10631 set_page_writeback(page);
10637 static const struct inode_operations btrfs_dir_inode_operations = {
10638 .getattr = btrfs_getattr,
10639 .lookup = btrfs_lookup,
10640 .create = btrfs_create,
10641 .unlink = btrfs_unlink,
10642 .link = btrfs_link,
10643 .mkdir = btrfs_mkdir,
10644 .rmdir = btrfs_rmdir,
10645 .rename = btrfs_rename2,
10646 .symlink = btrfs_symlink,
10647 .setattr = btrfs_setattr,
10648 .mknod = btrfs_mknod,
10649 .listxattr = btrfs_listxattr,
10650 .permission = btrfs_permission,
10651 .get_acl = btrfs_get_acl,
10652 .set_acl = btrfs_set_acl,
10653 .update_time = btrfs_update_time,
10654 .tmpfile = btrfs_tmpfile,
10656 static const struct inode_operations btrfs_dir_ro_inode_operations = {
10657 .lookup = btrfs_lookup,
10658 .permission = btrfs_permission,
10659 .update_time = btrfs_update_time,
10662 static const struct file_operations btrfs_dir_file_operations = {
10663 .llseek = generic_file_llseek,
10664 .read = generic_read_dir,
10665 .iterate_shared = btrfs_real_readdir,
10666 .open = btrfs_opendir,
10667 .unlocked_ioctl = btrfs_ioctl,
10668 #ifdef CONFIG_COMPAT
10669 .compat_ioctl = btrfs_compat_ioctl,
10671 .release = btrfs_release_file,
10672 .fsync = btrfs_sync_file,
10675 static const struct extent_io_ops btrfs_extent_io_ops = {
10676 /* mandatory callbacks */
10677 .submit_bio_hook = btrfs_submit_bio_hook,
10678 .readpage_end_io_hook = btrfs_readpage_end_io_hook,
10679 .merge_bio_hook = btrfs_merge_bio_hook,
10680 .readpage_io_failed_hook = btrfs_readpage_io_failed_hook,
10681 .tree_fs_info = iotree_fs_info,
10682 .set_range_writeback = btrfs_set_range_writeback,
10684 /* optional callbacks */
10685 .fill_delalloc = run_delalloc_range,
10686 .writepage_end_io_hook = btrfs_writepage_end_io_hook,
10687 .writepage_start_hook = btrfs_writepage_start_hook,
10688 .set_bit_hook = btrfs_set_bit_hook,
10689 .clear_bit_hook = btrfs_clear_bit_hook,
10690 .merge_extent_hook = btrfs_merge_extent_hook,
10691 .split_extent_hook = btrfs_split_extent_hook,
10692 .check_extent_io_range = btrfs_check_extent_io_range,
10696 * btrfs doesn't support the bmap operation because swapfiles
10697 * use bmap to make a mapping of extents in the file. They assume
10698 * these extents won't change over the life of the file and they
10699 * use the bmap result to do IO directly to the drive.
10701 * the btrfs bmap call would return logical addresses that aren't
10702 * suitable for IO and they also will change frequently as COW
10703 * operations happen. So, swapfile + btrfs == corruption.
10705 * For now we're avoiding this by dropping bmap.
10707 static const struct address_space_operations btrfs_aops = {
10708 .readpage = btrfs_readpage,
10709 .writepage = btrfs_writepage,
10710 .writepages = btrfs_writepages,
10711 .readpages = btrfs_readpages,
10712 .direct_IO = btrfs_direct_IO,
10713 .invalidatepage = btrfs_invalidatepage,
10714 .releasepage = btrfs_releasepage,
10715 .set_page_dirty = btrfs_set_page_dirty,
10716 .error_remove_page = generic_error_remove_page,
10719 static const struct address_space_operations btrfs_symlink_aops = {
10720 .readpage = btrfs_readpage,
10721 .writepage = btrfs_writepage,
10722 .invalidatepage = btrfs_invalidatepage,
10723 .releasepage = btrfs_releasepage,
10726 static const struct inode_operations btrfs_file_inode_operations = {
10727 .getattr = btrfs_getattr,
10728 .setattr = btrfs_setattr,
10729 .listxattr = btrfs_listxattr,
10730 .permission = btrfs_permission,
10731 .fiemap = btrfs_fiemap,
10732 .get_acl = btrfs_get_acl,
10733 .set_acl = btrfs_set_acl,
10734 .update_time = btrfs_update_time,
10736 static const struct inode_operations btrfs_special_inode_operations = {
10737 .getattr = btrfs_getattr,
10738 .setattr = btrfs_setattr,
10739 .permission = btrfs_permission,
10740 .listxattr = btrfs_listxattr,
10741 .get_acl = btrfs_get_acl,
10742 .set_acl = btrfs_set_acl,
10743 .update_time = btrfs_update_time,
10745 static const struct inode_operations btrfs_symlink_inode_operations = {
10746 .get_link = page_get_link,
10747 .getattr = btrfs_getattr,
10748 .setattr = btrfs_setattr,
10749 .permission = btrfs_permission,
10750 .listxattr = btrfs_listxattr,
10751 .update_time = btrfs_update_time,
10754 const struct dentry_operations btrfs_dentry_operations = {
10755 .d_delete = btrfs_dentry_delete,
10756 .d_release = btrfs_dentry_release,