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;
964 u64 cur_alloc_size = 0;
965 u64 blocksize = fs_info->sectorsize;
966 struct btrfs_key ins;
967 struct extent_map *em;
969 unsigned long page_ops;
970 bool extent_reserved = false;
973 if (btrfs_is_free_space_inode(BTRFS_I(inode))) {
979 num_bytes = ALIGN(end - start + 1, blocksize);
980 num_bytes = max(blocksize, num_bytes);
981 ASSERT(num_bytes <= btrfs_super_total_bytes(fs_info->super_copy));
983 inode_should_defrag(BTRFS_I(inode), start, end, num_bytes, SZ_64K);
986 /* lets try to make an inline extent */
987 ret = cow_file_range_inline(root, inode, start, end, 0,
988 BTRFS_COMPRESS_NONE, NULL);
991 * We use DO_ACCOUNTING here because we need the
992 * delalloc_release_metadata to be run _after_ we drop
993 * our outstanding extent for clearing delalloc for this
996 extent_clear_unlock_delalloc(inode, start, end,
998 EXTENT_LOCKED | EXTENT_DELALLOC |
999 EXTENT_DELALLOC_NEW | EXTENT_DEFRAG |
1000 EXTENT_DO_ACCOUNTING, PAGE_UNLOCK |
1001 PAGE_CLEAR_DIRTY | PAGE_SET_WRITEBACK |
1002 PAGE_END_WRITEBACK);
1003 *nr_written = *nr_written +
1004 (end - start + PAGE_SIZE) / PAGE_SIZE;
1007 } else if (ret < 0) {
1012 alloc_hint = get_extent_allocation_hint(inode, start, num_bytes);
1013 btrfs_drop_extent_cache(BTRFS_I(inode), start,
1014 start + num_bytes - 1, 0);
1016 while (num_bytes > 0) {
1017 cur_alloc_size = num_bytes;
1018 ret = btrfs_reserve_extent(root, cur_alloc_size, cur_alloc_size,
1019 fs_info->sectorsize, 0, alloc_hint,
1023 cur_alloc_size = ins.offset;
1024 extent_reserved = true;
1026 ram_size = ins.offset;
1027 em = create_io_em(inode, start, ins.offset, /* len */
1028 start, /* orig_start */
1029 ins.objectid, /* block_start */
1030 ins.offset, /* block_len */
1031 ins.offset, /* orig_block_len */
1032 ram_size, /* ram_bytes */
1033 BTRFS_COMPRESS_NONE, /* compress_type */
1034 BTRFS_ORDERED_REGULAR /* type */);
1037 free_extent_map(em);
1039 ret = btrfs_add_ordered_extent(inode, start, ins.objectid,
1040 ram_size, cur_alloc_size, 0);
1042 goto out_drop_extent_cache;
1044 if (root->root_key.objectid ==
1045 BTRFS_DATA_RELOC_TREE_OBJECTID) {
1046 ret = btrfs_reloc_clone_csums(inode, start,
1049 * Only drop cache here, and process as normal.
1051 * We must not allow extent_clear_unlock_delalloc()
1052 * at out_unlock label to free meta of this ordered
1053 * extent, as its meta should be freed by
1054 * btrfs_finish_ordered_io().
1056 * So we must continue until @start is increased to
1057 * skip current ordered extent.
1060 btrfs_drop_extent_cache(BTRFS_I(inode), start,
1061 start + ram_size - 1, 0);
1064 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
1066 /* we're not doing compressed IO, don't unlock the first
1067 * page (which the caller expects to stay locked), don't
1068 * clear any dirty bits and don't set any writeback bits
1070 * Do set the Private2 bit so we know this page was properly
1071 * setup for writepage
1073 page_ops = unlock ? PAGE_UNLOCK : 0;
1074 page_ops |= PAGE_SET_PRIVATE2;
1076 extent_clear_unlock_delalloc(inode, start,
1077 start + ram_size - 1,
1078 delalloc_end, locked_page,
1079 EXTENT_LOCKED | EXTENT_DELALLOC,
1081 if (num_bytes < cur_alloc_size)
1084 num_bytes -= cur_alloc_size;
1085 alloc_hint = ins.objectid + ins.offset;
1086 start += cur_alloc_size;
1087 extent_reserved = false;
1090 * btrfs_reloc_clone_csums() error, since start is increased
1091 * extent_clear_unlock_delalloc() at out_unlock label won't
1092 * free metadata of current ordered extent, we're OK to exit.
1100 out_drop_extent_cache:
1101 btrfs_drop_extent_cache(BTRFS_I(inode), start, start + ram_size - 1, 0);
1103 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
1104 btrfs_free_reserved_extent(fs_info, ins.objectid, ins.offset, 1);
1106 clear_bits = EXTENT_LOCKED | EXTENT_DELALLOC | EXTENT_DELALLOC_NEW |
1107 EXTENT_DEFRAG | EXTENT_CLEAR_META_RESV;
1108 page_ops = PAGE_UNLOCK | PAGE_CLEAR_DIRTY | PAGE_SET_WRITEBACK |
1111 * If we reserved an extent for our delalloc range (or a subrange) and
1112 * failed to create the respective ordered extent, then it means that
1113 * when we reserved the extent we decremented the extent's size from
1114 * the data space_info's bytes_may_use counter and incremented the
1115 * space_info's bytes_reserved counter by the same amount. We must make
1116 * sure extent_clear_unlock_delalloc() does not try to decrement again
1117 * the data space_info's bytes_may_use counter, therefore we do not pass
1118 * it the flag EXTENT_CLEAR_DATA_RESV.
1120 if (extent_reserved) {
1121 extent_clear_unlock_delalloc(inode, start,
1122 start + cur_alloc_size,
1123 start + cur_alloc_size,
1127 start += cur_alloc_size;
1131 extent_clear_unlock_delalloc(inode, start, end, delalloc_end,
1133 clear_bits | EXTENT_CLEAR_DATA_RESV,
1139 * work queue call back to started compression on a file and pages
1141 static noinline void async_cow_start(struct btrfs_work *work)
1143 struct async_cow *async_cow;
1145 async_cow = container_of(work, struct async_cow, work);
1147 compress_file_range(async_cow->inode, async_cow->locked_page,
1148 async_cow->start, async_cow->end, async_cow,
1150 if (num_added == 0) {
1151 btrfs_add_delayed_iput(async_cow->inode);
1152 async_cow->inode = NULL;
1157 * work queue call back to submit previously compressed pages
1159 static noinline void async_cow_submit(struct btrfs_work *work)
1161 struct btrfs_fs_info *fs_info;
1162 struct async_cow *async_cow;
1163 struct btrfs_root *root;
1164 unsigned long nr_pages;
1166 async_cow = container_of(work, struct async_cow, work);
1168 root = async_cow->root;
1169 fs_info = root->fs_info;
1170 nr_pages = (async_cow->end - async_cow->start + PAGE_SIZE) >>
1174 * atomic_sub_return implies a barrier for waitqueue_active
1176 if (atomic_sub_return(nr_pages, &fs_info->async_delalloc_pages) <
1178 waitqueue_active(&fs_info->async_submit_wait))
1179 wake_up(&fs_info->async_submit_wait);
1181 if (async_cow->inode)
1182 submit_compressed_extents(async_cow->inode, async_cow);
1185 static noinline void async_cow_free(struct btrfs_work *work)
1187 struct async_cow *async_cow;
1188 async_cow = container_of(work, struct async_cow, work);
1189 if (async_cow->inode)
1190 btrfs_add_delayed_iput(async_cow->inode);
1194 static int cow_file_range_async(struct inode *inode, struct page *locked_page,
1195 u64 start, u64 end, int *page_started,
1196 unsigned long *nr_written,
1197 unsigned int write_flags)
1199 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1200 struct async_cow *async_cow;
1201 struct btrfs_root *root = BTRFS_I(inode)->root;
1202 unsigned long nr_pages;
1205 clear_extent_bit(&BTRFS_I(inode)->io_tree, start, end, EXTENT_LOCKED,
1207 while (start < end) {
1208 async_cow = kmalloc(sizeof(*async_cow), GFP_NOFS);
1209 BUG_ON(!async_cow); /* -ENOMEM */
1210 async_cow->inode = igrab(inode);
1211 async_cow->root = root;
1212 async_cow->locked_page = locked_page;
1213 async_cow->start = start;
1214 async_cow->write_flags = write_flags;
1216 if (BTRFS_I(inode)->flags & BTRFS_INODE_NOCOMPRESS &&
1217 !btrfs_test_opt(fs_info, FORCE_COMPRESS))
1220 cur_end = min(end, start + SZ_512K - 1);
1222 async_cow->end = cur_end;
1223 INIT_LIST_HEAD(&async_cow->extents);
1225 btrfs_init_work(&async_cow->work,
1226 btrfs_delalloc_helper,
1227 async_cow_start, async_cow_submit,
1230 nr_pages = (cur_end - start + PAGE_SIZE) >>
1232 atomic_add(nr_pages, &fs_info->async_delalloc_pages);
1234 btrfs_queue_work(fs_info->delalloc_workers, &async_cow->work);
1236 *nr_written += nr_pages;
1237 start = cur_end + 1;
1243 static noinline int csum_exist_in_range(struct btrfs_fs_info *fs_info,
1244 u64 bytenr, u64 num_bytes)
1247 struct btrfs_ordered_sum *sums;
1250 ret = btrfs_lookup_csums_range(fs_info->csum_root, bytenr,
1251 bytenr + num_bytes - 1, &list, 0);
1252 if (ret == 0 && list_empty(&list))
1255 while (!list_empty(&list)) {
1256 sums = list_entry(list.next, struct btrfs_ordered_sum, list);
1257 list_del(&sums->list);
1264 * when nowcow writeback call back. This checks for snapshots or COW copies
1265 * of the extents that exist in the file, and COWs the file as required.
1267 * If no cow copies or snapshots exist, we write directly to the existing
1270 static noinline int run_delalloc_nocow(struct inode *inode,
1271 struct page *locked_page,
1272 u64 start, u64 end, int *page_started, int force,
1273 unsigned long *nr_written)
1275 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1276 struct btrfs_root *root = BTRFS_I(inode)->root;
1277 struct extent_buffer *leaf;
1278 struct btrfs_path *path;
1279 struct btrfs_file_extent_item *fi;
1280 struct btrfs_key found_key;
1281 struct extent_map *em;
1296 u64 ino = btrfs_ino(BTRFS_I(inode));
1298 path = btrfs_alloc_path();
1300 extent_clear_unlock_delalloc(inode, start, end, end,
1302 EXTENT_LOCKED | EXTENT_DELALLOC |
1303 EXTENT_DO_ACCOUNTING |
1304 EXTENT_DEFRAG, PAGE_UNLOCK |
1306 PAGE_SET_WRITEBACK |
1307 PAGE_END_WRITEBACK);
1311 nolock = btrfs_is_free_space_inode(BTRFS_I(inode));
1313 cow_start = (u64)-1;
1316 ret = btrfs_lookup_file_extent(NULL, root, path, ino,
1320 if (ret > 0 && path->slots[0] > 0 && check_prev) {
1321 leaf = path->nodes[0];
1322 btrfs_item_key_to_cpu(leaf, &found_key,
1323 path->slots[0] - 1);
1324 if (found_key.objectid == ino &&
1325 found_key.type == BTRFS_EXTENT_DATA_KEY)
1330 leaf = path->nodes[0];
1331 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
1332 ret = btrfs_next_leaf(root, path);
1334 if (cow_start != (u64)-1)
1335 cur_offset = cow_start;
1340 leaf = path->nodes[0];
1346 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
1348 if (found_key.objectid > ino)
1350 if (WARN_ON_ONCE(found_key.objectid < ino) ||
1351 found_key.type < BTRFS_EXTENT_DATA_KEY) {
1355 if (found_key.type > BTRFS_EXTENT_DATA_KEY ||
1356 found_key.offset > end)
1359 if (found_key.offset > cur_offset) {
1360 extent_end = found_key.offset;
1365 fi = btrfs_item_ptr(leaf, path->slots[0],
1366 struct btrfs_file_extent_item);
1367 extent_type = btrfs_file_extent_type(leaf, fi);
1369 ram_bytes = btrfs_file_extent_ram_bytes(leaf, fi);
1370 if (extent_type == BTRFS_FILE_EXTENT_REG ||
1371 extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
1372 disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
1373 extent_offset = btrfs_file_extent_offset(leaf, fi);
1374 extent_end = found_key.offset +
1375 btrfs_file_extent_num_bytes(leaf, fi);
1377 btrfs_file_extent_disk_num_bytes(leaf, fi);
1378 if (extent_end <= start) {
1382 if (disk_bytenr == 0)
1384 if (btrfs_file_extent_compression(leaf, fi) ||
1385 btrfs_file_extent_encryption(leaf, fi) ||
1386 btrfs_file_extent_other_encoding(leaf, fi))
1388 if (extent_type == BTRFS_FILE_EXTENT_REG && !force)
1390 if (btrfs_extent_readonly(fs_info, disk_bytenr))
1392 if (btrfs_cross_ref_exist(root, ino,
1394 extent_offset, disk_bytenr))
1396 disk_bytenr += extent_offset;
1397 disk_bytenr += cur_offset - found_key.offset;
1398 num_bytes = min(end + 1, extent_end) - cur_offset;
1400 * if there are pending snapshots for this root,
1401 * we fall into common COW way.
1404 err = btrfs_start_write_no_snapshotting(root);
1409 * force cow if csum exists in the range.
1410 * this ensure that csum for a given extent are
1411 * either valid or do not exist.
1413 if (csum_exist_in_range(fs_info, disk_bytenr,
1416 btrfs_end_write_no_snapshotting(root);
1419 if (!btrfs_inc_nocow_writers(fs_info, disk_bytenr)) {
1421 btrfs_end_write_no_snapshotting(root);
1425 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
1426 extent_end = found_key.offset +
1427 btrfs_file_extent_inline_len(leaf,
1428 path->slots[0], fi);
1429 extent_end = ALIGN(extent_end,
1430 fs_info->sectorsize);
1435 if (extent_end <= start) {
1437 if (!nolock && nocow)
1438 btrfs_end_write_no_snapshotting(root);
1440 btrfs_dec_nocow_writers(fs_info, disk_bytenr);
1444 if (cow_start == (u64)-1)
1445 cow_start = cur_offset;
1446 cur_offset = extent_end;
1447 if (cur_offset > end)
1453 btrfs_release_path(path);
1454 if (cow_start != (u64)-1) {
1455 ret = cow_file_range(inode, locked_page,
1456 cow_start, found_key.offset - 1,
1457 end, page_started, nr_written, 1,
1460 if (!nolock && nocow)
1461 btrfs_end_write_no_snapshotting(root);
1463 btrfs_dec_nocow_writers(fs_info,
1467 cow_start = (u64)-1;
1470 if (extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
1471 u64 orig_start = found_key.offset - extent_offset;
1473 em = create_io_em(inode, cur_offset, num_bytes,
1475 disk_bytenr, /* block_start */
1476 num_bytes, /* block_len */
1477 disk_num_bytes, /* orig_block_len */
1478 ram_bytes, BTRFS_COMPRESS_NONE,
1479 BTRFS_ORDERED_PREALLOC);
1481 if (!nolock && nocow)
1482 btrfs_end_write_no_snapshotting(root);
1484 btrfs_dec_nocow_writers(fs_info,
1489 free_extent_map(em);
1492 if (extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
1493 type = BTRFS_ORDERED_PREALLOC;
1495 type = BTRFS_ORDERED_NOCOW;
1498 ret = btrfs_add_ordered_extent(inode, cur_offset, disk_bytenr,
1499 num_bytes, num_bytes, type);
1501 btrfs_dec_nocow_writers(fs_info, disk_bytenr);
1502 BUG_ON(ret); /* -ENOMEM */
1504 if (root->root_key.objectid ==
1505 BTRFS_DATA_RELOC_TREE_OBJECTID)
1507 * Error handled later, as we must prevent
1508 * extent_clear_unlock_delalloc() in error handler
1509 * from freeing metadata of created ordered extent.
1511 ret = btrfs_reloc_clone_csums(inode, cur_offset,
1514 extent_clear_unlock_delalloc(inode, cur_offset,
1515 cur_offset + num_bytes - 1, end,
1516 locked_page, EXTENT_LOCKED |
1518 EXTENT_CLEAR_DATA_RESV,
1519 PAGE_UNLOCK | PAGE_SET_PRIVATE2);
1521 if (!nolock && nocow)
1522 btrfs_end_write_no_snapshotting(root);
1523 cur_offset = extent_end;
1526 * btrfs_reloc_clone_csums() error, now we're OK to call error
1527 * handler, as metadata for created ordered extent will only
1528 * be freed by btrfs_finish_ordered_io().
1532 if (cur_offset > end)
1535 btrfs_release_path(path);
1537 if (cur_offset <= end && cow_start == (u64)-1) {
1538 cow_start = cur_offset;
1542 if (cow_start != (u64)-1) {
1543 ret = cow_file_range(inode, locked_page, cow_start, end, end,
1544 page_started, nr_written, 1, NULL);
1550 if (ret && cur_offset < end)
1551 extent_clear_unlock_delalloc(inode, cur_offset, end, end,
1552 locked_page, EXTENT_LOCKED |
1553 EXTENT_DELALLOC | EXTENT_DEFRAG |
1554 EXTENT_DO_ACCOUNTING, PAGE_UNLOCK |
1556 PAGE_SET_WRITEBACK |
1557 PAGE_END_WRITEBACK);
1558 btrfs_free_path(path);
1562 static inline int need_force_cow(struct inode *inode, u64 start, u64 end)
1565 if (!(BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW) &&
1566 !(BTRFS_I(inode)->flags & BTRFS_INODE_PREALLOC))
1570 * @defrag_bytes is a hint value, no spinlock held here,
1571 * if is not zero, it means the file is defragging.
1572 * Force cow if given extent needs to be defragged.
1574 if (BTRFS_I(inode)->defrag_bytes &&
1575 test_range_bit(&BTRFS_I(inode)->io_tree, start, end,
1576 EXTENT_DEFRAG, 0, NULL))
1583 * extent_io.c call back to do delayed allocation processing
1585 static int run_delalloc_range(void *private_data, struct page *locked_page,
1586 u64 start, u64 end, int *page_started,
1587 unsigned long *nr_written,
1588 struct writeback_control *wbc)
1590 struct inode *inode = private_data;
1592 int force_cow = need_force_cow(inode, start, end);
1593 unsigned int write_flags = wbc_to_write_flags(wbc);
1595 if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW && !force_cow) {
1596 ret = run_delalloc_nocow(inode, locked_page, start, end,
1597 page_started, 1, nr_written);
1598 } else if (BTRFS_I(inode)->flags & BTRFS_INODE_PREALLOC && !force_cow) {
1599 ret = run_delalloc_nocow(inode, locked_page, start, end,
1600 page_started, 0, nr_written);
1601 } else if (!inode_need_compress(inode, start, end)) {
1602 ret = cow_file_range(inode, locked_page, start, end, end,
1603 page_started, nr_written, 1, NULL);
1605 set_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
1606 &BTRFS_I(inode)->runtime_flags);
1607 ret = cow_file_range_async(inode, locked_page, start, end,
1608 page_started, nr_written,
1612 btrfs_cleanup_ordered_extents(inode, start, end - start + 1);
1616 static void btrfs_split_extent_hook(void *private_data,
1617 struct extent_state *orig, u64 split)
1619 struct inode *inode = private_data;
1622 /* not delalloc, ignore it */
1623 if (!(orig->state & EXTENT_DELALLOC))
1626 size = orig->end - orig->start + 1;
1627 if (size > BTRFS_MAX_EXTENT_SIZE) {
1632 * See the explanation in btrfs_merge_extent_hook, the same
1633 * applies here, just in reverse.
1635 new_size = orig->end - split + 1;
1636 num_extents = count_max_extents(new_size);
1637 new_size = split - orig->start;
1638 num_extents += count_max_extents(new_size);
1639 if (count_max_extents(size) >= num_extents)
1643 spin_lock(&BTRFS_I(inode)->lock);
1644 btrfs_mod_outstanding_extents(BTRFS_I(inode), 1);
1645 spin_unlock(&BTRFS_I(inode)->lock);
1649 * extent_io.c merge_extent_hook, used to track merged delayed allocation
1650 * extents so we can keep track of new extents that are just merged onto old
1651 * extents, such as when we are doing sequential writes, so we can properly
1652 * account for the metadata space we'll need.
1654 static void btrfs_merge_extent_hook(void *private_data,
1655 struct extent_state *new,
1656 struct extent_state *other)
1658 struct inode *inode = private_data;
1659 u64 new_size, old_size;
1662 /* not delalloc, ignore it */
1663 if (!(other->state & EXTENT_DELALLOC))
1666 if (new->start > other->start)
1667 new_size = new->end - other->start + 1;
1669 new_size = other->end - new->start + 1;
1671 /* we're not bigger than the max, unreserve the space and go */
1672 if (new_size <= BTRFS_MAX_EXTENT_SIZE) {
1673 spin_lock(&BTRFS_I(inode)->lock);
1674 btrfs_mod_outstanding_extents(BTRFS_I(inode), -1);
1675 spin_unlock(&BTRFS_I(inode)->lock);
1680 * We have to add up either side to figure out how many extents were
1681 * accounted for before we merged into one big extent. If the number of
1682 * extents we accounted for is <= the amount we need for the new range
1683 * then we can return, otherwise drop. Think of it like this
1687 * So we've grown the extent by a MAX_SIZE extent, this would mean we
1688 * need 2 outstanding extents, on one side we have 1 and the other side
1689 * we have 1 so they are == and we can return. But in this case
1691 * [MAX_SIZE+4k][MAX_SIZE+4k]
1693 * Each range on their own accounts for 2 extents, but merged together
1694 * they are only 3 extents worth of accounting, so we need to drop in
1697 old_size = other->end - other->start + 1;
1698 num_extents = count_max_extents(old_size);
1699 old_size = new->end - new->start + 1;
1700 num_extents += count_max_extents(old_size);
1701 if (count_max_extents(new_size) >= num_extents)
1704 spin_lock(&BTRFS_I(inode)->lock);
1705 btrfs_mod_outstanding_extents(BTRFS_I(inode), -1);
1706 spin_unlock(&BTRFS_I(inode)->lock);
1709 static void btrfs_add_delalloc_inodes(struct btrfs_root *root,
1710 struct inode *inode)
1712 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1714 spin_lock(&root->delalloc_lock);
1715 if (list_empty(&BTRFS_I(inode)->delalloc_inodes)) {
1716 list_add_tail(&BTRFS_I(inode)->delalloc_inodes,
1717 &root->delalloc_inodes);
1718 set_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1719 &BTRFS_I(inode)->runtime_flags);
1720 root->nr_delalloc_inodes++;
1721 if (root->nr_delalloc_inodes == 1) {
1722 spin_lock(&fs_info->delalloc_root_lock);
1723 BUG_ON(!list_empty(&root->delalloc_root));
1724 list_add_tail(&root->delalloc_root,
1725 &fs_info->delalloc_roots);
1726 spin_unlock(&fs_info->delalloc_root_lock);
1729 spin_unlock(&root->delalloc_lock);
1732 static void btrfs_del_delalloc_inode(struct btrfs_root *root,
1733 struct btrfs_inode *inode)
1735 struct btrfs_fs_info *fs_info = btrfs_sb(inode->vfs_inode.i_sb);
1737 spin_lock(&root->delalloc_lock);
1738 if (!list_empty(&inode->delalloc_inodes)) {
1739 list_del_init(&inode->delalloc_inodes);
1740 clear_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1741 &inode->runtime_flags);
1742 root->nr_delalloc_inodes--;
1743 if (!root->nr_delalloc_inodes) {
1744 spin_lock(&fs_info->delalloc_root_lock);
1745 BUG_ON(list_empty(&root->delalloc_root));
1746 list_del_init(&root->delalloc_root);
1747 spin_unlock(&fs_info->delalloc_root_lock);
1750 spin_unlock(&root->delalloc_lock);
1754 * extent_io.c set_bit_hook, used to track delayed allocation
1755 * bytes in this file, and to maintain the list of inodes that
1756 * have pending delalloc work to be done.
1758 static void btrfs_set_bit_hook(void *private_data,
1759 struct extent_state *state, unsigned *bits)
1761 struct inode *inode = private_data;
1763 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1765 if ((*bits & EXTENT_DEFRAG) && !(*bits & EXTENT_DELALLOC))
1768 * set_bit and clear bit hooks normally require _irqsave/restore
1769 * but in this case, we are only testing for the DELALLOC
1770 * bit, which is only set or cleared with irqs on
1772 if (!(state->state & EXTENT_DELALLOC) && (*bits & EXTENT_DELALLOC)) {
1773 struct btrfs_root *root = BTRFS_I(inode)->root;
1774 u64 len = state->end + 1 - state->start;
1775 u32 num_extents = count_max_extents(len);
1776 bool do_list = !btrfs_is_free_space_inode(BTRFS_I(inode));
1778 spin_lock(&BTRFS_I(inode)->lock);
1779 btrfs_mod_outstanding_extents(BTRFS_I(inode), num_extents);
1780 spin_unlock(&BTRFS_I(inode)->lock);
1782 /* For sanity tests */
1783 if (btrfs_is_testing(fs_info))
1786 percpu_counter_add_batch(&fs_info->delalloc_bytes, len,
1787 fs_info->delalloc_batch);
1788 spin_lock(&BTRFS_I(inode)->lock);
1789 BTRFS_I(inode)->delalloc_bytes += len;
1790 if (*bits & EXTENT_DEFRAG)
1791 BTRFS_I(inode)->defrag_bytes += len;
1792 if (do_list && !test_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1793 &BTRFS_I(inode)->runtime_flags))
1794 btrfs_add_delalloc_inodes(root, inode);
1795 spin_unlock(&BTRFS_I(inode)->lock);
1798 if (!(state->state & EXTENT_DELALLOC_NEW) &&
1799 (*bits & EXTENT_DELALLOC_NEW)) {
1800 spin_lock(&BTRFS_I(inode)->lock);
1801 BTRFS_I(inode)->new_delalloc_bytes += state->end + 1 -
1803 spin_unlock(&BTRFS_I(inode)->lock);
1808 * extent_io.c clear_bit_hook, see set_bit_hook for why
1810 static void btrfs_clear_bit_hook(void *private_data,
1811 struct extent_state *state,
1814 struct btrfs_inode *inode = BTRFS_I((struct inode *)private_data);
1815 struct btrfs_fs_info *fs_info = btrfs_sb(inode->vfs_inode.i_sb);
1816 u64 len = state->end + 1 - state->start;
1817 u32 num_extents = count_max_extents(len);
1819 if ((state->state & EXTENT_DEFRAG) && (*bits & EXTENT_DEFRAG)) {
1820 spin_lock(&inode->lock);
1821 inode->defrag_bytes -= len;
1822 spin_unlock(&inode->lock);
1826 * set_bit and clear bit hooks normally require _irqsave/restore
1827 * but in this case, we are only testing for the DELALLOC
1828 * bit, which is only set or cleared with irqs on
1830 if ((state->state & EXTENT_DELALLOC) && (*bits & EXTENT_DELALLOC)) {
1831 struct btrfs_root *root = inode->root;
1832 bool do_list = !btrfs_is_free_space_inode(inode);
1834 spin_lock(&inode->lock);
1835 btrfs_mod_outstanding_extents(inode, -num_extents);
1836 spin_unlock(&inode->lock);
1839 * We don't reserve metadata space for space cache inodes so we
1840 * don't need to call dellalloc_release_metadata if there is an
1843 if (*bits & EXTENT_CLEAR_META_RESV &&
1844 root != fs_info->tree_root)
1845 btrfs_delalloc_release_metadata(inode, len);
1847 /* For sanity tests. */
1848 if (btrfs_is_testing(fs_info))
1851 if (root->root_key.objectid != BTRFS_DATA_RELOC_TREE_OBJECTID &&
1852 do_list && !(state->state & EXTENT_NORESERVE) &&
1853 (*bits & EXTENT_CLEAR_DATA_RESV))
1854 btrfs_free_reserved_data_space_noquota(
1858 percpu_counter_add_batch(&fs_info->delalloc_bytes, -len,
1859 fs_info->delalloc_batch);
1860 spin_lock(&inode->lock);
1861 inode->delalloc_bytes -= len;
1862 if (do_list && inode->delalloc_bytes == 0 &&
1863 test_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1864 &inode->runtime_flags))
1865 btrfs_del_delalloc_inode(root, inode);
1866 spin_unlock(&inode->lock);
1869 if ((state->state & EXTENT_DELALLOC_NEW) &&
1870 (*bits & EXTENT_DELALLOC_NEW)) {
1871 spin_lock(&inode->lock);
1872 ASSERT(inode->new_delalloc_bytes >= len);
1873 inode->new_delalloc_bytes -= len;
1874 spin_unlock(&inode->lock);
1879 * extent_io.c merge_bio_hook, this must check the chunk tree to make sure
1880 * we don't create bios that span stripes or chunks
1882 * return 1 if page cannot be merged to bio
1883 * return 0 if page can be merged to bio
1884 * return error otherwise
1886 int btrfs_merge_bio_hook(struct page *page, unsigned long offset,
1887 size_t size, struct bio *bio,
1888 unsigned long bio_flags)
1890 struct inode *inode = page->mapping->host;
1891 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1892 u64 logical = (u64)bio->bi_iter.bi_sector << 9;
1897 if (bio_flags & EXTENT_BIO_COMPRESSED)
1900 length = bio->bi_iter.bi_size;
1901 map_length = length;
1902 ret = btrfs_map_block(fs_info, btrfs_op(bio), logical, &map_length,
1906 if (map_length < length + size)
1912 * in order to insert checksums into the metadata in large chunks,
1913 * we wait until bio submission time. All the pages in the bio are
1914 * checksummed and sums are attached onto the ordered extent record.
1916 * At IO completion time the cums attached on the ordered extent record
1917 * are inserted into the btree
1919 static blk_status_t __btrfs_submit_bio_start(void *private_data, struct bio *bio,
1920 int mirror_num, unsigned long bio_flags,
1923 struct inode *inode = private_data;
1924 blk_status_t ret = 0;
1926 ret = btrfs_csum_one_bio(inode, bio, 0, 0);
1927 BUG_ON(ret); /* -ENOMEM */
1932 * in order to insert checksums into the metadata in large chunks,
1933 * we wait until bio submission time. All the pages in the bio are
1934 * checksummed and sums are attached onto the ordered extent record.
1936 * At IO completion time the cums attached on the ordered extent record
1937 * are inserted into the btree
1939 static blk_status_t __btrfs_submit_bio_done(void *private_data, struct bio *bio,
1940 int mirror_num, unsigned long bio_flags,
1943 struct inode *inode = private_data;
1944 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1947 ret = btrfs_map_bio(fs_info, bio, mirror_num, 1);
1949 bio->bi_status = ret;
1956 * extent_io.c submission hook. This does the right thing for csum calculation
1957 * on write, or reading the csums from the tree before a read.
1959 * Rules about async/sync submit,
1960 * a) read: sync submit
1962 * b) write without checksum: sync submit
1964 * c) write with checksum:
1965 * c-1) if bio is issued by fsync: sync submit
1966 * (sync_writers != 0)
1968 * c-2) if root is reloc root: sync submit
1969 * (only in case of buffered IO)
1971 * c-3) otherwise: async submit
1973 static blk_status_t btrfs_submit_bio_hook(void *private_data, struct bio *bio,
1974 int mirror_num, unsigned long bio_flags,
1977 struct inode *inode = private_data;
1978 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1979 struct btrfs_root *root = BTRFS_I(inode)->root;
1980 enum btrfs_wq_endio_type metadata = BTRFS_WQ_ENDIO_DATA;
1981 blk_status_t ret = 0;
1983 int async = !atomic_read(&BTRFS_I(inode)->sync_writers);
1985 skip_sum = BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM;
1987 if (btrfs_is_free_space_inode(BTRFS_I(inode)))
1988 metadata = BTRFS_WQ_ENDIO_FREE_SPACE;
1990 if (bio_op(bio) != REQ_OP_WRITE) {
1991 ret = btrfs_bio_wq_end_io(fs_info, bio, metadata);
1995 if (bio_flags & EXTENT_BIO_COMPRESSED) {
1996 ret = btrfs_submit_compressed_read(inode, bio,
2000 } else if (!skip_sum) {
2001 ret = btrfs_lookup_bio_sums(inode, bio, NULL);
2006 } else if (async && !skip_sum) {
2007 /* csum items have already been cloned */
2008 if (root->root_key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID)
2010 /* we're doing a write, do the async checksumming */
2011 ret = btrfs_wq_submit_bio(fs_info, bio, mirror_num, bio_flags,
2013 __btrfs_submit_bio_start,
2014 __btrfs_submit_bio_done);
2016 } else if (!skip_sum) {
2017 ret = btrfs_csum_one_bio(inode, bio, 0, 0);
2023 ret = btrfs_map_bio(fs_info, bio, mirror_num, 0);
2027 bio->bi_status = ret;
2034 * given a list of ordered sums record them in the inode. This happens
2035 * at IO completion time based on sums calculated at bio submission time.
2037 static noinline int add_pending_csums(struct btrfs_trans_handle *trans,
2038 struct inode *inode, struct list_head *list)
2040 struct btrfs_ordered_sum *sum;
2043 list_for_each_entry(sum, list, list) {
2044 trans->adding_csums = true;
2045 ret = btrfs_csum_file_blocks(trans,
2046 BTRFS_I(inode)->root->fs_info->csum_root, sum);
2047 trans->adding_csums = false;
2054 int btrfs_set_extent_delalloc(struct inode *inode, u64 start, u64 end,
2055 unsigned int extra_bits,
2056 struct extent_state **cached_state, int dedupe)
2058 WARN_ON((end & (PAGE_SIZE - 1)) == 0);
2059 return set_extent_delalloc(&BTRFS_I(inode)->io_tree, start, end,
2060 extra_bits, cached_state);
2063 /* see btrfs_writepage_start_hook for details on why this is required */
2064 struct btrfs_writepage_fixup {
2066 struct btrfs_work work;
2069 static void btrfs_writepage_fixup_worker(struct btrfs_work *work)
2071 struct btrfs_writepage_fixup *fixup;
2072 struct btrfs_ordered_extent *ordered;
2073 struct extent_state *cached_state = NULL;
2074 struct extent_changeset *data_reserved = NULL;
2076 struct inode *inode;
2081 fixup = container_of(work, struct btrfs_writepage_fixup, work);
2085 if (!page->mapping || !PageDirty(page) || !PageChecked(page)) {
2086 ClearPageChecked(page);
2090 inode = page->mapping->host;
2091 page_start = page_offset(page);
2092 page_end = page_offset(page) + PAGE_SIZE - 1;
2094 lock_extent_bits(&BTRFS_I(inode)->io_tree, page_start, page_end,
2097 /* already ordered? We're done */
2098 if (PagePrivate2(page))
2101 ordered = btrfs_lookup_ordered_range(BTRFS_I(inode), page_start,
2104 unlock_extent_cached(&BTRFS_I(inode)->io_tree, page_start,
2105 page_end, &cached_state);
2107 btrfs_start_ordered_extent(inode, ordered, 1);
2108 btrfs_put_ordered_extent(ordered);
2112 ret = btrfs_delalloc_reserve_space(inode, &data_reserved, page_start,
2115 mapping_set_error(page->mapping, ret);
2116 end_extent_writepage(page, ret, page_start, page_end);
2117 ClearPageChecked(page);
2121 ret = btrfs_set_extent_delalloc(inode, page_start, page_end, 0,
2124 mapping_set_error(page->mapping, ret);
2125 end_extent_writepage(page, ret, page_start, page_end);
2126 ClearPageChecked(page);
2130 ClearPageChecked(page);
2131 set_page_dirty(page);
2132 btrfs_delalloc_release_extents(BTRFS_I(inode), PAGE_SIZE);
2134 unlock_extent_cached(&BTRFS_I(inode)->io_tree, page_start, page_end,
2140 extent_changeset_free(data_reserved);
2144 * There are a few paths in the higher layers of the kernel that directly
2145 * set the page dirty bit without asking the filesystem if it is a
2146 * good idea. This causes problems because we want to make sure COW
2147 * properly happens and the data=ordered rules are followed.
2149 * In our case any range that doesn't have the ORDERED bit set
2150 * hasn't been properly setup for IO. We kick off an async process
2151 * to fix it up. The async helper will wait for ordered extents, set
2152 * the delalloc bit and make it safe to write the page.
2154 static int btrfs_writepage_start_hook(struct page *page, u64 start, u64 end)
2156 struct inode *inode = page->mapping->host;
2157 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2158 struct btrfs_writepage_fixup *fixup;
2160 /* this page is properly in the ordered list */
2161 if (TestClearPagePrivate2(page))
2164 if (PageChecked(page))
2167 fixup = kzalloc(sizeof(*fixup), GFP_NOFS);
2171 SetPageChecked(page);
2173 btrfs_init_work(&fixup->work, btrfs_fixup_helper,
2174 btrfs_writepage_fixup_worker, NULL, NULL);
2176 btrfs_queue_work(fs_info->fixup_workers, &fixup->work);
2180 static int insert_reserved_file_extent(struct btrfs_trans_handle *trans,
2181 struct inode *inode, u64 file_pos,
2182 u64 disk_bytenr, u64 disk_num_bytes,
2183 u64 num_bytes, u64 ram_bytes,
2184 u8 compression, u8 encryption,
2185 u16 other_encoding, int extent_type)
2187 struct btrfs_root *root = BTRFS_I(inode)->root;
2188 struct btrfs_file_extent_item *fi;
2189 struct btrfs_path *path;
2190 struct extent_buffer *leaf;
2191 struct btrfs_key ins;
2193 int extent_inserted = 0;
2196 path = btrfs_alloc_path();
2201 * we may be replacing one extent in the tree with another.
2202 * The new extent is pinned in the extent map, and we don't want
2203 * to drop it from the cache until it is completely in the btree.
2205 * So, tell btrfs_drop_extents to leave this extent in the cache.
2206 * the caller is expected to unpin it and allow it to be merged
2209 ret = __btrfs_drop_extents(trans, root, inode, path, file_pos,
2210 file_pos + num_bytes, NULL, 0,
2211 1, sizeof(*fi), &extent_inserted);
2215 if (!extent_inserted) {
2216 ins.objectid = btrfs_ino(BTRFS_I(inode));
2217 ins.offset = file_pos;
2218 ins.type = BTRFS_EXTENT_DATA_KEY;
2220 path->leave_spinning = 1;
2221 ret = btrfs_insert_empty_item(trans, root, path, &ins,
2226 leaf = path->nodes[0];
2227 fi = btrfs_item_ptr(leaf, path->slots[0],
2228 struct btrfs_file_extent_item);
2229 btrfs_set_file_extent_generation(leaf, fi, trans->transid);
2230 btrfs_set_file_extent_type(leaf, fi, extent_type);
2231 btrfs_set_file_extent_disk_bytenr(leaf, fi, disk_bytenr);
2232 btrfs_set_file_extent_disk_num_bytes(leaf, fi, disk_num_bytes);
2233 btrfs_set_file_extent_offset(leaf, fi, 0);
2234 btrfs_set_file_extent_num_bytes(leaf, fi, num_bytes);
2235 btrfs_set_file_extent_ram_bytes(leaf, fi, ram_bytes);
2236 btrfs_set_file_extent_compression(leaf, fi, compression);
2237 btrfs_set_file_extent_encryption(leaf, fi, encryption);
2238 btrfs_set_file_extent_other_encoding(leaf, fi, other_encoding);
2240 btrfs_mark_buffer_dirty(leaf);
2241 btrfs_release_path(path);
2243 inode_add_bytes(inode, num_bytes);
2245 ins.objectid = disk_bytenr;
2246 ins.offset = disk_num_bytes;
2247 ins.type = BTRFS_EXTENT_ITEM_KEY;
2250 * Release the reserved range from inode dirty range map, as it is
2251 * already moved into delayed_ref_head
2253 ret = btrfs_qgroup_release_data(inode, file_pos, ram_bytes);
2257 ret = btrfs_alloc_reserved_file_extent(trans, root,
2258 btrfs_ino(BTRFS_I(inode)),
2259 file_pos, qg_released, &ins);
2261 btrfs_free_path(path);
2266 /* snapshot-aware defrag */
2267 struct sa_defrag_extent_backref {
2268 struct rb_node node;
2269 struct old_sa_defrag_extent *old;
2278 struct old_sa_defrag_extent {
2279 struct list_head list;
2280 struct new_sa_defrag_extent *new;
2289 struct new_sa_defrag_extent {
2290 struct rb_root root;
2291 struct list_head head;
2292 struct btrfs_path *path;
2293 struct inode *inode;
2301 static int backref_comp(struct sa_defrag_extent_backref *b1,
2302 struct sa_defrag_extent_backref *b2)
2304 if (b1->root_id < b2->root_id)
2306 else if (b1->root_id > b2->root_id)
2309 if (b1->inum < b2->inum)
2311 else if (b1->inum > b2->inum)
2314 if (b1->file_pos < b2->file_pos)
2316 else if (b1->file_pos > b2->file_pos)
2320 * [------------------------------] ===> (a range of space)
2321 * |<--->| |<---->| =============> (fs/file tree A)
2322 * |<---------------------------->| ===> (fs/file tree B)
2324 * A range of space can refer to two file extents in one tree while
2325 * refer to only one file extent in another tree.
2327 * So we may process a disk offset more than one time(two extents in A)
2328 * and locate at the same extent(one extent in B), then insert two same
2329 * backrefs(both refer to the extent in B).
2334 static void backref_insert(struct rb_root *root,
2335 struct sa_defrag_extent_backref *backref)
2337 struct rb_node **p = &root->rb_node;
2338 struct rb_node *parent = NULL;
2339 struct sa_defrag_extent_backref *entry;
2344 entry = rb_entry(parent, struct sa_defrag_extent_backref, node);
2346 ret = backref_comp(backref, entry);
2350 p = &(*p)->rb_right;
2353 rb_link_node(&backref->node, parent, p);
2354 rb_insert_color(&backref->node, root);
2358 * Note the backref might has changed, and in this case we just return 0.
2360 static noinline int record_one_backref(u64 inum, u64 offset, u64 root_id,
2363 struct btrfs_file_extent_item *extent;
2364 struct old_sa_defrag_extent *old = ctx;
2365 struct new_sa_defrag_extent *new = old->new;
2366 struct btrfs_path *path = new->path;
2367 struct btrfs_key key;
2368 struct btrfs_root *root;
2369 struct sa_defrag_extent_backref *backref;
2370 struct extent_buffer *leaf;
2371 struct inode *inode = new->inode;
2372 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2378 if (BTRFS_I(inode)->root->root_key.objectid == root_id &&
2379 inum == btrfs_ino(BTRFS_I(inode)))
2382 key.objectid = root_id;
2383 key.type = BTRFS_ROOT_ITEM_KEY;
2384 key.offset = (u64)-1;
2386 root = btrfs_read_fs_root_no_name(fs_info, &key);
2388 if (PTR_ERR(root) == -ENOENT)
2391 btrfs_debug(fs_info, "inum=%llu, offset=%llu, root_id=%llu",
2392 inum, offset, root_id);
2393 return PTR_ERR(root);
2396 key.objectid = inum;
2397 key.type = BTRFS_EXTENT_DATA_KEY;
2398 if (offset > (u64)-1 << 32)
2401 key.offset = offset;
2403 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2404 if (WARN_ON(ret < 0))
2411 leaf = path->nodes[0];
2412 slot = path->slots[0];
2414 if (slot >= btrfs_header_nritems(leaf)) {
2415 ret = btrfs_next_leaf(root, path);
2418 } else if (ret > 0) {
2427 btrfs_item_key_to_cpu(leaf, &key, slot);
2429 if (key.objectid > inum)
2432 if (key.objectid < inum || key.type != BTRFS_EXTENT_DATA_KEY)
2435 extent = btrfs_item_ptr(leaf, slot,
2436 struct btrfs_file_extent_item);
2438 if (btrfs_file_extent_disk_bytenr(leaf, extent) != old->bytenr)
2442 * 'offset' refers to the exact key.offset,
2443 * NOT the 'offset' field in btrfs_extent_data_ref, ie.
2444 * (key.offset - extent_offset).
2446 if (key.offset != offset)
2449 extent_offset = btrfs_file_extent_offset(leaf, extent);
2450 num_bytes = btrfs_file_extent_num_bytes(leaf, extent);
2452 if (extent_offset >= old->extent_offset + old->offset +
2453 old->len || extent_offset + num_bytes <=
2454 old->extent_offset + old->offset)
2459 backref = kmalloc(sizeof(*backref), GFP_NOFS);
2465 backref->root_id = root_id;
2466 backref->inum = inum;
2467 backref->file_pos = offset;
2468 backref->num_bytes = num_bytes;
2469 backref->extent_offset = extent_offset;
2470 backref->generation = btrfs_file_extent_generation(leaf, extent);
2472 backref_insert(&new->root, backref);
2475 btrfs_release_path(path);
2480 static noinline bool record_extent_backrefs(struct btrfs_path *path,
2481 struct new_sa_defrag_extent *new)
2483 struct btrfs_fs_info *fs_info = btrfs_sb(new->inode->i_sb);
2484 struct old_sa_defrag_extent *old, *tmp;
2489 list_for_each_entry_safe(old, tmp, &new->head, list) {
2490 ret = iterate_inodes_from_logical(old->bytenr +
2491 old->extent_offset, fs_info,
2492 path, record_one_backref,
2494 if (ret < 0 && ret != -ENOENT)
2497 /* no backref to be processed for this extent */
2499 list_del(&old->list);
2504 if (list_empty(&new->head))
2510 static int relink_is_mergable(struct extent_buffer *leaf,
2511 struct btrfs_file_extent_item *fi,
2512 struct new_sa_defrag_extent *new)
2514 if (btrfs_file_extent_disk_bytenr(leaf, fi) != new->bytenr)
2517 if (btrfs_file_extent_type(leaf, fi) != BTRFS_FILE_EXTENT_REG)
2520 if (btrfs_file_extent_compression(leaf, fi) != new->compress_type)
2523 if (btrfs_file_extent_encryption(leaf, fi) ||
2524 btrfs_file_extent_other_encoding(leaf, fi))
2531 * Note the backref might has changed, and in this case we just return 0.
2533 static noinline int relink_extent_backref(struct btrfs_path *path,
2534 struct sa_defrag_extent_backref *prev,
2535 struct sa_defrag_extent_backref *backref)
2537 struct btrfs_file_extent_item *extent;
2538 struct btrfs_file_extent_item *item;
2539 struct btrfs_ordered_extent *ordered;
2540 struct btrfs_trans_handle *trans;
2541 struct btrfs_root *root;
2542 struct btrfs_key key;
2543 struct extent_buffer *leaf;
2544 struct old_sa_defrag_extent *old = backref->old;
2545 struct new_sa_defrag_extent *new = old->new;
2546 struct btrfs_fs_info *fs_info = btrfs_sb(new->inode->i_sb);
2547 struct inode *inode;
2548 struct extent_state *cached = NULL;
2557 if (prev && prev->root_id == backref->root_id &&
2558 prev->inum == backref->inum &&
2559 prev->file_pos + prev->num_bytes == backref->file_pos)
2562 /* step 1: get root */
2563 key.objectid = backref->root_id;
2564 key.type = BTRFS_ROOT_ITEM_KEY;
2565 key.offset = (u64)-1;
2567 index = srcu_read_lock(&fs_info->subvol_srcu);
2569 root = btrfs_read_fs_root_no_name(fs_info, &key);
2571 srcu_read_unlock(&fs_info->subvol_srcu, index);
2572 if (PTR_ERR(root) == -ENOENT)
2574 return PTR_ERR(root);
2577 if (btrfs_root_readonly(root)) {
2578 srcu_read_unlock(&fs_info->subvol_srcu, index);
2582 /* step 2: get inode */
2583 key.objectid = backref->inum;
2584 key.type = BTRFS_INODE_ITEM_KEY;
2587 inode = btrfs_iget(fs_info->sb, &key, root, NULL);
2588 if (IS_ERR(inode)) {
2589 srcu_read_unlock(&fs_info->subvol_srcu, index);
2593 srcu_read_unlock(&fs_info->subvol_srcu, index);
2595 /* step 3: relink backref */
2596 lock_start = backref->file_pos;
2597 lock_end = backref->file_pos + backref->num_bytes - 1;
2598 lock_extent_bits(&BTRFS_I(inode)->io_tree, lock_start, lock_end,
2601 ordered = btrfs_lookup_first_ordered_extent(inode, lock_end);
2603 btrfs_put_ordered_extent(ordered);
2607 trans = btrfs_join_transaction(root);
2608 if (IS_ERR(trans)) {
2609 ret = PTR_ERR(trans);
2613 key.objectid = backref->inum;
2614 key.type = BTRFS_EXTENT_DATA_KEY;
2615 key.offset = backref->file_pos;
2617 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2620 } else if (ret > 0) {
2625 extent = btrfs_item_ptr(path->nodes[0], path->slots[0],
2626 struct btrfs_file_extent_item);
2628 if (btrfs_file_extent_generation(path->nodes[0], extent) !=
2629 backref->generation)
2632 btrfs_release_path(path);
2634 start = backref->file_pos;
2635 if (backref->extent_offset < old->extent_offset + old->offset)
2636 start += old->extent_offset + old->offset -
2637 backref->extent_offset;
2639 len = min(backref->extent_offset + backref->num_bytes,
2640 old->extent_offset + old->offset + old->len);
2641 len -= max(backref->extent_offset, old->extent_offset + old->offset);
2643 ret = btrfs_drop_extents(trans, root, inode, start,
2648 key.objectid = btrfs_ino(BTRFS_I(inode));
2649 key.type = BTRFS_EXTENT_DATA_KEY;
2652 path->leave_spinning = 1;
2654 struct btrfs_file_extent_item *fi;
2656 struct btrfs_key found_key;
2658 ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
2663 leaf = path->nodes[0];
2664 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
2666 fi = btrfs_item_ptr(leaf, path->slots[0],
2667 struct btrfs_file_extent_item);
2668 extent_len = btrfs_file_extent_num_bytes(leaf, fi);
2670 if (extent_len + found_key.offset == start &&
2671 relink_is_mergable(leaf, fi, new)) {
2672 btrfs_set_file_extent_num_bytes(leaf, fi,
2674 btrfs_mark_buffer_dirty(leaf);
2675 inode_add_bytes(inode, len);
2681 btrfs_release_path(path);
2686 ret = btrfs_insert_empty_item(trans, root, path, &key,
2689 btrfs_abort_transaction(trans, ret);
2693 leaf = path->nodes[0];
2694 item = btrfs_item_ptr(leaf, path->slots[0],
2695 struct btrfs_file_extent_item);
2696 btrfs_set_file_extent_disk_bytenr(leaf, item, new->bytenr);
2697 btrfs_set_file_extent_disk_num_bytes(leaf, item, new->disk_len);
2698 btrfs_set_file_extent_offset(leaf, item, start - new->file_pos);
2699 btrfs_set_file_extent_num_bytes(leaf, item, len);
2700 btrfs_set_file_extent_ram_bytes(leaf, item, new->len);
2701 btrfs_set_file_extent_generation(leaf, item, trans->transid);
2702 btrfs_set_file_extent_type(leaf, item, BTRFS_FILE_EXTENT_REG);
2703 btrfs_set_file_extent_compression(leaf, item, new->compress_type);
2704 btrfs_set_file_extent_encryption(leaf, item, 0);
2705 btrfs_set_file_extent_other_encoding(leaf, item, 0);
2707 btrfs_mark_buffer_dirty(leaf);
2708 inode_add_bytes(inode, len);
2709 btrfs_release_path(path);
2711 ret = btrfs_inc_extent_ref(trans, root, new->bytenr,
2713 backref->root_id, backref->inum,
2714 new->file_pos); /* start - extent_offset */
2716 btrfs_abort_transaction(trans, ret);
2722 btrfs_release_path(path);
2723 path->leave_spinning = 0;
2724 btrfs_end_transaction(trans);
2726 unlock_extent_cached(&BTRFS_I(inode)->io_tree, lock_start, lock_end,
2732 static void free_sa_defrag_extent(struct new_sa_defrag_extent *new)
2734 struct old_sa_defrag_extent *old, *tmp;
2739 list_for_each_entry_safe(old, tmp, &new->head, list) {
2745 static void relink_file_extents(struct new_sa_defrag_extent *new)
2747 struct btrfs_fs_info *fs_info = btrfs_sb(new->inode->i_sb);
2748 struct btrfs_path *path;
2749 struct sa_defrag_extent_backref *backref;
2750 struct sa_defrag_extent_backref *prev = NULL;
2751 struct inode *inode;
2752 struct btrfs_root *root;
2753 struct rb_node *node;
2757 root = BTRFS_I(inode)->root;
2759 path = btrfs_alloc_path();
2763 if (!record_extent_backrefs(path, new)) {
2764 btrfs_free_path(path);
2767 btrfs_release_path(path);
2770 node = rb_first(&new->root);
2773 rb_erase(node, &new->root);
2775 backref = rb_entry(node, struct sa_defrag_extent_backref, node);
2777 ret = relink_extent_backref(path, prev, backref);
2790 btrfs_free_path(path);
2792 free_sa_defrag_extent(new);
2794 atomic_dec(&fs_info->defrag_running);
2795 wake_up(&fs_info->transaction_wait);
2798 static struct new_sa_defrag_extent *
2799 record_old_file_extents(struct inode *inode,
2800 struct btrfs_ordered_extent *ordered)
2802 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2803 struct btrfs_root *root = BTRFS_I(inode)->root;
2804 struct btrfs_path *path;
2805 struct btrfs_key key;
2806 struct old_sa_defrag_extent *old;
2807 struct new_sa_defrag_extent *new;
2810 new = kmalloc(sizeof(*new), GFP_NOFS);
2815 new->file_pos = ordered->file_offset;
2816 new->len = ordered->len;
2817 new->bytenr = ordered->start;
2818 new->disk_len = ordered->disk_len;
2819 new->compress_type = ordered->compress_type;
2820 new->root = RB_ROOT;
2821 INIT_LIST_HEAD(&new->head);
2823 path = btrfs_alloc_path();
2827 key.objectid = btrfs_ino(BTRFS_I(inode));
2828 key.type = BTRFS_EXTENT_DATA_KEY;
2829 key.offset = new->file_pos;
2831 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2834 if (ret > 0 && path->slots[0] > 0)
2837 /* find out all the old extents for the file range */
2839 struct btrfs_file_extent_item *extent;
2840 struct extent_buffer *l;
2849 slot = path->slots[0];
2851 if (slot >= btrfs_header_nritems(l)) {
2852 ret = btrfs_next_leaf(root, path);
2860 btrfs_item_key_to_cpu(l, &key, slot);
2862 if (key.objectid != btrfs_ino(BTRFS_I(inode)))
2864 if (key.type != BTRFS_EXTENT_DATA_KEY)
2866 if (key.offset >= new->file_pos + new->len)
2869 extent = btrfs_item_ptr(l, slot, struct btrfs_file_extent_item);
2871 num_bytes = btrfs_file_extent_num_bytes(l, extent);
2872 if (key.offset + num_bytes < new->file_pos)
2875 disk_bytenr = btrfs_file_extent_disk_bytenr(l, extent);
2879 extent_offset = btrfs_file_extent_offset(l, extent);
2881 old = kmalloc(sizeof(*old), GFP_NOFS);
2885 offset = max(new->file_pos, key.offset);
2886 end = min(new->file_pos + new->len, key.offset + num_bytes);
2888 old->bytenr = disk_bytenr;
2889 old->extent_offset = extent_offset;
2890 old->offset = offset - key.offset;
2891 old->len = end - offset;
2894 list_add_tail(&old->list, &new->head);
2900 btrfs_free_path(path);
2901 atomic_inc(&fs_info->defrag_running);
2906 btrfs_free_path(path);
2908 free_sa_defrag_extent(new);
2912 static void btrfs_release_delalloc_bytes(struct btrfs_fs_info *fs_info,
2915 struct btrfs_block_group_cache *cache;
2917 cache = btrfs_lookup_block_group(fs_info, start);
2920 spin_lock(&cache->lock);
2921 cache->delalloc_bytes -= len;
2922 spin_unlock(&cache->lock);
2924 btrfs_put_block_group(cache);
2927 /* as ordered data IO finishes, this gets called so we can finish
2928 * an ordered extent if the range of bytes in the file it covers are
2931 static int btrfs_finish_ordered_io(struct btrfs_ordered_extent *ordered_extent)
2933 struct inode *inode = ordered_extent->inode;
2934 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2935 struct btrfs_root *root = BTRFS_I(inode)->root;
2936 struct btrfs_trans_handle *trans = NULL;
2937 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
2938 struct extent_state *cached_state = NULL;
2939 struct new_sa_defrag_extent *new = NULL;
2940 int compress_type = 0;
2942 u64 logical_len = ordered_extent->len;
2944 bool truncated = false;
2945 bool range_locked = false;
2946 bool clear_new_delalloc_bytes = false;
2948 if (!test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags) &&
2949 !test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags) &&
2950 !test_bit(BTRFS_ORDERED_DIRECT, &ordered_extent->flags))
2951 clear_new_delalloc_bytes = true;
2953 nolock = btrfs_is_free_space_inode(BTRFS_I(inode));
2955 if (test_bit(BTRFS_ORDERED_IOERR, &ordered_extent->flags)) {
2960 btrfs_free_io_failure_record(BTRFS_I(inode),
2961 ordered_extent->file_offset,
2962 ordered_extent->file_offset +
2963 ordered_extent->len - 1);
2965 if (test_bit(BTRFS_ORDERED_TRUNCATED, &ordered_extent->flags)) {
2967 logical_len = ordered_extent->truncated_len;
2968 /* Truncated the entire extent, don't bother adding */
2973 if (test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags)) {
2974 BUG_ON(!list_empty(&ordered_extent->list)); /* Logic error */
2977 * For mwrite(mmap + memset to write) case, we still reserve
2978 * space for NOCOW range.
2979 * As NOCOW won't cause a new delayed ref, just free the space
2981 btrfs_qgroup_free_data(inode, NULL, ordered_extent->file_offset,
2982 ordered_extent->len);
2983 btrfs_ordered_update_i_size(inode, 0, ordered_extent);
2985 trans = btrfs_join_transaction_nolock(root);
2987 trans = btrfs_join_transaction(root);
2988 if (IS_ERR(trans)) {
2989 ret = PTR_ERR(trans);
2993 trans->block_rsv = &BTRFS_I(inode)->block_rsv;
2994 ret = btrfs_update_inode_fallback(trans, root, inode);
2995 if (ret) /* -ENOMEM or corruption */
2996 btrfs_abort_transaction(trans, ret);
3000 range_locked = true;
3001 lock_extent_bits(io_tree, ordered_extent->file_offset,
3002 ordered_extent->file_offset + ordered_extent->len - 1,
3005 ret = test_range_bit(io_tree, ordered_extent->file_offset,
3006 ordered_extent->file_offset + ordered_extent->len - 1,
3007 EXTENT_DEFRAG, 0, cached_state);
3009 u64 last_snapshot = btrfs_root_last_snapshot(&root->root_item);
3010 if (0 && last_snapshot >= BTRFS_I(inode)->generation)
3011 /* the inode is shared */
3012 new = record_old_file_extents(inode, ordered_extent);
3014 clear_extent_bit(io_tree, ordered_extent->file_offset,
3015 ordered_extent->file_offset + ordered_extent->len - 1,
3016 EXTENT_DEFRAG, 0, 0, &cached_state);
3020 trans = btrfs_join_transaction_nolock(root);
3022 trans = btrfs_join_transaction(root);
3023 if (IS_ERR(trans)) {
3024 ret = PTR_ERR(trans);
3029 trans->block_rsv = &BTRFS_I(inode)->block_rsv;
3031 if (test_bit(BTRFS_ORDERED_COMPRESSED, &ordered_extent->flags))
3032 compress_type = ordered_extent->compress_type;
3033 if (test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags)) {
3034 BUG_ON(compress_type);
3035 btrfs_qgroup_free_data(inode, NULL, ordered_extent->file_offset,
3036 ordered_extent->len);
3037 ret = btrfs_mark_extent_written(trans, BTRFS_I(inode),
3038 ordered_extent->file_offset,
3039 ordered_extent->file_offset +
3042 BUG_ON(root == fs_info->tree_root);
3043 ret = insert_reserved_file_extent(trans, inode,
3044 ordered_extent->file_offset,
3045 ordered_extent->start,
3046 ordered_extent->disk_len,
3047 logical_len, logical_len,
3048 compress_type, 0, 0,
3049 BTRFS_FILE_EXTENT_REG);
3051 btrfs_release_delalloc_bytes(fs_info,
3052 ordered_extent->start,
3053 ordered_extent->disk_len);
3055 unpin_extent_cache(&BTRFS_I(inode)->extent_tree,
3056 ordered_extent->file_offset, ordered_extent->len,
3059 btrfs_abort_transaction(trans, ret);
3063 ret = add_pending_csums(trans, inode, &ordered_extent->list);
3065 btrfs_abort_transaction(trans, ret);
3069 btrfs_ordered_update_i_size(inode, 0, ordered_extent);
3070 ret = btrfs_update_inode_fallback(trans, root, inode);
3071 if (ret) { /* -ENOMEM or corruption */
3072 btrfs_abort_transaction(trans, ret);
3077 if (range_locked || clear_new_delalloc_bytes) {
3078 unsigned int clear_bits = 0;
3081 clear_bits |= EXTENT_LOCKED;
3082 if (clear_new_delalloc_bytes)
3083 clear_bits |= EXTENT_DELALLOC_NEW;
3084 clear_extent_bit(&BTRFS_I(inode)->io_tree,
3085 ordered_extent->file_offset,
3086 ordered_extent->file_offset +
3087 ordered_extent->len - 1,
3089 (clear_bits & EXTENT_LOCKED) ? 1 : 0,
3094 btrfs_end_transaction(trans);
3096 if (ret || truncated) {
3100 start = ordered_extent->file_offset + logical_len;
3102 start = ordered_extent->file_offset;
3103 end = ordered_extent->file_offset + ordered_extent->len - 1;
3104 clear_extent_uptodate(io_tree, start, end, NULL);
3106 /* Drop the cache for the part of the extent we didn't write. */
3107 btrfs_drop_extent_cache(BTRFS_I(inode), start, end, 0);
3110 * If the ordered extent had an IOERR or something else went
3111 * wrong we need to return the space for this ordered extent
3112 * back to the allocator. We only free the extent in the
3113 * truncated case if we didn't write out the extent at all.
3115 if ((ret || !logical_len) &&
3116 !test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags) &&
3117 !test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags))
3118 btrfs_free_reserved_extent(fs_info,
3119 ordered_extent->start,
3120 ordered_extent->disk_len, 1);
3125 * This needs to be done to make sure anybody waiting knows we are done
3126 * updating everything for this ordered extent.
3128 btrfs_remove_ordered_extent(inode, ordered_extent);
3130 /* for snapshot-aware defrag */
3133 free_sa_defrag_extent(new);
3134 atomic_dec(&fs_info->defrag_running);
3136 relink_file_extents(new);
3141 btrfs_put_ordered_extent(ordered_extent);
3142 /* once for the tree */
3143 btrfs_put_ordered_extent(ordered_extent);
3148 static void finish_ordered_fn(struct btrfs_work *work)
3150 struct btrfs_ordered_extent *ordered_extent;
3151 ordered_extent = container_of(work, struct btrfs_ordered_extent, work);
3152 btrfs_finish_ordered_io(ordered_extent);
3155 static void btrfs_writepage_end_io_hook(struct page *page, u64 start, u64 end,
3156 struct extent_state *state, int uptodate)
3158 struct inode *inode = page->mapping->host;
3159 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
3160 struct btrfs_ordered_extent *ordered_extent = NULL;
3161 struct btrfs_workqueue *wq;
3162 btrfs_work_func_t func;
3164 trace_btrfs_writepage_end_io_hook(page, start, end, uptodate);
3166 ClearPagePrivate2(page);
3167 if (!btrfs_dec_test_ordered_pending(inode, &ordered_extent, start,
3168 end - start + 1, uptodate))
3171 if (btrfs_is_free_space_inode(BTRFS_I(inode))) {
3172 wq = fs_info->endio_freespace_worker;
3173 func = btrfs_freespace_write_helper;
3175 wq = fs_info->endio_write_workers;
3176 func = btrfs_endio_write_helper;
3179 btrfs_init_work(&ordered_extent->work, func, finish_ordered_fn, NULL,
3181 btrfs_queue_work(wq, &ordered_extent->work);
3184 static int __readpage_endio_check(struct inode *inode,
3185 struct btrfs_io_bio *io_bio,
3186 int icsum, struct page *page,
3187 int pgoff, u64 start, size_t len)
3193 csum_expected = *(((u32 *)io_bio->csum) + icsum);
3195 kaddr = kmap_atomic(page);
3196 csum = btrfs_csum_data(kaddr + pgoff, csum, len);
3197 btrfs_csum_final(csum, (u8 *)&csum);
3198 if (csum != csum_expected)
3201 kunmap_atomic(kaddr);
3204 btrfs_print_data_csum_error(BTRFS_I(inode), start, csum, csum_expected,
3205 io_bio->mirror_num);
3206 memset(kaddr + pgoff, 1, len);
3207 flush_dcache_page(page);
3208 kunmap_atomic(kaddr);
3213 * when reads are done, we need to check csums to verify the data is correct
3214 * if there's a match, we allow the bio to finish. If not, the code in
3215 * extent_io.c will try to find good copies for us.
3217 static int btrfs_readpage_end_io_hook(struct btrfs_io_bio *io_bio,
3218 u64 phy_offset, struct page *page,
3219 u64 start, u64 end, int mirror)
3221 size_t offset = start - page_offset(page);
3222 struct inode *inode = page->mapping->host;
3223 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
3224 struct btrfs_root *root = BTRFS_I(inode)->root;
3226 if (PageChecked(page)) {
3227 ClearPageChecked(page);
3231 if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)
3234 if (root->root_key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID &&
3235 test_range_bit(io_tree, start, end, EXTENT_NODATASUM, 1, NULL)) {
3236 clear_extent_bits(io_tree, start, end, EXTENT_NODATASUM);
3240 phy_offset >>= inode->i_sb->s_blocksize_bits;
3241 return __readpage_endio_check(inode, io_bio, phy_offset, page, offset,
3242 start, (size_t)(end - start + 1));
3246 * btrfs_add_delayed_iput - perform a delayed iput on @inode
3248 * @inode: The inode we want to perform iput on
3250 * This function uses the generic vfs_inode::i_count to track whether we should
3251 * just decrement it (in case it's > 1) or if this is the last iput then link
3252 * the inode to the delayed iput machinery. Delayed iputs are processed at
3253 * transaction commit time/superblock commit/cleaner kthread.
3255 void btrfs_add_delayed_iput(struct inode *inode)
3257 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
3258 struct btrfs_inode *binode = BTRFS_I(inode);
3260 if (atomic_add_unless(&inode->i_count, -1, 1))
3263 spin_lock(&fs_info->delayed_iput_lock);
3264 ASSERT(list_empty(&binode->delayed_iput));
3265 list_add_tail(&binode->delayed_iput, &fs_info->delayed_iputs);
3266 spin_unlock(&fs_info->delayed_iput_lock);
3269 void btrfs_run_delayed_iputs(struct btrfs_fs_info *fs_info)
3272 spin_lock(&fs_info->delayed_iput_lock);
3273 while (!list_empty(&fs_info->delayed_iputs)) {
3274 struct btrfs_inode *inode;
3276 inode = list_first_entry(&fs_info->delayed_iputs,
3277 struct btrfs_inode, delayed_iput);
3278 list_del_init(&inode->delayed_iput);
3279 spin_unlock(&fs_info->delayed_iput_lock);
3280 iput(&inode->vfs_inode);
3281 spin_lock(&fs_info->delayed_iput_lock);
3283 spin_unlock(&fs_info->delayed_iput_lock);
3287 * This is called in transaction commit time. If there are no orphan
3288 * files in the subvolume, it removes orphan item and frees block_rsv
3291 void btrfs_orphan_commit_root(struct btrfs_trans_handle *trans,
3292 struct btrfs_root *root)
3294 struct btrfs_fs_info *fs_info = root->fs_info;
3295 struct btrfs_block_rsv *block_rsv;
3298 if (atomic_read(&root->orphan_inodes) ||
3299 root->orphan_cleanup_state != ORPHAN_CLEANUP_DONE)
3302 spin_lock(&root->orphan_lock);
3303 if (atomic_read(&root->orphan_inodes)) {
3304 spin_unlock(&root->orphan_lock);
3308 if (root->orphan_cleanup_state != ORPHAN_CLEANUP_DONE) {
3309 spin_unlock(&root->orphan_lock);
3313 block_rsv = root->orphan_block_rsv;
3314 root->orphan_block_rsv = NULL;
3315 spin_unlock(&root->orphan_lock);
3317 if (test_bit(BTRFS_ROOT_ORPHAN_ITEM_INSERTED, &root->state) &&
3318 btrfs_root_refs(&root->root_item) > 0) {
3319 ret = btrfs_del_orphan_item(trans, fs_info->tree_root,
3320 root->root_key.objectid);
3322 btrfs_abort_transaction(trans, ret);
3324 clear_bit(BTRFS_ROOT_ORPHAN_ITEM_INSERTED,
3329 WARN_ON(block_rsv->size > 0);
3330 btrfs_free_block_rsv(fs_info, block_rsv);
3335 * This creates an orphan entry for the given inode in case something goes
3336 * wrong in the middle of an unlink/truncate.
3338 * NOTE: caller of this function should reserve 5 units of metadata for
3341 int btrfs_orphan_add(struct btrfs_trans_handle *trans,
3342 struct btrfs_inode *inode)
3344 struct btrfs_fs_info *fs_info = btrfs_sb(inode->vfs_inode.i_sb);
3345 struct btrfs_root *root = inode->root;
3346 struct btrfs_block_rsv *block_rsv = NULL;
3351 if (!root->orphan_block_rsv) {
3352 block_rsv = btrfs_alloc_block_rsv(fs_info,
3353 BTRFS_BLOCK_RSV_TEMP);
3358 if (!test_and_set_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
3359 &inode->runtime_flags)) {
3362 * For proper ENOSPC handling, we should do orphan
3363 * cleanup when mounting. But this introduces backward
3364 * compatibility issue.
3366 if (!xchg(&root->orphan_item_inserted, 1))
3374 if (!test_and_set_bit(BTRFS_INODE_ORPHAN_META_RESERVED,
3375 &inode->runtime_flags))
3378 spin_lock(&root->orphan_lock);
3379 /* If someone has created ->orphan_block_rsv, be happy to use it. */
3380 if (!root->orphan_block_rsv) {
3381 root->orphan_block_rsv = block_rsv;
3382 } else if (block_rsv) {
3383 btrfs_free_block_rsv(fs_info, block_rsv);
3388 atomic_inc(&root->orphan_inodes);
3389 spin_unlock(&root->orphan_lock);
3391 /* grab metadata reservation from transaction handle */
3393 ret = btrfs_orphan_reserve_metadata(trans, inode);
3397 * dec doesn't need spin_lock as ->orphan_block_rsv
3398 * would be released only if ->orphan_inodes is
3401 atomic_dec(&root->orphan_inodes);
3402 clear_bit(BTRFS_INODE_ORPHAN_META_RESERVED,
3403 &inode->runtime_flags);
3405 clear_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
3406 &inode->runtime_flags);
3411 /* insert an orphan item to track this unlinked/truncated file */
3413 ret = btrfs_insert_orphan_item(trans, root, btrfs_ino(inode));
3416 clear_bit(BTRFS_INODE_ORPHAN_META_RESERVED,
3417 &inode->runtime_flags);
3418 btrfs_orphan_release_metadata(inode);
3421 * btrfs_orphan_commit_root may race with us and set
3422 * ->orphan_block_rsv to zero, in order to avoid that,
3423 * decrease ->orphan_inodes after everything is done.
3425 atomic_dec(&root->orphan_inodes);
3426 if (ret != -EEXIST) {
3427 clear_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
3428 &inode->runtime_flags);
3429 btrfs_abort_transaction(trans, ret);
3436 /* insert an orphan item to track subvolume contains orphan files */
3438 ret = btrfs_insert_orphan_item(trans, fs_info->tree_root,
3439 root->root_key.objectid);
3440 if (ret && ret != -EEXIST) {
3441 btrfs_abort_transaction(trans, ret);
3449 * We have done the truncate/delete so we can go ahead and remove the orphan
3450 * item for this particular inode.
3452 static int btrfs_orphan_del(struct btrfs_trans_handle *trans,
3453 struct btrfs_inode *inode)
3455 struct btrfs_root *root = inode->root;
3456 int delete_item = 0;
3459 if (test_and_clear_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
3460 &inode->runtime_flags))
3463 if (delete_item && trans)
3464 ret = btrfs_del_orphan_item(trans, root, btrfs_ino(inode));
3466 if (test_and_clear_bit(BTRFS_INODE_ORPHAN_META_RESERVED,
3467 &inode->runtime_flags))
3468 btrfs_orphan_release_metadata(inode);
3471 * btrfs_orphan_commit_root may race with us and set ->orphan_block_rsv
3472 * to zero, in order to avoid that, decrease ->orphan_inodes after
3473 * everything is done.
3476 atomic_dec(&root->orphan_inodes);
3482 * this cleans up any orphans that may be left on the list from the last use
3485 int btrfs_orphan_cleanup(struct btrfs_root *root)
3487 struct btrfs_fs_info *fs_info = root->fs_info;
3488 struct btrfs_path *path;
3489 struct extent_buffer *leaf;
3490 struct btrfs_key key, found_key;
3491 struct btrfs_trans_handle *trans;
3492 struct inode *inode;
3493 u64 last_objectid = 0;
3494 int ret = 0, nr_unlink = 0, nr_truncate = 0;
3496 if (cmpxchg(&root->orphan_cleanup_state, 0, ORPHAN_CLEANUP_STARTED))
3499 path = btrfs_alloc_path();
3504 path->reada = READA_BACK;
3506 key.objectid = BTRFS_ORPHAN_OBJECTID;
3507 key.type = BTRFS_ORPHAN_ITEM_KEY;
3508 key.offset = (u64)-1;
3511 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
3516 * if ret == 0 means we found what we were searching for, which
3517 * is weird, but possible, so only screw with path if we didn't
3518 * find the key and see if we have stuff that matches
3522 if (path->slots[0] == 0)
3527 /* pull out the item */
3528 leaf = path->nodes[0];
3529 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
3531 /* make sure the item matches what we want */
3532 if (found_key.objectid != BTRFS_ORPHAN_OBJECTID)
3534 if (found_key.type != BTRFS_ORPHAN_ITEM_KEY)
3537 /* release the path since we're done with it */
3538 btrfs_release_path(path);
3541 * this is where we are basically btrfs_lookup, without the
3542 * crossing root thing. we store the inode number in the
3543 * offset of the orphan item.
3546 if (found_key.offset == last_objectid) {
3548 "Error removing orphan entry, stopping orphan cleanup");
3553 last_objectid = found_key.offset;
3555 found_key.objectid = found_key.offset;
3556 found_key.type = BTRFS_INODE_ITEM_KEY;
3557 found_key.offset = 0;
3558 inode = btrfs_iget(fs_info->sb, &found_key, root, NULL);
3559 ret = PTR_ERR_OR_ZERO(inode);
3560 if (ret && ret != -ENOENT)
3563 if (ret == -ENOENT && root == fs_info->tree_root) {
3564 struct btrfs_root *dead_root;
3565 struct btrfs_fs_info *fs_info = root->fs_info;
3566 int is_dead_root = 0;
3569 * this is an orphan in the tree root. Currently these
3570 * could come from 2 sources:
3571 * a) a snapshot deletion in progress
3572 * b) a free space cache inode
3573 * We need to distinguish those two, as the snapshot
3574 * orphan must not get deleted.
3575 * find_dead_roots already ran before us, so if this
3576 * is a snapshot deletion, we should find the root
3577 * in the dead_roots list
3579 spin_lock(&fs_info->trans_lock);
3580 list_for_each_entry(dead_root, &fs_info->dead_roots,
3582 if (dead_root->root_key.objectid ==
3583 found_key.objectid) {
3588 spin_unlock(&fs_info->trans_lock);
3590 /* prevent this orphan from being found again */
3591 key.offset = found_key.objectid - 1;
3596 * Inode is already gone but the orphan item is still there,
3597 * kill the orphan item.
3599 if (ret == -ENOENT) {
3600 trans = btrfs_start_transaction(root, 1);
3601 if (IS_ERR(trans)) {
3602 ret = PTR_ERR(trans);
3605 btrfs_debug(fs_info, "auto deleting %Lu",
3606 found_key.objectid);
3607 ret = btrfs_del_orphan_item(trans, root,
3608 found_key.objectid);
3609 btrfs_end_transaction(trans);
3616 * add this inode to the orphan list so btrfs_orphan_del does
3617 * the proper thing when we hit it
3619 set_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
3620 &BTRFS_I(inode)->runtime_flags);
3621 atomic_inc(&root->orphan_inodes);
3623 /* if we have links, this was a truncate, lets do that */
3624 if (inode->i_nlink) {
3625 if (WARN_ON(!S_ISREG(inode->i_mode))) {
3631 /* 1 for the orphan item deletion. */
3632 trans = btrfs_start_transaction(root, 1);
3633 if (IS_ERR(trans)) {
3635 ret = PTR_ERR(trans);
3638 ret = btrfs_orphan_add(trans, BTRFS_I(inode));
3639 btrfs_end_transaction(trans);
3645 ret = btrfs_truncate(inode);
3647 btrfs_orphan_del(NULL, BTRFS_I(inode));
3652 /* this will do delete_inode and everything for us */
3657 /* release the path since we're done with it */
3658 btrfs_release_path(path);
3660 root->orphan_cleanup_state = ORPHAN_CLEANUP_DONE;
3662 if (root->orphan_block_rsv)
3663 btrfs_block_rsv_release(fs_info, root->orphan_block_rsv,
3666 if (root->orphan_block_rsv ||
3667 test_bit(BTRFS_ROOT_ORPHAN_ITEM_INSERTED, &root->state)) {
3668 trans = btrfs_join_transaction(root);
3670 btrfs_end_transaction(trans);
3674 btrfs_debug(fs_info, "unlinked %d orphans", nr_unlink);
3676 btrfs_debug(fs_info, "truncated %d orphans", nr_truncate);
3680 btrfs_err(fs_info, "could not do orphan cleanup %d", ret);
3681 btrfs_free_path(path);
3686 * very simple check to peek ahead in the leaf looking for xattrs. If we
3687 * don't find any xattrs, we know there can't be any acls.
3689 * slot is the slot the inode is in, objectid is the objectid of the inode
3691 static noinline int acls_after_inode_item(struct extent_buffer *leaf,
3692 int slot, u64 objectid,
3693 int *first_xattr_slot)
3695 u32 nritems = btrfs_header_nritems(leaf);
3696 struct btrfs_key found_key;
3697 static u64 xattr_access = 0;
3698 static u64 xattr_default = 0;
3701 if (!xattr_access) {
3702 xattr_access = btrfs_name_hash(XATTR_NAME_POSIX_ACL_ACCESS,
3703 strlen(XATTR_NAME_POSIX_ACL_ACCESS));
3704 xattr_default = btrfs_name_hash(XATTR_NAME_POSIX_ACL_DEFAULT,
3705 strlen(XATTR_NAME_POSIX_ACL_DEFAULT));
3709 *first_xattr_slot = -1;
3710 while (slot < nritems) {
3711 btrfs_item_key_to_cpu(leaf, &found_key, slot);
3713 /* we found a different objectid, there must not be acls */
3714 if (found_key.objectid != objectid)
3717 /* we found an xattr, assume we've got an acl */
3718 if (found_key.type == BTRFS_XATTR_ITEM_KEY) {
3719 if (*first_xattr_slot == -1)
3720 *first_xattr_slot = slot;
3721 if (found_key.offset == xattr_access ||
3722 found_key.offset == xattr_default)
3727 * we found a key greater than an xattr key, there can't
3728 * be any acls later on
3730 if (found_key.type > BTRFS_XATTR_ITEM_KEY)
3737 * it goes inode, inode backrefs, xattrs, extents,
3738 * so if there are a ton of hard links to an inode there can
3739 * be a lot of backrefs. Don't waste time searching too hard,
3740 * this is just an optimization
3745 /* we hit the end of the leaf before we found an xattr or
3746 * something larger than an xattr. We have to assume the inode
3749 if (*first_xattr_slot == -1)
3750 *first_xattr_slot = slot;
3755 * read an inode from the btree into the in-memory inode
3757 static int btrfs_read_locked_inode(struct inode *inode)
3759 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
3760 struct btrfs_path *path;
3761 struct extent_buffer *leaf;
3762 struct btrfs_inode_item *inode_item;
3763 struct btrfs_root *root = BTRFS_I(inode)->root;
3764 struct btrfs_key location;
3769 bool filled = false;
3770 int first_xattr_slot;
3772 ret = btrfs_fill_inode(inode, &rdev);
3776 path = btrfs_alloc_path();
3782 memcpy(&location, &BTRFS_I(inode)->location, sizeof(location));
3784 ret = btrfs_lookup_inode(NULL, root, path, &location, 0);
3791 leaf = path->nodes[0];
3796 inode_item = btrfs_item_ptr(leaf, path->slots[0],
3797 struct btrfs_inode_item);
3798 inode->i_mode = btrfs_inode_mode(leaf, inode_item);
3799 set_nlink(inode, btrfs_inode_nlink(leaf, inode_item));
3800 i_uid_write(inode, btrfs_inode_uid(leaf, inode_item));
3801 i_gid_write(inode, btrfs_inode_gid(leaf, inode_item));
3802 btrfs_i_size_write(BTRFS_I(inode), btrfs_inode_size(leaf, inode_item));
3804 inode->i_atime.tv_sec = btrfs_timespec_sec(leaf, &inode_item->atime);
3805 inode->i_atime.tv_nsec = btrfs_timespec_nsec(leaf, &inode_item->atime);
3807 inode->i_mtime.tv_sec = btrfs_timespec_sec(leaf, &inode_item->mtime);
3808 inode->i_mtime.tv_nsec = btrfs_timespec_nsec(leaf, &inode_item->mtime);
3810 inode->i_ctime.tv_sec = btrfs_timespec_sec(leaf, &inode_item->ctime);
3811 inode->i_ctime.tv_nsec = btrfs_timespec_nsec(leaf, &inode_item->ctime);
3813 BTRFS_I(inode)->i_otime.tv_sec =
3814 btrfs_timespec_sec(leaf, &inode_item->otime);
3815 BTRFS_I(inode)->i_otime.tv_nsec =
3816 btrfs_timespec_nsec(leaf, &inode_item->otime);
3818 inode_set_bytes(inode, btrfs_inode_nbytes(leaf, inode_item));
3819 BTRFS_I(inode)->generation = btrfs_inode_generation(leaf, inode_item);
3820 BTRFS_I(inode)->last_trans = btrfs_inode_transid(leaf, inode_item);
3822 inode_set_iversion_queried(inode,
3823 btrfs_inode_sequence(leaf, inode_item));
3824 inode->i_generation = BTRFS_I(inode)->generation;
3826 rdev = btrfs_inode_rdev(leaf, inode_item);
3828 BTRFS_I(inode)->index_cnt = (u64)-1;
3829 BTRFS_I(inode)->flags = btrfs_inode_flags(leaf, inode_item);
3833 * If we were modified in the current generation and evicted from memory
3834 * and then re-read we need to do a full sync since we don't have any
3835 * idea about which extents were modified before we were evicted from
3838 * This is required for both inode re-read from disk and delayed inode
3839 * in delayed_nodes_tree.
3841 if (BTRFS_I(inode)->last_trans == fs_info->generation)
3842 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
3843 &BTRFS_I(inode)->runtime_flags);
3846 * We don't persist the id of the transaction where an unlink operation
3847 * against the inode was last made. So here we assume the inode might
3848 * have been evicted, and therefore the exact value of last_unlink_trans
3849 * lost, and set it to last_trans to avoid metadata inconsistencies
3850 * between the inode and its parent if the inode is fsync'ed and the log
3851 * replayed. For example, in the scenario:
3854 * ln mydir/foo mydir/bar
3857 * echo 2 > /proc/sys/vm/drop_caches # evicts inode
3858 * xfs_io -c fsync mydir/foo
3860 * mount fs, triggers fsync log replay
3862 * We must make sure that when we fsync our inode foo we also log its
3863 * parent inode, otherwise after log replay the parent still has the
3864 * dentry with the "bar" name but our inode foo has a link count of 1
3865 * and doesn't have an inode ref with the name "bar" anymore.
3867 * Setting last_unlink_trans to last_trans is a pessimistic approach,
3868 * but it guarantees correctness at the expense of occasional full
3869 * transaction commits on fsync if our inode is a directory, or if our
3870 * inode is not a directory, logging its parent unnecessarily.
3872 BTRFS_I(inode)->last_unlink_trans = BTRFS_I(inode)->last_trans;
3875 if (inode->i_nlink != 1 ||
3876 path->slots[0] >= btrfs_header_nritems(leaf))
3879 btrfs_item_key_to_cpu(leaf, &location, path->slots[0]);
3880 if (location.objectid != btrfs_ino(BTRFS_I(inode)))
3883 ptr = btrfs_item_ptr_offset(leaf, path->slots[0]);
3884 if (location.type == BTRFS_INODE_REF_KEY) {
3885 struct btrfs_inode_ref *ref;
3887 ref = (struct btrfs_inode_ref *)ptr;
3888 BTRFS_I(inode)->dir_index = btrfs_inode_ref_index(leaf, ref);
3889 } else if (location.type == BTRFS_INODE_EXTREF_KEY) {
3890 struct btrfs_inode_extref *extref;
3892 extref = (struct btrfs_inode_extref *)ptr;
3893 BTRFS_I(inode)->dir_index = btrfs_inode_extref_index(leaf,
3898 * try to precache a NULL acl entry for files that don't have
3899 * any xattrs or acls
3901 maybe_acls = acls_after_inode_item(leaf, path->slots[0],
3902 btrfs_ino(BTRFS_I(inode)), &first_xattr_slot);
3903 if (first_xattr_slot != -1) {
3904 path->slots[0] = first_xattr_slot;
3905 ret = btrfs_load_inode_props(inode, path);
3908 "error loading props for ino %llu (root %llu): %d",
3909 btrfs_ino(BTRFS_I(inode)),
3910 root->root_key.objectid, ret);
3912 btrfs_free_path(path);
3915 cache_no_acl(inode);
3917 switch (inode->i_mode & S_IFMT) {
3919 inode->i_mapping->a_ops = &btrfs_aops;
3920 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
3921 inode->i_fop = &btrfs_file_operations;
3922 inode->i_op = &btrfs_file_inode_operations;
3925 inode->i_fop = &btrfs_dir_file_operations;
3926 inode->i_op = &btrfs_dir_inode_operations;
3929 inode->i_op = &btrfs_symlink_inode_operations;
3930 inode_nohighmem(inode);
3931 inode->i_mapping->a_ops = &btrfs_symlink_aops;
3934 inode->i_op = &btrfs_special_inode_operations;
3935 init_special_inode(inode, inode->i_mode, rdev);
3939 btrfs_update_iflags(inode);
3943 btrfs_free_path(path);
3944 make_bad_inode(inode);
3949 * given a leaf and an inode, copy the inode fields into the leaf
3951 static void fill_inode_item(struct btrfs_trans_handle *trans,
3952 struct extent_buffer *leaf,
3953 struct btrfs_inode_item *item,
3954 struct inode *inode)
3956 struct btrfs_map_token token;
3958 btrfs_init_map_token(&token);
3960 btrfs_set_token_inode_uid(leaf, item, i_uid_read(inode), &token);
3961 btrfs_set_token_inode_gid(leaf, item, i_gid_read(inode), &token);
3962 btrfs_set_token_inode_size(leaf, item, BTRFS_I(inode)->disk_i_size,
3964 btrfs_set_token_inode_mode(leaf, item, inode->i_mode, &token);
3965 btrfs_set_token_inode_nlink(leaf, item, inode->i_nlink, &token);
3967 btrfs_set_token_timespec_sec(leaf, &item->atime,
3968 inode->i_atime.tv_sec, &token);
3969 btrfs_set_token_timespec_nsec(leaf, &item->atime,
3970 inode->i_atime.tv_nsec, &token);
3972 btrfs_set_token_timespec_sec(leaf, &item->mtime,
3973 inode->i_mtime.tv_sec, &token);
3974 btrfs_set_token_timespec_nsec(leaf, &item->mtime,
3975 inode->i_mtime.tv_nsec, &token);
3977 btrfs_set_token_timespec_sec(leaf, &item->ctime,
3978 inode->i_ctime.tv_sec, &token);
3979 btrfs_set_token_timespec_nsec(leaf, &item->ctime,
3980 inode->i_ctime.tv_nsec, &token);
3982 btrfs_set_token_timespec_sec(leaf, &item->otime,
3983 BTRFS_I(inode)->i_otime.tv_sec, &token);
3984 btrfs_set_token_timespec_nsec(leaf, &item->otime,
3985 BTRFS_I(inode)->i_otime.tv_nsec, &token);
3987 btrfs_set_token_inode_nbytes(leaf, item, inode_get_bytes(inode),
3989 btrfs_set_token_inode_generation(leaf, item, BTRFS_I(inode)->generation,
3991 btrfs_set_token_inode_sequence(leaf, item, inode_peek_iversion(inode),
3993 btrfs_set_token_inode_transid(leaf, item, trans->transid, &token);
3994 btrfs_set_token_inode_rdev(leaf, item, inode->i_rdev, &token);
3995 btrfs_set_token_inode_flags(leaf, item, BTRFS_I(inode)->flags, &token);
3996 btrfs_set_token_inode_block_group(leaf, item, 0, &token);
4000 * copy everything in the in-memory inode into the btree.
4002 static noinline int btrfs_update_inode_item(struct btrfs_trans_handle *trans,
4003 struct btrfs_root *root, struct inode *inode)
4005 struct btrfs_inode_item *inode_item;
4006 struct btrfs_path *path;
4007 struct extent_buffer *leaf;
4010 path = btrfs_alloc_path();
4014 path->leave_spinning = 1;
4015 ret = btrfs_lookup_inode(trans, root, path, &BTRFS_I(inode)->location,
4023 leaf = path->nodes[0];
4024 inode_item = btrfs_item_ptr(leaf, path->slots[0],
4025 struct btrfs_inode_item);
4027 fill_inode_item(trans, leaf, inode_item, inode);
4028 btrfs_mark_buffer_dirty(leaf);
4029 btrfs_set_inode_last_trans(trans, inode);
4032 btrfs_free_path(path);
4037 * copy everything in the in-memory inode into the btree.
4039 noinline int btrfs_update_inode(struct btrfs_trans_handle *trans,
4040 struct btrfs_root *root, struct inode *inode)
4042 struct btrfs_fs_info *fs_info = root->fs_info;
4046 * If the inode is a free space inode, we can deadlock during commit
4047 * if we put it into the delayed code.
4049 * The data relocation inode should also be directly updated
4052 if (!btrfs_is_free_space_inode(BTRFS_I(inode))
4053 && root->root_key.objectid != BTRFS_DATA_RELOC_TREE_OBJECTID
4054 && !test_bit(BTRFS_FS_LOG_RECOVERING, &fs_info->flags)) {
4055 btrfs_update_root_times(trans, root);
4057 ret = btrfs_delayed_update_inode(trans, root, inode);
4059 btrfs_set_inode_last_trans(trans, inode);
4063 return btrfs_update_inode_item(trans, root, inode);
4066 noinline int btrfs_update_inode_fallback(struct btrfs_trans_handle *trans,
4067 struct btrfs_root *root,
4068 struct inode *inode)
4072 ret = btrfs_update_inode(trans, root, inode);
4074 return btrfs_update_inode_item(trans, root, inode);
4079 * unlink helper that gets used here in inode.c and in the tree logging
4080 * recovery code. It remove a link in a directory with a given name, and
4081 * also drops the back refs in the inode to the directory
4083 static int __btrfs_unlink_inode(struct btrfs_trans_handle *trans,
4084 struct btrfs_root *root,
4085 struct btrfs_inode *dir,
4086 struct btrfs_inode *inode,
4087 const char *name, int name_len)
4089 struct btrfs_fs_info *fs_info = root->fs_info;
4090 struct btrfs_path *path;
4092 struct extent_buffer *leaf;
4093 struct btrfs_dir_item *di;
4094 struct btrfs_key key;
4096 u64 ino = btrfs_ino(inode);
4097 u64 dir_ino = btrfs_ino(dir);
4099 path = btrfs_alloc_path();
4105 path->leave_spinning = 1;
4106 di = btrfs_lookup_dir_item(trans, root, path, dir_ino,
4107 name, name_len, -1);
4116 leaf = path->nodes[0];
4117 btrfs_dir_item_key_to_cpu(leaf, di, &key);
4118 ret = btrfs_delete_one_dir_name(trans, root, path, di);
4121 btrfs_release_path(path);
4124 * If we don't have dir index, we have to get it by looking up
4125 * the inode ref, since we get the inode ref, remove it directly,
4126 * it is unnecessary to do delayed deletion.
4128 * But if we have dir index, needn't search inode ref to get it.
4129 * Since the inode ref is close to the inode item, it is better
4130 * that we delay to delete it, and just do this deletion when
4131 * we update the inode item.
4133 if (inode->dir_index) {
4134 ret = btrfs_delayed_delete_inode_ref(inode);
4136 index = inode->dir_index;
4141 ret = btrfs_del_inode_ref(trans, root, name, name_len, ino,
4145 "failed to delete reference to %.*s, inode %llu parent %llu",
4146 name_len, name, ino, dir_ino);
4147 btrfs_abort_transaction(trans, ret);
4151 ret = btrfs_delete_delayed_dir_index(trans, fs_info, dir, index);
4153 btrfs_abort_transaction(trans, ret);
4157 ret = btrfs_del_inode_ref_in_log(trans, root, name, name_len, inode,
4159 if (ret != 0 && ret != -ENOENT) {
4160 btrfs_abort_transaction(trans, ret);
4164 ret = btrfs_del_dir_entries_in_log(trans, root, name, name_len, dir,
4169 btrfs_abort_transaction(trans, ret);
4171 btrfs_free_path(path);
4175 btrfs_i_size_write(dir, dir->vfs_inode.i_size - name_len * 2);
4176 inode_inc_iversion(&inode->vfs_inode);
4177 inode_inc_iversion(&dir->vfs_inode);
4178 inode->vfs_inode.i_ctime = dir->vfs_inode.i_mtime =
4179 dir->vfs_inode.i_ctime = current_time(&inode->vfs_inode);
4180 ret = btrfs_update_inode(trans, root, &dir->vfs_inode);
4185 int btrfs_unlink_inode(struct btrfs_trans_handle *trans,
4186 struct btrfs_root *root,
4187 struct btrfs_inode *dir, struct btrfs_inode *inode,
4188 const char *name, int name_len)
4191 ret = __btrfs_unlink_inode(trans, root, dir, inode, name, name_len);
4193 drop_nlink(&inode->vfs_inode);
4194 ret = btrfs_update_inode(trans, root, &inode->vfs_inode);
4200 * helper to start transaction for unlink and rmdir.
4202 * unlink and rmdir are special in btrfs, they do not always free space, so
4203 * if we cannot make our reservations the normal way try and see if there is
4204 * plenty of slack room in the global reserve to migrate, otherwise we cannot
4205 * allow the unlink to occur.
4207 static struct btrfs_trans_handle *__unlink_start_trans(struct inode *dir)
4209 struct btrfs_root *root = BTRFS_I(dir)->root;
4212 * 1 for the possible orphan item
4213 * 1 for the dir item
4214 * 1 for the dir index
4215 * 1 for the inode ref
4218 return btrfs_start_transaction_fallback_global_rsv(root, 5, 5);
4221 static int btrfs_unlink(struct inode *dir, struct dentry *dentry)
4223 struct btrfs_root *root = BTRFS_I(dir)->root;
4224 struct btrfs_trans_handle *trans;
4225 struct inode *inode = d_inode(dentry);
4228 trans = __unlink_start_trans(dir);
4230 return PTR_ERR(trans);
4232 btrfs_record_unlink_dir(trans, BTRFS_I(dir), BTRFS_I(d_inode(dentry)),
4235 ret = btrfs_unlink_inode(trans, root, BTRFS_I(dir),
4236 BTRFS_I(d_inode(dentry)), dentry->d_name.name,
4237 dentry->d_name.len);
4241 if (inode->i_nlink == 0) {
4242 ret = btrfs_orphan_add(trans, BTRFS_I(inode));
4248 btrfs_end_transaction(trans);
4249 btrfs_btree_balance_dirty(root->fs_info);
4253 int btrfs_unlink_subvol(struct btrfs_trans_handle *trans,
4254 struct btrfs_root *root,
4255 struct inode *dir, u64 objectid,
4256 const char *name, int name_len)
4258 struct btrfs_fs_info *fs_info = root->fs_info;
4259 struct btrfs_path *path;
4260 struct extent_buffer *leaf;
4261 struct btrfs_dir_item *di;
4262 struct btrfs_key key;
4265 u64 dir_ino = btrfs_ino(BTRFS_I(dir));
4267 path = btrfs_alloc_path();
4271 di = btrfs_lookup_dir_item(trans, root, path, dir_ino,
4272 name, name_len, -1);
4273 if (IS_ERR_OR_NULL(di)) {
4281 leaf = path->nodes[0];
4282 btrfs_dir_item_key_to_cpu(leaf, di, &key);
4283 WARN_ON(key.type != BTRFS_ROOT_ITEM_KEY || key.objectid != objectid);
4284 ret = btrfs_delete_one_dir_name(trans, root, path, di);
4286 btrfs_abort_transaction(trans, ret);
4289 btrfs_release_path(path);
4291 ret = btrfs_del_root_ref(trans, fs_info, objectid,
4292 root->root_key.objectid, dir_ino,
4293 &index, name, name_len);
4295 if (ret != -ENOENT) {
4296 btrfs_abort_transaction(trans, ret);
4299 di = btrfs_search_dir_index_item(root, path, dir_ino,
4301 if (IS_ERR_OR_NULL(di)) {
4306 btrfs_abort_transaction(trans, ret);
4310 leaf = path->nodes[0];
4311 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
4312 btrfs_release_path(path);
4315 btrfs_release_path(path);
4317 ret = btrfs_delete_delayed_dir_index(trans, fs_info, BTRFS_I(dir), index);
4319 btrfs_abort_transaction(trans, ret);
4323 btrfs_i_size_write(BTRFS_I(dir), dir->i_size - name_len * 2);
4324 inode_inc_iversion(dir);
4325 dir->i_mtime = dir->i_ctime = current_time(dir);
4326 ret = btrfs_update_inode_fallback(trans, root, dir);
4328 btrfs_abort_transaction(trans, ret);
4330 btrfs_free_path(path);
4334 static int btrfs_rmdir(struct inode *dir, struct dentry *dentry)
4336 struct inode *inode = d_inode(dentry);
4338 struct btrfs_root *root = BTRFS_I(dir)->root;
4339 struct btrfs_trans_handle *trans;
4340 u64 last_unlink_trans;
4342 if (inode->i_size > BTRFS_EMPTY_DIR_SIZE)
4344 if (btrfs_ino(BTRFS_I(inode)) == BTRFS_FIRST_FREE_OBJECTID)
4347 trans = __unlink_start_trans(dir);
4349 return PTR_ERR(trans);
4351 if (unlikely(btrfs_ino(BTRFS_I(inode)) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)) {
4352 err = btrfs_unlink_subvol(trans, root, dir,
4353 BTRFS_I(inode)->location.objectid,
4354 dentry->d_name.name,
4355 dentry->d_name.len);
4359 err = btrfs_orphan_add(trans, BTRFS_I(inode));
4363 last_unlink_trans = BTRFS_I(inode)->last_unlink_trans;
4365 /* now the directory is empty */
4366 err = btrfs_unlink_inode(trans, root, BTRFS_I(dir),
4367 BTRFS_I(d_inode(dentry)), dentry->d_name.name,
4368 dentry->d_name.len);
4370 btrfs_i_size_write(BTRFS_I(inode), 0);
4372 * Propagate the last_unlink_trans value of the deleted dir to
4373 * its parent directory. This is to prevent an unrecoverable
4374 * log tree in the case we do something like this:
4376 * 2) create snapshot under dir foo
4377 * 3) delete the snapshot
4380 * 6) fsync foo or some file inside foo
4382 if (last_unlink_trans >= trans->transid)
4383 BTRFS_I(dir)->last_unlink_trans = last_unlink_trans;
4386 btrfs_end_transaction(trans);
4387 btrfs_btree_balance_dirty(root->fs_info);
4392 static int truncate_space_check(struct btrfs_trans_handle *trans,
4393 struct btrfs_root *root,
4396 struct btrfs_fs_info *fs_info = root->fs_info;
4400 * This is only used to apply pressure to the enospc system, we don't
4401 * intend to use this reservation at all.
4403 bytes_deleted = btrfs_csum_bytes_to_leaves(fs_info, bytes_deleted);
4404 bytes_deleted *= fs_info->nodesize;
4405 ret = btrfs_block_rsv_add(root, &fs_info->trans_block_rsv,
4406 bytes_deleted, BTRFS_RESERVE_NO_FLUSH);
4408 trace_btrfs_space_reservation(fs_info, "transaction",
4411 trans->bytes_reserved += bytes_deleted;
4418 * Return this if we need to call truncate_block for the last bit of the
4421 #define NEED_TRUNCATE_BLOCK 1
4424 * this can truncate away extent items, csum items and directory items.
4425 * It starts at a high offset and removes keys until it can't find
4426 * any higher than new_size
4428 * csum items that cross the new i_size are truncated to the new size
4431 * min_type is the minimum key type to truncate down to. If set to 0, this
4432 * will kill all the items on this inode, including the INODE_ITEM_KEY.
4434 int btrfs_truncate_inode_items(struct btrfs_trans_handle *trans,
4435 struct btrfs_root *root,
4436 struct inode *inode,
4437 u64 new_size, u32 min_type)
4439 struct btrfs_fs_info *fs_info = root->fs_info;
4440 struct btrfs_path *path;
4441 struct extent_buffer *leaf;
4442 struct btrfs_file_extent_item *fi;
4443 struct btrfs_key key;
4444 struct btrfs_key found_key;
4445 u64 extent_start = 0;
4446 u64 extent_num_bytes = 0;
4447 u64 extent_offset = 0;
4449 u64 last_size = new_size;
4450 u32 found_type = (u8)-1;
4453 int pending_del_nr = 0;
4454 int pending_del_slot = 0;
4455 int extent_type = -1;
4458 u64 ino = btrfs_ino(BTRFS_I(inode));
4459 u64 bytes_deleted = 0;
4460 bool be_nice = false;
4461 bool should_throttle = false;
4462 bool should_end = false;
4464 BUG_ON(new_size > 0 && min_type != BTRFS_EXTENT_DATA_KEY);
4467 * for non-free space inodes and ref cows, we want to back off from
4470 if (!btrfs_is_free_space_inode(BTRFS_I(inode)) &&
4471 test_bit(BTRFS_ROOT_REF_COWS, &root->state))
4474 path = btrfs_alloc_path();
4477 path->reada = READA_BACK;
4480 * We want to drop from the next block forward in case this new size is
4481 * not block aligned since we will be keeping the last block of the
4482 * extent just the way it is.
4484 if (test_bit(BTRFS_ROOT_REF_COWS, &root->state) ||
4485 root == fs_info->tree_root)
4486 btrfs_drop_extent_cache(BTRFS_I(inode), ALIGN(new_size,
4487 fs_info->sectorsize),
4491 * This function is also used to drop the items in the log tree before
4492 * we relog the inode, so if root != BTRFS_I(inode)->root, it means
4493 * it is used to drop the loged items. So we shouldn't kill the delayed
4496 if (min_type == 0 && root == BTRFS_I(inode)->root)
4497 btrfs_kill_delayed_inode_items(BTRFS_I(inode));
4500 key.offset = (u64)-1;
4505 * with a 16K leaf size and 128MB extents, you can actually queue
4506 * up a huge file in a single leaf. Most of the time that
4507 * bytes_deleted is > 0, it will be huge by the time we get here
4509 if (be_nice && bytes_deleted > SZ_32M) {
4510 if (btrfs_should_end_transaction(trans)) {
4517 path->leave_spinning = 1;
4518 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
4525 /* there are no items in the tree for us to truncate, we're
4528 if (path->slots[0] == 0)
4535 leaf = path->nodes[0];
4536 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
4537 found_type = found_key.type;
4539 if (found_key.objectid != ino)
4542 if (found_type < min_type)
4545 item_end = found_key.offset;
4546 if (found_type == BTRFS_EXTENT_DATA_KEY) {
4547 fi = btrfs_item_ptr(leaf, path->slots[0],
4548 struct btrfs_file_extent_item);
4549 extent_type = btrfs_file_extent_type(leaf, fi);
4550 if (extent_type != BTRFS_FILE_EXTENT_INLINE) {
4552 btrfs_file_extent_num_bytes(leaf, fi);
4554 trace_btrfs_truncate_show_fi_regular(
4555 BTRFS_I(inode), leaf, fi,
4557 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
4558 item_end += btrfs_file_extent_inline_len(leaf,
4559 path->slots[0], fi);
4561 trace_btrfs_truncate_show_fi_inline(
4562 BTRFS_I(inode), leaf, fi, path->slots[0],
4567 if (found_type > min_type) {
4570 if (item_end < new_size)
4572 if (found_key.offset >= new_size)
4578 /* FIXME, shrink the extent if the ref count is only 1 */
4579 if (found_type != BTRFS_EXTENT_DATA_KEY)
4582 if (extent_type != BTRFS_FILE_EXTENT_INLINE) {
4584 extent_start = btrfs_file_extent_disk_bytenr(leaf, fi);
4586 u64 orig_num_bytes =
4587 btrfs_file_extent_num_bytes(leaf, fi);
4588 extent_num_bytes = ALIGN(new_size -
4590 fs_info->sectorsize);
4591 btrfs_set_file_extent_num_bytes(leaf, fi,
4593 num_dec = (orig_num_bytes -
4595 if (test_bit(BTRFS_ROOT_REF_COWS,
4598 inode_sub_bytes(inode, num_dec);
4599 btrfs_mark_buffer_dirty(leaf);
4602 btrfs_file_extent_disk_num_bytes(leaf,
4604 extent_offset = found_key.offset -
4605 btrfs_file_extent_offset(leaf, fi);
4607 /* FIXME blocksize != 4096 */
4608 num_dec = btrfs_file_extent_num_bytes(leaf, fi);
4609 if (extent_start != 0) {
4611 if (test_bit(BTRFS_ROOT_REF_COWS,
4613 inode_sub_bytes(inode, num_dec);
4616 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
4618 * we can't truncate inline items that have had
4622 btrfs_file_extent_encryption(leaf, fi) == 0 &&
4623 btrfs_file_extent_other_encoding(leaf, fi) == 0 &&
4624 btrfs_file_extent_compression(leaf, fi) == 0) {
4625 u32 size = (u32)(new_size - found_key.offset);
4627 btrfs_set_file_extent_ram_bytes(leaf, fi, size);
4628 size = btrfs_file_extent_calc_inline_size(size);
4629 btrfs_truncate_item(root->fs_info, path, size, 1);
4630 } else if (!del_item) {
4632 * We have to bail so the last_size is set to
4633 * just before this extent.
4635 err = NEED_TRUNCATE_BLOCK;
4639 if (test_bit(BTRFS_ROOT_REF_COWS, &root->state))
4640 inode_sub_bytes(inode, item_end + 1 - new_size);
4644 last_size = found_key.offset;
4646 last_size = new_size;
4648 if (!pending_del_nr) {
4649 /* no pending yet, add ourselves */
4650 pending_del_slot = path->slots[0];
4652 } else if (pending_del_nr &&
4653 path->slots[0] + 1 == pending_del_slot) {
4654 /* hop on the pending chunk */
4656 pending_del_slot = path->slots[0];
4663 should_throttle = false;
4666 (test_bit(BTRFS_ROOT_REF_COWS, &root->state) ||
4667 root == fs_info->tree_root)) {
4668 btrfs_set_path_blocking(path);
4669 bytes_deleted += extent_num_bytes;
4670 ret = btrfs_free_extent(trans, root, extent_start,
4671 extent_num_bytes, 0,
4672 btrfs_header_owner(leaf),
4673 ino, extent_offset);
4675 if (btrfs_should_throttle_delayed_refs(trans, fs_info))
4676 btrfs_async_run_delayed_refs(fs_info,
4677 trans->delayed_ref_updates * 2,
4680 if (truncate_space_check(trans, root,
4681 extent_num_bytes)) {
4684 if (btrfs_should_throttle_delayed_refs(trans,
4686 should_throttle = true;
4690 if (found_type == BTRFS_INODE_ITEM_KEY)
4693 if (path->slots[0] == 0 ||
4694 path->slots[0] != pending_del_slot ||
4695 should_throttle || should_end) {
4696 if (pending_del_nr) {
4697 ret = btrfs_del_items(trans, root, path,
4701 btrfs_abort_transaction(trans, ret);
4706 btrfs_release_path(path);
4707 if (should_throttle) {
4708 unsigned long updates = trans->delayed_ref_updates;
4710 trans->delayed_ref_updates = 0;
4711 ret = btrfs_run_delayed_refs(trans,
4719 * if we failed to refill our space rsv, bail out
4720 * and let the transaction restart
4732 if (pending_del_nr) {
4733 ret = btrfs_del_items(trans, root, path, pending_del_slot,
4736 btrfs_abort_transaction(trans, ret);
4739 if (root->root_key.objectid != BTRFS_TREE_LOG_OBJECTID) {
4740 ASSERT(last_size >= new_size);
4741 if (!err && last_size > new_size)
4742 last_size = new_size;
4743 btrfs_ordered_update_i_size(inode, last_size, NULL);
4746 btrfs_free_path(path);
4748 if (be_nice && bytes_deleted > SZ_32M) {
4749 unsigned long updates = trans->delayed_ref_updates;
4751 trans->delayed_ref_updates = 0;
4752 ret = btrfs_run_delayed_refs(trans, fs_info,
4762 * btrfs_truncate_block - read, zero a chunk and write a block
4763 * @inode - inode that we're zeroing
4764 * @from - the offset to start zeroing
4765 * @len - the length to zero, 0 to zero the entire range respective to the
4767 * @front - zero up to the offset instead of from the offset on
4769 * This will find the block for the "from" offset and cow the block and zero the
4770 * part we want to zero. This is used with truncate and hole punching.
4772 int btrfs_truncate_block(struct inode *inode, loff_t from, loff_t len,
4775 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
4776 struct address_space *mapping = inode->i_mapping;
4777 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
4778 struct btrfs_ordered_extent *ordered;
4779 struct extent_state *cached_state = NULL;
4780 struct extent_changeset *data_reserved = NULL;
4782 u32 blocksize = fs_info->sectorsize;
4783 pgoff_t index = from >> PAGE_SHIFT;
4784 unsigned offset = from & (blocksize - 1);
4786 gfp_t mask = btrfs_alloc_write_mask(mapping);
4791 if (IS_ALIGNED(offset, blocksize) &&
4792 (!len || IS_ALIGNED(len, blocksize)))
4795 block_start = round_down(from, blocksize);
4796 block_end = block_start + blocksize - 1;
4798 ret = btrfs_delalloc_reserve_space(inode, &data_reserved,
4799 block_start, blocksize);
4804 page = find_or_create_page(mapping, index, mask);
4806 btrfs_delalloc_release_space(inode, data_reserved,
4807 block_start, blocksize);
4808 btrfs_delalloc_release_extents(BTRFS_I(inode), blocksize);
4813 if (!PageUptodate(page)) {
4814 ret = btrfs_readpage(NULL, page);
4816 if (page->mapping != mapping) {
4821 if (!PageUptodate(page)) {
4826 wait_on_page_writeback(page);
4828 lock_extent_bits(io_tree, block_start, block_end, &cached_state);
4829 set_page_extent_mapped(page);
4831 ordered = btrfs_lookup_ordered_extent(inode, block_start);
4833 unlock_extent_cached(io_tree, block_start, block_end,
4837 btrfs_start_ordered_extent(inode, ordered, 1);
4838 btrfs_put_ordered_extent(ordered);
4842 clear_extent_bit(&BTRFS_I(inode)->io_tree, block_start, block_end,
4843 EXTENT_DIRTY | EXTENT_DELALLOC |
4844 EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG,
4845 0, 0, &cached_state);
4847 ret = btrfs_set_extent_delalloc(inode, block_start, block_end, 0,
4850 unlock_extent_cached(io_tree, block_start, block_end,
4855 if (offset != blocksize) {
4857 len = blocksize - offset;
4860 memset(kaddr + (block_start - page_offset(page)),
4863 memset(kaddr + (block_start - page_offset(page)) + offset,
4865 flush_dcache_page(page);
4868 ClearPageChecked(page);
4869 set_page_dirty(page);
4870 unlock_extent_cached(io_tree, block_start, block_end, &cached_state);
4874 btrfs_delalloc_release_space(inode, data_reserved, block_start,
4876 btrfs_delalloc_release_extents(BTRFS_I(inode), blocksize);
4880 extent_changeset_free(data_reserved);
4884 static int maybe_insert_hole(struct btrfs_root *root, struct inode *inode,
4885 u64 offset, u64 len)
4887 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
4888 struct btrfs_trans_handle *trans;
4892 * Still need to make sure the inode looks like it's been updated so
4893 * that any holes get logged if we fsync.
4895 if (btrfs_fs_incompat(fs_info, NO_HOLES)) {
4896 BTRFS_I(inode)->last_trans = fs_info->generation;
4897 BTRFS_I(inode)->last_sub_trans = root->log_transid;
4898 BTRFS_I(inode)->last_log_commit = root->last_log_commit;
4903 * 1 - for the one we're dropping
4904 * 1 - for the one we're adding
4905 * 1 - for updating the inode.
4907 trans = btrfs_start_transaction(root, 3);
4909 return PTR_ERR(trans);
4911 ret = btrfs_drop_extents(trans, root, inode, offset, offset + len, 1);
4913 btrfs_abort_transaction(trans, ret);
4914 btrfs_end_transaction(trans);
4918 ret = btrfs_insert_file_extent(trans, root, btrfs_ino(BTRFS_I(inode)),
4919 offset, 0, 0, len, 0, len, 0, 0, 0);
4921 btrfs_abort_transaction(trans, ret);
4923 btrfs_update_inode(trans, root, inode);
4924 btrfs_end_transaction(trans);
4929 * This function puts in dummy file extents for the area we're creating a hole
4930 * for. So if we are truncating this file to a larger size we need to insert
4931 * these file extents so that btrfs_get_extent will return a EXTENT_MAP_HOLE for
4932 * the range between oldsize and size
4934 int btrfs_cont_expand(struct inode *inode, loff_t oldsize, loff_t size)
4936 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
4937 struct btrfs_root *root = BTRFS_I(inode)->root;
4938 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
4939 struct extent_map *em = NULL;
4940 struct extent_state *cached_state = NULL;
4941 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
4942 u64 hole_start = ALIGN(oldsize, fs_info->sectorsize);
4943 u64 block_end = ALIGN(size, fs_info->sectorsize);
4950 * If our size started in the middle of a block we need to zero out the
4951 * rest of the block before we expand the i_size, otherwise we could
4952 * expose stale data.
4954 err = btrfs_truncate_block(inode, oldsize, 0, 0);
4958 if (size <= hole_start)
4962 struct btrfs_ordered_extent *ordered;
4964 lock_extent_bits(io_tree, hole_start, block_end - 1,
4966 ordered = btrfs_lookup_ordered_range(BTRFS_I(inode), hole_start,
4967 block_end - hole_start);
4970 unlock_extent_cached(io_tree, hole_start, block_end - 1,
4972 btrfs_start_ordered_extent(inode, ordered, 1);
4973 btrfs_put_ordered_extent(ordered);
4976 cur_offset = hole_start;
4978 em = btrfs_get_extent(BTRFS_I(inode), NULL, 0, cur_offset,
4979 block_end - cur_offset, 0);
4985 last_byte = min(extent_map_end(em), block_end);
4986 last_byte = ALIGN(last_byte, fs_info->sectorsize);
4987 if (!test_bit(EXTENT_FLAG_PREALLOC, &em->flags)) {
4988 struct extent_map *hole_em;
4989 hole_size = last_byte - cur_offset;
4991 err = maybe_insert_hole(root, inode, cur_offset,
4995 btrfs_drop_extent_cache(BTRFS_I(inode), cur_offset,
4996 cur_offset + hole_size - 1, 0);
4997 hole_em = alloc_extent_map();
4999 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
5000 &BTRFS_I(inode)->runtime_flags);
5003 hole_em->start = cur_offset;
5004 hole_em->len = hole_size;
5005 hole_em->orig_start = cur_offset;
5007 hole_em->block_start = EXTENT_MAP_HOLE;
5008 hole_em->block_len = 0;
5009 hole_em->orig_block_len = 0;
5010 hole_em->ram_bytes = hole_size;
5011 hole_em->bdev = fs_info->fs_devices->latest_bdev;
5012 hole_em->compress_type = BTRFS_COMPRESS_NONE;
5013 hole_em->generation = fs_info->generation;
5016 write_lock(&em_tree->lock);
5017 err = add_extent_mapping(em_tree, hole_em, 1);
5018 write_unlock(&em_tree->lock);
5021 btrfs_drop_extent_cache(BTRFS_I(inode),
5026 free_extent_map(hole_em);
5029 free_extent_map(em);
5031 cur_offset = last_byte;
5032 if (cur_offset >= block_end)
5035 free_extent_map(em);
5036 unlock_extent_cached(io_tree, hole_start, block_end - 1, &cached_state);
5040 static int btrfs_setsize(struct inode *inode, struct iattr *attr)
5042 struct btrfs_root *root = BTRFS_I(inode)->root;
5043 struct btrfs_trans_handle *trans;
5044 loff_t oldsize = i_size_read(inode);
5045 loff_t newsize = attr->ia_size;
5046 int mask = attr->ia_valid;
5050 * The regular truncate() case without ATTR_CTIME and ATTR_MTIME is a
5051 * special case where we need to update the times despite not having
5052 * these flags set. For all other operations the VFS set these flags
5053 * explicitly if it wants a timestamp update.
5055 if (newsize != oldsize) {
5056 inode_inc_iversion(inode);
5057 if (!(mask & (ATTR_CTIME | ATTR_MTIME)))
5058 inode->i_ctime = inode->i_mtime =
5059 current_time(inode);
5062 if (newsize > oldsize) {
5064 * Don't do an expanding truncate while snapshotting is ongoing.
5065 * This is to ensure the snapshot captures a fully consistent
5066 * state of this file - if the snapshot captures this expanding
5067 * truncation, it must capture all writes that happened before
5070 btrfs_wait_for_snapshot_creation(root);
5071 ret = btrfs_cont_expand(inode, oldsize, newsize);
5073 btrfs_end_write_no_snapshotting(root);
5077 trans = btrfs_start_transaction(root, 1);
5078 if (IS_ERR(trans)) {
5079 btrfs_end_write_no_snapshotting(root);
5080 return PTR_ERR(trans);
5083 i_size_write(inode, newsize);
5084 btrfs_ordered_update_i_size(inode, i_size_read(inode), NULL);
5085 pagecache_isize_extended(inode, oldsize, newsize);
5086 ret = btrfs_update_inode(trans, root, inode);
5087 btrfs_end_write_no_snapshotting(root);
5088 btrfs_end_transaction(trans);
5092 * We're truncating a file that used to have good data down to
5093 * zero. Make sure it gets into the ordered flush list so that
5094 * any new writes get down to disk quickly.
5097 set_bit(BTRFS_INODE_ORDERED_DATA_CLOSE,
5098 &BTRFS_I(inode)->runtime_flags);
5101 * 1 for the orphan item we're going to add
5102 * 1 for the orphan item deletion.
5104 trans = btrfs_start_transaction(root, 2);
5106 return PTR_ERR(trans);
5109 * We need to do this in case we fail at _any_ point during the
5110 * actual truncate. Once we do the truncate_setsize we could
5111 * invalidate pages which forces any outstanding ordered io to
5112 * be instantly completed which will give us extents that need
5113 * to be truncated. If we fail to get an orphan inode down we
5114 * could have left over extents that were never meant to live,
5115 * so we need to guarantee from this point on that everything
5116 * will be consistent.
5118 ret = btrfs_orphan_add(trans, BTRFS_I(inode));
5119 btrfs_end_transaction(trans);
5123 /* we don't support swapfiles, so vmtruncate shouldn't fail */
5124 truncate_setsize(inode, newsize);
5126 /* Disable nonlocked read DIO to avoid the end less truncate */
5127 btrfs_inode_block_unlocked_dio(BTRFS_I(inode));
5128 inode_dio_wait(inode);
5129 btrfs_inode_resume_unlocked_dio(BTRFS_I(inode));
5131 ret = btrfs_truncate(inode);
5132 if (ret && inode->i_nlink) {
5135 /* To get a stable disk_i_size */
5136 err = btrfs_wait_ordered_range(inode, 0, (u64)-1);
5138 btrfs_orphan_del(NULL, BTRFS_I(inode));
5143 * failed to truncate, disk_i_size is only adjusted down
5144 * as we remove extents, so it should represent the true
5145 * size of the inode, so reset the in memory size and
5146 * delete our orphan entry.
5148 trans = btrfs_join_transaction(root);
5149 if (IS_ERR(trans)) {
5150 btrfs_orphan_del(NULL, BTRFS_I(inode));
5153 i_size_write(inode, BTRFS_I(inode)->disk_i_size);
5154 err = btrfs_orphan_del(trans, BTRFS_I(inode));
5156 btrfs_abort_transaction(trans, err);
5157 btrfs_end_transaction(trans);
5164 static int btrfs_setattr(struct dentry *dentry, struct iattr *attr)
5166 struct inode *inode = d_inode(dentry);
5167 struct btrfs_root *root = BTRFS_I(inode)->root;
5170 if (btrfs_root_readonly(root))
5173 err = setattr_prepare(dentry, attr);
5177 if (S_ISREG(inode->i_mode) && (attr->ia_valid & ATTR_SIZE)) {
5178 err = btrfs_setsize(inode, attr);
5183 if (attr->ia_valid) {
5184 setattr_copy(inode, attr);
5185 inode_inc_iversion(inode);
5186 err = btrfs_dirty_inode(inode);
5188 if (!err && attr->ia_valid & ATTR_MODE)
5189 err = posix_acl_chmod(inode, inode->i_mode);
5196 * While truncating the inode pages during eviction, we get the VFS calling
5197 * btrfs_invalidatepage() against each page of the inode. This is slow because
5198 * the calls to btrfs_invalidatepage() result in a huge amount of calls to
5199 * lock_extent_bits() and clear_extent_bit(), which keep merging and splitting
5200 * extent_state structures over and over, wasting lots of time.
5202 * Therefore if the inode is being evicted, let btrfs_invalidatepage() skip all
5203 * those expensive operations on a per page basis and do only the ordered io
5204 * finishing, while we release here the extent_map and extent_state structures,
5205 * without the excessive merging and splitting.
5207 static void evict_inode_truncate_pages(struct inode *inode)
5209 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
5210 struct extent_map_tree *map_tree = &BTRFS_I(inode)->extent_tree;
5211 struct rb_node *node;
5213 ASSERT(inode->i_state & I_FREEING);
5214 truncate_inode_pages_final(&inode->i_data);
5216 write_lock(&map_tree->lock);
5217 while (!RB_EMPTY_ROOT(&map_tree->map)) {
5218 struct extent_map *em;
5220 node = rb_first(&map_tree->map);
5221 em = rb_entry(node, struct extent_map, rb_node);
5222 clear_bit(EXTENT_FLAG_PINNED, &em->flags);
5223 clear_bit(EXTENT_FLAG_LOGGING, &em->flags);
5224 remove_extent_mapping(map_tree, em);
5225 free_extent_map(em);
5226 if (need_resched()) {
5227 write_unlock(&map_tree->lock);
5229 write_lock(&map_tree->lock);
5232 write_unlock(&map_tree->lock);
5235 * Keep looping until we have no more ranges in the io tree.
5236 * We can have ongoing bios started by readpages (called from readahead)
5237 * that have their endio callback (extent_io.c:end_bio_extent_readpage)
5238 * still in progress (unlocked the pages in the bio but did not yet
5239 * unlocked the ranges in the io tree). Therefore this means some
5240 * ranges can still be locked and eviction started because before
5241 * submitting those bios, which are executed by a separate task (work
5242 * queue kthread), inode references (inode->i_count) were not taken
5243 * (which would be dropped in the end io callback of each bio).
5244 * Therefore here we effectively end up waiting for those bios and
5245 * anyone else holding locked ranges without having bumped the inode's
5246 * reference count - if we don't do it, when they access the inode's
5247 * io_tree to unlock a range it may be too late, leading to an
5248 * use-after-free issue.
5250 spin_lock(&io_tree->lock);
5251 while (!RB_EMPTY_ROOT(&io_tree->state)) {
5252 struct extent_state *state;
5253 struct extent_state *cached_state = NULL;
5257 node = rb_first(&io_tree->state);
5258 state = rb_entry(node, struct extent_state, rb_node);
5259 start = state->start;
5261 spin_unlock(&io_tree->lock);
5263 lock_extent_bits(io_tree, start, end, &cached_state);
5266 * If still has DELALLOC flag, the extent didn't reach disk,
5267 * and its reserved space won't be freed by delayed_ref.
5268 * So we need to free its reserved space here.
5269 * (Refer to comment in btrfs_invalidatepage, case 2)
5271 * Note, end is the bytenr of last byte, so we need + 1 here.
5273 if (state->state & EXTENT_DELALLOC)
5274 btrfs_qgroup_free_data(inode, NULL, start, end - start + 1);
5276 clear_extent_bit(io_tree, start, end,
5277 EXTENT_LOCKED | EXTENT_DIRTY |
5278 EXTENT_DELALLOC | EXTENT_DO_ACCOUNTING |
5279 EXTENT_DEFRAG, 1, 1, &cached_state);
5282 spin_lock(&io_tree->lock);
5284 spin_unlock(&io_tree->lock);
5287 void btrfs_evict_inode(struct inode *inode)
5289 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
5290 struct btrfs_trans_handle *trans;
5291 struct btrfs_root *root = BTRFS_I(inode)->root;
5292 struct btrfs_block_rsv *rsv, *global_rsv;
5293 int steal_from_global = 0;
5297 trace_btrfs_inode_evict(inode);
5304 min_size = btrfs_calc_trunc_metadata_size(fs_info, 1);
5306 evict_inode_truncate_pages(inode);
5308 if (inode->i_nlink &&
5309 ((btrfs_root_refs(&root->root_item) != 0 &&
5310 root->root_key.objectid != BTRFS_ROOT_TREE_OBJECTID) ||
5311 btrfs_is_free_space_inode(BTRFS_I(inode))))
5314 if (is_bad_inode(inode)) {
5315 btrfs_orphan_del(NULL, BTRFS_I(inode));
5318 /* do we really want it for ->i_nlink > 0 and zero btrfs_root_refs? */
5319 if (!special_file(inode->i_mode))
5320 btrfs_wait_ordered_range(inode, 0, (u64)-1);
5322 btrfs_free_io_failure_record(BTRFS_I(inode), 0, (u64)-1);
5324 if (test_bit(BTRFS_FS_LOG_RECOVERING, &fs_info->flags)) {
5325 BUG_ON(test_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
5326 &BTRFS_I(inode)->runtime_flags));
5330 if (inode->i_nlink > 0) {
5331 BUG_ON(btrfs_root_refs(&root->root_item) != 0 &&
5332 root->root_key.objectid != BTRFS_ROOT_TREE_OBJECTID);
5336 ret = btrfs_commit_inode_delayed_inode(BTRFS_I(inode));
5338 btrfs_orphan_del(NULL, BTRFS_I(inode));
5342 rsv = btrfs_alloc_block_rsv(fs_info, BTRFS_BLOCK_RSV_TEMP);
5344 btrfs_orphan_del(NULL, BTRFS_I(inode));
5347 rsv->size = min_size;
5349 global_rsv = &fs_info->global_block_rsv;
5351 btrfs_i_size_write(BTRFS_I(inode), 0);
5354 * This is a bit simpler than btrfs_truncate since we've already
5355 * reserved our space for our orphan item in the unlink, so we just
5356 * need to reserve some slack space in case we add bytes and update
5357 * inode item when doing the truncate.
5360 ret = btrfs_block_rsv_refill(root, rsv, min_size,
5361 BTRFS_RESERVE_FLUSH_LIMIT);
5364 * Try and steal from the global reserve since we will
5365 * likely not use this space anyway, we want to try as
5366 * hard as possible to get this to work.
5369 steal_from_global++;
5371 steal_from_global = 0;
5375 * steal_from_global == 0: we reserved stuff, hooray!
5376 * steal_from_global == 1: we didn't reserve stuff, boo!
5377 * steal_from_global == 2: we've committed, still not a lot of
5378 * room but maybe we'll have room in the global reserve this
5380 * steal_from_global == 3: abandon all hope!
5382 if (steal_from_global > 2) {
5384 "Could not get space for a delete, will truncate on mount %d",
5386 btrfs_orphan_del(NULL, BTRFS_I(inode));
5387 btrfs_free_block_rsv(fs_info, rsv);
5391 trans = btrfs_join_transaction(root);
5392 if (IS_ERR(trans)) {
5393 btrfs_orphan_del(NULL, BTRFS_I(inode));
5394 btrfs_free_block_rsv(fs_info, rsv);
5399 * We can't just steal from the global reserve, we need to make
5400 * sure there is room to do it, if not we need to commit and try
5403 if (steal_from_global) {
5404 if (!btrfs_check_space_for_delayed_refs(trans, fs_info))
5405 ret = btrfs_block_rsv_migrate(global_rsv, rsv,
5412 * Couldn't steal from the global reserve, we have too much
5413 * pending stuff built up, commit the transaction and try it
5417 ret = btrfs_commit_transaction(trans);
5419 btrfs_orphan_del(NULL, BTRFS_I(inode));
5420 btrfs_free_block_rsv(fs_info, rsv);
5425 steal_from_global = 0;
5428 trans->block_rsv = rsv;
5430 ret = btrfs_truncate_inode_items(trans, root, inode, 0, 0);
5431 if (ret != -ENOSPC && ret != -EAGAIN)
5434 trans->block_rsv = &fs_info->trans_block_rsv;
5435 btrfs_end_transaction(trans);
5437 btrfs_btree_balance_dirty(fs_info);
5440 btrfs_free_block_rsv(fs_info, rsv);
5443 * Errors here aren't a big deal, it just means we leave orphan items
5444 * in the tree. They will be cleaned up on the next mount.
5447 trans->block_rsv = root->orphan_block_rsv;
5448 btrfs_orphan_del(trans, BTRFS_I(inode));
5450 btrfs_orphan_del(NULL, BTRFS_I(inode));
5453 trans->block_rsv = &fs_info->trans_block_rsv;
5454 if (!(root == fs_info->tree_root ||
5455 root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID))
5456 btrfs_return_ino(root, btrfs_ino(BTRFS_I(inode)));
5458 btrfs_end_transaction(trans);
5459 btrfs_btree_balance_dirty(fs_info);
5461 btrfs_remove_delayed_node(BTRFS_I(inode));
5466 * this returns the key found in the dir entry in the location pointer.
5467 * If no dir entries were found, location->objectid is 0.
5469 static int btrfs_inode_by_name(struct inode *dir, struct dentry *dentry,
5470 struct btrfs_key *location)
5472 const char *name = dentry->d_name.name;
5473 int namelen = dentry->d_name.len;
5474 struct btrfs_dir_item *di;
5475 struct btrfs_path *path;
5476 struct btrfs_root *root = BTRFS_I(dir)->root;
5479 path = btrfs_alloc_path();
5483 di = btrfs_lookup_dir_item(NULL, root, path, btrfs_ino(BTRFS_I(dir)),
5488 if (IS_ERR_OR_NULL(di))
5491 btrfs_dir_item_key_to_cpu(path->nodes[0], di, location);
5492 if (location->type != BTRFS_INODE_ITEM_KEY &&
5493 location->type != BTRFS_ROOT_ITEM_KEY) {
5494 btrfs_warn(root->fs_info,
5495 "%s gets something invalid in DIR_ITEM (name %s, directory ino %llu, location(%llu %u %llu))",
5496 __func__, name, btrfs_ino(BTRFS_I(dir)),
5497 location->objectid, location->type, location->offset);
5501 btrfs_free_path(path);
5504 location->objectid = 0;
5509 * when we hit a tree root in a directory, the btrfs part of the inode
5510 * needs to be changed to reflect the root directory of the tree root. This
5511 * is kind of like crossing a mount point.
5513 static int fixup_tree_root_location(struct btrfs_fs_info *fs_info,
5515 struct dentry *dentry,
5516 struct btrfs_key *location,
5517 struct btrfs_root **sub_root)
5519 struct btrfs_path *path;
5520 struct btrfs_root *new_root;
5521 struct btrfs_root_ref *ref;
5522 struct extent_buffer *leaf;
5523 struct btrfs_key key;
5527 path = btrfs_alloc_path();
5534 key.objectid = BTRFS_I(dir)->root->root_key.objectid;
5535 key.type = BTRFS_ROOT_REF_KEY;
5536 key.offset = location->objectid;
5538 ret = btrfs_search_slot(NULL, fs_info->tree_root, &key, path, 0, 0);
5545 leaf = path->nodes[0];
5546 ref = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_root_ref);
5547 if (btrfs_root_ref_dirid(leaf, ref) != btrfs_ino(BTRFS_I(dir)) ||
5548 btrfs_root_ref_name_len(leaf, ref) != dentry->d_name.len)
5551 ret = memcmp_extent_buffer(leaf, dentry->d_name.name,
5552 (unsigned long)(ref + 1),
5553 dentry->d_name.len);
5557 btrfs_release_path(path);
5559 new_root = btrfs_read_fs_root_no_name(fs_info, location);
5560 if (IS_ERR(new_root)) {
5561 err = PTR_ERR(new_root);
5565 *sub_root = new_root;
5566 location->objectid = btrfs_root_dirid(&new_root->root_item);
5567 location->type = BTRFS_INODE_ITEM_KEY;
5568 location->offset = 0;
5571 btrfs_free_path(path);
5575 static void inode_tree_add(struct inode *inode)
5577 struct btrfs_root *root = BTRFS_I(inode)->root;
5578 struct btrfs_inode *entry;
5580 struct rb_node *parent;
5581 struct rb_node *new = &BTRFS_I(inode)->rb_node;
5582 u64 ino = btrfs_ino(BTRFS_I(inode));
5584 if (inode_unhashed(inode))
5587 spin_lock(&root->inode_lock);
5588 p = &root->inode_tree.rb_node;
5591 entry = rb_entry(parent, struct btrfs_inode, rb_node);
5593 if (ino < btrfs_ino(BTRFS_I(&entry->vfs_inode)))
5594 p = &parent->rb_left;
5595 else if (ino > btrfs_ino(BTRFS_I(&entry->vfs_inode)))
5596 p = &parent->rb_right;
5598 WARN_ON(!(entry->vfs_inode.i_state &
5599 (I_WILL_FREE | I_FREEING)));
5600 rb_replace_node(parent, new, &root->inode_tree);
5601 RB_CLEAR_NODE(parent);
5602 spin_unlock(&root->inode_lock);
5606 rb_link_node(new, parent, p);
5607 rb_insert_color(new, &root->inode_tree);
5608 spin_unlock(&root->inode_lock);
5611 static void inode_tree_del(struct inode *inode)
5613 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
5614 struct btrfs_root *root = BTRFS_I(inode)->root;
5617 spin_lock(&root->inode_lock);
5618 if (!RB_EMPTY_NODE(&BTRFS_I(inode)->rb_node)) {
5619 rb_erase(&BTRFS_I(inode)->rb_node, &root->inode_tree);
5620 RB_CLEAR_NODE(&BTRFS_I(inode)->rb_node);
5621 empty = RB_EMPTY_ROOT(&root->inode_tree);
5623 spin_unlock(&root->inode_lock);
5625 if (empty && btrfs_root_refs(&root->root_item) == 0) {
5626 synchronize_srcu(&fs_info->subvol_srcu);
5627 spin_lock(&root->inode_lock);
5628 empty = RB_EMPTY_ROOT(&root->inode_tree);
5629 spin_unlock(&root->inode_lock);
5631 btrfs_add_dead_root(root);
5635 void btrfs_invalidate_inodes(struct btrfs_root *root)
5637 struct btrfs_fs_info *fs_info = root->fs_info;
5638 struct rb_node *node;
5639 struct rb_node *prev;
5640 struct btrfs_inode *entry;
5641 struct inode *inode;
5644 if (!test_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state))
5645 WARN_ON(btrfs_root_refs(&root->root_item) != 0);
5647 spin_lock(&root->inode_lock);
5649 node = root->inode_tree.rb_node;
5653 entry = rb_entry(node, struct btrfs_inode, rb_node);
5655 if (objectid < btrfs_ino(BTRFS_I(&entry->vfs_inode)))
5656 node = node->rb_left;
5657 else if (objectid > btrfs_ino(BTRFS_I(&entry->vfs_inode)))
5658 node = node->rb_right;
5664 entry = rb_entry(prev, struct btrfs_inode, rb_node);
5665 if (objectid <= btrfs_ino(BTRFS_I(&entry->vfs_inode))) {
5669 prev = rb_next(prev);
5673 entry = rb_entry(node, struct btrfs_inode, rb_node);
5674 objectid = btrfs_ino(BTRFS_I(&entry->vfs_inode)) + 1;
5675 inode = igrab(&entry->vfs_inode);
5677 spin_unlock(&root->inode_lock);
5678 if (atomic_read(&inode->i_count) > 1)
5679 d_prune_aliases(inode);
5681 * btrfs_drop_inode will have it removed from
5682 * the inode cache when its usage count
5687 spin_lock(&root->inode_lock);
5691 if (cond_resched_lock(&root->inode_lock))
5694 node = rb_next(node);
5696 spin_unlock(&root->inode_lock);
5699 static int btrfs_init_locked_inode(struct inode *inode, void *p)
5701 struct btrfs_iget_args *args = p;
5702 inode->i_ino = args->location->objectid;
5703 memcpy(&BTRFS_I(inode)->location, args->location,
5704 sizeof(*args->location));
5705 BTRFS_I(inode)->root = args->root;
5709 static int btrfs_find_actor(struct inode *inode, void *opaque)
5711 struct btrfs_iget_args *args = opaque;
5712 return args->location->objectid == BTRFS_I(inode)->location.objectid &&
5713 args->root == BTRFS_I(inode)->root;
5716 static struct inode *btrfs_iget_locked(struct super_block *s,
5717 struct btrfs_key *location,
5718 struct btrfs_root *root)
5720 struct inode *inode;
5721 struct btrfs_iget_args args;
5722 unsigned long hashval = btrfs_inode_hash(location->objectid, root);
5724 args.location = location;
5727 inode = iget5_locked(s, hashval, btrfs_find_actor,
5728 btrfs_init_locked_inode,
5733 /* Get an inode object given its location and corresponding root.
5734 * Returns in *is_new if the inode was read from disk
5736 struct inode *btrfs_iget(struct super_block *s, struct btrfs_key *location,
5737 struct btrfs_root *root, int *new)
5739 struct inode *inode;
5741 inode = btrfs_iget_locked(s, location, root);
5743 return ERR_PTR(-ENOMEM);
5745 if (inode->i_state & I_NEW) {
5748 ret = btrfs_read_locked_inode(inode);
5749 if (!is_bad_inode(inode)) {
5750 inode_tree_add(inode);
5751 unlock_new_inode(inode);
5755 unlock_new_inode(inode);
5758 inode = ERR_PTR(ret < 0 ? ret : -ESTALE);
5765 static struct inode *new_simple_dir(struct super_block *s,
5766 struct btrfs_key *key,
5767 struct btrfs_root *root)
5769 struct inode *inode = new_inode(s);
5772 return ERR_PTR(-ENOMEM);
5774 BTRFS_I(inode)->root = root;
5775 memcpy(&BTRFS_I(inode)->location, key, sizeof(*key));
5776 set_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags);
5778 inode->i_ino = BTRFS_EMPTY_SUBVOL_DIR_OBJECTID;
5779 inode->i_op = &btrfs_dir_ro_inode_operations;
5780 inode->i_opflags &= ~IOP_XATTR;
5781 inode->i_fop = &simple_dir_operations;
5782 inode->i_mode = S_IFDIR | S_IRUGO | S_IWUSR | S_IXUGO;
5783 inode->i_mtime = current_time(inode);
5784 inode->i_atime = inode->i_mtime;
5785 inode->i_ctime = inode->i_mtime;
5786 BTRFS_I(inode)->i_otime = inode->i_mtime;
5791 struct inode *btrfs_lookup_dentry(struct inode *dir, struct dentry *dentry)
5793 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
5794 struct inode *inode;
5795 struct btrfs_root *root = BTRFS_I(dir)->root;
5796 struct btrfs_root *sub_root = root;
5797 struct btrfs_key location;
5801 if (dentry->d_name.len > BTRFS_NAME_LEN)
5802 return ERR_PTR(-ENAMETOOLONG);
5804 ret = btrfs_inode_by_name(dir, dentry, &location);
5806 return ERR_PTR(ret);
5808 if (location.objectid == 0)
5809 return ERR_PTR(-ENOENT);
5811 if (location.type == BTRFS_INODE_ITEM_KEY) {
5812 inode = btrfs_iget(dir->i_sb, &location, root, NULL);
5816 index = srcu_read_lock(&fs_info->subvol_srcu);
5817 ret = fixup_tree_root_location(fs_info, dir, dentry,
5818 &location, &sub_root);
5821 inode = ERR_PTR(ret);
5823 inode = new_simple_dir(dir->i_sb, &location, sub_root);
5825 inode = btrfs_iget(dir->i_sb, &location, sub_root, NULL);
5827 srcu_read_unlock(&fs_info->subvol_srcu, index);
5829 if (!IS_ERR(inode) && root != sub_root) {
5830 down_read(&fs_info->cleanup_work_sem);
5831 if (!sb_rdonly(inode->i_sb))
5832 ret = btrfs_orphan_cleanup(sub_root);
5833 up_read(&fs_info->cleanup_work_sem);
5836 inode = ERR_PTR(ret);
5843 static int btrfs_dentry_delete(const struct dentry *dentry)
5845 struct btrfs_root *root;
5846 struct inode *inode = d_inode(dentry);
5848 if (!inode && !IS_ROOT(dentry))
5849 inode = d_inode(dentry->d_parent);
5852 root = BTRFS_I(inode)->root;
5853 if (btrfs_root_refs(&root->root_item) == 0)
5856 if (btrfs_ino(BTRFS_I(inode)) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)
5862 static void btrfs_dentry_release(struct dentry *dentry)
5864 kfree(dentry->d_fsdata);
5867 static struct dentry *btrfs_lookup(struct inode *dir, struct dentry *dentry,
5870 struct inode *inode;
5872 inode = btrfs_lookup_dentry(dir, dentry);
5873 if (IS_ERR(inode)) {
5874 if (PTR_ERR(inode) == -ENOENT)
5877 return ERR_CAST(inode);
5880 return d_splice_alias(inode, dentry);
5883 unsigned char btrfs_filetype_table[] = {
5884 DT_UNKNOWN, DT_REG, DT_DIR, DT_CHR, DT_BLK, DT_FIFO, DT_SOCK, DT_LNK
5888 * All this infrastructure exists because dir_emit can fault, and we are holding
5889 * the tree lock when doing readdir. For now just allocate a buffer and copy
5890 * our information into that, and then dir_emit from the buffer. This is
5891 * similar to what NFS does, only we don't keep the buffer around in pagecache
5892 * because I'm afraid I'll mess that up. Long term we need to make filldir do
5893 * copy_to_user_inatomic so we don't have to worry about page faulting under the
5896 static int btrfs_opendir(struct inode *inode, struct file *file)
5898 struct btrfs_file_private *private;
5900 private = kzalloc(sizeof(struct btrfs_file_private), GFP_KERNEL);
5903 private->filldir_buf = kzalloc(PAGE_SIZE, GFP_KERNEL);
5904 if (!private->filldir_buf) {
5908 file->private_data = private;
5919 static int btrfs_filldir(void *addr, int entries, struct dir_context *ctx)
5922 struct dir_entry *entry = addr;
5923 char *name = (char *)(entry + 1);
5925 ctx->pos = entry->offset;
5926 if (!dir_emit(ctx, name, entry->name_len, entry->ino,
5929 addr += sizeof(struct dir_entry) + entry->name_len;
5935 static int btrfs_real_readdir(struct file *file, struct dir_context *ctx)
5937 struct inode *inode = file_inode(file);
5938 struct btrfs_root *root = BTRFS_I(inode)->root;
5939 struct btrfs_file_private *private = file->private_data;
5940 struct btrfs_dir_item *di;
5941 struct btrfs_key key;
5942 struct btrfs_key found_key;
5943 struct btrfs_path *path;
5945 struct list_head ins_list;
5946 struct list_head del_list;
5948 struct extent_buffer *leaf;
5955 struct btrfs_key location;
5957 if (!dir_emit_dots(file, ctx))
5960 path = btrfs_alloc_path();
5964 addr = private->filldir_buf;
5965 path->reada = READA_FORWARD;
5967 INIT_LIST_HEAD(&ins_list);
5968 INIT_LIST_HEAD(&del_list);
5969 put = btrfs_readdir_get_delayed_items(inode, &ins_list, &del_list);
5972 key.type = BTRFS_DIR_INDEX_KEY;
5973 key.offset = ctx->pos;
5974 key.objectid = btrfs_ino(BTRFS_I(inode));
5976 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
5981 struct dir_entry *entry;
5983 leaf = path->nodes[0];
5984 slot = path->slots[0];
5985 if (slot >= btrfs_header_nritems(leaf)) {
5986 ret = btrfs_next_leaf(root, path);
5994 btrfs_item_key_to_cpu(leaf, &found_key, slot);
5996 if (found_key.objectid != key.objectid)
5998 if (found_key.type != BTRFS_DIR_INDEX_KEY)
6000 if (found_key.offset < ctx->pos)
6002 if (btrfs_should_delete_dir_index(&del_list, found_key.offset))
6004 di = btrfs_item_ptr(leaf, slot, struct btrfs_dir_item);
6005 name_len = btrfs_dir_name_len(leaf, di);
6006 if ((total_len + sizeof(struct dir_entry) + name_len) >=
6008 btrfs_release_path(path);
6009 ret = btrfs_filldir(private->filldir_buf, entries, ctx);
6012 addr = private->filldir_buf;
6019 entry->name_len = name_len;
6020 name_ptr = (char *)(entry + 1);
6021 read_extent_buffer(leaf, name_ptr, (unsigned long)(di + 1),
6023 entry->type = btrfs_filetype_table[btrfs_dir_type(leaf, di)];
6024 btrfs_dir_item_key_to_cpu(leaf, di, &location);
6025 entry->ino = location.objectid;
6026 entry->offset = found_key.offset;
6028 addr += sizeof(struct dir_entry) + name_len;
6029 total_len += sizeof(struct dir_entry) + name_len;
6033 btrfs_release_path(path);
6035 ret = btrfs_filldir(private->filldir_buf, entries, ctx);
6039 ret = btrfs_readdir_delayed_dir_index(ctx, &ins_list);
6044 * Stop new entries from being returned after we return the last
6047 * New directory entries are assigned a strictly increasing
6048 * offset. This means that new entries created during readdir
6049 * are *guaranteed* to be seen in the future by that readdir.
6050 * This has broken buggy programs which operate on names as
6051 * they're returned by readdir. Until we re-use freed offsets
6052 * we have this hack to stop new entries from being returned
6053 * under the assumption that they'll never reach this huge
6056 * This is being careful not to overflow 32bit loff_t unless the
6057 * last entry requires it because doing so has broken 32bit apps
6060 if (ctx->pos >= INT_MAX)
6061 ctx->pos = LLONG_MAX;
6068 btrfs_readdir_put_delayed_items(inode, &ins_list, &del_list);
6069 btrfs_free_path(path);
6073 int btrfs_write_inode(struct inode *inode, struct writeback_control *wbc)
6075 struct btrfs_root *root = BTRFS_I(inode)->root;
6076 struct btrfs_trans_handle *trans;
6078 bool nolock = false;
6080 if (test_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags))
6083 if (btrfs_fs_closing(root->fs_info) &&
6084 btrfs_is_free_space_inode(BTRFS_I(inode)))
6087 if (wbc->sync_mode == WB_SYNC_ALL) {
6089 trans = btrfs_join_transaction_nolock(root);
6091 trans = btrfs_join_transaction(root);
6093 return PTR_ERR(trans);
6094 ret = btrfs_commit_transaction(trans);
6100 * This is somewhat expensive, updating the tree every time the
6101 * inode changes. But, it is most likely to find the inode in cache.
6102 * FIXME, needs more benchmarking...there are no reasons other than performance
6103 * to keep or drop this code.
6105 static int btrfs_dirty_inode(struct inode *inode)
6107 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
6108 struct btrfs_root *root = BTRFS_I(inode)->root;
6109 struct btrfs_trans_handle *trans;
6112 if (test_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags))
6115 trans = btrfs_join_transaction(root);
6117 return PTR_ERR(trans);
6119 ret = btrfs_update_inode(trans, root, inode);
6120 if (ret && ret == -ENOSPC) {
6121 /* whoops, lets try again with the full transaction */
6122 btrfs_end_transaction(trans);
6123 trans = btrfs_start_transaction(root, 1);
6125 return PTR_ERR(trans);
6127 ret = btrfs_update_inode(trans, root, inode);
6129 btrfs_end_transaction(trans);
6130 if (BTRFS_I(inode)->delayed_node)
6131 btrfs_balance_delayed_items(fs_info);
6137 * This is a copy of file_update_time. We need this so we can return error on
6138 * ENOSPC for updating the inode in the case of file write and mmap writes.
6140 static int btrfs_update_time(struct inode *inode, struct timespec *now,
6143 struct btrfs_root *root = BTRFS_I(inode)->root;
6144 bool dirty = flags & ~S_VERSION;
6146 if (btrfs_root_readonly(root))
6149 if (flags & S_VERSION)
6150 dirty |= inode_maybe_inc_iversion(inode, dirty);
6151 if (flags & S_CTIME)
6152 inode->i_ctime = *now;
6153 if (flags & S_MTIME)
6154 inode->i_mtime = *now;
6155 if (flags & S_ATIME)
6156 inode->i_atime = *now;
6157 return dirty ? btrfs_dirty_inode(inode) : 0;
6161 * find the highest existing sequence number in a directory
6162 * and then set the in-memory index_cnt variable to reflect
6163 * free sequence numbers
6165 static int btrfs_set_inode_index_count(struct btrfs_inode *inode)
6167 struct btrfs_root *root = inode->root;
6168 struct btrfs_key key, found_key;
6169 struct btrfs_path *path;
6170 struct extent_buffer *leaf;
6173 key.objectid = btrfs_ino(inode);
6174 key.type = BTRFS_DIR_INDEX_KEY;
6175 key.offset = (u64)-1;
6177 path = btrfs_alloc_path();
6181 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
6184 /* FIXME: we should be able to handle this */
6190 * MAGIC NUMBER EXPLANATION:
6191 * since we search a directory based on f_pos we have to start at 2
6192 * since '.' and '..' have f_pos of 0 and 1 respectively, so everybody
6193 * else has to start at 2
6195 if (path->slots[0] == 0) {
6196 inode->index_cnt = 2;
6202 leaf = path->nodes[0];
6203 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
6205 if (found_key.objectid != btrfs_ino(inode) ||
6206 found_key.type != BTRFS_DIR_INDEX_KEY) {
6207 inode->index_cnt = 2;
6211 inode->index_cnt = found_key.offset + 1;
6213 btrfs_free_path(path);
6218 * helper to find a free sequence number in a given directory. This current
6219 * code is very simple, later versions will do smarter things in the btree
6221 int btrfs_set_inode_index(struct btrfs_inode *dir, u64 *index)
6225 if (dir->index_cnt == (u64)-1) {
6226 ret = btrfs_inode_delayed_dir_index_count(dir);
6228 ret = btrfs_set_inode_index_count(dir);
6234 *index = dir->index_cnt;
6240 static int btrfs_insert_inode_locked(struct inode *inode)
6242 struct btrfs_iget_args args;
6243 args.location = &BTRFS_I(inode)->location;
6244 args.root = BTRFS_I(inode)->root;
6246 return insert_inode_locked4(inode,
6247 btrfs_inode_hash(inode->i_ino, BTRFS_I(inode)->root),
6248 btrfs_find_actor, &args);
6252 * Inherit flags from the parent inode.
6254 * Currently only the compression flags and the cow flags are inherited.
6256 static void btrfs_inherit_iflags(struct inode *inode, struct inode *dir)
6263 flags = BTRFS_I(dir)->flags;
6265 if (flags & BTRFS_INODE_NOCOMPRESS) {
6266 BTRFS_I(inode)->flags &= ~BTRFS_INODE_COMPRESS;
6267 BTRFS_I(inode)->flags |= BTRFS_INODE_NOCOMPRESS;
6268 } else if (flags & BTRFS_INODE_COMPRESS) {
6269 BTRFS_I(inode)->flags &= ~BTRFS_INODE_NOCOMPRESS;
6270 BTRFS_I(inode)->flags |= BTRFS_INODE_COMPRESS;
6273 if (flags & BTRFS_INODE_NODATACOW) {
6274 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATACOW;
6275 if (S_ISREG(inode->i_mode))
6276 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATASUM;
6279 btrfs_update_iflags(inode);
6282 static struct inode *btrfs_new_inode(struct btrfs_trans_handle *trans,
6283 struct btrfs_root *root,
6285 const char *name, int name_len,
6286 u64 ref_objectid, u64 objectid,
6287 umode_t mode, u64 *index)
6289 struct btrfs_fs_info *fs_info = root->fs_info;
6290 struct inode *inode;
6291 struct btrfs_inode_item *inode_item;
6292 struct btrfs_key *location;
6293 struct btrfs_path *path;
6294 struct btrfs_inode_ref *ref;
6295 struct btrfs_key key[2];
6297 int nitems = name ? 2 : 1;
6301 path = btrfs_alloc_path();
6303 return ERR_PTR(-ENOMEM);
6305 inode = new_inode(fs_info->sb);
6307 btrfs_free_path(path);
6308 return ERR_PTR(-ENOMEM);
6312 * O_TMPFILE, set link count to 0, so that after this point,
6313 * we fill in an inode item with the correct link count.
6316 set_nlink(inode, 0);
6319 * we have to initialize this early, so we can reclaim the inode
6320 * number if we fail afterwards in this function.
6322 inode->i_ino = objectid;
6325 trace_btrfs_inode_request(dir);
6327 ret = btrfs_set_inode_index(BTRFS_I(dir), index);
6329 btrfs_free_path(path);
6331 return ERR_PTR(ret);
6337 * index_cnt is ignored for everything but a dir,
6338 * btrfs_set_inode_index_count has an explanation for the magic
6341 BTRFS_I(inode)->index_cnt = 2;
6342 BTRFS_I(inode)->dir_index = *index;
6343 BTRFS_I(inode)->root = root;
6344 BTRFS_I(inode)->generation = trans->transid;
6345 inode->i_generation = BTRFS_I(inode)->generation;
6348 * We could have gotten an inode number from somebody who was fsynced
6349 * and then removed in this same transaction, so let's just set full
6350 * sync since it will be a full sync anyway and this will blow away the
6351 * old info in the log.
6353 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &BTRFS_I(inode)->runtime_flags);
6355 key[0].objectid = objectid;
6356 key[0].type = BTRFS_INODE_ITEM_KEY;
6359 sizes[0] = sizeof(struct btrfs_inode_item);
6363 * Start new inodes with an inode_ref. This is slightly more
6364 * efficient for small numbers of hard links since they will
6365 * be packed into one item. Extended refs will kick in if we
6366 * add more hard links than can fit in the ref item.
6368 key[1].objectid = objectid;
6369 key[1].type = BTRFS_INODE_REF_KEY;
6370 key[1].offset = ref_objectid;
6372 sizes[1] = name_len + sizeof(*ref);
6375 location = &BTRFS_I(inode)->location;
6376 location->objectid = objectid;
6377 location->offset = 0;
6378 location->type = BTRFS_INODE_ITEM_KEY;
6380 ret = btrfs_insert_inode_locked(inode);
6384 path->leave_spinning = 1;
6385 ret = btrfs_insert_empty_items(trans, root, path, key, sizes, nitems);
6389 inode_init_owner(inode, dir, mode);
6390 inode_set_bytes(inode, 0);
6392 inode->i_mtime = current_time(inode);
6393 inode->i_atime = inode->i_mtime;
6394 inode->i_ctime = inode->i_mtime;
6395 BTRFS_I(inode)->i_otime = inode->i_mtime;
6397 inode_item = btrfs_item_ptr(path->nodes[0], path->slots[0],
6398 struct btrfs_inode_item);
6399 memzero_extent_buffer(path->nodes[0], (unsigned long)inode_item,
6400 sizeof(*inode_item));
6401 fill_inode_item(trans, path->nodes[0], inode_item, inode);
6404 ref = btrfs_item_ptr(path->nodes[0], path->slots[0] + 1,
6405 struct btrfs_inode_ref);
6406 btrfs_set_inode_ref_name_len(path->nodes[0], ref, name_len);
6407 btrfs_set_inode_ref_index(path->nodes[0], ref, *index);
6408 ptr = (unsigned long)(ref + 1);
6409 write_extent_buffer(path->nodes[0], name, ptr, name_len);
6412 btrfs_mark_buffer_dirty(path->nodes[0]);
6413 btrfs_free_path(path);
6415 btrfs_inherit_iflags(inode, dir);
6417 if (S_ISREG(mode)) {
6418 if (btrfs_test_opt(fs_info, NODATASUM))
6419 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATASUM;
6420 if (btrfs_test_opt(fs_info, NODATACOW))
6421 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATACOW |
6422 BTRFS_INODE_NODATASUM;
6425 inode_tree_add(inode);
6427 trace_btrfs_inode_new(inode);
6428 btrfs_set_inode_last_trans(trans, inode);
6430 btrfs_update_root_times(trans, root);
6432 ret = btrfs_inode_inherit_props(trans, inode, dir);
6435 "error inheriting props for ino %llu (root %llu): %d",
6436 btrfs_ino(BTRFS_I(inode)), root->root_key.objectid, ret);
6441 unlock_new_inode(inode);
6444 BTRFS_I(dir)->index_cnt--;
6445 btrfs_free_path(path);
6447 return ERR_PTR(ret);
6450 static inline u8 btrfs_inode_type(struct inode *inode)
6452 return btrfs_type_by_mode[(inode->i_mode & S_IFMT) >> S_SHIFT];
6456 * utility function to add 'inode' into 'parent_inode' with
6457 * a give name and a given sequence number.
6458 * if 'add_backref' is true, also insert a backref from the
6459 * inode to the parent directory.
6461 int btrfs_add_link(struct btrfs_trans_handle *trans,
6462 struct btrfs_inode *parent_inode, struct btrfs_inode *inode,
6463 const char *name, int name_len, int add_backref, u64 index)
6465 struct btrfs_fs_info *fs_info = btrfs_sb(inode->vfs_inode.i_sb);
6467 struct btrfs_key key;
6468 struct btrfs_root *root = parent_inode->root;
6469 u64 ino = btrfs_ino(inode);
6470 u64 parent_ino = btrfs_ino(parent_inode);
6472 if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
6473 memcpy(&key, &inode->root->root_key, sizeof(key));
6476 key.type = BTRFS_INODE_ITEM_KEY;
6480 if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
6481 ret = btrfs_add_root_ref(trans, fs_info, key.objectid,
6482 root->root_key.objectid, parent_ino,
6483 index, name, name_len);
6484 } else if (add_backref) {
6485 ret = btrfs_insert_inode_ref(trans, root, name, name_len, ino,
6489 /* Nothing to clean up yet */
6493 ret = btrfs_insert_dir_item(trans, root, name, name_len,
6495 btrfs_inode_type(&inode->vfs_inode), index);
6496 if (ret == -EEXIST || ret == -EOVERFLOW)
6499 btrfs_abort_transaction(trans, ret);
6503 btrfs_i_size_write(parent_inode, parent_inode->vfs_inode.i_size +
6505 inode_inc_iversion(&parent_inode->vfs_inode);
6506 parent_inode->vfs_inode.i_mtime = parent_inode->vfs_inode.i_ctime =
6507 current_time(&parent_inode->vfs_inode);
6508 ret = btrfs_update_inode(trans, root, &parent_inode->vfs_inode);
6510 btrfs_abort_transaction(trans, ret);
6514 if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
6517 err = btrfs_del_root_ref(trans, fs_info, key.objectid,
6518 root->root_key.objectid, parent_ino,
6519 &local_index, name, name_len);
6521 } else if (add_backref) {
6525 err = btrfs_del_inode_ref(trans, root, name, name_len,
6526 ino, parent_ino, &local_index);
6531 static int btrfs_add_nondir(struct btrfs_trans_handle *trans,
6532 struct btrfs_inode *dir, struct dentry *dentry,
6533 struct btrfs_inode *inode, int backref, u64 index)
6535 int err = btrfs_add_link(trans, dir, inode,
6536 dentry->d_name.name, dentry->d_name.len,
6543 static int btrfs_mknod(struct inode *dir, struct dentry *dentry,
6544 umode_t mode, dev_t rdev)
6546 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
6547 struct btrfs_trans_handle *trans;
6548 struct btrfs_root *root = BTRFS_I(dir)->root;
6549 struct inode *inode = NULL;
6556 * 2 for inode item and ref
6558 * 1 for xattr if selinux is on
6560 trans = btrfs_start_transaction(root, 5);
6562 return PTR_ERR(trans);
6564 err = btrfs_find_free_ino(root, &objectid);
6568 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
6569 dentry->d_name.len, btrfs_ino(BTRFS_I(dir)), objectid,
6571 if (IS_ERR(inode)) {
6572 err = PTR_ERR(inode);
6577 * If the active LSM wants to access the inode during
6578 * d_instantiate it needs these. Smack checks to see
6579 * if the filesystem supports xattrs by looking at the
6582 inode->i_op = &btrfs_special_inode_operations;
6583 init_special_inode(inode, inode->i_mode, rdev);
6585 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
6587 goto out_unlock_inode;
6589 err = btrfs_add_nondir(trans, BTRFS_I(dir), dentry, BTRFS_I(inode),
6592 goto out_unlock_inode;
6594 btrfs_update_inode(trans, root, inode);
6595 unlock_new_inode(inode);
6596 d_instantiate(dentry, inode);
6600 btrfs_end_transaction(trans);
6601 btrfs_btree_balance_dirty(fs_info);
6603 inode_dec_link_count(inode);
6610 unlock_new_inode(inode);
6615 static int btrfs_create(struct inode *dir, struct dentry *dentry,
6616 umode_t mode, bool excl)
6618 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
6619 struct btrfs_trans_handle *trans;
6620 struct btrfs_root *root = BTRFS_I(dir)->root;
6621 struct inode *inode = NULL;
6622 int drop_inode_on_err = 0;
6628 * 2 for inode item and ref
6630 * 1 for xattr if selinux is on
6632 trans = btrfs_start_transaction(root, 5);
6634 return PTR_ERR(trans);
6636 err = btrfs_find_free_ino(root, &objectid);
6640 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
6641 dentry->d_name.len, btrfs_ino(BTRFS_I(dir)), objectid,
6643 if (IS_ERR(inode)) {
6644 err = PTR_ERR(inode);
6647 drop_inode_on_err = 1;
6649 * If the active LSM wants to access the inode during
6650 * d_instantiate it needs these. Smack checks to see
6651 * if the filesystem supports xattrs by looking at the
6654 inode->i_fop = &btrfs_file_operations;
6655 inode->i_op = &btrfs_file_inode_operations;
6656 inode->i_mapping->a_ops = &btrfs_aops;
6658 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
6660 goto out_unlock_inode;
6662 err = btrfs_update_inode(trans, root, inode);
6664 goto out_unlock_inode;
6666 err = btrfs_add_nondir(trans, BTRFS_I(dir), dentry, BTRFS_I(inode),
6669 goto out_unlock_inode;
6671 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
6672 unlock_new_inode(inode);
6673 d_instantiate(dentry, inode);
6676 btrfs_end_transaction(trans);
6677 if (err && drop_inode_on_err) {
6678 inode_dec_link_count(inode);
6681 btrfs_btree_balance_dirty(fs_info);
6685 unlock_new_inode(inode);
6690 static int btrfs_link(struct dentry *old_dentry, struct inode *dir,
6691 struct dentry *dentry)
6693 struct btrfs_trans_handle *trans = NULL;
6694 struct btrfs_root *root = BTRFS_I(dir)->root;
6695 struct inode *inode = d_inode(old_dentry);
6696 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
6701 /* do not allow sys_link's with other subvols of the same device */
6702 if (root->objectid != BTRFS_I(inode)->root->objectid)
6705 if (inode->i_nlink >= BTRFS_LINK_MAX)
6708 err = btrfs_set_inode_index(BTRFS_I(dir), &index);
6713 * 2 items for inode and inode ref
6714 * 2 items for dir items
6715 * 1 item for parent inode
6717 trans = btrfs_start_transaction(root, 5);
6718 if (IS_ERR(trans)) {
6719 err = PTR_ERR(trans);
6724 /* There are several dir indexes for this inode, clear the cache. */
6725 BTRFS_I(inode)->dir_index = 0ULL;
6727 inode_inc_iversion(inode);
6728 inode->i_ctime = current_time(inode);
6730 set_bit(BTRFS_INODE_COPY_EVERYTHING, &BTRFS_I(inode)->runtime_flags);
6732 err = btrfs_add_nondir(trans, BTRFS_I(dir), dentry, BTRFS_I(inode),
6738 struct dentry *parent = dentry->d_parent;
6739 err = btrfs_update_inode(trans, root, inode);
6742 if (inode->i_nlink == 1) {
6744 * If new hard link count is 1, it's a file created
6745 * with open(2) O_TMPFILE flag.
6747 err = btrfs_orphan_del(trans, BTRFS_I(inode));
6751 d_instantiate(dentry, inode);
6752 btrfs_log_new_name(trans, BTRFS_I(inode), NULL, parent);
6757 btrfs_end_transaction(trans);
6759 inode_dec_link_count(inode);
6762 btrfs_btree_balance_dirty(fs_info);
6766 static int btrfs_mkdir(struct inode *dir, struct dentry *dentry, umode_t mode)
6768 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
6769 struct inode *inode = NULL;
6770 struct btrfs_trans_handle *trans;
6771 struct btrfs_root *root = BTRFS_I(dir)->root;
6773 int drop_on_err = 0;
6778 * 2 items for inode and ref
6779 * 2 items for dir items
6780 * 1 for xattr if selinux is on
6782 trans = btrfs_start_transaction(root, 5);
6784 return PTR_ERR(trans);
6786 err = btrfs_find_free_ino(root, &objectid);
6790 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
6791 dentry->d_name.len, btrfs_ino(BTRFS_I(dir)), objectid,
6792 S_IFDIR | mode, &index);
6793 if (IS_ERR(inode)) {
6794 err = PTR_ERR(inode);
6799 /* these must be set before we unlock the inode */
6800 inode->i_op = &btrfs_dir_inode_operations;
6801 inode->i_fop = &btrfs_dir_file_operations;
6803 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
6805 goto out_fail_inode;
6807 btrfs_i_size_write(BTRFS_I(inode), 0);
6808 err = btrfs_update_inode(trans, root, inode);
6810 goto out_fail_inode;
6812 err = btrfs_add_link(trans, BTRFS_I(dir), BTRFS_I(inode),
6813 dentry->d_name.name,
6814 dentry->d_name.len, 0, index);
6816 goto out_fail_inode;
6818 d_instantiate(dentry, inode);
6820 * mkdir is special. We're unlocking after we call d_instantiate
6821 * to avoid a race with nfsd calling d_instantiate.
6823 unlock_new_inode(inode);
6827 btrfs_end_transaction(trans);
6829 inode_dec_link_count(inode);
6832 btrfs_btree_balance_dirty(fs_info);
6836 unlock_new_inode(inode);
6840 static noinline int uncompress_inline(struct btrfs_path *path,
6842 size_t pg_offset, u64 extent_offset,
6843 struct btrfs_file_extent_item *item)
6846 struct extent_buffer *leaf = path->nodes[0];
6849 unsigned long inline_size;
6853 WARN_ON(pg_offset != 0);
6854 compress_type = btrfs_file_extent_compression(leaf, item);
6855 max_size = btrfs_file_extent_ram_bytes(leaf, item);
6856 inline_size = btrfs_file_extent_inline_item_len(leaf,
6857 btrfs_item_nr(path->slots[0]));
6858 tmp = kmalloc(inline_size, GFP_NOFS);
6861 ptr = btrfs_file_extent_inline_start(item);
6863 read_extent_buffer(leaf, tmp, ptr, inline_size);
6865 max_size = min_t(unsigned long, PAGE_SIZE, max_size);
6866 ret = btrfs_decompress(compress_type, tmp, page,
6867 extent_offset, inline_size, max_size);
6870 * decompression code contains a memset to fill in any space between the end
6871 * of the uncompressed data and the end of max_size in case the decompressed
6872 * data ends up shorter than ram_bytes. That doesn't cover the hole between
6873 * the end of an inline extent and the beginning of the next block, so we
6874 * cover that region here.
6877 if (max_size + pg_offset < PAGE_SIZE) {
6878 char *map = kmap(page);
6879 memset(map + pg_offset + max_size, 0, PAGE_SIZE - max_size - pg_offset);
6887 * a bit scary, this does extent mapping from logical file offset to the disk.
6888 * the ugly parts come from merging extents from the disk with the in-ram
6889 * representation. This gets more complex because of the data=ordered code,
6890 * where the in-ram extents might be locked pending data=ordered completion.
6892 * This also copies inline extents directly into the page.
6894 struct extent_map *btrfs_get_extent(struct btrfs_inode *inode,
6896 size_t pg_offset, u64 start, u64 len,
6899 struct btrfs_fs_info *fs_info = btrfs_sb(inode->vfs_inode.i_sb);
6902 u64 extent_start = 0;
6904 u64 objectid = btrfs_ino(inode);
6906 struct btrfs_path *path = NULL;
6907 struct btrfs_root *root = inode->root;
6908 struct btrfs_file_extent_item *item;
6909 struct extent_buffer *leaf;
6910 struct btrfs_key found_key;
6911 struct extent_map *em = NULL;
6912 struct extent_map_tree *em_tree = &inode->extent_tree;
6913 struct extent_io_tree *io_tree = &inode->io_tree;
6914 const bool new_inline = !page || create;
6916 read_lock(&em_tree->lock);
6917 em = lookup_extent_mapping(em_tree, start, len);
6919 em->bdev = fs_info->fs_devices->latest_bdev;
6920 read_unlock(&em_tree->lock);
6923 if (em->start > start || em->start + em->len <= start)
6924 free_extent_map(em);
6925 else if (em->block_start == EXTENT_MAP_INLINE && page)
6926 free_extent_map(em);
6930 em = alloc_extent_map();
6935 em->bdev = fs_info->fs_devices->latest_bdev;
6936 em->start = EXTENT_MAP_HOLE;
6937 em->orig_start = EXTENT_MAP_HOLE;
6939 em->block_len = (u64)-1;
6942 path = btrfs_alloc_path();
6948 * Chances are we'll be called again, so go ahead and do
6951 path->reada = READA_FORWARD;
6954 ret = btrfs_lookup_file_extent(NULL, root, path, objectid, start, 0);
6961 if (path->slots[0] == 0)
6966 leaf = path->nodes[0];
6967 item = btrfs_item_ptr(leaf, path->slots[0],
6968 struct btrfs_file_extent_item);
6969 /* are we inside the extent that was found? */
6970 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
6971 found_type = found_key.type;
6972 if (found_key.objectid != objectid ||
6973 found_type != BTRFS_EXTENT_DATA_KEY) {
6975 * If we backup past the first extent we want to move forward
6976 * and see if there is an extent in front of us, otherwise we'll
6977 * say there is a hole for our whole search range which can
6984 found_type = btrfs_file_extent_type(leaf, item);
6985 extent_start = found_key.offset;
6986 if (found_type == BTRFS_FILE_EXTENT_REG ||
6987 found_type == BTRFS_FILE_EXTENT_PREALLOC) {
6988 extent_end = extent_start +
6989 btrfs_file_extent_num_bytes(leaf, item);
6991 trace_btrfs_get_extent_show_fi_regular(inode, leaf, item,
6993 } else if (found_type == BTRFS_FILE_EXTENT_INLINE) {
6995 size = btrfs_file_extent_inline_len(leaf, path->slots[0], item);
6996 extent_end = ALIGN(extent_start + size,
6997 fs_info->sectorsize);
6999 trace_btrfs_get_extent_show_fi_inline(inode, leaf, item,
7004 if (start >= extent_end) {
7006 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
7007 ret = btrfs_next_leaf(root, path);
7014 leaf = path->nodes[0];
7016 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
7017 if (found_key.objectid != objectid ||
7018 found_key.type != BTRFS_EXTENT_DATA_KEY)
7020 if (start + len <= found_key.offset)
7022 if (start > found_key.offset)
7025 em->orig_start = start;
7026 em->len = found_key.offset - start;
7030 btrfs_extent_item_to_extent_map(inode, path, item,
7033 if (found_type == BTRFS_FILE_EXTENT_REG ||
7034 found_type == BTRFS_FILE_EXTENT_PREALLOC) {
7036 } else if (found_type == BTRFS_FILE_EXTENT_INLINE) {
7040 size_t extent_offset;
7046 size = btrfs_file_extent_inline_len(leaf, path->slots[0], item);
7047 extent_offset = page_offset(page) + pg_offset - extent_start;
7048 copy_size = min_t(u64, PAGE_SIZE - pg_offset,
7049 size - extent_offset);
7050 em->start = extent_start + extent_offset;
7051 em->len = ALIGN(copy_size, fs_info->sectorsize);
7052 em->orig_block_len = em->len;
7053 em->orig_start = em->start;
7054 ptr = btrfs_file_extent_inline_start(item) + extent_offset;
7055 if (!PageUptodate(page)) {
7056 if (btrfs_file_extent_compression(leaf, item) !=
7057 BTRFS_COMPRESS_NONE) {
7058 ret = uncompress_inline(path, page, pg_offset,
7059 extent_offset, item);
7066 read_extent_buffer(leaf, map + pg_offset, ptr,
7068 if (pg_offset + copy_size < PAGE_SIZE) {
7069 memset(map + pg_offset + copy_size, 0,
7070 PAGE_SIZE - pg_offset -
7075 flush_dcache_page(page);
7077 set_extent_uptodate(io_tree, em->start,
7078 extent_map_end(em) - 1, NULL, GFP_NOFS);
7083 em->orig_start = start;
7086 em->block_start = EXTENT_MAP_HOLE;
7088 btrfs_release_path(path);
7089 if (em->start > start || extent_map_end(em) <= start) {
7091 "bad extent! em: [%llu %llu] passed [%llu %llu]",
7092 em->start, em->len, start, len);
7098 write_lock(&em_tree->lock);
7099 err = btrfs_add_extent_mapping(em_tree, &em, start, len);
7100 write_unlock(&em_tree->lock);
7103 trace_btrfs_get_extent(root, inode, em);
7105 btrfs_free_path(path);
7107 free_extent_map(em);
7108 return ERR_PTR(err);
7110 BUG_ON(!em); /* Error is always set */
7114 struct extent_map *btrfs_get_extent_fiemap(struct btrfs_inode *inode,
7116 size_t pg_offset, u64 start, u64 len,
7119 struct extent_map *em;
7120 struct extent_map *hole_em = NULL;
7121 u64 range_start = start;
7127 em = btrfs_get_extent(inode, page, pg_offset, start, len, create);
7131 * If our em maps to:
7133 * - a pre-alloc extent,
7134 * there might actually be delalloc bytes behind it.
7136 if (em->block_start != EXTENT_MAP_HOLE &&
7137 !test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
7142 /* check to see if we've wrapped (len == -1 or similar) */
7151 /* ok, we didn't find anything, lets look for delalloc */
7152 found = count_range_bits(&inode->io_tree, &range_start,
7153 end, len, EXTENT_DELALLOC, 1);
7154 found_end = range_start + found;
7155 if (found_end < range_start)
7156 found_end = (u64)-1;
7159 * we didn't find anything useful, return
7160 * the original results from get_extent()
7162 if (range_start > end || found_end <= start) {
7168 /* adjust the range_start to make sure it doesn't
7169 * go backwards from the start they passed in
7171 range_start = max(start, range_start);
7172 found = found_end - range_start;
7175 u64 hole_start = start;
7178 em = alloc_extent_map();
7184 * when btrfs_get_extent can't find anything it
7185 * returns one huge hole
7187 * make sure what it found really fits our range, and
7188 * adjust to make sure it is based on the start from
7192 u64 calc_end = extent_map_end(hole_em);
7194 if (calc_end <= start || (hole_em->start > end)) {
7195 free_extent_map(hole_em);
7198 hole_start = max(hole_em->start, start);
7199 hole_len = calc_end - hole_start;
7203 if (hole_em && range_start > hole_start) {
7204 /* our hole starts before our delalloc, so we
7205 * have to return just the parts of the hole
7206 * that go until the delalloc starts
7208 em->len = min(hole_len,
7209 range_start - hole_start);
7210 em->start = hole_start;
7211 em->orig_start = hole_start;
7213 * don't adjust block start at all,
7214 * it is fixed at EXTENT_MAP_HOLE
7216 em->block_start = hole_em->block_start;
7217 em->block_len = hole_len;
7218 if (test_bit(EXTENT_FLAG_PREALLOC, &hole_em->flags))
7219 set_bit(EXTENT_FLAG_PREALLOC, &em->flags);
7221 em->start = range_start;
7223 em->orig_start = range_start;
7224 em->block_start = EXTENT_MAP_DELALLOC;
7225 em->block_len = found;
7232 free_extent_map(hole_em);
7234 free_extent_map(em);
7235 return ERR_PTR(err);
7240 static struct extent_map *btrfs_create_dio_extent(struct inode *inode,
7243 const u64 orig_start,
7244 const u64 block_start,
7245 const u64 block_len,
7246 const u64 orig_block_len,
7247 const u64 ram_bytes,
7250 struct extent_map *em = NULL;
7253 if (type != BTRFS_ORDERED_NOCOW) {
7254 em = create_io_em(inode, start, len, orig_start,
7255 block_start, block_len, orig_block_len,
7257 BTRFS_COMPRESS_NONE, /* compress_type */
7262 ret = btrfs_add_ordered_extent_dio(inode, start, block_start,
7263 len, block_len, type);
7266 free_extent_map(em);
7267 btrfs_drop_extent_cache(BTRFS_I(inode), start,
7268 start + len - 1, 0);
7277 static struct extent_map *btrfs_new_extent_direct(struct inode *inode,
7280 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7281 struct btrfs_root *root = BTRFS_I(inode)->root;
7282 struct extent_map *em;
7283 struct btrfs_key ins;
7287 alloc_hint = get_extent_allocation_hint(inode, start, len);
7288 ret = btrfs_reserve_extent(root, len, len, fs_info->sectorsize,
7289 0, alloc_hint, &ins, 1, 1);
7291 return ERR_PTR(ret);
7293 em = btrfs_create_dio_extent(inode, start, ins.offset, start,
7294 ins.objectid, ins.offset, ins.offset,
7295 ins.offset, BTRFS_ORDERED_REGULAR);
7296 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
7298 btrfs_free_reserved_extent(fs_info, ins.objectid,
7305 * returns 1 when the nocow is safe, < 1 on error, 0 if the
7306 * block must be cow'd
7308 noinline int can_nocow_extent(struct inode *inode, u64 offset, u64 *len,
7309 u64 *orig_start, u64 *orig_block_len,
7312 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7313 struct btrfs_path *path;
7315 struct extent_buffer *leaf;
7316 struct btrfs_root *root = BTRFS_I(inode)->root;
7317 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
7318 struct btrfs_file_extent_item *fi;
7319 struct btrfs_key key;
7326 bool nocow = (BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW);
7328 path = btrfs_alloc_path();
7332 ret = btrfs_lookup_file_extent(NULL, root, path,
7333 btrfs_ino(BTRFS_I(inode)), offset, 0);
7337 slot = path->slots[0];
7340 /* can't find the item, must cow */
7347 leaf = path->nodes[0];
7348 btrfs_item_key_to_cpu(leaf, &key, slot);
7349 if (key.objectid != btrfs_ino(BTRFS_I(inode)) ||
7350 key.type != BTRFS_EXTENT_DATA_KEY) {
7351 /* not our file or wrong item type, must cow */
7355 if (key.offset > offset) {
7356 /* Wrong offset, must cow */
7360 fi = btrfs_item_ptr(leaf, slot, struct btrfs_file_extent_item);
7361 found_type = btrfs_file_extent_type(leaf, fi);
7362 if (found_type != BTRFS_FILE_EXTENT_REG &&
7363 found_type != BTRFS_FILE_EXTENT_PREALLOC) {
7364 /* not a regular extent, must cow */
7368 if (!nocow && found_type == BTRFS_FILE_EXTENT_REG)
7371 extent_end = key.offset + btrfs_file_extent_num_bytes(leaf, fi);
7372 if (extent_end <= offset)
7375 disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
7376 if (disk_bytenr == 0)
7379 if (btrfs_file_extent_compression(leaf, fi) ||
7380 btrfs_file_extent_encryption(leaf, fi) ||
7381 btrfs_file_extent_other_encoding(leaf, fi))
7384 backref_offset = btrfs_file_extent_offset(leaf, fi);
7387 *orig_start = key.offset - backref_offset;
7388 *orig_block_len = btrfs_file_extent_disk_num_bytes(leaf, fi);
7389 *ram_bytes = btrfs_file_extent_ram_bytes(leaf, fi);
7392 if (btrfs_extent_readonly(fs_info, disk_bytenr))
7395 num_bytes = min(offset + *len, extent_end) - offset;
7396 if (!nocow && found_type == BTRFS_FILE_EXTENT_PREALLOC) {
7399 range_end = round_up(offset + num_bytes,
7400 root->fs_info->sectorsize) - 1;
7401 ret = test_range_bit(io_tree, offset, range_end,
7402 EXTENT_DELALLOC, 0, NULL);
7409 btrfs_release_path(path);
7412 * look for other files referencing this extent, if we
7413 * find any we must cow
7416 ret = btrfs_cross_ref_exist(root, btrfs_ino(BTRFS_I(inode)),
7417 key.offset - backref_offset, disk_bytenr);
7424 * adjust disk_bytenr and num_bytes to cover just the bytes
7425 * in this extent we are about to write. If there
7426 * are any csums in that range we have to cow in order
7427 * to keep the csums correct
7429 disk_bytenr += backref_offset;
7430 disk_bytenr += offset - key.offset;
7431 if (csum_exist_in_range(fs_info, disk_bytenr, num_bytes))
7434 * all of the above have passed, it is safe to overwrite this extent
7440 btrfs_free_path(path);
7444 bool btrfs_page_exists_in_range(struct inode *inode, loff_t start, loff_t end)
7446 struct radix_tree_root *root = &inode->i_mapping->page_tree;
7448 void **pagep = NULL;
7449 struct page *page = NULL;
7450 unsigned long start_idx;
7451 unsigned long end_idx;
7453 start_idx = start >> PAGE_SHIFT;
7456 * end is the last byte in the last page. end == start is legal
7458 end_idx = end >> PAGE_SHIFT;
7462 /* Most of the code in this while loop is lifted from
7463 * find_get_page. It's been modified to begin searching from a
7464 * page and return just the first page found in that range. If the
7465 * found idx is less than or equal to the end idx then we know that
7466 * a page exists. If no pages are found or if those pages are
7467 * outside of the range then we're fine (yay!) */
7468 while (page == NULL &&
7469 radix_tree_gang_lookup_slot(root, &pagep, NULL, start_idx, 1)) {
7470 page = radix_tree_deref_slot(pagep);
7471 if (unlikely(!page))
7474 if (radix_tree_exception(page)) {
7475 if (radix_tree_deref_retry(page)) {
7480 * Otherwise, shmem/tmpfs must be storing a swap entry
7481 * here as an exceptional entry: so return it without
7482 * attempting to raise page count.
7485 break; /* TODO: Is this relevant for this use case? */
7488 if (!page_cache_get_speculative(page)) {
7494 * Has the page moved?
7495 * This is part of the lockless pagecache protocol. See
7496 * include/linux/pagemap.h for details.
7498 if (unlikely(page != *pagep)) {
7505 if (page->index <= end_idx)
7514 static int lock_extent_direct(struct inode *inode, u64 lockstart, u64 lockend,
7515 struct extent_state **cached_state, int writing)
7517 struct btrfs_ordered_extent *ordered;
7521 lock_extent_bits(&BTRFS_I(inode)->io_tree, lockstart, lockend,
7524 * We're concerned with the entire range that we're going to be
7525 * doing DIO to, so we need to make sure there's no ordered
7526 * extents in this range.
7528 ordered = btrfs_lookup_ordered_range(BTRFS_I(inode), lockstart,
7529 lockend - lockstart + 1);
7532 * We need to make sure there are no buffered pages in this
7533 * range either, we could have raced between the invalidate in
7534 * generic_file_direct_write and locking the extent. The
7535 * invalidate needs to happen so that reads after a write do not
7540 !btrfs_page_exists_in_range(inode, lockstart, lockend)))
7543 unlock_extent_cached(&BTRFS_I(inode)->io_tree, lockstart, lockend,
7548 * If we are doing a DIO read and the ordered extent we
7549 * found is for a buffered write, we can not wait for it
7550 * to complete and retry, because if we do so we can
7551 * deadlock with concurrent buffered writes on page
7552 * locks. This happens only if our DIO read covers more
7553 * than one extent map, if at this point has already
7554 * created an ordered extent for a previous extent map
7555 * and locked its range in the inode's io tree, and a
7556 * concurrent write against that previous extent map's
7557 * range and this range started (we unlock the ranges
7558 * in the io tree only when the bios complete and
7559 * buffered writes always lock pages before attempting
7560 * to lock range in the io tree).
7563 test_bit(BTRFS_ORDERED_DIRECT, &ordered->flags))
7564 btrfs_start_ordered_extent(inode, ordered, 1);
7567 btrfs_put_ordered_extent(ordered);
7570 * We could trigger writeback for this range (and wait
7571 * for it to complete) and then invalidate the pages for
7572 * this range (through invalidate_inode_pages2_range()),
7573 * but that can lead us to a deadlock with a concurrent
7574 * call to readpages() (a buffered read or a defrag call
7575 * triggered a readahead) on a page lock due to an
7576 * ordered dio extent we created before but did not have
7577 * yet a corresponding bio submitted (whence it can not
7578 * complete), which makes readpages() wait for that
7579 * ordered extent to complete while holding a lock on
7594 /* The callers of this must take lock_extent() */
7595 static struct extent_map *create_io_em(struct inode *inode, u64 start, u64 len,
7596 u64 orig_start, u64 block_start,
7597 u64 block_len, u64 orig_block_len,
7598 u64 ram_bytes, int compress_type,
7601 struct extent_map_tree *em_tree;
7602 struct extent_map *em;
7603 struct btrfs_root *root = BTRFS_I(inode)->root;
7606 ASSERT(type == BTRFS_ORDERED_PREALLOC ||
7607 type == BTRFS_ORDERED_COMPRESSED ||
7608 type == BTRFS_ORDERED_NOCOW ||
7609 type == BTRFS_ORDERED_REGULAR);
7611 em_tree = &BTRFS_I(inode)->extent_tree;
7612 em = alloc_extent_map();
7614 return ERR_PTR(-ENOMEM);
7617 em->orig_start = orig_start;
7619 em->block_len = block_len;
7620 em->block_start = block_start;
7621 em->bdev = root->fs_info->fs_devices->latest_bdev;
7622 em->orig_block_len = orig_block_len;
7623 em->ram_bytes = ram_bytes;
7624 em->generation = -1;
7625 set_bit(EXTENT_FLAG_PINNED, &em->flags);
7626 if (type == BTRFS_ORDERED_PREALLOC) {
7627 set_bit(EXTENT_FLAG_FILLING, &em->flags);
7628 } else if (type == BTRFS_ORDERED_COMPRESSED) {
7629 set_bit(EXTENT_FLAG_COMPRESSED, &em->flags);
7630 em->compress_type = compress_type;
7634 btrfs_drop_extent_cache(BTRFS_I(inode), em->start,
7635 em->start + em->len - 1, 0);
7636 write_lock(&em_tree->lock);
7637 ret = add_extent_mapping(em_tree, em, 1);
7638 write_unlock(&em_tree->lock);
7640 * The caller has taken lock_extent(), who could race with us
7643 } while (ret == -EEXIST);
7646 free_extent_map(em);
7647 return ERR_PTR(ret);
7650 /* em got 2 refs now, callers needs to do free_extent_map once. */
7654 static int btrfs_get_blocks_direct(struct inode *inode, sector_t iblock,
7655 struct buffer_head *bh_result, int create)
7657 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7658 struct extent_map *em;
7659 struct extent_state *cached_state = NULL;
7660 struct btrfs_dio_data *dio_data = NULL;
7661 u64 start = iblock << inode->i_blkbits;
7662 u64 lockstart, lockend;
7663 u64 len = bh_result->b_size;
7664 int unlock_bits = EXTENT_LOCKED;
7668 unlock_bits |= EXTENT_DIRTY;
7670 len = min_t(u64, len, fs_info->sectorsize);
7673 lockend = start + len - 1;
7675 if (current->journal_info) {
7677 * Need to pull our outstanding extents and set journal_info to NULL so
7678 * that anything that needs to check if there's a transaction doesn't get
7681 dio_data = current->journal_info;
7682 current->journal_info = NULL;
7686 * If this errors out it's because we couldn't invalidate pagecache for
7687 * this range and we need to fallback to buffered.
7689 if (lock_extent_direct(inode, lockstart, lockend, &cached_state,
7695 em = btrfs_get_extent(BTRFS_I(inode), NULL, 0, start, len, 0);
7702 * Ok for INLINE and COMPRESSED extents we need to fallback on buffered
7703 * io. INLINE is special, and we could probably kludge it in here, but
7704 * it's still buffered so for safety lets just fall back to the generic
7707 * For COMPRESSED we _have_ to read the entire extent in so we can
7708 * decompress it, so there will be buffering required no matter what we
7709 * do, so go ahead and fallback to buffered.
7711 * We return -ENOTBLK because that's what makes DIO go ahead and go back
7712 * to buffered IO. Don't blame me, this is the price we pay for using
7715 if (test_bit(EXTENT_FLAG_COMPRESSED, &em->flags) ||
7716 em->block_start == EXTENT_MAP_INLINE) {
7717 free_extent_map(em);
7722 /* Just a good old fashioned hole, return */
7723 if (!create && (em->block_start == EXTENT_MAP_HOLE ||
7724 test_bit(EXTENT_FLAG_PREALLOC, &em->flags))) {
7725 free_extent_map(em);
7730 * We don't allocate a new extent in the following cases
7732 * 1) The inode is marked as NODATACOW. In this case we'll just use the
7734 * 2) The extent is marked as PREALLOC. We're good to go here and can
7735 * just use the extent.
7739 len = min(len, em->len - (start - em->start));
7740 lockstart = start + len;
7744 if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags) ||
7745 ((BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW) &&
7746 em->block_start != EXTENT_MAP_HOLE)) {
7748 u64 block_start, orig_start, orig_block_len, ram_bytes;
7750 if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
7751 type = BTRFS_ORDERED_PREALLOC;
7753 type = BTRFS_ORDERED_NOCOW;
7754 len = min(len, em->len - (start - em->start));
7755 block_start = em->block_start + (start - em->start);
7757 if (can_nocow_extent(inode, start, &len, &orig_start,
7758 &orig_block_len, &ram_bytes) == 1 &&
7759 btrfs_inc_nocow_writers(fs_info, block_start)) {
7760 struct extent_map *em2;
7762 em2 = btrfs_create_dio_extent(inode, start, len,
7763 orig_start, block_start,
7764 len, orig_block_len,
7766 btrfs_dec_nocow_writers(fs_info, block_start);
7767 if (type == BTRFS_ORDERED_PREALLOC) {
7768 free_extent_map(em);
7771 if (em2 && IS_ERR(em2)) {
7776 * For inode marked NODATACOW or extent marked PREALLOC,
7777 * use the existing or preallocated extent, so does not
7778 * need to adjust btrfs_space_info's bytes_may_use.
7780 btrfs_free_reserved_data_space_noquota(inode,
7787 * this will cow the extent, reset the len in case we changed
7790 len = bh_result->b_size;
7791 free_extent_map(em);
7792 em = btrfs_new_extent_direct(inode, start, len);
7797 len = min(len, em->len - (start - em->start));
7799 bh_result->b_blocknr = (em->block_start + (start - em->start)) >>
7801 bh_result->b_size = len;
7802 bh_result->b_bdev = em->bdev;
7803 set_buffer_mapped(bh_result);
7805 if (!test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
7806 set_buffer_new(bh_result);
7809 * Need to update the i_size under the extent lock so buffered
7810 * readers will get the updated i_size when we unlock.
7812 if (!dio_data->overwrite && start + len > i_size_read(inode))
7813 i_size_write(inode, start + len);
7815 WARN_ON(dio_data->reserve < len);
7816 dio_data->reserve -= len;
7817 dio_data->unsubmitted_oe_range_end = start + len;
7818 current->journal_info = dio_data;
7822 * In the case of write we need to clear and unlock the entire range,
7823 * in the case of read we need to unlock only the end area that we
7824 * aren't using if there is any left over space.
7826 if (lockstart < lockend) {
7827 clear_extent_bit(&BTRFS_I(inode)->io_tree, lockstart,
7828 lockend, unlock_bits, 1, 0,
7831 free_extent_state(cached_state);
7834 free_extent_map(em);
7839 clear_extent_bit(&BTRFS_I(inode)->io_tree, lockstart, lockend,
7840 unlock_bits, 1, 0, &cached_state);
7843 current->journal_info = dio_data;
7847 static inline blk_status_t submit_dio_repair_bio(struct inode *inode,
7851 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7854 BUG_ON(bio_op(bio) == REQ_OP_WRITE);
7856 ret = btrfs_bio_wq_end_io(fs_info, bio, BTRFS_WQ_ENDIO_DIO_REPAIR);
7860 ret = btrfs_map_bio(fs_info, bio, mirror_num, 0);
7865 static int btrfs_check_dio_repairable(struct inode *inode,
7866 struct bio *failed_bio,
7867 struct io_failure_record *failrec,
7870 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7873 num_copies = btrfs_num_copies(fs_info, failrec->logical, failrec->len);
7874 if (num_copies == 1) {
7876 * we only have a single copy of the data, so don't bother with
7877 * all the retry and error correction code that follows. no
7878 * matter what the error is, it is very likely to persist.
7880 btrfs_debug(fs_info,
7881 "Check DIO Repairable: cannot repair, num_copies=%d, next_mirror %d, failed_mirror %d",
7882 num_copies, failrec->this_mirror, failed_mirror);
7886 failrec->failed_mirror = failed_mirror;
7887 failrec->this_mirror++;
7888 if (failrec->this_mirror == failed_mirror)
7889 failrec->this_mirror++;
7891 if (failrec->this_mirror > num_copies) {
7892 btrfs_debug(fs_info,
7893 "Check DIO Repairable: (fail) num_copies=%d, next_mirror %d, failed_mirror %d",
7894 num_copies, failrec->this_mirror, failed_mirror);
7901 static blk_status_t dio_read_error(struct inode *inode, struct bio *failed_bio,
7902 struct page *page, unsigned int pgoff,
7903 u64 start, u64 end, int failed_mirror,
7904 bio_end_io_t *repair_endio, void *repair_arg)
7906 struct io_failure_record *failrec;
7907 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
7908 struct extent_io_tree *failure_tree = &BTRFS_I(inode)->io_failure_tree;
7911 unsigned int read_mode = 0;
7914 blk_status_t status;
7915 struct bio_vec bvec;
7917 BUG_ON(bio_op(failed_bio) == REQ_OP_WRITE);
7919 ret = btrfs_get_io_failure_record(inode, start, end, &failrec);
7921 return errno_to_blk_status(ret);
7923 ret = btrfs_check_dio_repairable(inode, failed_bio, failrec,
7926 free_io_failure(failure_tree, io_tree, failrec);
7927 return BLK_STS_IOERR;
7930 segs = bio_segments(failed_bio);
7931 bio_get_first_bvec(failed_bio, &bvec);
7933 (bvec.bv_len > btrfs_inode_sectorsize(inode)))
7934 read_mode |= REQ_FAILFAST_DEV;
7936 isector = start - btrfs_io_bio(failed_bio)->logical;
7937 isector >>= inode->i_sb->s_blocksize_bits;
7938 bio = btrfs_create_repair_bio(inode, failed_bio, failrec, page,
7939 pgoff, isector, repair_endio, repair_arg);
7940 bio_set_op_attrs(bio, REQ_OP_READ, read_mode);
7942 btrfs_debug(BTRFS_I(inode)->root->fs_info,
7943 "repair DIO read error: submitting new dio read[%#x] to this_mirror=%d, in_validation=%d",
7944 read_mode, failrec->this_mirror, failrec->in_validation);
7946 status = submit_dio_repair_bio(inode, bio, failrec->this_mirror);
7948 free_io_failure(failure_tree, io_tree, failrec);
7955 struct btrfs_retry_complete {
7956 struct completion done;
7957 struct inode *inode;
7962 static void btrfs_retry_endio_nocsum(struct bio *bio)
7964 struct btrfs_retry_complete *done = bio->bi_private;
7965 struct inode *inode = done->inode;
7966 struct bio_vec *bvec;
7967 struct extent_io_tree *io_tree, *failure_tree;
7973 ASSERT(bio->bi_vcnt == 1);
7974 io_tree = &BTRFS_I(inode)->io_tree;
7975 failure_tree = &BTRFS_I(inode)->io_failure_tree;
7976 ASSERT(bio_first_bvec_all(bio)->bv_len == btrfs_inode_sectorsize(inode));
7979 ASSERT(!bio_flagged(bio, BIO_CLONED));
7980 bio_for_each_segment_all(bvec, bio, i)
7981 clean_io_failure(BTRFS_I(inode)->root->fs_info, failure_tree,
7982 io_tree, done->start, bvec->bv_page,
7983 btrfs_ino(BTRFS_I(inode)), 0);
7985 complete(&done->done);
7989 static blk_status_t __btrfs_correct_data_nocsum(struct inode *inode,
7990 struct btrfs_io_bio *io_bio)
7992 struct btrfs_fs_info *fs_info;
7993 struct bio_vec bvec;
7994 struct bvec_iter iter;
7995 struct btrfs_retry_complete done;
8001 blk_status_t err = BLK_STS_OK;
8003 fs_info = BTRFS_I(inode)->root->fs_info;
8004 sectorsize = fs_info->sectorsize;
8006 start = io_bio->logical;
8008 io_bio->bio.bi_iter = io_bio->iter;
8010 bio_for_each_segment(bvec, &io_bio->bio, iter) {
8011 nr_sectors = BTRFS_BYTES_TO_BLKS(fs_info, bvec.bv_len);
8012 pgoff = bvec.bv_offset;
8014 next_block_or_try_again:
8017 init_completion(&done.done);
8019 ret = dio_read_error(inode, &io_bio->bio, bvec.bv_page,
8020 pgoff, start, start + sectorsize - 1,
8022 btrfs_retry_endio_nocsum, &done);
8028 wait_for_completion_io(&done.done);
8030 if (!done.uptodate) {
8031 /* We might have another mirror, so try again */
8032 goto next_block_or_try_again;
8036 start += sectorsize;
8040 pgoff += sectorsize;
8041 ASSERT(pgoff < PAGE_SIZE);
8042 goto next_block_or_try_again;
8049 static void btrfs_retry_endio(struct bio *bio)
8051 struct btrfs_retry_complete *done = bio->bi_private;
8052 struct btrfs_io_bio *io_bio = btrfs_io_bio(bio);
8053 struct extent_io_tree *io_tree, *failure_tree;
8054 struct inode *inode = done->inode;
8055 struct bio_vec *bvec;
8065 ASSERT(bio->bi_vcnt == 1);
8066 ASSERT(bio_first_bvec_all(bio)->bv_len == btrfs_inode_sectorsize(done->inode));
8068 io_tree = &BTRFS_I(inode)->io_tree;
8069 failure_tree = &BTRFS_I(inode)->io_failure_tree;
8071 ASSERT(!bio_flagged(bio, BIO_CLONED));
8072 bio_for_each_segment_all(bvec, bio, i) {
8073 ret = __readpage_endio_check(inode, io_bio, i, bvec->bv_page,
8074 bvec->bv_offset, done->start,
8077 clean_io_failure(BTRFS_I(inode)->root->fs_info,
8078 failure_tree, io_tree, done->start,
8080 btrfs_ino(BTRFS_I(inode)),
8086 done->uptodate = uptodate;
8088 complete(&done->done);
8092 static blk_status_t __btrfs_subio_endio_read(struct inode *inode,
8093 struct btrfs_io_bio *io_bio, blk_status_t err)
8095 struct btrfs_fs_info *fs_info;
8096 struct bio_vec bvec;
8097 struct bvec_iter iter;
8098 struct btrfs_retry_complete done;
8105 bool uptodate = (err == 0);
8107 blk_status_t status;
8109 fs_info = BTRFS_I(inode)->root->fs_info;
8110 sectorsize = fs_info->sectorsize;
8113 start = io_bio->logical;
8115 io_bio->bio.bi_iter = io_bio->iter;
8117 bio_for_each_segment(bvec, &io_bio->bio, iter) {
8118 nr_sectors = BTRFS_BYTES_TO_BLKS(fs_info, bvec.bv_len);
8120 pgoff = bvec.bv_offset;
8123 csum_pos = BTRFS_BYTES_TO_BLKS(fs_info, offset);
8124 ret = __readpage_endio_check(inode, io_bio, csum_pos,
8125 bvec.bv_page, pgoff, start, sectorsize);
8132 init_completion(&done.done);
8134 status = dio_read_error(inode, &io_bio->bio, bvec.bv_page,
8135 pgoff, start, start + sectorsize - 1,
8136 io_bio->mirror_num, btrfs_retry_endio,
8143 wait_for_completion_io(&done.done);
8145 if (!done.uptodate) {
8146 /* We might have another mirror, so try again */
8150 offset += sectorsize;
8151 start += sectorsize;
8157 pgoff += sectorsize;
8158 ASSERT(pgoff < PAGE_SIZE);
8166 static blk_status_t btrfs_subio_endio_read(struct inode *inode,
8167 struct btrfs_io_bio *io_bio, blk_status_t err)
8169 bool skip_csum = BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM;
8173 return __btrfs_correct_data_nocsum(inode, io_bio);
8177 return __btrfs_subio_endio_read(inode, io_bio, err);
8181 static void btrfs_endio_direct_read(struct bio *bio)
8183 struct btrfs_dio_private *dip = bio->bi_private;
8184 struct inode *inode = dip->inode;
8185 struct bio *dio_bio;
8186 struct btrfs_io_bio *io_bio = btrfs_io_bio(bio);
8187 blk_status_t err = bio->bi_status;
8189 if (dip->flags & BTRFS_DIO_ORIG_BIO_SUBMITTED)
8190 err = btrfs_subio_endio_read(inode, io_bio, err);
8192 unlock_extent(&BTRFS_I(inode)->io_tree, dip->logical_offset,
8193 dip->logical_offset + dip->bytes - 1);
8194 dio_bio = dip->dio_bio;
8198 dio_bio->bi_status = err;
8199 dio_end_io(dio_bio);
8202 io_bio->end_io(io_bio, blk_status_to_errno(err));
8206 static void __endio_write_update_ordered(struct inode *inode,
8207 const u64 offset, const u64 bytes,
8208 const bool uptodate)
8210 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
8211 struct btrfs_ordered_extent *ordered = NULL;
8212 struct btrfs_workqueue *wq;
8213 btrfs_work_func_t func;
8214 u64 ordered_offset = offset;
8215 u64 ordered_bytes = bytes;
8219 if (btrfs_is_free_space_inode(BTRFS_I(inode))) {
8220 wq = fs_info->endio_freespace_worker;
8221 func = btrfs_freespace_write_helper;
8223 wq = fs_info->endio_write_workers;
8224 func = btrfs_endio_write_helper;
8228 last_offset = ordered_offset;
8229 ret = btrfs_dec_test_first_ordered_pending(inode, &ordered,
8236 btrfs_init_work(&ordered->work, func, finish_ordered_fn, NULL, NULL);
8237 btrfs_queue_work(wq, &ordered->work);
8240 * If btrfs_dec_test_ordered_pending does not find any ordered extent
8241 * in the range, we can exit.
8243 if (ordered_offset == last_offset)
8246 * our bio might span multiple ordered extents. If we haven't
8247 * completed the accounting for the whole dio, go back and try again
8249 if (ordered_offset < offset + bytes) {
8250 ordered_bytes = offset + bytes - ordered_offset;
8256 static void btrfs_endio_direct_write(struct bio *bio)
8258 struct btrfs_dio_private *dip = bio->bi_private;
8259 struct bio *dio_bio = dip->dio_bio;
8261 __endio_write_update_ordered(dip->inode, dip->logical_offset,
8262 dip->bytes, !bio->bi_status);
8266 dio_bio->bi_status = bio->bi_status;
8267 dio_end_io(dio_bio);
8271 static blk_status_t __btrfs_submit_bio_start_direct_io(void *private_data,
8272 struct bio *bio, int mirror_num,
8273 unsigned long bio_flags, u64 offset)
8275 struct inode *inode = private_data;
8277 ret = btrfs_csum_one_bio(inode, bio, offset, 1);
8278 BUG_ON(ret); /* -ENOMEM */
8282 static void btrfs_end_dio_bio(struct bio *bio)
8284 struct btrfs_dio_private *dip = bio->bi_private;
8285 blk_status_t err = bio->bi_status;
8288 btrfs_warn(BTRFS_I(dip->inode)->root->fs_info,
8289 "direct IO failed ino %llu rw %d,%u sector %#Lx len %u err no %d",
8290 btrfs_ino(BTRFS_I(dip->inode)), bio_op(bio),
8292 (unsigned long long)bio->bi_iter.bi_sector,
8293 bio->bi_iter.bi_size, err);
8295 if (dip->subio_endio)
8296 err = dip->subio_endio(dip->inode, btrfs_io_bio(bio), err);
8302 * before atomic variable goto zero, we must make sure
8303 * dip->errors is perceived to be set.
8305 smp_mb__before_atomic();
8308 /* if there are more bios still pending for this dio, just exit */
8309 if (!atomic_dec_and_test(&dip->pending_bios))
8313 bio_io_error(dip->orig_bio);
8315 dip->dio_bio->bi_status = BLK_STS_OK;
8316 bio_endio(dip->orig_bio);
8322 static inline blk_status_t btrfs_lookup_and_bind_dio_csum(struct inode *inode,
8323 struct btrfs_dio_private *dip,
8327 struct btrfs_io_bio *io_bio = btrfs_io_bio(bio);
8328 struct btrfs_io_bio *orig_io_bio = btrfs_io_bio(dip->orig_bio);
8332 * We load all the csum data we need when we submit
8333 * the first bio to reduce the csum tree search and
8336 if (dip->logical_offset == file_offset) {
8337 ret = btrfs_lookup_bio_sums_dio(inode, dip->orig_bio,
8343 if (bio == dip->orig_bio)
8346 file_offset -= dip->logical_offset;
8347 file_offset >>= inode->i_sb->s_blocksize_bits;
8348 io_bio->csum = (u8 *)(((u32 *)orig_io_bio->csum) + file_offset);
8353 static inline blk_status_t
8354 __btrfs_submit_dio_bio(struct bio *bio, struct inode *inode, u64 file_offset,
8357 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
8358 struct btrfs_dio_private *dip = bio->bi_private;
8359 bool write = bio_op(bio) == REQ_OP_WRITE;
8362 /* Check btrfs_submit_bio_hook() for rules about async submit. */
8364 async_submit = !atomic_read(&BTRFS_I(inode)->sync_writers);
8367 ret = btrfs_bio_wq_end_io(fs_info, bio, BTRFS_WQ_ENDIO_DATA);
8372 if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)
8375 if (write && async_submit) {
8376 ret = btrfs_wq_submit_bio(fs_info, bio, 0, 0,
8378 __btrfs_submit_bio_start_direct_io,
8379 __btrfs_submit_bio_done);
8383 * If we aren't doing async submit, calculate the csum of the
8386 ret = btrfs_csum_one_bio(inode, bio, file_offset, 1);
8390 ret = btrfs_lookup_and_bind_dio_csum(inode, dip, bio,
8396 ret = btrfs_map_bio(fs_info, bio, 0, 0);
8401 static int btrfs_submit_direct_hook(struct btrfs_dio_private *dip)
8403 struct inode *inode = dip->inode;
8404 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
8406 struct bio *orig_bio = dip->orig_bio;
8407 u64 start_sector = orig_bio->bi_iter.bi_sector;
8408 u64 file_offset = dip->logical_offset;
8410 int async_submit = 0;
8412 int clone_offset = 0;
8415 blk_status_t status;
8417 map_length = orig_bio->bi_iter.bi_size;
8418 submit_len = map_length;
8419 ret = btrfs_map_block(fs_info, btrfs_op(orig_bio), start_sector << 9,
8420 &map_length, NULL, 0);
8424 if (map_length >= submit_len) {
8426 dip->flags |= BTRFS_DIO_ORIG_BIO_SUBMITTED;
8430 /* async crcs make it difficult to collect full stripe writes. */
8431 if (btrfs_data_alloc_profile(fs_info) & BTRFS_BLOCK_GROUP_RAID56_MASK)
8437 ASSERT(map_length <= INT_MAX);
8438 atomic_inc(&dip->pending_bios);
8440 clone_len = min_t(int, submit_len, map_length);
8443 * This will never fail as it's passing GPF_NOFS and
8444 * the allocation is backed by btrfs_bioset.
8446 bio = btrfs_bio_clone_partial(orig_bio, clone_offset,
8448 bio->bi_private = dip;
8449 bio->bi_end_io = btrfs_end_dio_bio;
8450 btrfs_io_bio(bio)->logical = file_offset;
8452 ASSERT(submit_len >= clone_len);
8453 submit_len -= clone_len;
8454 if (submit_len == 0)
8458 * Increase the count before we submit the bio so we know
8459 * the end IO handler won't happen before we increase the
8460 * count. Otherwise, the dip might get freed before we're
8461 * done setting it up.
8463 atomic_inc(&dip->pending_bios);
8465 status = __btrfs_submit_dio_bio(bio, inode, file_offset,
8469 atomic_dec(&dip->pending_bios);
8473 clone_offset += clone_len;
8474 start_sector += clone_len >> 9;
8475 file_offset += clone_len;
8477 map_length = submit_len;
8478 ret = btrfs_map_block(fs_info, btrfs_op(orig_bio),
8479 start_sector << 9, &map_length, NULL, 0);
8482 } while (submit_len > 0);
8485 status = __btrfs_submit_dio_bio(bio, inode, file_offset, async_submit);
8493 * before atomic variable goto zero, we must
8494 * make sure dip->errors is perceived to be set.
8496 smp_mb__before_atomic();
8497 if (atomic_dec_and_test(&dip->pending_bios))
8498 bio_io_error(dip->orig_bio);
8500 /* bio_end_io() will handle error, so we needn't return it */
8504 static void btrfs_submit_direct(struct bio *dio_bio, struct inode *inode,
8507 struct btrfs_dio_private *dip = NULL;
8508 struct bio *bio = NULL;
8509 struct btrfs_io_bio *io_bio;
8510 bool write = (bio_op(dio_bio) == REQ_OP_WRITE);
8513 bio = btrfs_bio_clone(dio_bio);
8515 dip = kzalloc(sizeof(*dip), GFP_NOFS);
8521 dip->private = dio_bio->bi_private;
8523 dip->logical_offset = file_offset;
8524 dip->bytes = dio_bio->bi_iter.bi_size;
8525 dip->disk_bytenr = (u64)dio_bio->bi_iter.bi_sector << 9;
8526 bio->bi_private = dip;
8527 dip->orig_bio = bio;
8528 dip->dio_bio = dio_bio;
8529 atomic_set(&dip->pending_bios, 0);
8530 io_bio = btrfs_io_bio(bio);
8531 io_bio->logical = file_offset;
8534 bio->bi_end_io = btrfs_endio_direct_write;
8536 bio->bi_end_io = btrfs_endio_direct_read;
8537 dip->subio_endio = btrfs_subio_endio_read;
8541 * Reset the range for unsubmitted ordered extents (to a 0 length range)
8542 * even if we fail to submit a bio, because in such case we do the
8543 * corresponding error handling below and it must not be done a second
8544 * time by btrfs_direct_IO().
8547 struct btrfs_dio_data *dio_data = current->journal_info;
8549 dio_data->unsubmitted_oe_range_end = dip->logical_offset +
8551 dio_data->unsubmitted_oe_range_start =
8552 dio_data->unsubmitted_oe_range_end;
8555 ret = btrfs_submit_direct_hook(dip);
8560 io_bio->end_io(io_bio, ret);
8564 * If we arrived here it means either we failed to submit the dip
8565 * or we either failed to clone the dio_bio or failed to allocate the
8566 * dip. If we cloned the dio_bio and allocated the dip, we can just
8567 * call bio_endio against our io_bio so that we get proper resource
8568 * cleanup if we fail to submit the dip, otherwise, we must do the
8569 * same as btrfs_endio_direct_[write|read] because we can't call these
8570 * callbacks - they require an allocated dip and a clone of dio_bio.
8575 * The end io callbacks free our dip, do the final put on bio
8576 * and all the cleanup and final put for dio_bio (through
8583 __endio_write_update_ordered(inode,
8585 dio_bio->bi_iter.bi_size,
8588 unlock_extent(&BTRFS_I(inode)->io_tree, file_offset,
8589 file_offset + dio_bio->bi_iter.bi_size - 1);
8591 dio_bio->bi_status = BLK_STS_IOERR;
8593 * Releases and cleans up our dio_bio, no need to bio_put()
8594 * nor bio_endio()/bio_io_error() against dio_bio.
8596 dio_end_io(dio_bio);
8603 static ssize_t check_direct_IO(struct btrfs_fs_info *fs_info,
8604 const struct iov_iter *iter, loff_t offset)
8608 unsigned int blocksize_mask = fs_info->sectorsize - 1;
8609 ssize_t retval = -EINVAL;
8611 if (offset & blocksize_mask)
8614 if (iov_iter_alignment(iter) & blocksize_mask)
8617 /* If this is a write we don't need to check anymore */
8618 if (iov_iter_rw(iter) != READ || !iter_is_iovec(iter))
8621 * Check to make sure we don't have duplicate iov_base's in this
8622 * iovec, if so return EINVAL, otherwise we'll get csum errors
8623 * when reading back.
8625 for (seg = 0; seg < iter->nr_segs; seg++) {
8626 for (i = seg + 1; i < iter->nr_segs; i++) {
8627 if (iter->iov[seg].iov_base == iter->iov[i].iov_base)
8636 static ssize_t btrfs_direct_IO(struct kiocb *iocb, struct iov_iter *iter)
8638 struct file *file = iocb->ki_filp;
8639 struct inode *inode = file->f_mapping->host;
8640 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
8641 struct btrfs_dio_data dio_data = { 0 };
8642 struct extent_changeset *data_reserved = NULL;
8643 loff_t offset = iocb->ki_pos;
8647 bool relock = false;
8650 if (check_direct_IO(fs_info, iter, offset))
8653 inode_dio_begin(inode);
8656 * The generic stuff only does filemap_write_and_wait_range, which
8657 * isn't enough if we've written compressed pages to this area, so
8658 * we need to flush the dirty pages again to make absolutely sure
8659 * that any outstanding dirty pages are on disk.
8661 count = iov_iter_count(iter);
8662 if (test_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
8663 &BTRFS_I(inode)->runtime_flags))
8664 filemap_fdatawrite_range(inode->i_mapping, offset,
8665 offset + count - 1);
8667 if (iov_iter_rw(iter) == WRITE) {
8669 * If the write DIO is beyond the EOF, we need update
8670 * the isize, but it is protected by i_mutex. So we can
8671 * not unlock the i_mutex at this case.
8673 if (offset + count <= inode->i_size) {
8674 dio_data.overwrite = 1;
8675 inode_unlock(inode);
8677 } else if (iocb->ki_flags & IOCB_NOWAIT) {
8681 ret = btrfs_delalloc_reserve_space(inode, &data_reserved,
8687 * We need to know how many extents we reserved so that we can
8688 * do the accounting properly if we go over the number we
8689 * originally calculated. Abuse current->journal_info for this.
8691 dio_data.reserve = round_up(count,
8692 fs_info->sectorsize);
8693 dio_data.unsubmitted_oe_range_start = (u64)offset;
8694 dio_data.unsubmitted_oe_range_end = (u64)offset;
8695 current->journal_info = &dio_data;
8696 down_read(&BTRFS_I(inode)->dio_sem);
8697 } else if (test_bit(BTRFS_INODE_READDIO_NEED_LOCK,
8698 &BTRFS_I(inode)->runtime_flags)) {
8699 inode_dio_end(inode);
8700 flags = DIO_LOCKING | DIO_SKIP_HOLES;
8704 ret = __blockdev_direct_IO(iocb, inode,
8705 fs_info->fs_devices->latest_bdev,
8706 iter, btrfs_get_blocks_direct, NULL,
8707 btrfs_submit_direct, flags);
8708 if (iov_iter_rw(iter) == WRITE) {
8709 up_read(&BTRFS_I(inode)->dio_sem);
8710 current->journal_info = NULL;
8711 if (ret < 0 && ret != -EIOCBQUEUED) {
8712 if (dio_data.reserve)
8713 btrfs_delalloc_release_space(inode, data_reserved,
8714 offset, dio_data.reserve);
8716 * On error we might have left some ordered extents
8717 * without submitting corresponding bios for them, so
8718 * cleanup them up to avoid other tasks getting them
8719 * and waiting for them to complete forever.
8721 if (dio_data.unsubmitted_oe_range_start <
8722 dio_data.unsubmitted_oe_range_end)
8723 __endio_write_update_ordered(inode,
8724 dio_data.unsubmitted_oe_range_start,
8725 dio_data.unsubmitted_oe_range_end -
8726 dio_data.unsubmitted_oe_range_start,
8728 } else if (ret >= 0 && (size_t)ret < count)
8729 btrfs_delalloc_release_space(inode, data_reserved,
8730 offset, count - (size_t)ret);
8731 btrfs_delalloc_release_extents(BTRFS_I(inode), count);
8735 inode_dio_end(inode);
8739 extent_changeset_free(data_reserved);
8743 #define BTRFS_FIEMAP_FLAGS (FIEMAP_FLAG_SYNC)
8745 static int btrfs_fiemap(struct inode *inode, struct fiemap_extent_info *fieinfo,
8746 __u64 start, __u64 len)
8750 ret = fiemap_check_flags(fieinfo, BTRFS_FIEMAP_FLAGS);
8754 return extent_fiemap(inode, fieinfo, start, len);
8757 int btrfs_readpage(struct file *file, struct page *page)
8759 struct extent_io_tree *tree;
8760 tree = &BTRFS_I(page->mapping->host)->io_tree;
8761 return extent_read_full_page(tree, page, btrfs_get_extent, 0);
8764 static int btrfs_writepage(struct page *page, struct writeback_control *wbc)
8766 struct inode *inode = page->mapping->host;
8769 if (current->flags & PF_MEMALLOC) {
8770 redirty_page_for_writepage(wbc, page);
8776 * If we are under memory pressure we will call this directly from the
8777 * VM, we need to make sure we have the inode referenced for the ordered
8778 * extent. If not just return like we didn't do anything.
8780 if (!igrab(inode)) {
8781 redirty_page_for_writepage(wbc, page);
8782 return AOP_WRITEPAGE_ACTIVATE;
8784 ret = extent_write_full_page(page, wbc);
8785 btrfs_add_delayed_iput(inode);
8789 static int btrfs_writepages(struct address_space *mapping,
8790 struct writeback_control *wbc)
8792 struct extent_io_tree *tree;
8794 tree = &BTRFS_I(mapping->host)->io_tree;
8795 return extent_writepages(tree, mapping, wbc);
8799 btrfs_readpages(struct file *file, struct address_space *mapping,
8800 struct list_head *pages, unsigned nr_pages)
8802 struct extent_io_tree *tree;
8803 tree = &BTRFS_I(mapping->host)->io_tree;
8804 return extent_readpages(tree, mapping, pages, nr_pages);
8806 static int __btrfs_releasepage(struct page *page, gfp_t gfp_flags)
8808 struct extent_io_tree *tree;
8809 struct extent_map_tree *map;
8812 tree = &BTRFS_I(page->mapping->host)->io_tree;
8813 map = &BTRFS_I(page->mapping->host)->extent_tree;
8814 ret = try_release_extent_mapping(map, tree, page, gfp_flags);
8816 ClearPagePrivate(page);
8817 set_page_private(page, 0);
8823 static int btrfs_releasepage(struct page *page, gfp_t gfp_flags)
8825 if (PageWriteback(page) || PageDirty(page))
8827 return __btrfs_releasepage(page, gfp_flags);
8830 static void btrfs_invalidatepage(struct page *page, unsigned int offset,
8831 unsigned int length)
8833 struct inode *inode = page->mapping->host;
8834 struct extent_io_tree *tree;
8835 struct btrfs_ordered_extent *ordered;
8836 struct extent_state *cached_state = NULL;
8837 u64 page_start = page_offset(page);
8838 u64 page_end = page_start + PAGE_SIZE - 1;
8841 int inode_evicting = inode->i_state & I_FREEING;
8844 * we have the page locked, so new writeback can't start,
8845 * and the dirty bit won't be cleared while we are here.
8847 * Wait for IO on this page so that we can safely clear
8848 * the PagePrivate2 bit and do ordered accounting
8850 wait_on_page_writeback(page);
8852 tree = &BTRFS_I(inode)->io_tree;
8854 btrfs_releasepage(page, GFP_NOFS);
8858 if (!inode_evicting)
8859 lock_extent_bits(tree, page_start, page_end, &cached_state);
8862 ordered = btrfs_lookup_ordered_range(BTRFS_I(inode), start,
8863 page_end - start + 1);
8865 end = min(page_end, ordered->file_offset + ordered->len - 1);
8867 * IO on this page will never be started, so we need
8868 * to account for any ordered extents now
8870 if (!inode_evicting)
8871 clear_extent_bit(tree, start, end,
8872 EXTENT_DIRTY | EXTENT_DELALLOC |
8873 EXTENT_DELALLOC_NEW |
8874 EXTENT_LOCKED | EXTENT_DO_ACCOUNTING |
8875 EXTENT_DEFRAG, 1, 0, &cached_state);
8877 * whoever cleared the private bit is responsible
8878 * for the finish_ordered_io
8880 if (TestClearPagePrivate2(page)) {
8881 struct btrfs_ordered_inode_tree *tree;
8884 tree = &BTRFS_I(inode)->ordered_tree;
8886 spin_lock_irq(&tree->lock);
8887 set_bit(BTRFS_ORDERED_TRUNCATED, &ordered->flags);
8888 new_len = start - ordered->file_offset;
8889 if (new_len < ordered->truncated_len)
8890 ordered->truncated_len = new_len;
8891 spin_unlock_irq(&tree->lock);
8893 if (btrfs_dec_test_ordered_pending(inode, &ordered,
8895 end - start + 1, 1))
8896 btrfs_finish_ordered_io(ordered);
8898 btrfs_put_ordered_extent(ordered);
8899 if (!inode_evicting) {
8900 cached_state = NULL;
8901 lock_extent_bits(tree, start, end,
8906 if (start < page_end)
8911 * Qgroup reserved space handler
8912 * Page here will be either
8913 * 1) Already written to disk
8914 * In this case, its reserved space is released from data rsv map
8915 * and will be freed by delayed_ref handler finally.
8916 * So even we call qgroup_free_data(), it won't decrease reserved
8918 * 2) Not written to disk
8919 * This means the reserved space should be freed here. However,
8920 * if a truncate invalidates the page (by clearing PageDirty)
8921 * and the page is accounted for while allocating extent
8922 * in btrfs_check_data_free_space() we let delayed_ref to
8923 * free the entire extent.
8925 if (PageDirty(page))
8926 btrfs_qgroup_free_data(inode, NULL, page_start, PAGE_SIZE);
8927 if (!inode_evicting) {
8928 clear_extent_bit(tree, page_start, page_end,
8929 EXTENT_LOCKED | EXTENT_DIRTY |
8930 EXTENT_DELALLOC | EXTENT_DELALLOC_NEW |
8931 EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG, 1, 1,
8934 __btrfs_releasepage(page, GFP_NOFS);
8937 ClearPageChecked(page);
8938 if (PagePrivate(page)) {
8939 ClearPagePrivate(page);
8940 set_page_private(page, 0);
8946 * btrfs_page_mkwrite() is not allowed to change the file size as it gets
8947 * called from a page fault handler when a page is first dirtied. Hence we must
8948 * be careful to check for EOF conditions here. We set the page up correctly
8949 * for a written page which means we get ENOSPC checking when writing into
8950 * holes and correct delalloc and unwritten extent mapping on filesystems that
8951 * support these features.
8953 * We are not allowed to take the i_mutex here so we have to play games to
8954 * protect against truncate races as the page could now be beyond EOF. Because
8955 * vmtruncate() writes the inode size before removing pages, once we have the
8956 * page lock we can determine safely if the page is beyond EOF. If it is not
8957 * beyond EOF, then the page is guaranteed safe against truncation until we
8960 int btrfs_page_mkwrite(struct vm_fault *vmf)
8962 struct page *page = vmf->page;
8963 struct inode *inode = file_inode(vmf->vma->vm_file);
8964 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
8965 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
8966 struct btrfs_ordered_extent *ordered;
8967 struct extent_state *cached_state = NULL;
8968 struct extent_changeset *data_reserved = NULL;
8970 unsigned long zero_start;
8979 reserved_space = PAGE_SIZE;
8981 sb_start_pagefault(inode->i_sb);
8982 page_start = page_offset(page);
8983 page_end = page_start + PAGE_SIZE - 1;
8987 * Reserving delalloc space after obtaining the page lock can lead to
8988 * deadlock. For example, if a dirty page is locked by this function
8989 * and the call to btrfs_delalloc_reserve_space() ends up triggering
8990 * dirty page write out, then the btrfs_writepage() function could
8991 * end up waiting indefinitely to get a lock on the page currently
8992 * being processed by btrfs_page_mkwrite() function.
8994 ret = btrfs_delalloc_reserve_space(inode, &data_reserved, page_start,
8997 ret = file_update_time(vmf->vma->vm_file);
9003 else /* -ENOSPC, -EIO, etc */
9004 ret = VM_FAULT_SIGBUS;
9010 ret = VM_FAULT_NOPAGE; /* make the VM retry the fault */
9013 size = i_size_read(inode);
9015 if ((page->mapping != inode->i_mapping) ||
9016 (page_start >= size)) {
9017 /* page got truncated out from underneath us */
9020 wait_on_page_writeback(page);
9022 lock_extent_bits(io_tree, page_start, page_end, &cached_state);
9023 set_page_extent_mapped(page);
9026 * we can't set the delalloc bits if there are pending ordered
9027 * extents. Drop our locks and wait for them to finish
9029 ordered = btrfs_lookup_ordered_range(BTRFS_I(inode), page_start,
9032 unlock_extent_cached(io_tree, page_start, page_end,
9035 btrfs_start_ordered_extent(inode, ordered, 1);
9036 btrfs_put_ordered_extent(ordered);
9040 if (page->index == ((size - 1) >> PAGE_SHIFT)) {
9041 reserved_space = round_up(size - page_start,
9042 fs_info->sectorsize);
9043 if (reserved_space < PAGE_SIZE) {
9044 end = page_start + reserved_space - 1;
9045 btrfs_delalloc_release_space(inode, data_reserved,
9046 page_start, PAGE_SIZE - reserved_space);
9051 * page_mkwrite gets called when the page is firstly dirtied after it's
9052 * faulted in, but write(2) could also dirty a page and set delalloc
9053 * bits, thus in this case for space account reason, we still need to
9054 * clear any delalloc bits within this page range since we have to
9055 * reserve data&meta space before lock_page() (see above comments).
9057 clear_extent_bit(&BTRFS_I(inode)->io_tree, page_start, end,
9058 EXTENT_DIRTY | EXTENT_DELALLOC |
9059 EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG,
9060 0, 0, &cached_state);
9062 ret = btrfs_set_extent_delalloc(inode, page_start, end, 0,
9065 unlock_extent_cached(io_tree, page_start, page_end,
9067 ret = VM_FAULT_SIGBUS;
9072 /* page is wholly or partially inside EOF */
9073 if (page_start + PAGE_SIZE > size)
9074 zero_start = size & ~PAGE_MASK;
9076 zero_start = PAGE_SIZE;
9078 if (zero_start != PAGE_SIZE) {
9080 memset(kaddr + zero_start, 0, PAGE_SIZE - zero_start);
9081 flush_dcache_page(page);
9084 ClearPageChecked(page);
9085 set_page_dirty(page);
9086 SetPageUptodate(page);
9088 BTRFS_I(inode)->last_trans = fs_info->generation;
9089 BTRFS_I(inode)->last_sub_trans = BTRFS_I(inode)->root->log_transid;
9090 BTRFS_I(inode)->last_log_commit = BTRFS_I(inode)->root->last_log_commit;
9092 unlock_extent_cached(io_tree, page_start, page_end, &cached_state);
9096 btrfs_delalloc_release_extents(BTRFS_I(inode), PAGE_SIZE);
9097 sb_end_pagefault(inode->i_sb);
9098 extent_changeset_free(data_reserved);
9099 return VM_FAULT_LOCKED;
9103 btrfs_delalloc_release_extents(BTRFS_I(inode), PAGE_SIZE);
9104 btrfs_delalloc_release_space(inode, data_reserved, page_start,
9107 sb_end_pagefault(inode->i_sb);
9108 extent_changeset_free(data_reserved);
9112 static int btrfs_truncate(struct inode *inode)
9114 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
9115 struct btrfs_root *root = BTRFS_I(inode)->root;
9116 struct btrfs_block_rsv *rsv;
9119 struct btrfs_trans_handle *trans;
9120 u64 mask = fs_info->sectorsize - 1;
9121 u64 min_size = btrfs_calc_trunc_metadata_size(fs_info, 1);
9123 ret = btrfs_wait_ordered_range(inode, inode->i_size & (~mask),
9129 * Yes ladies and gentlemen, this is indeed ugly. The fact is we have
9130 * 3 things going on here
9132 * 1) We need to reserve space for our orphan item and the space to
9133 * delete our orphan item. Lord knows we don't want to have a dangling
9134 * orphan item because we didn't reserve space to remove it.
9136 * 2) We need to reserve space to update our inode.
9138 * 3) We need to have something to cache all the space that is going to
9139 * be free'd up by the truncate operation, but also have some slack
9140 * space reserved in case it uses space during the truncate (thank you
9141 * very much snapshotting).
9143 * And we need these to all be separate. The fact is we can use a lot of
9144 * space doing the truncate, and we have no earthly idea how much space
9145 * we will use, so we need the truncate reservation to be separate so it
9146 * doesn't end up using space reserved for updating the inode or
9147 * removing the orphan item. We also need to be able to stop the
9148 * transaction and start a new one, which means we need to be able to
9149 * update the inode several times, and we have no idea of knowing how
9150 * many times that will be, so we can't just reserve 1 item for the
9151 * entirety of the operation, so that has to be done separately as well.
9152 * Then there is the orphan item, which does indeed need to be held on
9153 * to for the whole operation, and we need nobody to touch this reserved
9154 * space except the orphan code.
9156 * So that leaves us with
9158 * 1) root->orphan_block_rsv - for the orphan deletion.
9159 * 2) rsv - for the truncate reservation, which we will steal from the
9160 * transaction reservation.
9161 * 3) fs_info->trans_block_rsv - this will have 1 items worth left for
9162 * updating the inode.
9164 rsv = btrfs_alloc_block_rsv(fs_info, BTRFS_BLOCK_RSV_TEMP);
9167 rsv->size = min_size;
9171 * 1 for the truncate slack space
9172 * 1 for updating the inode.
9174 trans = btrfs_start_transaction(root, 2);
9175 if (IS_ERR(trans)) {
9176 err = PTR_ERR(trans);
9180 /* Migrate the slack space for the truncate to our reserve */
9181 ret = btrfs_block_rsv_migrate(&fs_info->trans_block_rsv, rsv,
9186 * So if we truncate and then write and fsync we normally would just
9187 * write the extents that changed, which is a problem if we need to
9188 * first truncate that entire inode. So set this flag so we write out
9189 * all of the extents in the inode to the sync log so we're completely
9192 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &BTRFS_I(inode)->runtime_flags);
9193 trans->block_rsv = rsv;
9196 ret = btrfs_truncate_inode_items(trans, root, inode,
9198 BTRFS_EXTENT_DATA_KEY);
9199 trans->block_rsv = &fs_info->trans_block_rsv;
9200 if (ret != -ENOSPC && ret != -EAGAIN) {
9205 ret = btrfs_update_inode(trans, root, inode);
9211 btrfs_end_transaction(trans);
9212 btrfs_btree_balance_dirty(fs_info);
9214 trans = btrfs_start_transaction(root, 2);
9215 if (IS_ERR(trans)) {
9216 ret = err = PTR_ERR(trans);
9221 btrfs_block_rsv_release(fs_info, rsv, -1);
9222 ret = btrfs_block_rsv_migrate(&fs_info->trans_block_rsv,
9224 BUG_ON(ret); /* shouldn't happen */
9225 trans->block_rsv = rsv;
9229 * We can't call btrfs_truncate_block inside a trans handle as we could
9230 * deadlock with freeze, if we got NEED_TRUNCATE_BLOCK then we know
9231 * we've truncated everything except the last little bit, and can do
9232 * btrfs_truncate_block and then update the disk_i_size.
9234 if (ret == NEED_TRUNCATE_BLOCK) {
9235 btrfs_end_transaction(trans);
9236 btrfs_btree_balance_dirty(fs_info);
9238 ret = btrfs_truncate_block(inode, inode->i_size, 0, 0);
9241 trans = btrfs_start_transaction(root, 1);
9242 if (IS_ERR(trans)) {
9243 ret = PTR_ERR(trans);
9246 btrfs_ordered_update_i_size(inode, inode->i_size, NULL);
9249 if (ret == 0 && inode->i_nlink > 0) {
9250 trans->block_rsv = root->orphan_block_rsv;
9251 ret = btrfs_orphan_del(trans, BTRFS_I(inode));
9257 trans->block_rsv = &fs_info->trans_block_rsv;
9258 ret = btrfs_update_inode(trans, root, inode);
9262 ret = btrfs_end_transaction(trans);
9263 btrfs_btree_balance_dirty(fs_info);
9266 btrfs_free_block_rsv(fs_info, rsv);
9275 * create a new subvolume directory/inode (helper for the ioctl).
9277 int btrfs_create_subvol_root(struct btrfs_trans_handle *trans,
9278 struct btrfs_root *new_root,
9279 struct btrfs_root *parent_root,
9282 struct inode *inode;
9286 inode = btrfs_new_inode(trans, new_root, NULL, "..", 2,
9287 new_dirid, new_dirid,
9288 S_IFDIR | (~current_umask() & S_IRWXUGO),
9291 return PTR_ERR(inode);
9292 inode->i_op = &btrfs_dir_inode_operations;
9293 inode->i_fop = &btrfs_dir_file_operations;
9295 set_nlink(inode, 1);
9296 btrfs_i_size_write(BTRFS_I(inode), 0);
9297 unlock_new_inode(inode);
9299 err = btrfs_subvol_inherit_props(trans, new_root, parent_root);
9301 btrfs_err(new_root->fs_info,
9302 "error inheriting subvolume %llu properties: %d",
9303 new_root->root_key.objectid, err);
9305 err = btrfs_update_inode(trans, new_root, inode);
9311 struct inode *btrfs_alloc_inode(struct super_block *sb)
9313 struct btrfs_fs_info *fs_info = btrfs_sb(sb);
9314 struct btrfs_inode *ei;
9315 struct inode *inode;
9317 ei = kmem_cache_alloc(btrfs_inode_cachep, GFP_KERNEL);
9324 ei->last_sub_trans = 0;
9325 ei->logged_trans = 0;
9326 ei->delalloc_bytes = 0;
9327 ei->new_delalloc_bytes = 0;
9328 ei->defrag_bytes = 0;
9329 ei->disk_i_size = 0;
9332 ei->index_cnt = (u64)-1;
9334 ei->last_unlink_trans = 0;
9335 ei->last_log_commit = 0;
9337 spin_lock_init(&ei->lock);
9338 ei->outstanding_extents = 0;
9339 if (sb->s_magic != BTRFS_TEST_MAGIC)
9340 btrfs_init_metadata_block_rsv(fs_info, &ei->block_rsv,
9341 BTRFS_BLOCK_RSV_DELALLOC);
9342 ei->runtime_flags = 0;
9343 ei->prop_compress = BTRFS_COMPRESS_NONE;
9344 ei->defrag_compress = BTRFS_COMPRESS_NONE;
9346 ei->delayed_node = NULL;
9348 ei->i_otime.tv_sec = 0;
9349 ei->i_otime.tv_nsec = 0;
9351 inode = &ei->vfs_inode;
9352 extent_map_tree_init(&ei->extent_tree);
9353 extent_io_tree_init(&ei->io_tree, inode);
9354 extent_io_tree_init(&ei->io_failure_tree, inode);
9355 ei->io_tree.track_uptodate = 1;
9356 ei->io_failure_tree.track_uptodate = 1;
9357 atomic_set(&ei->sync_writers, 0);
9358 mutex_init(&ei->log_mutex);
9359 mutex_init(&ei->delalloc_mutex);
9360 btrfs_ordered_inode_tree_init(&ei->ordered_tree);
9361 INIT_LIST_HEAD(&ei->delalloc_inodes);
9362 INIT_LIST_HEAD(&ei->delayed_iput);
9363 RB_CLEAR_NODE(&ei->rb_node);
9364 init_rwsem(&ei->dio_sem);
9369 #ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
9370 void btrfs_test_destroy_inode(struct inode *inode)
9372 btrfs_drop_extent_cache(BTRFS_I(inode), 0, (u64)-1, 0);
9373 kmem_cache_free(btrfs_inode_cachep, BTRFS_I(inode));
9377 static void btrfs_i_callback(struct rcu_head *head)
9379 struct inode *inode = container_of(head, struct inode, i_rcu);
9380 kmem_cache_free(btrfs_inode_cachep, BTRFS_I(inode));
9383 void btrfs_destroy_inode(struct inode *inode)
9385 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
9386 struct btrfs_ordered_extent *ordered;
9387 struct btrfs_root *root = BTRFS_I(inode)->root;
9389 WARN_ON(!hlist_empty(&inode->i_dentry));
9390 WARN_ON(inode->i_data.nrpages);
9391 WARN_ON(BTRFS_I(inode)->block_rsv.reserved);
9392 WARN_ON(BTRFS_I(inode)->block_rsv.size);
9393 WARN_ON(BTRFS_I(inode)->outstanding_extents);
9394 WARN_ON(BTRFS_I(inode)->delalloc_bytes);
9395 WARN_ON(BTRFS_I(inode)->new_delalloc_bytes);
9396 WARN_ON(BTRFS_I(inode)->csum_bytes);
9397 WARN_ON(BTRFS_I(inode)->defrag_bytes);
9400 * This can happen where we create an inode, but somebody else also
9401 * created the same inode and we need to destroy the one we already
9407 if (test_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
9408 &BTRFS_I(inode)->runtime_flags)) {
9409 btrfs_info(fs_info, "inode %llu still on the orphan list",
9410 btrfs_ino(BTRFS_I(inode)));
9411 atomic_dec(&root->orphan_inodes);
9415 ordered = btrfs_lookup_first_ordered_extent(inode, (u64)-1);
9420 "found ordered extent %llu %llu on inode cleanup",
9421 ordered->file_offset, ordered->len);
9422 btrfs_remove_ordered_extent(inode, ordered);
9423 btrfs_put_ordered_extent(ordered);
9424 btrfs_put_ordered_extent(ordered);
9427 btrfs_qgroup_check_reserved_leak(inode);
9428 inode_tree_del(inode);
9429 btrfs_drop_extent_cache(BTRFS_I(inode), 0, (u64)-1, 0);
9431 call_rcu(&inode->i_rcu, btrfs_i_callback);
9434 int btrfs_drop_inode(struct inode *inode)
9436 struct btrfs_root *root = BTRFS_I(inode)->root;
9441 /* the snap/subvol tree is on deleting */
9442 if (btrfs_root_refs(&root->root_item) == 0)
9445 return generic_drop_inode(inode);
9448 static void init_once(void *foo)
9450 struct btrfs_inode *ei = (struct btrfs_inode *) foo;
9452 inode_init_once(&ei->vfs_inode);
9455 void btrfs_destroy_cachep(void)
9458 * Make sure all delayed rcu free inodes are flushed before we
9462 kmem_cache_destroy(btrfs_inode_cachep);
9463 kmem_cache_destroy(btrfs_trans_handle_cachep);
9464 kmem_cache_destroy(btrfs_path_cachep);
9465 kmem_cache_destroy(btrfs_free_space_cachep);
9468 int __init btrfs_init_cachep(void)
9470 btrfs_inode_cachep = kmem_cache_create("btrfs_inode",
9471 sizeof(struct btrfs_inode), 0,
9472 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD | SLAB_ACCOUNT,
9474 if (!btrfs_inode_cachep)
9477 btrfs_trans_handle_cachep = kmem_cache_create("btrfs_trans_handle",
9478 sizeof(struct btrfs_trans_handle), 0,
9479 SLAB_TEMPORARY | SLAB_MEM_SPREAD, NULL);
9480 if (!btrfs_trans_handle_cachep)
9483 btrfs_path_cachep = kmem_cache_create("btrfs_path",
9484 sizeof(struct btrfs_path), 0,
9485 SLAB_MEM_SPREAD, NULL);
9486 if (!btrfs_path_cachep)
9489 btrfs_free_space_cachep = kmem_cache_create("btrfs_free_space",
9490 sizeof(struct btrfs_free_space), 0,
9491 SLAB_MEM_SPREAD, NULL);
9492 if (!btrfs_free_space_cachep)
9497 btrfs_destroy_cachep();
9501 static int btrfs_getattr(const struct path *path, struct kstat *stat,
9502 u32 request_mask, unsigned int flags)
9505 struct inode *inode = d_inode(path->dentry);
9506 u32 blocksize = inode->i_sb->s_blocksize;
9507 u32 bi_flags = BTRFS_I(inode)->flags;
9509 stat->result_mask |= STATX_BTIME;
9510 stat->btime.tv_sec = BTRFS_I(inode)->i_otime.tv_sec;
9511 stat->btime.tv_nsec = BTRFS_I(inode)->i_otime.tv_nsec;
9512 if (bi_flags & BTRFS_INODE_APPEND)
9513 stat->attributes |= STATX_ATTR_APPEND;
9514 if (bi_flags & BTRFS_INODE_COMPRESS)
9515 stat->attributes |= STATX_ATTR_COMPRESSED;
9516 if (bi_flags & BTRFS_INODE_IMMUTABLE)
9517 stat->attributes |= STATX_ATTR_IMMUTABLE;
9518 if (bi_flags & BTRFS_INODE_NODUMP)
9519 stat->attributes |= STATX_ATTR_NODUMP;
9521 stat->attributes_mask |= (STATX_ATTR_APPEND |
9522 STATX_ATTR_COMPRESSED |
9523 STATX_ATTR_IMMUTABLE |
9526 generic_fillattr(inode, stat);
9527 stat->dev = BTRFS_I(inode)->root->anon_dev;
9529 spin_lock(&BTRFS_I(inode)->lock);
9530 delalloc_bytes = BTRFS_I(inode)->new_delalloc_bytes;
9531 spin_unlock(&BTRFS_I(inode)->lock);
9532 stat->blocks = (ALIGN(inode_get_bytes(inode), blocksize) +
9533 ALIGN(delalloc_bytes, blocksize)) >> 9;
9537 static int btrfs_rename_exchange(struct inode *old_dir,
9538 struct dentry *old_dentry,
9539 struct inode *new_dir,
9540 struct dentry *new_dentry)
9542 struct btrfs_fs_info *fs_info = btrfs_sb(old_dir->i_sb);
9543 struct btrfs_trans_handle *trans;
9544 struct btrfs_root *root = BTRFS_I(old_dir)->root;
9545 struct btrfs_root *dest = BTRFS_I(new_dir)->root;
9546 struct inode *new_inode = new_dentry->d_inode;
9547 struct inode *old_inode = old_dentry->d_inode;
9548 struct timespec ctime = current_time(old_inode);
9549 struct dentry *parent;
9550 u64 old_ino = btrfs_ino(BTRFS_I(old_inode));
9551 u64 new_ino = btrfs_ino(BTRFS_I(new_inode));
9556 bool root_log_pinned = false;
9557 bool dest_log_pinned = false;
9559 /* we only allow rename subvolume link between subvolumes */
9560 if (old_ino != BTRFS_FIRST_FREE_OBJECTID && root != dest)
9563 /* close the race window with snapshot create/destroy ioctl */
9564 if (old_ino == BTRFS_FIRST_FREE_OBJECTID)
9565 down_read(&fs_info->subvol_sem);
9566 if (new_ino == BTRFS_FIRST_FREE_OBJECTID)
9567 down_read(&fs_info->subvol_sem);
9570 * We want to reserve the absolute worst case amount of items. So if
9571 * both inodes are subvols and we need to unlink them then that would
9572 * require 4 item modifications, but if they are both normal inodes it
9573 * would require 5 item modifications, so we'll assume their normal
9574 * inodes. So 5 * 2 is 10, plus 2 for the new links, so 12 total items
9575 * should cover the worst case number of items we'll modify.
9577 trans = btrfs_start_transaction(root, 12);
9578 if (IS_ERR(trans)) {
9579 ret = PTR_ERR(trans);
9584 * We need to find a free sequence number both in the source and
9585 * in the destination directory for the exchange.
9587 ret = btrfs_set_inode_index(BTRFS_I(new_dir), &old_idx);
9590 ret = btrfs_set_inode_index(BTRFS_I(old_dir), &new_idx);
9594 BTRFS_I(old_inode)->dir_index = 0ULL;
9595 BTRFS_I(new_inode)->dir_index = 0ULL;
9597 /* Reference for the source. */
9598 if (old_ino == BTRFS_FIRST_FREE_OBJECTID) {
9599 /* force full log commit if subvolume involved. */
9600 btrfs_set_log_full_commit(fs_info, trans);
9602 btrfs_pin_log_trans(root);
9603 root_log_pinned = true;
9604 ret = btrfs_insert_inode_ref(trans, dest,
9605 new_dentry->d_name.name,
9606 new_dentry->d_name.len,
9608 btrfs_ino(BTRFS_I(new_dir)),
9614 /* And now for the dest. */
9615 if (new_ino == BTRFS_FIRST_FREE_OBJECTID) {
9616 /* force full log commit if subvolume involved. */
9617 btrfs_set_log_full_commit(fs_info, trans);
9619 btrfs_pin_log_trans(dest);
9620 dest_log_pinned = true;
9621 ret = btrfs_insert_inode_ref(trans, root,
9622 old_dentry->d_name.name,
9623 old_dentry->d_name.len,
9625 btrfs_ino(BTRFS_I(old_dir)),
9631 /* Update inode version and ctime/mtime. */
9632 inode_inc_iversion(old_dir);
9633 inode_inc_iversion(new_dir);
9634 inode_inc_iversion(old_inode);
9635 inode_inc_iversion(new_inode);
9636 old_dir->i_ctime = old_dir->i_mtime = ctime;
9637 new_dir->i_ctime = new_dir->i_mtime = ctime;
9638 old_inode->i_ctime = ctime;
9639 new_inode->i_ctime = ctime;
9641 if (old_dentry->d_parent != new_dentry->d_parent) {
9642 btrfs_record_unlink_dir(trans, BTRFS_I(old_dir),
9643 BTRFS_I(old_inode), 1);
9644 btrfs_record_unlink_dir(trans, BTRFS_I(new_dir),
9645 BTRFS_I(new_inode), 1);
9648 /* src is a subvolume */
9649 if (old_ino == BTRFS_FIRST_FREE_OBJECTID) {
9650 root_objectid = BTRFS_I(old_inode)->root->root_key.objectid;
9651 ret = btrfs_unlink_subvol(trans, root, old_dir,
9653 old_dentry->d_name.name,
9654 old_dentry->d_name.len);
9655 } else { /* src is an inode */
9656 ret = __btrfs_unlink_inode(trans, root, BTRFS_I(old_dir),
9657 BTRFS_I(old_dentry->d_inode),
9658 old_dentry->d_name.name,
9659 old_dentry->d_name.len);
9661 ret = btrfs_update_inode(trans, root, old_inode);
9664 btrfs_abort_transaction(trans, ret);
9668 /* dest is a subvolume */
9669 if (new_ino == BTRFS_FIRST_FREE_OBJECTID) {
9670 root_objectid = BTRFS_I(new_inode)->root->root_key.objectid;
9671 ret = btrfs_unlink_subvol(trans, dest, new_dir,
9673 new_dentry->d_name.name,
9674 new_dentry->d_name.len);
9675 } else { /* dest is an inode */
9676 ret = __btrfs_unlink_inode(trans, dest, BTRFS_I(new_dir),
9677 BTRFS_I(new_dentry->d_inode),
9678 new_dentry->d_name.name,
9679 new_dentry->d_name.len);
9681 ret = btrfs_update_inode(trans, dest, new_inode);
9684 btrfs_abort_transaction(trans, ret);
9688 ret = btrfs_add_link(trans, BTRFS_I(new_dir), BTRFS_I(old_inode),
9689 new_dentry->d_name.name,
9690 new_dentry->d_name.len, 0, old_idx);
9692 btrfs_abort_transaction(trans, ret);
9696 ret = btrfs_add_link(trans, BTRFS_I(old_dir), BTRFS_I(new_inode),
9697 old_dentry->d_name.name,
9698 old_dentry->d_name.len, 0, new_idx);
9700 btrfs_abort_transaction(trans, ret);
9704 if (old_inode->i_nlink == 1)
9705 BTRFS_I(old_inode)->dir_index = old_idx;
9706 if (new_inode->i_nlink == 1)
9707 BTRFS_I(new_inode)->dir_index = new_idx;
9709 if (root_log_pinned) {
9710 parent = new_dentry->d_parent;
9711 btrfs_log_new_name(trans, BTRFS_I(old_inode), BTRFS_I(old_dir),
9713 btrfs_end_log_trans(root);
9714 root_log_pinned = false;
9716 if (dest_log_pinned) {
9717 parent = old_dentry->d_parent;
9718 btrfs_log_new_name(trans, BTRFS_I(new_inode), BTRFS_I(new_dir),
9720 btrfs_end_log_trans(dest);
9721 dest_log_pinned = false;
9725 * If we have pinned a log and an error happened, we unpin tasks
9726 * trying to sync the log and force them to fallback to a transaction
9727 * commit if the log currently contains any of the inodes involved in
9728 * this rename operation (to ensure we do not persist a log with an
9729 * inconsistent state for any of these inodes or leading to any
9730 * inconsistencies when replayed). If the transaction was aborted, the
9731 * abortion reason is propagated to userspace when attempting to commit
9732 * the transaction. If the log does not contain any of these inodes, we
9733 * allow the tasks to sync it.
9735 if (ret && (root_log_pinned || dest_log_pinned)) {
9736 if (btrfs_inode_in_log(BTRFS_I(old_dir), fs_info->generation) ||
9737 btrfs_inode_in_log(BTRFS_I(new_dir), fs_info->generation) ||
9738 btrfs_inode_in_log(BTRFS_I(old_inode), fs_info->generation) ||
9740 btrfs_inode_in_log(BTRFS_I(new_inode), fs_info->generation)))
9741 btrfs_set_log_full_commit(fs_info, trans);
9743 if (root_log_pinned) {
9744 btrfs_end_log_trans(root);
9745 root_log_pinned = false;
9747 if (dest_log_pinned) {
9748 btrfs_end_log_trans(dest);
9749 dest_log_pinned = false;
9752 ret = btrfs_end_transaction(trans);
9754 if (new_ino == BTRFS_FIRST_FREE_OBJECTID)
9755 up_read(&fs_info->subvol_sem);
9756 if (old_ino == BTRFS_FIRST_FREE_OBJECTID)
9757 up_read(&fs_info->subvol_sem);
9762 static int btrfs_whiteout_for_rename(struct btrfs_trans_handle *trans,
9763 struct btrfs_root *root,
9765 struct dentry *dentry)
9768 struct inode *inode;
9772 ret = btrfs_find_free_ino(root, &objectid);
9776 inode = btrfs_new_inode(trans, root, dir,
9777 dentry->d_name.name,
9779 btrfs_ino(BTRFS_I(dir)),
9781 S_IFCHR | WHITEOUT_MODE,
9784 if (IS_ERR(inode)) {
9785 ret = PTR_ERR(inode);
9789 inode->i_op = &btrfs_special_inode_operations;
9790 init_special_inode(inode, inode->i_mode,
9793 ret = btrfs_init_inode_security(trans, inode, dir,
9798 ret = btrfs_add_nondir(trans, BTRFS_I(dir), dentry,
9799 BTRFS_I(inode), 0, index);
9803 ret = btrfs_update_inode(trans, root, inode);
9805 unlock_new_inode(inode);
9807 inode_dec_link_count(inode);
9813 static int btrfs_rename(struct inode *old_dir, struct dentry *old_dentry,
9814 struct inode *new_dir, struct dentry *new_dentry,
9817 struct btrfs_fs_info *fs_info = btrfs_sb(old_dir->i_sb);
9818 struct btrfs_trans_handle *trans;
9819 unsigned int trans_num_items;
9820 struct btrfs_root *root = BTRFS_I(old_dir)->root;
9821 struct btrfs_root *dest = BTRFS_I(new_dir)->root;
9822 struct inode *new_inode = d_inode(new_dentry);
9823 struct inode *old_inode = d_inode(old_dentry);
9827 u64 old_ino = btrfs_ino(BTRFS_I(old_inode));
9828 bool log_pinned = false;
9830 if (btrfs_ino(BTRFS_I(new_dir)) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)
9833 /* we only allow rename subvolume link between subvolumes */
9834 if (old_ino != BTRFS_FIRST_FREE_OBJECTID && root != dest)
9837 if (old_ino == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID ||
9838 (new_inode && btrfs_ino(BTRFS_I(new_inode)) == BTRFS_FIRST_FREE_OBJECTID))
9841 if (S_ISDIR(old_inode->i_mode) && new_inode &&
9842 new_inode->i_size > BTRFS_EMPTY_DIR_SIZE)
9846 /* check for collisions, even if the name isn't there */
9847 ret = btrfs_check_dir_item_collision(dest, new_dir->i_ino,
9848 new_dentry->d_name.name,
9849 new_dentry->d_name.len);
9852 if (ret == -EEXIST) {
9854 * eexist without a new_inode */
9855 if (WARN_ON(!new_inode)) {
9859 /* maybe -EOVERFLOW */
9866 * we're using rename to replace one file with another. Start IO on it
9867 * now so we don't add too much work to the end of the transaction
9869 if (new_inode && S_ISREG(old_inode->i_mode) && new_inode->i_size)
9870 filemap_flush(old_inode->i_mapping);
9872 /* close the racy window with snapshot create/destroy ioctl */
9873 if (old_ino == BTRFS_FIRST_FREE_OBJECTID)
9874 down_read(&fs_info->subvol_sem);
9876 * We want to reserve the absolute worst case amount of items. So if
9877 * both inodes are subvols and we need to unlink them then that would
9878 * require 4 item modifications, but if they are both normal inodes it
9879 * would require 5 item modifications, so we'll assume they are normal
9880 * inodes. So 5 * 2 is 10, plus 1 for the new link, so 11 total items
9881 * should cover the worst case number of items we'll modify.
9882 * If our rename has the whiteout flag, we need more 5 units for the
9883 * new inode (1 inode item, 1 inode ref, 2 dir items and 1 xattr item
9884 * when selinux is enabled).
9886 trans_num_items = 11;
9887 if (flags & RENAME_WHITEOUT)
9888 trans_num_items += 5;
9889 trans = btrfs_start_transaction(root, trans_num_items);
9890 if (IS_ERR(trans)) {
9891 ret = PTR_ERR(trans);
9896 btrfs_record_root_in_trans(trans, dest);
9898 ret = btrfs_set_inode_index(BTRFS_I(new_dir), &index);
9902 BTRFS_I(old_inode)->dir_index = 0ULL;
9903 if (unlikely(old_ino == BTRFS_FIRST_FREE_OBJECTID)) {
9904 /* force full log commit if subvolume involved. */
9905 btrfs_set_log_full_commit(fs_info, trans);
9907 btrfs_pin_log_trans(root);
9909 ret = btrfs_insert_inode_ref(trans, dest,
9910 new_dentry->d_name.name,
9911 new_dentry->d_name.len,
9913 btrfs_ino(BTRFS_I(new_dir)), index);
9918 inode_inc_iversion(old_dir);
9919 inode_inc_iversion(new_dir);
9920 inode_inc_iversion(old_inode);
9921 old_dir->i_ctime = old_dir->i_mtime =
9922 new_dir->i_ctime = new_dir->i_mtime =
9923 old_inode->i_ctime = current_time(old_dir);
9925 if (old_dentry->d_parent != new_dentry->d_parent)
9926 btrfs_record_unlink_dir(trans, BTRFS_I(old_dir),
9927 BTRFS_I(old_inode), 1);
9929 if (unlikely(old_ino == BTRFS_FIRST_FREE_OBJECTID)) {
9930 root_objectid = BTRFS_I(old_inode)->root->root_key.objectid;
9931 ret = btrfs_unlink_subvol(trans, root, old_dir, root_objectid,
9932 old_dentry->d_name.name,
9933 old_dentry->d_name.len);
9935 ret = __btrfs_unlink_inode(trans, root, BTRFS_I(old_dir),
9936 BTRFS_I(d_inode(old_dentry)),
9937 old_dentry->d_name.name,
9938 old_dentry->d_name.len);
9940 ret = btrfs_update_inode(trans, root, old_inode);
9943 btrfs_abort_transaction(trans, ret);
9948 inode_inc_iversion(new_inode);
9949 new_inode->i_ctime = current_time(new_inode);
9950 if (unlikely(btrfs_ino(BTRFS_I(new_inode)) ==
9951 BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)) {
9952 root_objectid = BTRFS_I(new_inode)->location.objectid;
9953 ret = btrfs_unlink_subvol(trans, dest, new_dir,
9955 new_dentry->d_name.name,
9956 new_dentry->d_name.len);
9957 BUG_ON(new_inode->i_nlink == 0);
9959 ret = btrfs_unlink_inode(trans, dest, BTRFS_I(new_dir),
9960 BTRFS_I(d_inode(new_dentry)),
9961 new_dentry->d_name.name,
9962 new_dentry->d_name.len);
9964 if (!ret && new_inode->i_nlink == 0)
9965 ret = btrfs_orphan_add(trans,
9966 BTRFS_I(d_inode(new_dentry)));
9968 btrfs_abort_transaction(trans, ret);
9973 ret = btrfs_add_link(trans, BTRFS_I(new_dir), BTRFS_I(old_inode),
9974 new_dentry->d_name.name,
9975 new_dentry->d_name.len, 0, index);
9977 btrfs_abort_transaction(trans, ret);
9981 if (old_inode->i_nlink == 1)
9982 BTRFS_I(old_inode)->dir_index = index;
9985 struct dentry *parent = new_dentry->d_parent;
9987 btrfs_log_new_name(trans, BTRFS_I(old_inode), BTRFS_I(old_dir),
9989 btrfs_end_log_trans(root);
9993 if (flags & RENAME_WHITEOUT) {
9994 ret = btrfs_whiteout_for_rename(trans, root, old_dir,
9998 btrfs_abort_transaction(trans, ret);
10004 * If we have pinned the log and an error happened, we unpin tasks
10005 * trying to sync the log and force them to fallback to a transaction
10006 * commit if the log currently contains any of the inodes involved in
10007 * this rename operation (to ensure we do not persist a log with an
10008 * inconsistent state for any of these inodes or leading to any
10009 * inconsistencies when replayed). If the transaction was aborted, the
10010 * abortion reason is propagated to userspace when attempting to commit
10011 * the transaction. If the log does not contain any of these inodes, we
10012 * allow the tasks to sync it.
10014 if (ret && log_pinned) {
10015 if (btrfs_inode_in_log(BTRFS_I(old_dir), fs_info->generation) ||
10016 btrfs_inode_in_log(BTRFS_I(new_dir), fs_info->generation) ||
10017 btrfs_inode_in_log(BTRFS_I(old_inode), fs_info->generation) ||
10019 btrfs_inode_in_log(BTRFS_I(new_inode), fs_info->generation)))
10020 btrfs_set_log_full_commit(fs_info, trans);
10022 btrfs_end_log_trans(root);
10023 log_pinned = false;
10025 btrfs_end_transaction(trans);
10027 if (old_ino == BTRFS_FIRST_FREE_OBJECTID)
10028 up_read(&fs_info->subvol_sem);
10033 static int btrfs_rename2(struct inode *old_dir, struct dentry *old_dentry,
10034 struct inode *new_dir, struct dentry *new_dentry,
10035 unsigned int flags)
10037 if (flags & ~(RENAME_NOREPLACE | RENAME_EXCHANGE | RENAME_WHITEOUT))
10040 if (flags & RENAME_EXCHANGE)
10041 return btrfs_rename_exchange(old_dir, old_dentry, new_dir,
10044 return btrfs_rename(old_dir, old_dentry, new_dir, new_dentry, flags);
10047 static void btrfs_run_delalloc_work(struct btrfs_work *work)
10049 struct btrfs_delalloc_work *delalloc_work;
10050 struct inode *inode;
10052 delalloc_work = container_of(work, struct btrfs_delalloc_work,
10054 inode = delalloc_work->inode;
10055 filemap_flush(inode->i_mapping);
10056 if (test_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
10057 &BTRFS_I(inode)->runtime_flags))
10058 filemap_flush(inode->i_mapping);
10060 if (delalloc_work->delay_iput)
10061 btrfs_add_delayed_iput(inode);
10064 complete(&delalloc_work->completion);
10067 struct btrfs_delalloc_work *btrfs_alloc_delalloc_work(struct inode *inode,
10070 struct btrfs_delalloc_work *work;
10072 work = kmalloc(sizeof(*work), GFP_NOFS);
10076 init_completion(&work->completion);
10077 INIT_LIST_HEAD(&work->list);
10078 work->inode = inode;
10079 work->delay_iput = delay_iput;
10080 WARN_ON_ONCE(!inode);
10081 btrfs_init_work(&work->work, btrfs_flush_delalloc_helper,
10082 btrfs_run_delalloc_work, NULL, NULL);
10087 void btrfs_wait_and_free_delalloc_work(struct btrfs_delalloc_work *work)
10089 wait_for_completion(&work->completion);
10094 * some fairly slow code that needs optimization. This walks the list
10095 * of all the inodes with pending delalloc and forces them to disk.
10097 static int __start_delalloc_inodes(struct btrfs_root *root, int delay_iput,
10100 struct btrfs_inode *binode;
10101 struct inode *inode;
10102 struct btrfs_delalloc_work *work, *next;
10103 struct list_head works;
10104 struct list_head splice;
10107 INIT_LIST_HEAD(&works);
10108 INIT_LIST_HEAD(&splice);
10110 mutex_lock(&root->delalloc_mutex);
10111 spin_lock(&root->delalloc_lock);
10112 list_splice_init(&root->delalloc_inodes, &splice);
10113 while (!list_empty(&splice)) {
10114 binode = list_entry(splice.next, struct btrfs_inode,
10117 list_move_tail(&binode->delalloc_inodes,
10118 &root->delalloc_inodes);
10119 inode = igrab(&binode->vfs_inode);
10121 cond_resched_lock(&root->delalloc_lock);
10124 spin_unlock(&root->delalloc_lock);
10126 work = btrfs_alloc_delalloc_work(inode, delay_iput);
10129 btrfs_add_delayed_iput(inode);
10135 list_add_tail(&work->list, &works);
10136 btrfs_queue_work(root->fs_info->flush_workers,
10139 if (nr != -1 && ret >= nr)
10142 spin_lock(&root->delalloc_lock);
10144 spin_unlock(&root->delalloc_lock);
10147 list_for_each_entry_safe(work, next, &works, list) {
10148 list_del_init(&work->list);
10149 btrfs_wait_and_free_delalloc_work(work);
10152 if (!list_empty_careful(&splice)) {
10153 spin_lock(&root->delalloc_lock);
10154 list_splice_tail(&splice, &root->delalloc_inodes);
10155 spin_unlock(&root->delalloc_lock);
10157 mutex_unlock(&root->delalloc_mutex);
10161 int btrfs_start_delalloc_inodes(struct btrfs_root *root, int delay_iput)
10163 struct btrfs_fs_info *fs_info = root->fs_info;
10166 if (test_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state))
10169 ret = __start_delalloc_inodes(root, delay_iput, -1);
10175 int btrfs_start_delalloc_roots(struct btrfs_fs_info *fs_info, int delay_iput,
10178 struct btrfs_root *root;
10179 struct list_head splice;
10182 if (test_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state))
10185 INIT_LIST_HEAD(&splice);
10187 mutex_lock(&fs_info->delalloc_root_mutex);
10188 spin_lock(&fs_info->delalloc_root_lock);
10189 list_splice_init(&fs_info->delalloc_roots, &splice);
10190 while (!list_empty(&splice) && nr) {
10191 root = list_first_entry(&splice, struct btrfs_root,
10193 root = btrfs_grab_fs_root(root);
10195 list_move_tail(&root->delalloc_root,
10196 &fs_info->delalloc_roots);
10197 spin_unlock(&fs_info->delalloc_root_lock);
10199 ret = __start_delalloc_inodes(root, delay_iput, nr);
10200 btrfs_put_fs_root(root);
10208 spin_lock(&fs_info->delalloc_root_lock);
10210 spin_unlock(&fs_info->delalloc_root_lock);
10214 if (!list_empty_careful(&splice)) {
10215 spin_lock(&fs_info->delalloc_root_lock);
10216 list_splice_tail(&splice, &fs_info->delalloc_roots);
10217 spin_unlock(&fs_info->delalloc_root_lock);
10219 mutex_unlock(&fs_info->delalloc_root_mutex);
10223 static int btrfs_symlink(struct inode *dir, struct dentry *dentry,
10224 const char *symname)
10226 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
10227 struct btrfs_trans_handle *trans;
10228 struct btrfs_root *root = BTRFS_I(dir)->root;
10229 struct btrfs_path *path;
10230 struct btrfs_key key;
10231 struct inode *inode = NULL;
10233 int drop_inode = 0;
10239 struct btrfs_file_extent_item *ei;
10240 struct extent_buffer *leaf;
10242 name_len = strlen(symname);
10243 if (name_len > BTRFS_MAX_INLINE_DATA_SIZE(fs_info))
10244 return -ENAMETOOLONG;
10247 * 2 items for inode item and ref
10248 * 2 items for dir items
10249 * 1 item for updating parent inode item
10250 * 1 item for the inline extent item
10251 * 1 item for xattr if selinux is on
10253 trans = btrfs_start_transaction(root, 7);
10255 return PTR_ERR(trans);
10257 err = btrfs_find_free_ino(root, &objectid);
10261 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
10262 dentry->d_name.len, btrfs_ino(BTRFS_I(dir)),
10263 objectid, S_IFLNK|S_IRWXUGO, &index);
10264 if (IS_ERR(inode)) {
10265 err = PTR_ERR(inode);
10270 * If the active LSM wants to access the inode during
10271 * d_instantiate it needs these. Smack checks to see
10272 * if the filesystem supports xattrs by looking at the
10275 inode->i_fop = &btrfs_file_operations;
10276 inode->i_op = &btrfs_file_inode_operations;
10277 inode->i_mapping->a_ops = &btrfs_aops;
10278 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
10280 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
10282 goto out_unlock_inode;
10284 path = btrfs_alloc_path();
10287 goto out_unlock_inode;
10289 key.objectid = btrfs_ino(BTRFS_I(inode));
10291 key.type = BTRFS_EXTENT_DATA_KEY;
10292 datasize = btrfs_file_extent_calc_inline_size(name_len);
10293 err = btrfs_insert_empty_item(trans, root, path, &key,
10296 btrfs_free_path(path);
10297 goto out_unlock_inode;
10299 leaf = path->nodes[0];
10300 ei = btrfs_item_ptr(leaf, path->slots[0],
10301 struct btrfs_file_extent_item);
10302 btrfs_set_file_extent_generation(leaf, ei, trans->transid);
10303 btrfs_set_file_extent_type(leaf, ei,
10304 BTRFS_FILE_EXTENT_INLINE);
10305 btrfs_set_file_extent_encryption(leaf, ei, 0);
10306 btrfs_set_file_extent_compression(leaf, ei, 0);
10307 btrfs_set_file_extent_other_encoding(leaf, ei, 0);
10308 btrfs_set_file_extent_ram_bytes(leaf, ei, name_len);
10310 ptr = btrfs_file_extent_inline_start(ei);
10311 write_extent_buffer(leaf, symname, ptr, name_len);
10312 btrfs_mark_buffer_dirty(leaf);
10313 btrfs_free_path(path);
10315 inode->i_op = &btrfs_symlink_inode_operations;
10316 inode_nohighmem(inode);
10317 inode->i_mapping->a_ops = &btrfs_symlink_aops;
10318 inode_set_bytes(inode, name_len);
10319 btrfs_i_size_write(BTRFS_I(inode), name_len);
10320 err = btrfs_update_inode(trans, root, inode);
10322 * Last step, add directory indexes for our symlink inode. This is the
10323 * last step to avoid extra cleanup of these indexes if an error happens
10327 err = btrfs_add_nondir(trans, BTRFS_I(dir), dentry,
10328 BTRFS_I(inode), 0, index);
10331 goto out_unlock_inode;
10334 unlock_new_inode(inode);
10335 d_instantiate(dentry, inode);
10338 btrfs_end_transaction(trans);
10340 inode_dec_link_count(inode);
10343 btrfs_btree_balance_dirty(fs_info);
10348 unlock_new_inode(inode);
10352 static int __btrfs_prealloc_file_range(struct inode *inode, int mode,
10353 u64 start, u64 num_bytes, u64 min_size,
10354 loff_t actual_len, u64 *alloc_hint,
10355 struct btrfs_trans_handle *trans)
10357 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
10358 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
10359 struct extent_map *em;
10360 struct btrfs_root *root = BTRFS_I(inode)->root;
10361 struct btrfs_key ins;
10362 u64 cur_offset = start;
10365 u64 last_alloc = (u64)-1;
10367 bool own_trans = true;
10368 u64 end = start + num_bytes - 1;
10372 while (num_bytes > 0) {
10374 trans = btrfs_start_transaction(root, 3);
10375 if (IS_ERR(trans)) {
10376 ret = PTR_ERR(trans);
10381 cur_bytes = min_t(u64, num_bytes, SZ_256M);
10382 cur_bytes = max(cur_bytes, min_size);
10384 * If we are severely fragmented we could end up with really
10385 * small allocations, so if the allocator is returning small
10386 * chunks lets make its job easier by only searching for those
10389 cur_bytes = min(cur_bytes, last_alloc);
10390 ret = btrfs_reserve_extent(root, cur_bytes, cur_bytes,
10391 min_size, 0, *alloc_hint, &ins, 1, 0);
10394 btrfs_end_transaction(trans);
10397 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
10399 last_alloc = ins.offset;
10400 ret = insert_reserved_file_extent(trans, inode,
10401 cur_offset, ins.objectid,
10402 ins.offset, ins.offset,
10403 ins.offset, 0, 0, 0,
10404 BTRFS_FILE_EXTENT_PREALLOC);
10406 btrfs_free_reserved_extent(fs_info, ins.objectid,
10408 btrfs_abort_transaction(trans, ret);
10410 btrfs_end_transaction(trans);
10414 btrfs_drop_extent_cache(BTRFS_I(inode), cur_offset,
10415 cur_offset + ins.offset -1, 0);
10417 em = alloc_extent_map();
10419 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
10420 &BTRFS_I(inode)->runtime_flags);
10424 em->start = cur_offset;
10425 em->orig_start = cur_offset;
10426 em->len = ins.offset;
10427 em->block_start = ins.objectid;
10428 em->block_len = ins.offset;
10429 em->orig_block_len = ins.offset;
10430 em->ram_bytes = ins.offset;
10431 em->bdev = fs_info->fs_devices->latest_bdev;
10432 set_bit(EXTENT_FLAG_PREALLOC, &em->flags);
10433 em->generation = trans->transid;
10436 write_lock(&em_tree->lock);
10437 ret = add_extent_mapping(em_tree, em, 1);
10438 write_unlock(&em_tree->lock);
10439 if (ret != -EEXIST)
10441 btrfs_drop_extent_cache(BTRFS_I(inode), cur_offset,
10442 cur_offset + ins.offset - 1,
10445 free_extent_map(em);
10447 num_bytes -= ins.offset;
10448 cur_offset += ins.offset;
10449 *alloc_hint = ins.objectid + ins.offset;
10451 inode_inc_iversion(inode);
10452 inode->i_ctime = current_time(inode);
10453 BTRFS_I(inode)->flags |= BTRFS_INODE_PREALLOC;
10454 if (!(mode & FALLOC_FL_KEEP_SIZE) &&
10455 (actual_len > inode->i_size) &&
10456 (cur_offset > inode->i_size)) {
10457 if (cur_offset > actual_len)
10458 i_size = actual_len;
10460 i_size = cur_offset;
10461 i_size_write(inode, i_size);
10462 btrfs_ordered_update_i_size(inode, i_size, NULL);
10465 ret = btrfs_update_inode(trans, root, inode);
10468 btrfs_abort_transaction(trans, ret);
10470 btrfs_end_transaction(trans);
10475 btrfs_end_transaction(trans);
10477 if (cur_offset < end)
10478 btrfs_free_reserved_data_space(inode, NULL, cur_offset,
10479 end - cur_offset + 1);
10483 int btrfs_prealloc_file_range(struct inode *inode, int mode,
10484 u64 start, u64 num_bytes, u64 min_size,
10485 loff_t actual_len, u64 *alloc_hint)
10487 return __btrfs_prealloc_file_range(inode, mode, start, num_bytes,
10488 min_size, actual_len, alloc_hint,
10492 int btrfs_prealloc_file_range_trans(struct inode *inode,
10493 struct btrfs_trans_handle *trans, int mode,
10494 u64 start, u64 num_bytes, u64 min_size,
10495 loff_t actual_len, u64 *alloc_hint)
10497 return __btrfs_prealloc_file_range(inode, mode, start, num_bytes,
10498 min_size, actual_len, alloc_hint, trans);
10501 static int btrfs_set_page_dirty(struct page *page)
10503 return __set_page_dirty_nobuffers(page);
10506 static int btrfs_permission(struct inode *inode, int mask)
10508 struct btrfs_root *root = BTRFS_I(inode)->root;
10509 umode_t mode = inode->i_mode;
10511 if (mask & MAY_WRITE &&
10512 (S_ISREG(mode) || S_ISDIR(mode) || S_ISLNK(mode))) {
10513 if (btrfs_root_readonly(root))
10515 if (BTRFS_I(inode)->flags & BTRFS_INODE_READONLY)
10518 return generic_permission(inode, mask);
10521 static int btrfs_tmpfile(struct inode *dir, struct dentry *dentry, umode_t mode)
10523 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
10524 struct btrfs_trans_handle *trans;
10525 struct btrfs_root *root = BTRFS_I(dir)->root;
10526 struct inode *inode = NULL;
10532 * 5 units required for adding orphan entry
10534 trans = btrfs_start_transaction(root, 5);
10536 return PTR_ERR(trans);
10538 ret = btrfs_find_free_ino(root, &objectid);
10542 inode = btrfs_new_inode(trans, root, dir, NULL, 0,
10543 btrfs_ino(BTRFS_I(dir)), objectid, mode, &index);
10544 if (IS_ERR(inode)) {
10545 ret = PTR_ERR(inode);
10550 inode->i_fop = &btrfs_file_operations;
10551 inode->i_op = &btrfs_file_inode_operations;
10553 inode->i_mapping->a_ops = &btrfs_aops;
10554 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
10556 ret = btrfs_init_inode_security(trans, inode, dir, NULL);
10560 ret = btrfs_update_inode(trans, root, inode);
10563 ret = btrfs_orphan_add(trans, BTRFS_I(inode));
10568 * We set number of links to 0 in btrfs_new_inode(), and here we set
10569 * it to 1 because d_tmpfile() will issue a warning if the count is 0,
10572 * d_tmpfile() -> inode_dec_link_count() -> drop_nlink()
10574 set_nlink(inode, 1);
10575 unlock_new_inode(inode);
10576 d_tmpfile(dentry, inode);
10577 mark_inode_dirty(inode);
10580 btrfs_end_transaction(trans);
10583 btrfs_btree_balance_dirty(fs_info);
10587 unlock_new_inode(inode);
10592 __attribute__((const))
10593 static int btrfs_readpage_io_failed_hook(struct page *page, int failed_mirror)
10598 static struct btrfs_fs_info *iotree_fs_info(void *private_data)
10600 struct inode *inode = private_data;
10601 return btrfs_sb(inode->i_sb);
10604 static void btrfs_check_extent_io_range(void *private_data, const char *caller,
10605 u64 start, u64 end)
10607 struct inode *inode = private_data;
10610 isize = i_size_read(inode);
10611 if (end >= PAGE_SIZE && (end % 2) == 0 && end != isize - 1) {
10612 btrfs_debug_rl(BTRFS_I(inode)->root->fs_info,
10613 "%s: ino %llu isize %llu odd range [%llu,%llu]",
10614 caller, btrfs_ino(BTRFS_I(inode)), isize, start, end);
10618 void btrfs_set_range_writeback(void *private_data, u64 start, u64 end)
10620 struct inode *inode = private_data;
10621 unsigned long index = start >> PAGE_SHIFT;
10622 unsigned long end_index = end >> PAGE_SHIFT;
10625 while (index <= end_index) {
10626 page = find_get_page(inode->i_mapping, index);
10627 ASSERT(page); /* Pages should be in the extent_io_tree */
10628 set_page_writeback(page);
10634 static const struct inode_operations btrfs_dir_inode_operations = {
10635 .getattr = btrfs_getattr,
10636 .lookup = btrfs_lookup,
10637 .create = btrfs_create,
10638 .unlink = btrfs_unlink,
10639 .link = btrfs_link,
10640 .mkdir = btrfs_mkdir,
10641 .rmdir = btrfs_rmdir,
10642 .rename = btrfs_rename2,
10643 .symlink = btrfs_symlink,
10644 .setattr = btrfs_setattr,
10645 .mknod = btrfs_mknod,
10646 .listxattr = btrfs_listxattr,
10647 .permission = btrfs_permission,
10648 .get_acl = btrfs_get_acl,
10649 .set_acl = btrfs_set_acl,
10650 .update_time = btrfs_update_time,
10651 .tmpfile = btrfs_tmpfile,
10653 static const struct inode_operations btrfs_dir_ro_inode_operations = {
10654 .lookup = btrfs_lookup,
10655 .permission = btrfs_permission,
10656 .update_time = btrfs_update_time,
10659 static const struct file_operations btrfs_dir_file_operations = {
10660 .llseek = generic_file_llseek,
10661 .read = generic_read_dir,
10662 .iterate_shared = btrfs_real_readdir,
10663 .open = btrfs_opendir,
10664 .unlocked_ioctl = btrfs_ioctl,
10665 #ifdef CONFIG_COMPAT
10666 .compat_ioctl = btrfs_compat_ioctl,
10668 .release = btrfs_release_file,
10669 .fsync = btrfs_sync_file,
10672 static const struct extent_io_ops btrfs_extent_io_ops = {
10673 /* mandatory callbacks */
10674 .submit_bio_hook = btrfs_submit_bio_hook,
10675 .readpage_end_io_hook = btrfs_readpage_end_io_hook,
10676 .merge_bio_hook = btrfs_merge_bio_hook,
10677 .readpage_io_failed_hook = btrfs_readpage_io_failed_hook,
10678 .tree_fs_info = iotree_fs_info,
10679 .set_range_writeback = btrfs_set_range_writeback,
10681 /* optional callbacks */
10682 .fill_delalloc = run_delalloc_range,
10683 .writepage_end_io_hook = btrfs_writepage_end_io_hook,
10684 .writepage_start_hook = btrfs_writepage_start_hook,
10685 .set_bit_hook = btrfs_set_bit_hook,
10686 .clear_bit_hook = btrfs_clear_bit_hook,
10687 .merge_extent_hook = btrfs_merge_extent_hook,
10688 .split_extent_hook = btrfs_split_extent_hook,
10689 .check_extent_io_range = btrfs_check_extent_io_range,
10693 * btrfs doesn't support the bmap operation because swapfiles
10694 * use bmap to make a mapping of extents in the file. They assume
10695 * these extents won't change over the life of the file and they
10696 * use the bmap result to do IO directly to the drive.
10698 * the btrfs bmap call would return logical addresses that aren't
10699 * suitable for IO and they also will change frequently as COW
10700 * operations happen. So, swapfile + btrfs == corruption.
10702 * For now we're avoiding this by dropping bmap.
10704 static const struct address_space_operations btrfs_aops = {
10705 .readpage = btrfs_readpage,
10706 .writepage = btrfs_writepage,
10707 .writepages = btrfs_writepages,
10708 .readpages = btrfs_readpages,
10709 .direct_IO = btrfs_direct_IO,
10710 .invalidatepage = btrfs_invalidatepage,
10711 .releasepage = btrfs_releasepage,
10712 .set_page_dirty = btrfs_set_page_dirty,
10713 .error_remove_page = generic_error_remove_page,
10716 static const struct address_space_operations btrfs_symlink_aops = {
10717 .readpage = btrfs_readpage,
10718 .writepage = btrfs_writepage,
10719 .invalidatepage = btrfs_invalidatepage,
10720 .releasepage = btrfs_releasepage,
10723 static const struct inode_operations btrfs_file_inode_operations = {
10724 .getattr = btrfs_getattr,
10725 .setattr = btrfs_setattr,
10726 .listxattr = btrfs_listxattr,
10727 .permission = btrfs_permission,
10728 .fiemap = btrfs_fiemap,
10729 .get_acl = btrfs_get_acl,
10730 .set_acl = btrfs_set_acl,
10731 .update_time = btrfs_update_time,
10733 static const struct inode_operations btrfs_special_inode_operations = {
10734 .getattr = btrfs_getattr,
10735 .setattr = btrfs_setattr,
10736 .permission = btrfs_permission,
10737 .listxattr = btrfs_listxattr,
10738 .get_acl = btrfs_get_acl,
10739 .set_acl = btrfs_set_acl,
10740 .update_time = btrfs_update_time,
10742 static const struct inode_operations btrfs_symlink_inode_operations = {
10743 .get_link = page_get_link,
10744 .getattr = btrfs_getattr,
10745 .setattr = btrfs_setattr,
10746 .permission = btrfs_permission,
10747 .listxattr = btrfs_listxattr,
10748 .update_time = btrfs_update_time,
10751 const struct dentry_operations btrfs_dentry_operations = {
10752 .d_delete = btrfs_dentry_delete,
10753 .d_release = btrfs_dentry_release,