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));
3245 void btrfs_add_delayed_iput(struct inode *inode)
3247 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
3248 struct btrfs_inode *binode = BTRFS_I(inode);
3250 if (atomic_add_unless(&inode->i_count, -1, 1))
3253 spin_lock(&fs_info->delayed_iput_lock);
3254 if (binode->delayed_iput_count == 0) {
3255 ASSERT(list_empty(&binode->delayed_iput));
3256 list_add_tail(&binode->delayed_iput, &fs_info->delayed_iputs);
3258 binode->delayed_iput_count++;
3260 spin_unlock(&fs_info->delayed_iput_lock);
3263 void btrfs_run_delayed_iputs(struct btrfs_fs_info *fs_info)
3266 spin_lock(&fs_info->delayed_iput_lock);
3267 while (!list_empty(&fs_info->delayed_iputs)) {
3268 struct btrfs_inode *inode;
3270 inode = list_first_entry(&fs_info->delayed_iputs,
3271 struct btrfs_inode, delayed_iput);
3272 if (inode->delayed_iput_count) {
3273 inode->delayed_iput_count--;
3274 list_move_tail(&inode->delayed_iput,
3275 &fs_info->delayed_iputs);
3277 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 spin_lock(&root->orphan_lock);
3359 if (!root->orphan_block_rsv) {
3360 root->orphan_block_rsv = block_rsv;
3361 } else if (block_rsv) {
3362 btrfs_free_block_rsv(fs_info, block_rsv);
3366 if (!test_and_set_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
3367 &inode->runtime_flags)) {
3370 * For proper ENOSPC handling, we should do orphan
3371 * cleanup when mounting. But this introduces backward
3372 * compatibility issue.
3374 if (!xchg(&root->orphan_item_inserted, 1))
3380 atomic_inc(&root->orphan_inodes);
3383 if (!test_and_set_bit(BTRFS_INODE_ORPHAN_META_RESERVED,
3384 &inode->runtime_flags))
3386 spin_unlock(&root->orphan_lock);
3388 /* grab metadata reservation from transaction handle */
3390 ret = btrfs_orphan_reserve_metadata(trans, inode);
3394 * dec doesn't need spin_lock as ->orphan_block_rsv
3395 * would be released only if ->orphan_inodes is
3398 atomic_dec(&root->orphan_inodes);
3399 clear_bit(BTRFS_INODE_ORPHAN_META_RESERVED,
3400 &inode->runtime_flags);
3402 clear_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
3403 &inode->runtime_flags);
3408 /* insert an orphan item to track this unlinked/truncated file */
3410 ret = btrfs_insert_orphan_item(trans, root, btrfs_ino(inode));
3413 clear_bit(BTRFS_INODE_ORPHAN_META_RESERVED,
3414 &inode->runtime_flags);
3415 btrfs_orphan_release_metadata(inode);
3418 * btrfs_orphan_commit_root may race with us and set
3419 * ->orphan_block_rsv to zero, in order to avoid that,
3420 * decrease ->orphan_inodes after everything is done.
3422 atomic_dec(&root->orphan_inodes);
3423 if (ret != -EEXIST) {
3424 clear_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
3425 &inode->runtime_flags);
3426 btrfs_abort_transaction(trans, ret);
3433 /* insert an orphan item to track subvolume contains orphan files */
3435 ret = btrfs_insert_orphan_item(trans, fs_info->tree_root,
3436 root->root_key.objectid);
3437 if (ret && ret != -EEXIST) {
3438 btrfs_abort_transaction(trans, ret);
3446 * We have done the truncate/delete so we can go ahead and remove the orphan
3447 * item for this particular inode.
3449 static int btrfs_orphan_del(struct btrfs_trans_handle *trans,
3450 struct btrfs_inode *inode)
3452 struct btrfs_root *root = inode->root;
3453 int delete_item = 0;
3456 if (test_and_clear_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
3457 &inode->runtime_flags))
3460 if (delete_item && trans)
3461 ret = btrfs_del_orphan_item(trans, root, btrfs_ino(inode));
3463 if (test_and_clear_bit(BTRFS_INODE_ORPHAN_META_RESERVED,
3464 &inode->runtime_flags))
3465 btrfs_orphan_release_metadata(inode);
3468 * btrfs_orphan_commit_root may race with us and set ->orphan_block_rsv
3469 * to zero, in order to avoid that, decrease ->orphan_inodes after
3470 * everything is done.
3473 atomic_dec(&root->orphan_inodes);
3479 * this cleans up any orphans that may be left on the list from the last use
3482 int btrfs_orphan_cleanup(struct btrfs_root *root)
3484 struct btrfs_fs_info *fs_info = root->fs_info;
3485 struct btrfs_path *path;
3486 struct extent_buffer *leaf;
3487 struct btrfs_key key, found_key;
3488 struct btrfs_trans_handle *trans;
3489 struct inode *inode;
3490 u64 last_objectid = 0;
3491 int ret = 0, nr_unlink = 0, nr_truncate = 0;
3493 if (cmpxchg(&root->orphan_cleanup_state, 0, ORPHAN_CLEANUP_STARTED))
3496 path = btrfs_alloc_path();
3501 path->reada = READA_BACK;
3503 key.objectid = BTRFS_ORPHAN_OBJECTID;
3504 key.type = BTRFS_ORPHAN_ITEM_KEY;
3505 key.offset = (u64)-1;
3508 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
3513 * if ret == 0 means we found what we were searching for, which
3514 * is weird, but possible, so only screw with path if we didn't
3515 * find the key and see if we have stuff that matches
3519 if (path->slots[0] == 0)
3524 /* pull out the item */
3525 leaf = path->nodes[0];
3526 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
3528 /* make sure the item matches what we want */
3529 if (found_key.objectid != BTRFS_ORPHAN_OBJECTID)
3531 if (found_key.type != BTRFS_ORPHAN_ITEM_KEY)
3534 /* release the path since we're done with it */
3535 btrfs_release_path(path);
3538 * this is where we are basically btrfs_lookup, without the
3539 * crossing root thing. we store the inode number in the
3540 * offset of the orphan item.
3543 if (found_key.offset == last_objectid) {
3545 "Error removing orphan entry, stopping orphan cleanup");
3550 last_objectid = found_key.offset;
3552 found_key.objectid = found_key.offset;
3553 found_key.type = BTRFS_INODE_ITEM_KEY;
3554 found_key.offset = 0;
3555 inode = btrfs_iget(fs_info->sb, &found_key, root, NULL);
3556 ret = PTR_ERR_OR_ZERO(inode);
3557 if (ret && ret != -ENOENT)
3560 if (ret == -ENOENT && root == fs_info->tree_root) {
3561 struct btrfs_root *dead_root;
3562 struct btrfs_fs_info *fs_info = root->fs_info;
3563 int is_dead_root = 0;
3566 * this is an orphan in the tree root. Currently these
3567 * could come from 2 sources:
3568 * a) a snapshot deletion in progress
3569 * b) a free space cache inode
3570 * We need to distinguish those two, as the snapshot
3571 * orphan must not get deleted.
3572 * find_dead_roots already ran before us, so if this
3573 * is a snapshot deletion, we should find the root
3574 * in the dead_roots list
3576 spin_lock(&fs_info->trans_lock);
3577 list_for_each_entry(dead_root, &fs_info->dead_roots,
3579 if (dead_root->root_key.objectid ==
3580 found_key.objectid) {
3585 spin_unlock(&fs_info->trans_lock);
3587 /* prevent this orphan from being found again */
3588 key.offset = found_key.objectid - 1;
3593 * Inode is already gone but the orphan item is still there,
3594 * kill the orphan item.
3596 if (ret == -ENOENT) {
3597 trans = btrfs_start_transaction(root, 1);
3598 if (IS_ERR(trans)) {
3599 ret = PTR_ERR(trans);
3602 btrfs_debug(fs_info, "auto deleting %Lu",
3603 found_key.objectid);
3604 ret = btrfs_del_orphan_item(trans, root,
3605 found_key.objectid);
3606 btrfs_end_transaction(trans);
3613 * add this inode to the orphan list so btrfs_orphan_del does
3614 * the proper thing when we hit it
3616 set_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
3617 &BTRFS_I(inode)->runtime_flags);
3618 atomic_inc(&root->orphan_inodes);
3620 /* if we have links, this was a truncate, lets do that */
3621 if (inode->i_nlink) {
3622 if (WARN_ON(!S_ISREG(inode->i_mode))) {
3628 /* 1 for the orphan item deletion. */
3629 trans = btrfs_start_transaction(root, 1);
3630 if (IS_ERR(trans)) {
3632 ret = PTR_ERR(trans);
3635 ret = btrfs_orphan_add(trans, BTRFS_I(inode));
3636 btrfs_end_transaction(trans);
3642 ret = btrfs_truncate(inode);
3644 btrfs_orphan_del(NULL, BTRFS_I(inode));
3649 /* this will do delete_inode and everything for us */
3654 /* release the path since we're done with it */
3655 btrfs_release_path(path);
3657 root->orphan_cleanup_state = ORPHAN_CLEANUP_DONE;
3659 if (root->orphan_block_rsv)
3660 btrfs_block_rsv_release(fs_info, root->orphan_block_rsv,
3663 if (root->orphan_block_rsv ||
3664 test_bit(BTRFS_ROOT_ORPHAN_ITEM_INSERTED, &root->state)) {
3665 trans = btrfs_join_transaction(root);
3667 btrfs_end_transaction(trans);
3671 btrfs_debug(fs_info, "unlinked %d orphans", nr_unlink);
3673 btrfs_debug(fs_info, "truncated %d orphans", nr_truncate);
3677 btrfs_err(fs_info, "could not do orphan cleanup %d", ret);
3678 btrfs_free_path(path);
3683 * very simple check to peek ahead in the leaf looking for xattrs. If we
3684 * don't find any xattrs, we know there can't be any acls.
3686 * slot is the slot the inode is in, objectid is the objectid of the inode
3688 static noinline int acls_after_inode_item(struct extent_buffer *leaf,
3689 int slot, u64 objectid,
3690 int *first_xattr_slot)
3692 u32 nritems = btrfs_header_nritems(leaf);
3693 struct btrfs_key found_key;
3694 static u64 xattr_access = 0;
3695 static u64 xattr_default = 0;
3698 if (!xattr_access) {
3699 xattr_access = btrfs_name_hash(XATTR_NAME_POSIX_ACL_ACCESS,
3700 strlen(XATTR_NAME_POSIX_ACL_ACCESS));
3701 xattr_default = btrfs_name_hash(XATTR_NAME_POSIX_ACL_DEFAULT,
3702 strlen(XATTR_NAME_POSIX_ACL_DEFAULT));
3706 *first_xattr_slot = -1;
3707 while (slot < nritems) {
3708 btrfs_item_key_to_cpu(leaf, &found_key, slot);
3710 /* we found a different objectid, there must not be acls */
3711 if (found_key.objectid != objectid)
3714 /* we found an xattr, assume we've got an acl */
3715 if (found_key.type == BTRFS_XATTR_ITEM_KEY) {
3716 if (*first_xattr_slot == -1)
3717 *first_xattr_slot = slot;
3718 if (found_key.offset == xattr_access ||
3719 found_key.offset == xattr_default)
3724 * we found a key greater than an xattr key, there can't
3725 * be any acls later on
3727 if (found_key.type > BTRFS_XATTR_ITEM_KEY)
3734 * it goes inode, inode backrefs, xattrs, extents,
3735 * so if there are a ton of hard links to an inode there can
3736 * be a lot of backrefs. Don't waste time searching too hard,
3737 * this is just an optimization
3742 /* we hit the end of the leaf before we found an xattr or
3743 * something larger than an xattr. We have to assume the inode
3746 if (*first_xattr_slot == -1)
3747 *first_xattr_slot = slot;
3752 * read an inode from the btree into the in-memory inode
3754 static int btrfs_read_locked_inode(struct inode *inode)
3756 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
3757 struct btrfs_path *path;
3758 struct extent_buffer *leaf;
3759 struct btrfs_inode_item *inode_item;
3760 struct btrfs_root *root = BTRFS_I(inode)->root;
3761 struct btrfs_key location;
3766 bool filled = false;
3767 int first_xattr_slot;
3769 ret = btrfs_fill_inode(inode, &rdev);
3773 path = btrfs_alloc_path();
3779 memcpy(&location, &BTRFS_I(inode)->location, sizeof(location));
3781 ret = btrfs_lookup_inode(NULL, root, path, &location, 0);
3788 leaf = path->nodes[0];
3793 inode_item = btrfs_item_ptr(leaf, path->slots[0],
3794 struct btrfs_inode_item);
3795 inode->i_mode = btrfs_inode_mode(leaf, inode_item);
3796 set_nlink(inode, btrfs_inode_nlink(leaf, inode_item));
3797 i_uid_write(inode, btrfs_inode_uid(leaf, inode_item));
3798 i_gid_write(inode, btrfs_inode_gid(leaf, inode_item));
3799 btrfs_i_size_write(BTRFS_I(inode), btrfs_inode_size(leaf, inode_item));
3801 inode->i_atime.tv_sec = btrfs_timespec_sec(leaf, &inode_item->atime);
3802 inode->i_atime.tv_nsec = btrfs_timespec_nsec(leaf, &inode_item->atime);
3804 inode->i_mtime.tv_sec = btrfs_timespec_sec(leaf, &inode_item->mtime);
3805 inode->i_mtime.tv_nsec = btrfs_timespec_nsec(leaf, &inode_item->mtime);
3807 inode->i_ctime.tv_sec = btrfs_timespec_sec(leaf, &inode_item->ctime);
3808 inode->i_ctime.tv_nsec = btrfs_timespec_nsec(leaf, &inode_item->ctime);
3810 BTRFS_I(inode)->i_otime.tv_sec =
3811 btrfs_timespec_sec(leaf, &inode_item->otime);
3812 BTRFS_I(inode)->i_otime.tv_nsec =
3813 btrfs_timespec_nsec(leaf, &inode_item->otime);
3815 inode_set_bytes(inode, btrfs_inode_nbytes(leaf, inode_item));
3816 BTRFS_I(inode)->generation = btrfs_inode_generation(leaf, inode_item);
3817 BTRFS_I(inode)->last_trans = btrfs_inode_transid(leaf, inode_item);
3819 inode_set_iversion_queried(inode,
3820 btrfs_inode_sequence(leaf, inode_item));
3821 inode->i_generation = BTRFS_I(inode)->generation;
3823 rdev = btrfs_inode_rdev(leaf, inode_item);
3825 BTRFS_I(inode)->index_cnt = (u64)-1;
3826 BTRFS_I(inode)->flags = btrfs_inode_flags(leaf, inode_item);
3830 * If we were modified in the current generation and evicted from memory
3831 * and then re-read we need to do a full sync since we don't have any
3832 * idea about which extents were modified before we were evicted from
3835 * This is required for both inode re-read from disk and delayed inode
3836 * in delayed_nodes_tree.
3838 if (BTRFS_I(inode)->last_trans == fs_info->generation)
3839 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
3840 &BTRFS_I(inode)->runtime_flags);
3843 * We don't persist the id of the transaction where an unlink operation
3844 * against the inode was last made. So here we assume the inode might
3845 * have been evicted, and therefore the exact value of last_unlink_trans
3846 * lost, and set it to last_trans to avoid metadata inconsistencies
3847 * between the inode and its parent if the inode is fsync'ed and the log
3848 * replayed. For example, in the scenario:
3851 * ln mydir/foo mydir/bar
3854 * echo 2 > /proc/sys/vm/drop_caches # evicts inode
3855 * xfs_io -c fsync mydir/foo
3857 * mount fs, triggers fsync log replay
3859 * We must make sure that when we fsync our inode foo we also log its
3860 * parent inode, otherwise after log replay the parent still has the
3861 * dentry with the "bar" name but our inode foo has a link count of 1
3862 * and doesn't have an inode ref with the name "bar" anymore.
3864 * Setting last_unlink_trans to last_trans is a pessimistic approach,
3865 * but it guarantees correctness at the expense of occasional full
3866 * transaction commits on fsync if our inode is a directory, or if our
3867 * inode is not a directory, logging its parent unnecessarily.
3869 BTRFS_I(inode)->last_unlink_trans = BTRFS_I(inode)->last_trans;
3872 if (inode->i_nlink != 1 ||
3873 path->slots[0] >= btrfs_header_nritems(leaf))
3876 btrfs_item_key_to_cpu(leaf, &location, path->slots[0]);
3877 if (location.objectid != btrfs_ino(BTRFS_I(inode)))
3880 ptr = btrfs_item_ptr_offset(leaf, path->slots[0]);
3881 if (location.type == BTRFS_INODE_REF_KEY) {
3882 struct btrfs_inode_ref *ref;
3884 ref = (struct btrfs_inode_ref *)ptr;
3885 BTRFS_I(inode)->dir_index = btrfs_inode_ref_index(leaf, ref);
3886 } else if (location.type == BTRFS_INODE_EXTREF_KEY) {
3887 struct btrfs_inode_extref *extref;
3889 extref = (struct btrfs_inode_extref *)ptr;
3890 BTRFS_I(inode)->dir_index = btrfs_inode_extref_index(leaf,
3895 * try to precache a NULL acl entry for files that don't have
3896 * any xattrs or acls
3898 maybe_acls = acls_after_inode_item(leaf, path->slots[0],
3899 btrfs_ino(BTRFS_I(inode)), &first_xattr_slot);
3900 if (first_xattr_slot != -1) {
3901 path->slots[0] = first_xattr_slot;
3902 ret = btrfs_load_inode_props(inode, path);
3905 "error loading props for ino %llu (root %llu): %d",
3906 btrfs_ino(BTRFS_I(inode)),
3907 root->root_key.objectid, ret);
3909 btrfs_free_path(path);
3912 cache_no_acl(inode);
3914 switch (inode->i_mode & S_IFMT) {
3916 inode->i_mapping->a_ops = &btrfs_aops;
3917 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
3918 inode->i_fop = &btrfs_file_operations;
3919 inode->i_op = &btrfs_file_inode_operations;
3922 inode->i_fop = &btrfs_dir_file_operations;
3923 inode->i_op = &btrfs_dir_inode_operations;
3926 inode->i_op = &btrfs_symlink_inode_operations;
3927 inode_nohighmem(inode);
3928 inode->i_mapping->a_ops = &btrfs_symlink_aops;
3931 inode->i_op = &btrfs_special_inode_operations;
3932 init_special_inode(inode, inode->i_mode, rdev);
3936 btrfs_update_iflags(inode);
3940 btrfs_free_path(path);
3941 make_bad_inode(inode);
3946 * given a leaf and an inode, copy the inode fields into the leaf
3948 static void fill_inode_item(struct btrfs_trans_handle *trans,
3949 struct extent_buffer *leaf,
3950 struct btrfs_inode_item *item,
3951 struct inode *inode)
3953 struct btrfs_map_token token;
3955 btrfs_init_map_token(&token);
3957 btrfs_set_token_inode_uid(leaf, item, i_uid_read(inode), &token);
3958 btrfs_set_token_inode_gid(leaf, item, i_gid_read(inode), &token);
3959 btrfs_set_token_inode_size(leaf, item, BTRFS_I(inode)->disk_i_size,
3961 btrfs_set_token_inode_mode(leaf, item, inode->i_mode, &token);
3962 btrfs_set_token_inode_nlink(leaf, item, inode->i_nlink, &token);
3964 btrfs_set_token_timespec_sec(leaf, &item->atime,
3965 inode->i_atime.tv_sec, &token);
3966 btrfs_set_token_timespec_nsec(leaf, &item->atime,
3967 inode->i_atime.tv_nsec, &token);
3969 btrfs_set_token_timespec_sec(leaf, &item->mtime,
3970 inode->i_mtime.tv_sec, &token);
3971 btrfs_set_token_timespec_nsec(leaf, &item->mtime,
3972 inode->i_mtime.tv_nsec, &token);
3974 btrfs_set_token_timespec_sec(leaf, &item->ctime,
3975 inode->i_ctime.tv_sec, &token);
3976 btrfs_set_token_timespec_nsec(leaf, &item->ctime,
3977 inode->i_ctime.tv_nsec, &token);
3979 btrfs_set_token_timespec_sec(leaf, &item->otime,
3980 BTRFS_I(inode)->i_otime.tv_sec, &token);
3981 btrfs_set_token_timespec_nsec(leaf, &item->otime,
3982 BTRFS_I(inode)->i_otime.tv_nsec, &token);
3984 btrfs_set_token_inode_nbytes(leaf, item, inode_get_bytes(inode),
3986 btrfs_set_token_inode_generation(leaf, item, BTRFS_I(inode)->generation,
3988 btrfs_set_token_inode_sequence(leaf, item, inode_peek_iversion(inode),
3990 btrfs_set_token_inode_transid(leaf, item, trans->transid, &token);
3991 btrfs_set_token_inode_rdev(leaf, item, inode->i_rdev, &token);
3992 btrfs_set_token_inode_flags(leaf, item, BTRFS_I(inode)->flags, &token);
3993 btrfs_set_token_inode_block_group(leaf, item, 0, &token);
3997 * copy everything in the in-memory inode into the btree.
3999 static noinline int btrfs_update_inode_item(struct btrfs_trans_handle *trans,
4000 struct btrfs_root *root, struct inode *inode)
4002 struct btrfs_inode_item *inode_item;
4003 struct btrfs_path *path;
4004 struct extent_buffer *leaf;
4007 path = btrfs_alloc_path();
4011 path->leave_spinning = 1;
4012 ret = btrfs_lookup_inode(trans, root, path, &BTRFS_I(inode)->location,
4020 leaf = path->nodes[0];
4021 inode_item = btrfs_item_ptr(leaf, path->slots[0],
4022 struct btrfs_inode_item);
4024 fill_inode_item(trans, leaf, inode_item, inode);
4025 btrfs_mark_buffer_dirty(leaf);
4026 btrfs_set_inode_last_trans(trans, inode);
4029 btrfs_free_path(path);
4034 * copy everything in the in-memory inode into the btree.
4036 noinline int btrfs_update_inode(struct btrfs_trans_handle *trans,
4037 struct btrfs_root *root, struct inode *inode)
4039 struct btrfs_fs_info *fs_info = root->fs_info;
4043 * If the inode is a free space inode, we can deadlock during commit
4044 * if we put it into the delayed code.
4046 * The data relocation inode should also be directly updated
4049 if (!btrfs_is_free_space_inode(BTRFS_I(inode))
4050 && root->root_key.objectid != BTRFS_DATA_RELOC_TREE_OBJECTID
4051 && !test_bit(BTRFS_FS_LOG_RECOVERING, &fs_info->flags)) {
4052 btrfs_update_root_times(trans, root);
4054 ret = btrfs_delayed_update_inode(trans, root, inode);
4056 btrfs_set_inode_last_trans(trans, inode);
4060 return btrfs_update_inode_item(trans, root, inode);
4063 noinline int btrfs_update_inode_fallback(struct btrfs_trans_handle *trans,
4064 struct btrfs_root *root,
4065 struct inode *inode)
4069 ret = btrfs_update_inode(trans, root, inode);
4071 return btrfs_update_inode_item(trans, root, inode);
4076 * unlink helper that gets used here in inode.c and in the tree logging
4077 * recovery code. It remove a link in a directory with a given name, and
4078 * also drops the back refs in the inode to the directory
4080 static int __btrfs_unlink_inode(struct btrfs_trans_handle *trans,
4081 struct btrfs_root *root,
4082 struct btrfs_inode *dir,
4083 struct btrfs_inode *inode,
4084 const char *name, int name_len)
4086 struct btrfs_fs_info *fs_info = root->fs_info;
4087 struct btrfs_path *path;
4089 struct extent_buffer *leaf;
4090 struct btrfs_dir_item *di;
4091 struct btrfs_key key;
4093 u64 ino = btrfs_ino(inode);
4094 u64 dir_ino = btrfs_ino(dir);
4096 path = btrfs_alloc_path();
4102 path->leave_spinning = 1;
4103 di = btrfs_lookup_dir_item(trans, root, path, dir_ino,
4104 name, name_len, -1);
4113 leaf = path->nodes[0];
4114 btrfs_dir_item_key_to_cpu(leaf, di, &key);
4115 ret = btrfs_delete_one_dir_name(trans, root, path, di);
4118 btrfs_release_path(path);
4121 * If we don't have dir index, we have to get it by looking up
4122 * the inode ref, since we get the inode ref, remove it directly,
4123 * it is unnecessary to do delayed deletion.
4125 * But if we have dir index, needn't search inode ref to get it.
4126 * Since the inode ref is close to the inode item, it is better
4127 * that we delay to delete it, and just do this deletion when
4128 * we update the inode item.
4130 if (inode->dir_index) {
4131 ret = btrfs_delayed_delete_inode_ref(inode);
4133 index = inode->dir_index;
4138 ret = btrfs_del_inode_ref(trans, root, name, name_len, ino,
4142 "failed to delete reference to %.*s, inode %llu parent %llu",
4143 name_len, name, ino, dir_ino);
4144 btrfs_abort_transaction(trans, ret);
4148 ret = btrfs_delete_delayed_dir_index(trans, fs_info, dir, index);
4150 btrfs_abort_transaction(trans, ret);
4154 ret = btrfs_del_inode_ref_in_log(trans, root, name, name_len, inode,
4156 if (ret != 0 && ret != -ENOENT) {
4157 btrfs_abort_transaction(trans, ret);
4161 ret = btrfs_del_dir_entries_in_log(trans, root, name, name_len, dir,
4166 btrfs_abort_transaction(trans, ret);
4168 btrfs_free_path(path);
4172 btrfs_i_size_write(dir, dir->vfs_inode.i_size - name_len * 2);
4173 inode_inc_iversion(&inode->vfs_inode);
4174 inode_inc_iversion(&dir->vfs_inode);
4175 inode->vfs_inode.i_ctime = dir->vfs_inode.i_mtime =
4176 dir->vfs_inode.i_ctime = current_time(&inode->vfs_inode);
4177 ret = btrfs_update_inode(trans, root, &dir->vfs_inode);
4182 int btrfs_unlink_inode(struct btrfs_trans_handle *trans,
4183 struct btrfs_root *root,
4184 struct btrfs_inode *dir, struct btrfs_inode *inode,
4185 const char *name, int name_len)
4188 ret = __btrfs_unlink_inode(trans, root, dir, inode, name, name_len);
4190 drop_nlink(&inode->vfs_inode);
4191 ret = btrfs_update_inode(trans, root, &inode->vfs_inode);
4197 * helper to start transaction for unlink and rmdir.
4199 * unlink and rmdir are special in btrfs, they do not always free space, so
4200 * if we cannot make our reservations the normal way try and see if there is
4201 * plenty of slack room in the global reserve to migrate, otherwise we cannot
4202 * allow the unlink to occur.
4204 static struct btrfs_trans_handle *__unlink_start_trans(struct inode *dir)
4206 struct btrfs_root *root = BTRFS_I(dir)->root;
4209 * 1 for the possible orphan item
4210 * 1 for the dir item
4211 * 1 for the dir index
4212 * 1 for the inode ref
4215 return btrfs_start_transaction_fallback_global_rsv(root, 5, 5);
4218 static int btrfs_unlink(struct inode *dir, struct dentry *dentry)
4220 struct btrfs_root *root = BTRFS_I(dir)->root;
4221 struct btrfs_trans_handle *trans;
4222 struct inode *inode = d_inode(dentry);
4225 trans = __unlink_start_trans(dir);
4227 return PTR_ERR(trans);
4229 btrfs_record_unlink_dir(trans, BTRFS_I(dir), BTRFS_I(d_inode(dentry)),
4232 ret = btrfs_unlink_inode(trans, root, BTRFS_I(dir),
4233 BTRFS_I(d_inode(dentry)), dentry->d_name.name,
4234 dentry->d_name.len);
4238 if (inode->i_nlink == 0) {
4239 ret = btrfs_orphan_add(trans, BTRFS_I(inode));
4245 btrfs_end_transaction(trans);
4246 btrfs_btree_balance_dirty(root->fs_info);
4250 int btrfs_unlink_subvol(struct btrfs_trans_handle *trans,
4251 struct btrfs_root *root,
4252 struct inode *dir, u64 objectid,
4253 const char *name, int name_len)
4255 struct btrfs_fs_info *fs_info = root->fs_info;
4256 struct btrfs_path *path;
4257 struct extent_buffer *leaf;
4258 struct btrfs_dir_item *di;
4259 struct btrfs_key key;
4262 u64 dir_ino = btrfs_ino(BTRFS_I(dir));
4264 path = btrfs_alloc_path();
4268 di = btrfs_lookup_dir_item(trans, root, path, dir_ino,
4269 name, name_len, -1);
4270 if (IS_ERR_OR_NULL(di)) {
4278 leaf = path->nodes[0];
4279 btrfs_dir_item_key_to_cpu(leaf, di, &key);
4280 WARN_ON(key.type != BTRFS_ROOT_ITEM_KEY || key.objectid != objectid);
4281 ret = btrfs_delete_one_dir_name(trans, root, path, di);
4283 btrfs_abort_transaction(trans, ret);
4286 btrfs_release_path(path);
4288 ret = btrfs_del_root_ref(trans, fs_info, objectid,
4289 root->root_key.objectid, dir_ino,
4290 &index, name, name_len);
4292 if (ret != -ENOENT) {
4293 btrfs_abort_transaction(trans, ret);
4296 di = btrfs_search_dir_index_item(root, path, dir_ino,
4298 if (IS_ERR_OR_NULL(di)) {
4303 btrfs_abort_transaction(trans, ret);
4307 leaf = path->nodes[0];
4308 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
4309 btrfs_release_path(path);
4312 btrfs_release_path(path);
4314 ret = btrfs_delete_delayed_dir_index(trans, fs_info, BTRFS_I(dir), index);
4316 btrfs_abort_transaction(trans, ret);
4320 btrfs_i_size_write(BTRFS_I(dir), dir->i_size - name_len * 2);
4321 inode_inc_iversion(dir);
4322 dir->i_mtime = dir->i_ctime = current_time(dir);
4323 ret = btrfs_update_inode_fallback(trans, root, dir);
4325 btrfs_abort_transaction(trans, ret);
4327 btrfs_free_path(path);
4331 static int btrfs_rmdir(struct inode *dir, struct dentry *dentry)
4333 struct inode *inode = d_inode(dentry);
4335 struct btrfs_root *root = BTRFS_I(dir)->root;
4336 struct btrfs_trans_handle *trans;
4337 u64 last_unlink_trans;
4339 if (inode->i_size > BTRFS_EMPTY_DIR_SIZE)
4341 if (btrfs_ino(BTRFS_I(inode)) == BTRFS_FIRST_FREE_OBJECTID)
4344 trans = __unlink_start_trans(dir);
4346 return PTR_ERR(trans);
4348 if (unlikely(btrfs_ino(BTRFS_I(inode)) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)) {
4349 err = btrfs_unlink_subvol(trans, root, dir,
4350 BTRFS_I(inode)->location.objectid,
4351 dentry->d_name.name,
4352 dentry->d_name.len);
4356 err = btrfs_orphan_add(trans, BTRFS_I(inode));
4360 last_unlink_trans = BTRFS_I(inode)->last_unlink_trans;
4362 /* now the directory is empty */
4363 err = btrfs_unlink_inode(trans, root, BTRFS_I(dir),
4364 BTRFS_I(d_inode(dentry)), dentry->d_name.name,
4365 dentry->d_name.len);
4367 btrfs_i_size_write(BTRFS_I(inode), 0);
4369 * Propagate the last_unlink_trans value of the deleted dir to
4370 * its parent directory. This is to prevent an unrecoverable
4371 * log tree in the case we do something like this:
4373 * 2) create snapshot under dir foo
4374 * 3) delete the snapshot
4377 * 6) fsync foo or some file inside foo
4379 if (last_unlink_trans >= trans->transid)
4380 BTRFS_I(dir)->last_unlink_trans = last_unlink_trans;
4383 btrfs_end_transaction(trans);
4384 btrfs_btree_balance_dirty(root->fs_info);
4389 static int truncate_space_check(struct btrfs_trans_handle *trans,
4390 struct btrfs_root *root,
4393 struct btrfs_fs_info *fs_info = root->fs_info;
4397 * This is only used to apply pressure to the enospc system, we don't
4398 * intend to use this reservation at all.
4400 bytes_deleted = btrfs_csum_bytes_to_leaves(fs_info, bytes_deleted);
4401 bytes_deleted *= fs_info->nodesize;
4402 ret = btrfs_block_rsv_add(root, &fs_info->trans_block_rsv,
4403 bytes_deleted, BTRFS_RESERVE_NO_FLUSH);
4405 trace_btrfs_space_reservation(fs_info, "transaction",
4408 trans->bytes_reserved += bytes_deleted;
4415 * Return this if we need to call truncate_block for the last bit of the
4418 #define NEED_TRUNCATE_BLOCK 1
4421 * this can truncate away extent items, csum items and directory items.
4422 * It starts at a high offset and removes keys until it can't find
4423 * any higher than new_size
4425 * csum items that cross the new i_size are truncated to the new size
4428 * min_type is the minimum key type to truncate down to. If set to 0, this
4429 * will kill all the items on this inode, including the INODE_ITEM_KEY.
4431 int btrfs_truncate_inode_items(struct btrfs_trans_handle *trans,
4432 struct btrfs_root *root,
4433 struct inode *inode,
4434 u64 new_size, u32 min_type)
4436 struct btrfs_fs_info *fs_info = root->fs_info;
4437 struct btrfs_path *path;
4438 struct extent_buffer *leaf;
4439 struct btrfs_file_extent_item *fi;
4440 struct btrfs_key key;
4441 struct btrfs_key found_key;
4442 u64 extent_start = 0;
4443 u64 extent_num_bytes = 0;
4444 u64 extent_offset = 0;
4446 u64 last_size = new_size;
4447 u32 found_type = (u8)-1;
4450 int pending_del_nr = 0;
4451 int pending_del_slot = 0;
4452 int extent_type = -1;
4455 u64 ino = btrfs_ino(BTRFS_I(inode));
4456 u64 bytes_deleted = 0;
4457 bool be_nice = false;
4458 bool should_throttle = false;
4459 bool should_end = false;
4461 BUG_ON(new_size > 0 && min_type != BTRFS_EXTENT_DATA_KEY);
4464 * for non-free space inodes and ref cows, we want to back off from
4467 if (!btrfs_is_free_space_inode(BTRFS_I(inode)) &&
4468 test_bit(BTRFS_ROOT_REF_COWS, &root->state))
4471 path = btrfs_alloc_path();
4474 path->reada = READA_BACK;
4477 * We want to drop from the next block forward in case this new size is
4478 * not block aligned since we will be keeping the last block of the
4479 * extent just the way it is.
4481 if (test_bit(BTRFS_ROOT_REF_COWS, &root->state) ||
4482 root == fs_info->tree_root)
4483 btrfs_drop_extent_cache(BTRFS_I(inode), ALIGN(new_size,
4484 fs_info->sectorsize),
4488 * This function is also used to drop the items in the log tree before
4489 * we relog the inode, so if root != BTRFS_I(inode)->root, it means
4490 * it is used to drop the loged items. So we shouldn't kill the delayed
4493 if (min_type == 0 && root == BTRFS_I(inode)->root)
4494 btrfs_kill_delayed_inode_items(BTRFS_I(inode));
4497 key.offset = (u64)-1;
4502 * with a 16K leaf size and 128MB extents, you can actually queue
4503 * up a huge file in a single leaf. Most of the time that
4504 * bytes_deleted is > 0, it will be huge by the time we get here
4506 if (be_nice && bytes_deleted > SZ_32M) {
4507 if (btrfs_should_end_transaction(trans)) {
4514 path->leave_spinning = 1;
4515 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
4522 /* there are no items in the tree for us to truncate, we're
4525 if (path->slots[0] == 0)
4532 leaf = path->nodes[0];
4533 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
4534 found_type = found_key.type;
4536 if (found_key.objectid != ino)
4539 if (found_type < min_type)
4542 item_end = found_key.offset;
4543 if (found_type == BTRFS_EXTENT_DATA_KEY) {
4544 fi = btrfs_item_ptr(leaf, path->slots[0],
4545 struct btrfs_file_extent_item);
4546 extent_type = btrfs_file_extent_type(leaf, fi);
4547 if (extent_type != BTRFS_FILE_EXTENT_INLINE) {
4549 btrfs_file_extent_num_bytes(leaf, fi);
4551 trace_btrfs_truncate_show_fi_regular(
4552 BTRFS_I(inode), leaf, fi,
4554 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
4555 item_end += btrfs_file_extent_inline_len(leaf,
4556 path->slots[0], fi);
4558 trace_btrfs_truncate_show_fi_inline(
4559 BTRFS_I(inode), leaf, fi, path->slots[0],
4564 if (found_type > min_type) {
4567 if (item_end < new_size)
4569 if (found_key.offset >= new_size)
4575 /* FIXME, shrink the extent if the ref count is only 1 */
4576 if (found_type != BTRFS_EXTENT_DATA_KEY)
4579 if (extent_type != BTRFS_FILE_EXTENT_INLINE) {
4581 extent_start = btrfs_file_extent_disk_bytenr(leaf, fi);
4583 u64 orig_num_bytes =
4584 btrfs_file_extent_num_bytes(leaf, fi);
4585 extent_num_bytes = ALIGN(new_size -
4587 fs_info->sectorsize);
4588 btrfs_set_file_extent_num_bytes(leaf, fi,
4590 num_dec = (orig_num_bytes -
4592 if (test_bit(BTRFS_ROOT_REF_COWS,
4595 inode_sub_bytes(inode, num_dec);
4596 btrfs_mark_buffer_dirty(leaf);
4599 btrfs_file_extent_disk_num_bytes(leaf,
4601 extent_offset = found_key.offset -
4602 btrfs_file_extent_offset(leaf, fi);
4604 /* FIXME blocksize != 4096 */
4605 num_dec = btrfs_file_extent_num_bytes(leaf, fi);
4606 if (extent_start != 0) {
4608 if (test_bit(BTRFS_ROOT_REF_COWS,
4610 inode_sub_bytes(inode, num_dec);
4613 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
4615 * we can't truncate inline items that have had
4619 btrfs_file_extent_encryption(leaf, fi) == 0 &&
4620 btrfs_file_extent_other_encoding(leaf, fi) == 0 &&
4621 btrfs_file_extent_compression(leaf, fi) == 0) {
4622 u32 size = (u32)(new_size - found_key.offset);
4624 btrfs_set_file_extent_ram_bytes(leaf, fi, size);
4625 size = btrfs_file_extent_calc_inline_size(size);
4626 btrfs_truncate_item(root->fs_info, path, size, 1);
4627 } else if (!del_item) {
4629 * We have to bail so the last_size is set to
4630 * just before this extent.
4632 err = NEED_TRUNCATE_BLOCK;
4636 if (test_bit(BTRFS_ROOT_REF_COWS, &root->state))
4637 inode_sub_bytes(inode, item_end + 1 - new_size);
4641 last_size = found_key.offset;
4643 last_size = new_size;
4645 if (!pending_del_nr) {
4646 /* no pending yet, add ourselves */
4647 pending_del_slot = path->slots[0];
4649 } else if (pending_del_nr &&
4650 path->slots[0] + 1 == pending_del_slot) {
4651 /* hop on the pending chunk */
4653 pending_del_slot = path->slots[0];
4660 should_throttle = false;
4663 (test_bit(BTRFS_ROOT_REF_COWS, &root->state) ||
4664 root == fs_info->tree_root)) {
4665 btrfs_set_path_blocking(path);
4666 bytes_deleted += extent_num_bytes;
4667 ret = btrfs_free_extent(trans, root, extent_start,
4668 extent_num_bytes, 0,
4669 btrfs_header_owner(leaf),
4670 ino, extent_offset);
4672 if (btrfs_should_throttle_delayed_refs(trans, fs_info))
4673 btrfs_async_run_delayed_refs(fs_info,
4674 trans->delayed_ref_updates * 2,
4677 if (truncate_space_check(trans, root,
4678 extent_num_bytes)) {
4681 if (btrfs_should_throttle_delayed_refs(trans,
4683 should_throttle = true;
4687 if (found_type == BTRFS_INODE_ITEM_KEY)
4690 if (path->slots[0] == 0 ||
4691 path->slots[0] != pending_del_slot ||
4692 should_throttle || should_end) {
4693 if (pending_del_nr) {
4694 ret = btrfs_del_items(trans, root, path,
4698 btrfs_abort_transaction(trans, ret);
4703 btrfs_release_path(path);
4704 if (should_throttle) {
4705 unsigned long updates = trans->delayed_ref_updates;
4707 trans->delayed_ref_updates = 0;
4708 ret = btrfs_run_delayed_refs(trans,
4716 * if we failed to refill our space rsv, bail out
4717 * and let the transaction restart
4729 if (pending_del_nr) {
4730 ret = btrfs_del_items(trans, root, path, pending_del_slot,
4733 btrfs_abort_transaction(trans, ret);
4736 if (root->root_key.objectid != BTRFS_TREE_LOG_OBJECTID) {
4737 ASSERT(last_size >= new_size);
4738 if (!err && last_size > new_size)
4739 last_size = new_size;
4740 btrfs_ordered_update_i_size(inode, last_size, NULL);
4743 btrfs_free_path(path);
4745 if (be_nice && bytes_deleted > SZ_32M) {
4746 unsigned long updates = trans->delayed_ref_updates;
4748 trans->delayed_ref_updates = 0;
4749 ret = btrfs_run_delayed_refs(trans, fs_info,
4759 * btrfs_truncate_block - read, zero a chunk and write a block
4760 * @inode - inode that we're zeroing
4761 * @from - the offset to start zeroing
4762 * @len - the length to zero, 0 to zero the entire range respective to the
4764 * @front - zero up to the offset instead of from the offset on
4766 * This will find the block for the "from" offset and cow the block and zero the
4767 * part we want to zero. This is used with truncate and hole punching.
4769 int btrfs_truncate_block(struct inode *inode, loff_t from, loff_t len,
4772 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
4773 struct address_space *mapping = inode->i_mapping;
4774 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
4775 struct btrfs_ordered_extent *ordered;
4776 struct extent_state *cached_state = NULL;
4777 struct extent_changeset *data_reserved = NULL;
4779 u32 blocksize = fs_info->sectorsize;
4780 pgoff_t index = from >> PAGE_SHIFT;
4781 unsigned offset = from & (blocksize - 1);
4783 gfp_t mask = btrfs_alloc_write_mask(mapping);
4788 if (IS_ALIGNED(offset, blocksize) &&
4789 (!len || IS_ALIGNED(len, blocksize)))
4792 block_start = round_down(from, blocksize);
4793 block_end = block_start + blocksize - 1;
4795 ret = btrfs_delalloc_reserve_space(inode, &data_reserved,
4796 block_start, blocksize);
4801 page = find_or_create_page(mapping, index, mask);
4803 btrfs_delalloc_release_space(inode, data_reserved,
4804 block_start, blocksize);
4805 btrfs_delalloc_release_extents(BTRFS_I(inode), blocksize);
4810 if (!PageUptodate(page)) {
4811 ret = btrfs_readpage(NULL, page);
4813 if (page->mapping != mapping) {
4818 if (!PageUptodate(page)) {
4823 wait_on_page_writeback(page);
4825 lock_extent_bits(io_tree, block_start, block_end, &cached_state);
4826 set_page_extent_mapped(page);
4828 ordered = btrfs_lookup_ordered_extent(inode, block_start);
4830 unlock_extent_cached(io_tree, block_start, block_end,
4834 btrfs_start_ordered_extent(inode, ordered, 1);
4835 btrfs_put_ordered_extent(ordered);
4839 clear_extent_bit(&BTRFS_I(inode)->io_tree, block_start, block_end,
4840 EXTENT_DIRTY | EXTENT_DELALLOC |
4841 EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG,
4842 0, 0, &cached_state);
4844 ret = btrfs_set_extent_delalloc(inode, block_start, block_end, 0,
4847 unlock_extent_cached(io_tree, block_start, block_end,
4852 if (offset != blocksize) {
4854 len = blocksize - offset;
4857 memset(kaddr + (block_start - page_offset(page)),
4860 memset(kaddr + (block_start - page_offset(page)) + offset,
4862 flush_dcache_page(page);
4865 ClearPageChecked(page);
4866 set_page_dirty(page);
4867 unlock_extent_cached(io_tree, block_start, block_end, &cached_state);
4871 btrfs_delalloc_release_space(inode, data_reserved, block_start,
4873 btrfs_delalloc_release_extents(BTRFS_I(inode), blocksize);
4877 extent_changeset_free(data_reserved);
4881 static int maybe_insert_hole(struct btrfs_root *root, struct inode *inode,
4882 u64 offset, u64 len)
4884 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
4885 struct btrfs_trans_handle *trans;
4889 * Still need to make sure the inode looks like it's been updated so
4890 * that any holes get logged if we fsync.
4892 if (btrfs_fs_incompat(fs_info, NO_HOLES)) {
4893 BTRFS_I(inode)->last_trans = fs_info->generation;
4894 BTRFS_I(inode)->last_sub_trans = root->log_transid;
4895 BTRFS_I(inode)->last_log_commit = root->last_log_commit;
4900 * 1 - for the one we're dropping
4901 * 1 - for the one we're adding
4902 * 1 - for updating the inode.
4904 trans = btrfs_start_transaction(root, 3);
4906 return PTR_ERR(trans);
4908 ret = btrfs_drop_extents(trans, root, inode, offset, offset + len, 1);
4910 btrfs_abort_transaction(trans, ret);
4911 btrfs_end_transaction(trans);
4915 ret = btrfs_insert_file_extent(trans, root, btrfs_ino(BTRFS_I(inode)),
4916 offset, 0, 0, len, 0, len, 0, 0, 0);
4918 btrfs_abort_transaction(trans, ret);
4920 btrfs_update_inode(trans, root, inode);
4921 btrfs_end_transaction(trans);
4926 * This function puts in dummy file extents for the area we're creating a hole
4927 * for. So if we are truncating this file to a larger size we need to insert
4928 * these file extents so that btrfs_get_extent will return a EXTENT_MAP_HOLE for
4929 * the range between oldsize and size
4931 int btrfs_cont_expand(struct inode *inode, loff_t oldsize, loff_t size)
4933 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
4934 struct btrfs_root *root = BTRFS_I(inode)->root;
4935 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
4936 struct extent_map *em = NULL;
4937 struct extent_state *cached_state = NULL;
4938 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
4939 u64 hole_start = ALIGN(oldsize, fs_info->sectorsize);
4940 u64 block_end = ALIGN(size, fs_info->sectorsize);
4947 * If our size started in the middle of a block we need to zero out the
4948 * rest of the block before we expand the i_size, otherwise we could
4949 * expose stale data.
4951 err = btrfs_truncate_block(inode, oldsize, 0, 0);
4955 if (size <= hole_start)
4959 struct btrfs_ordered_extent *ordered;
4961 lock_extent_bits(io_tree, hole_start, block_end - 1,
4963 ordered = btrfs_lookup_ordered_range(BTRFS_I(inode), hole_start,
4964 block_end - hole_start);
4967 unlock_extent_cached(io_tree, hole_start, block_end - 1,
4969 btrfs_start_ordered_extent(inode, ordered, 1);
4970 btrfs_put_ordered_extent(ordered);
4973 cur_offset = hole_start;
4975 em = btrfs_get_extent(BTRFS_I(inode), NULL, 0, cur_offset,
4976 block_end - cur_offset, 0);
4982 last_byte = min(extent_map_end(em), block_end);
4983 last_byte = ALIGN(last_byte, fs_info->sectorsize);
4984 if (!test_bit(EXTENT_FLAG_PREALLOC, &em->flags)) {
4985 struct extent_map *hole_em;
4986 hole_size = last_byte - cur_offset;
4988 err = maybe_insert_hole(root, inode, cur_offset,
4992 btrfs_drop_extent_cache(BTRFS_I(inode), cur_offset,
4993 cur_offset + hole_size - 1, 0);
4994 hole_em = alloc_extent_map();
4996 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
4997 &BTRFS_I(inode)->runtime_flags);
5000 hole_em->start = cur_offset;
5001 hole_em->len = hole_size;
5002 hole_em->orig_start = cur_offset;
5004 hole_em->block_start = EXTENT_MAP_HOLE;
5005 hole_em->block_len = 0;
5006 hole_em->orig_block_len = 0;
5007 hole_em->ram_bytes = hole_size;
5008 hole_em->bdev = fs_info->fs_devices->latest_bdev;
5009 hole_em->compress_type = BTRFS_COMPRESS_NONE;
5010 hole_em->generation = fs_info->generation;
5013 write_lock(&em_tree->lock);
5014 err = add_extent_mapping(em_tree, hole_em, 1);
5015 write_unlock(&em_tree->lock);
5018 btrfs_drop_extent_cache(BTRFS_I(inode),
5023 free_extent_map(hole_em);
5026 free_extent_map(em);
5028 cur_offset = last_byte;
5029 if (cur_offset >= block_end)
5032 free_extent_map(em);
5033 unlock_extent_cached(io_tree, hole_start, block_end - 1, &cached_state);
5037 static int btrfs_setsize(struct inode *inode, struct iattr *attr)
5039 struct btrfs_root *root = BTRFS_I(inode)->root;
5040 struct btrfs_trans_handle *trans;
5041 loff_t oldsize = i_size_read(inode);
5042 loff_t newsize = attr->ia_size;
5043 int mask = attr->ia_valid;
5047 * The regular truncate() case without ATTR_CTIME and ATTR_MTIME is a
5048 * special case where we need to update the times despite not having
5049 * these flags set. For all other operations the VFS set these flags
5050 * explicitly if it wants a timestamp update.
5052 if (newsize != oldsize) {
5053 inode_inc_iversion(inode);
5054 if (!(mask & (ATTR_CTIME | ATTR_MTIME)))
5055 inode->i_ctime = inode->i_mtime =
5056 current_time(inode);
5059 if (newsize > oldsize) {
5061 * Don't do an expanding truncate while snapshotting is ongoing.
5062 * This is to ensure the snapshot captures a fully consistent
5063 * state of this file - if the snapshot captures this expanding
5064 * truncation, it must capture all writes that happened before
5067 btrfs_wait_for_snapshot_creation(root);
5068 ret = btrfs_cont_expand(inode, oldsize, newsize);
5070 btrfs_end_write_no_snapshotting(root);
5074 trans = btrfs_start_transaction(root, 1);
5075 if (IS_ERR(trans)) {
5076 btrfs_end_write_no_snapshotting(root);
5077 return PTR_ERR(trans);
5080 i_size_write(inode, newsize);
5081 btrfs_ordered_update_i_size(inode, i_size_read(inode), NULL);
5082 pagecache_isize_extended(inode, oldsize, newsize);
5083 ret = btrfs_update_inode(trans, root, inode);
5084 btrfs_end_write_no_snapshotting(root);
5085 btrfs_end_transaction(trans);
5089 * We're truncating a file that used to have good data down to
5090 * zero. Make sure it gets into the ordered flush list so that
5091 * any new writes get down to disk quickly.
5094 set_bit(BTRFS_INODE_ORDERED_DATA_CLOSE,
5095 &BTRFS_I(inode)->runtime_flags);
5098 * 1 for the orphan item we're going to add
5099 * 1 for the orphan item deletion.
5101 trans = btrfs_start_transaction(root, 2);
5103 return PTR_ERR(trans);
5106 * We need to do this in case we fail at _any_ point during the
5107 * actual truncate. Once we do the truncate_setsize we could
5108 * invalidate pages which forces any outstanding ordered io to
5109 * be instantly completed which will give us extents that need
5110 * to be truncated. If we fail to get an orphan inode down we
5111 * could have left over extents that were never meant to live,
5112 * so we need to guarantee from this point on that everything
5113 * will be consistent.
5115 ret = btrfs_orphan_add(trans, BTRFS_I(inode));
5116 btrfs_end_transaction(trans);
5120 /* we don't support swapfiles, so vmtruncate shouldn't fail */
5121 truncate_setsize(inode, newsize);
5123 /* Disable nonlocked read DIO to avoid the end less truncate */
5124 btrfs_inode_block_unlocked_dio(BTRFS_I(inode));
5125 inode_dio_wait(inode);
5126 btrfs_inode_resume_unlocked_dio(BTRFS_I(inode));
5128 ret = btrfs_truncate(inode);
5129 if (ret && inode->i_nlink) {
5132 /* To get a stable disk_i_size */
5133 err = btrfs_wait_ordered_range(inode, 0, (u64)-1);
5135 btrfs_orphan_del(NULL, BTRFS_I(inode));
5140 * failed to truncate, disk_i_size is only adjusted down
5141 * as we remove extents, so it should represent the true
5142 * size of the inode, so reset the in memory size and
5143 * delete our orphan entry.
5145 trans = btrfs_join_transaction(root);
5146 if (IS_ERR(trans)) {
5147 btrfs_orphan_del(NULL, BTRFS_I(inode));
5150 i_size_write(inode, BTRFS_I(inode)->disk_i_size);
5151 err = btrfs_orphan_del(trans, BTRFS_I(inode));
5153 btrfs_abort_transaction(trans, err);
5154 btrfs_end_transaction(trans);
5161 static int btrfs_setattr(struct dentry *dentry, struct iattr *attr)
5163 struct inode *inode = d_inode(dentry);
5164 struct btrfs_root *root = BTRFS_I(inode)->root;
5167 if (btrfs_root_readonly(root))
5170 err = setattr_prepare(dentry, attr);
5174 if (S_ISREG(inode->i_mode) && (attr->ia_valid & ATTR_SIZE)) {
5175 err = btrfs_setsize(inode, attr);
5180 if (attr->ia_valid) {
5181 setattr_copy(inode, attr);
5182 inode_inc_iversion(inode);
5183 err = btrfs_dirty_inode(inode);
5185 if (!err && attr->ia_valid & ATTR_MODE)
5186 err = posix_acl_chmod(inode, inode->i_mode);
5193 * While truncating the inode pages during eviction, we get the VFS calling
5194 * btrfs_invalidatepage() against each page of the inode. This is slow because
5195 * the calls to btrfs_invalidatepage() result in a huge amount of calls to
5196 * lock_extent_bits() and clear_extent_bit(), which keep merging and splitting
5197 * extent_state structures over and over, wasting lots of time.
5199 * Therefore if the inode is being evicted, let btrfs_invalidatepage() skip all
5200 * those expensive operations on a per page basis and do only the ordered io
5201 * finishing, while we release here the extent_map and extent_state structures,
5202 * without the excessive merging and splitting.
5204 static void evict_inode_truncate_pages(struct inode *inode)
5206 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
5207 struct extent_map_tree *map_tree = &BTRFS_I(inode)->extent_tree;
5208 struct rb_node *node;
5210 ASSERT(inode->i_state & I_FREEING);
5211 truncate_inode_pages_final(&inode->i_data);
5213 write_lock(&map_tree->lock);
5214 while (!RB_EMPTY_ROOT(&map_tree->map)) {
5215 struct extent_map *em;
5217 node = rb_first(&map_tree->map);
5218 em = rb_entry(node, struct extent_map, rb_node);
5219 clear_bit(EXTENT_FLAG_PINNED, &em->flags);
5220 clear_bit(EXTENT_FLAG_LOGGING, &em->flags);
5221 remove_extent_mapping(map_tree, em);
5222 free_extent_map(em);
5223 if (need_resched()) {
5224 write_unlock(&map_tree->lock);
5226 write_lock(&map_tree->lock);
5229 write_unlock(&map_tree->lock);
5232 * Keep looping until we have no more ranges in the io tree.
5233 * We can have ongoing bios started by readpages (called from readahead)
5234 * that have their endio callback (extent_io.c:end_bio_extent_readpage)
5235 * still in progress (unlocked the pages in the bio but did not yet
5236 * unlocked the ranges in the io tree). Therefore this means some
5237 * ranges can still be locked and eviction started because before
5238 * submitting those bios, which are executed by a separate task (work
5239 * queue kthread), inode references (inode->i_count) were not taken
5240 * (which would be dropped in the end io callback of each bio).
5241 * Therefore here we effectively end up waiting for those bios and
5242 * anyone else holding locked ranges without having bumped the inode's
5243 * reference count - if we don't do it, when they access the inode's
5244 * io_tree to unlock a range it may be too late, leading to an
5245 * use-after-free issue.
5247 spin_lock(&io_tree->lock);
5248 while (!RB_EMPTY_ROOT(&io_tree->state)) {
5249 struct extent_state *state;
5250 struct extent_state *cached_state = NULL;
5254 node = rb_first(&io_tree->state);
5255 state = rb_entry(node, struct extent_state, rb_node);
5256 start = state->start;
5258 spin_unlock(&io_tree->lock);
5260 lock_extent_bits(io_tree, start, end, &cached_state);
5263 * If still has DELALLOC flag, the extent didn't reach disk,
5264 * and its reserved space won't be freed by delayed_ref.
5265 * So we need to free its reserved space here.
5266 * (Refer to comment in btrfs_invalidatepage, case 2)
5268 * Note, end is the bytenr of last byte, so we need + 1 here.
5270 if (state->state & EXTENT_DELALLOC)
5271 btrfs_qgroup_free_data(inode, NULL, start, end - start + 1);
5273 clear_extent_bit(io_tree, start, end,
5274 EXTENT_LOCKED | EXTENT_DIRTY |
5275 EXTENT_DELALLOC | EXTENT_DO_ACCOUNTING |
5276 EXTENT_DEFRAG, 1, 1, &cached_state);
5279 spin_lock(&io_tree->lock);
5281 spin_unlock(&io_tree->lock);
5284 void btrfs_evict_inode(struct inode *inode)
5286 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
5287 struct btrfs_trans_handle *trans;
5288 struct btrfs_root *root = BTRFS_I(inode)->root;
5289 struct btrfs_block_rsv *rsv, *global_rsv;
5290 int steal_from_global = 0;
5294 trace_btrfs_inode_evict(inode);
5301 min_size = btrfs_calc_trunc_metadata_size(fs_info, 1);
5303 evict_inode_truncate_pages(inode);
5305 if (inode->i_nlink &&
5306 ((btrfs_root_refs(&root->root_item) != 0 &&
5307 root->root_key.objectid != BTRFS_ROOT_TREE_OBJECTID) ||
5308 btrfs_is_free_space_inode(BTRFS_I(inode))))
5311 if (is_bad_inode(inode)) {
5312 btrfs_orphan_del(NULL, BTRFS_I(inode));
5315 /* do we really want it for ->i_nlink > 0 and zero btrfs_root_refs? */
5316 if (!special_file(inode->i_mode))
5317 btrfs_wait_ordered_range(inode, 0, (u64)-1);
5319 btrfs_free_io_failure_record(BTRFS_I(inode), 0, (u64)-1);
5321 if (test_bit(BTRFS_FS_LOG_RECOVERING, &fs_info->flags)) {
5322 BUG_ON(test_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
5323 &BTRFS_I(inode)->runtime_flags));
5327 if (inode->i_nlink > 0) {
5328 BUG_ON(btrfs_root_refs(&root->root_item) != 0 &&
5329 root->root_key.objectid != BTRFS_ROOT_TREE_OBJECTID);
5333 ret = btrfs_commit_inode_delayed_inode(BTRFS_I(inode));
5335 btrfs_orphan_del(NULL, BTRFS_I(inode));
5339 rsv = btrfs_alloc_block_rsv(fs_info, BTRFS_BLOCK_RSV_TEMP);
5341 btrfs_orphan_del(NULL, BTRFS_I(inode));
5344 rsv->size = min_size;
5346 global_rsv = &fs_info->global_block_rsv;
5348 btrfs_i_size_write(BTRFS_I(inode), 0);
5351 * This is a bit simpler than btrfs_truncate since we've already
5352 * reserved our space for our orphan item in the unlink, so we just
5353 * need to reserve some slack space in case we add bytes and update
5354 * inode item when doing the truncate.
5357 ret = btrfs_block_rsv_refill(root, rsv, min_size,
5358 BTRFS_RESERVE_FLUSH_LIMIT);
5361 * Try and steal from the global reserve since we will
5362 * likely not use this space anyway, we want to try as
5363 * hard as possible to get this to work.
5366 steal_from_global++;
5368 steal_from_global = 0;
5372 * steal_from_global == 0: we reserved stuff, hooray!
5373 * steal_from_global == 1: we didn't reserve stuff, boo!
5374 * steal_from_global == 2: we've committed, still not a lot of
5375 * room but maybe we'll have room in the global reserve this
5377 * steal_from_global == 3: abandon all hope!
5379 if (steal_from_global > 2) {
5381 "Could not get space for a delete, will truncate on mount %d",
5383 btrfs_orphan_del(NULL, BTRFS_I(inode));
5384 btrfs_free_block_rsv(fs_info, rsv);
5388 trans = btrfs_join_transaction(root);
5389 if (IS_ERR(trans)) {
5390 btrfs_orphan_del(NULL, BTRFS_I(inode));
5391 btrfs_free_block_rsv(fs_info, rsv);
5396 * We can't just steal from the global reserve, we need to make
5397 * sure there is room to do it, if not we need to commit and try
5400 if (steal_from_global) {
5401 if (!btrfs_check_space_for_delayed_refs(trans, fs_info))
5402 ret = btrfs_block_rsv_migrate(global_rsv, rsv,
5409 * Couldn't steal from the global reserve, we have too much
5410 * pending stuff built up, commit the transaction and try it
5414 ret = btrfs_commit_transaction(trans);
5416 btrfs_orphan_del(NULL, BTRFS_I(inode));
5417 btrfs_free_block_rsv(fs_info, rsv);
5422 steal_from_global = 0;
5425 trans->block_rsv = rsv;
5427 ret = btrfs_truncate_inode_items(trans, root, inode, 0, 0);
5428 if (ret != -ENOSPC && ret != -EAGAIN)
5431 trans->block_rsv = &fs_info->trans_block_rsv;
5432 btrfs_end_transaction(trans);
5434 btrfs_btree_balance_dirty(fs_info);
5437 btrfs_free_block_rsv(fs_info, rsv);
5440 * Errors here aren't a big deal, it just means we leave orphan items
5441 * in the tree. They will be cleaned up on the next mount.
5444 trans->block_rsv = root->orphan_block_rsv;
5445 btrfs_orphan_del(trans, BTRFS_I(inode));
5447 btrfs_orphan_del(NULL, BTRFS_I(inode));
5450 trans->block_rsv = &fs_info->trans_block_rsv;
5451 if (!(root == fs_info->tree_root ||
5452 root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID))
5453 btrfs_return_ino(root, btrfs_ino(BTRFS_I(inode)));
5455 btrfs_end_transaction(trans);
5456 btrfs_btree_balance_dirty(fs_info);
5458 btrfs_remove_delayed_node(BTRFS_I(inode));
5463 * this returns the key found in the dir entry in the location pointer.
5464 * If no dir entries were found, location->objectid is 0.
5466 static int btrfs_inode_by_name(struct inode *dir, struct dentry *dentry,
5467 struct btrfs_key *location)
5469 const char *name = dentry->d_name.name;
5470 int namelen = dentry->d_name.len;
5471 struct btrfs_dir_item *di;
5472 struct btrfs_path *path;
5473 struct btrfs_root *root = BTRFS_I(dir)->root;
5476 path = btrfs_alloc_path();
5480 di = btrfs_lookup_dir_item(NULL, root, path, btrfs_ino(BTRFS_I(dir)),
5485 if (IS_ERR_OR_NULL(di))
5488 btrfs_dir_item_key_to_cpu(path->nodes[0], di, location);
5489 if (location->type != BTRFS_INODE_ITEM_KEY &&
5490 location->type != BTRFS_ROOT_ITEM_KEY) {
5491 btrfs_warn(root->fs_info,
5492 "%s gets something invalid in DIR_ITEM (name %s, directory ino %llu, location(%llu %u %llu))",
5493 __func__, name, btrfs_ino(BTRFS_I(dir)),
5494 location->objectid, location->type, location->offset);
5498 btrfs_free_path(path);
5501 location->objectid = 0;
5506 * when we hit a tree root in a directory, the btrfs part of the inode
5507 * needs to be changed to reflect the root directory of the tree root. This
5508 * is kind of like crossing a mount point.
5510 static int fixup_tree_root_location(struct btrfs_fs_info *fs_info,
5512 struct dentry *dentry,
5513 struct btrfs_key *location,
5514 struct btrfs_root **sub_root)
5516 struct btrfs_path *path;
5517 struct btrfs_root *new_root;
5518 struct btrfs_root_ref *ref;
5519 struct extent_buffer *leaf;
5520 struct btrfs_key key;
5524 path = btrfs_alloc_path();
5531 key.objectid = BTRFS_I(dir)->root->root_key.objectid;
5532 key.type = BTRFS_ROOT_REF_KEY;
5533 key.offset = location->objectid;
5535 ret = btrfs_search_slot(NULL, fs_info->tree_root, &key, path, 0, 0);
5542 leaf = path->nodes[0];
5543 ref = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_root_ref);
5544 if (btrfs_root_ref_dirid(leaf, ref) != btrfs_ino(BTRFS_I(dir)) ||
5545 btrfs_root_ref_name_len(leaf, ref) != dentry->d_name.len)
5548 ret = memcmp_extent_buffer(leaf, dentry->d_name.name,
5549 (unsigned long)(ref + 1),
5550 dentry->d_name.len);
5554 btrfs_release_path(path);
5556 new_root = btrfs_read_fs_root_no_name(fs_info, location);
5557 if (IS_ERR(new_root)) {
5558 err = PTR_ERR(new_root);
5562 *sub_root = new_root;
5563 location->objectid = btrfs_root_dirid(&new_root->root_item);
5564 location->type = BTRFS_INODE_ITEM_KEY;
5565 location->offset = 0;
5568 btrfs_free_path(path);
5572 static void inode_tree_add(struct inode *inode)
5574 struct btrfs_root *root = BTRFS_I(inode)->root;
5575 struct btrfs_inode *entry;
5577 struct rb_node *parent;
5578 struct rb_node *new = &BTRFS_I(inode)->rb_node;
5579 u64 ino = btrfs_ino(BTRFS_I(inode));
5581 if (inode_unhashed(inode))
5584 spin_lock(&root->inode_lock);
5585 p = &root->inode_tree.rb_node;
5588 entry = rb_entry(parent, struct btrfs_inode, rb_node);
5590 if (ino < btrfs_ino(BTRFS_I(&entry->vfs_inode)))
5591 p = &parent->rb_left;
5592 else if (ino > btrfs_ino(BTRFS_I(&entry->vfs_inode)))
5593 p = &parent->rb_right;
5595 WARN_ON(!(entry->vfs_inode.i_state &
5596 (I_WILL_FREE | I_FREEING)));
5597 rb_replace_node(parent, new, &root->inode_tree);
5598 RB_CLEAR_NODE(parent);
5599 spin_unlock(&root->inode_lock);
5603 rb_link_node(new, parent, p);
5604 rb_insert_color(new, &root->inode_tree);
5605 spin_unlock(&root->inode_lock);
5608 static void inode_tree_del(struct inode *inode)
5610 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
5611 struct btrfs_root *root = BTRFS_I(inode)->root;
5614 spin_lock(&root->inode_lock);
5615 if (!RB_EMPTY_NODE(&BTRFS_I(inode)->rb_node)) {
5616 rb_erase(&BTRFS_I(inode)->rb_node, &root->inode_tree);
5617 RB_CLEAR_NODE(&BTRFS_I(inode)->rb_node);
5618 empty = RB_EMPTY_ROOT(&root->inode_tree);
5620 spin_unlock(&root->inode_lock);
5622 if (empty && btrfs_root_refs(&root->root_item) == 0) {
5623 synchronize_srcu(&fs_info->subvol_srcu);
5624 spin_lock(&root->inode_lock);
5625 empty = RB_EMPTY_ROOT(&root->inode_tree);
5626 spin_unlock(&root->inode_lock);
5628 btrfs_add_dead_root(root);
5632 void btrfs_invalidate_inodes(struct btrfs_root *root)
5634 struct btrfs_fs_info *fs_info = root->fs_info;
5635 struct rb_node *node;
5636 struct rb_node *prev;
5637 struct btrfs_inode *entry;
5638 struct inode *inode;
5641 if (!test_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state))
5642 WARN_ON(btrfs_root_refs(&root->root_item) != 0);
5644 spin_lock(&root->inode_lock);
5646 node = root->inode_tree.rb_node;
5650 entry = rb_entry(node, struct btrfs_inode, rb_node);
5652 if (objectid < btrfs_ino(BTRFS_I(&entry->vfs_inode)))
5653 node = node->rb_left;
5654 else if (objectid > btrfs_ino(BTRFS_I(&entry->vfs_inode)))
5655 node = node->rb_right;
5661 entry = rb_entry(prev, struct btrfs_inode, rb_node);
5662 if (objectid <= btrfs_ino(BTRFS_I(&entry->vfs_inode))) {
5666 prev = rb_next(prev);
5670 entry = rb_entry(node, struct btrfs_inode, rb_node);
5671 objectid = btrfs_ino(BTRFS_I(&entry->vfs_inode)) + 1;
5672 inode = igrab(&entry->vfs_inode);
5674 spin_unlock(&root->inode_lock);
5675 if (atomic_read(&inode->i_count) > 1)
5676 d_prune_aliases(inode);
5678 * btrfs_drop_inode will have it removed from
5679 * the inode cache when its usage count
5684 spin_lock(&root->inode_lock);
5688 if (cond_resched_lock(&root->inode_lock))
5691 node = rb_next(node);
5693 spin_unlock(&root->inode_lock);
5696 static int btrfs_init_locked_inode(struct inode *inode, void *p)
5698 struct btrfs_iget_args *args = p;
5699 inode->i_ino = args->location->objectid;
5700 memcpy(&BTRFS_I(inode)->location, args->location,
5701 sizeof(*args->location));
5702 BTRFS_I(inode)->root = args->root;
5706 static int btrfs_find_actor(struct inode *inode, void *opaque)
5708 struct btrfs_iget_args *args = opaque;
5709 return args->location->objectid == BTRFS_I(inode)->location.objectid &&
5710 args->root == BTRFS_I(inode)->root;
5713 static struct inode *btrfs_iget_locked(struct super_block *s,
5714 struct btrfs_key *location,
5715 struct btrfs_root *root)
5717 struct inode *inode;
5718 struct btrfs_iget_args args;
5719 unsigned long hashval = btrfs_inode_hash(location->objectid, root);
5721 args.location = location;
5724 inode = iget5_locked(s, hashval, btrfs_find_actor,
5725 btrfs_init_locked_inode,
5730 /* Get an inode object given its location and corresponding root.
5731 * Returns in *is_new if the inode was read from disk
5733 struct inode *btrfs_iget(struct super_block *s, struct btrfs_key *location,
5734 struct btrfs_root *root, int *new)
5736 struct inode *inode;
5738 inode = btrfs_iget_locked(s, location, root);
5740 return ERR_PTR(-ENOMEM);
5742 if (inode->i_state & I_NEW) {
5745 ret = btrfs_read_locked_inode(inode);
5746 if (!is_bad_inode(inode)) {
5747 inode_tree_add(inode);
5748 unlock_new_inode(inode);
5752 unlock_new_inode(inode);
5755 inode = ERR_PTR(ret < 0 ? ret : -ESTALE);
5762 static struct inode *new_simple_dir(struct super_block *s,
5763 struct btrfs_key *key,
5764 struct btrfs_root *root)
5766 struct inode *inode = new_inode(s);
5769 return ERR_PTR(-ENOMEM);
5771 BTRFS_I(inode)->root = root;
5772 memcpy(&BTRFS_I(inode)->location, key, sizeof(*key));
5773 set_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags);
5775 inode->i_ino = BTRFS_EMPTY_SUBVOL_DIR_OBJECTID;
5776 inode->i_op = &btrfs_dir_ro_inode_operations;
5777 inode->i_opflags &= ~IOP_XATTR;
5778 inode->i_fop = &simple_dir_operations;
5779 inode->i_mode = S_IFDIR | S_IRUGO | S_IWUSR | S_IXUGO;
5780 inode->i_mtime = current_time(inode);
5781 inode->i_atime = inode->i_mtime;
5782 inode->i_ctime = inode->i_mtime;
5783 BTRFS_I(inode)->i_otime = inode->i_mtime;
5788 struct inode *btrfs_lookup_dentry(struct inode *dir, struct dentry *dentry)
5790 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
5791 struct inode *inode;
5792 struct btrfs_root *root = BTRFS_I(dir)->root;
5793 struct btrfs_root *sub_root = root;
5794 struct btrfs_key location;
5798 if (dentry->d_name.len > BTRFS_NAME_LEN)
5799 return ERR_PTR(-ENAMETOOLONG);
5801 ret = btrfs_inode_by_name(dir, dentry, &location);
5803 return ERR_PTR(ret);
5805 if (location.objectid == 0)
5806 return ERR_PTR(-ENOENT);
5808 if (location.type == BTRFS_INODE_ITEM_KEY) {
5809 inode = btrfs_iget(dir->i_sb, &location, root, NULL);
5813 index = srcu_read_lock(&fs_info->subvol_srcu);
5814 ret = fixup_tree_root_location(fs_info, dir, dentry,
5815 &location, &sub_root);
5818 inode = ERR_PTR(ret);
5820 inode = new_simple_dir(dir->i_sb, &location, sub_root);
5822 inode = btrfs_iget(dir->i_sb, &location, sub_root, NULL);
5824 srcu_read_unlock(&fs_info->subvol_srcu, index);
5826 if (!IS_ERR(inode) && root != sub_root) {
5827 down_read(&fs_info->cleanup_work_sem);
5828 if (!sb_rdonly(inode->i_sb))
5829 ret = btrfs_orphan_cleanup(sub_root);
5830 up_read(&fs_info->cleanup_work_sem);
5833 inode = ERR_PTR(ret);
5840 static int btrfs_dentry_delete(const struct dentry *dentry)
5842 struct btrfs_root *root;
5843 struct inode *inode = d_inode(dentry);
5845 if (!inode && !IS_ROOT(dentry))
5846 inode = d_inode(dentry->d_parent);
5849 root = BTRFS_I(inode)->root;
5850 if (btrfs_root_refs(&root->root_item) == 0)
5853 if (btrfs_ino(BTRFS_I(inode)) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)
5859 static void btrfs_dentry_release(struct dentry *dentry)
5861 kfree(dentry->d_fsdata);
5864 static struct dentry *btrfs_lookup(struct inode *dir, struct dentry *dentry,
5867 struct inode *inode;
5869 inode = btrfs_lookup_dentry(dir, dentry);
5870 if (IS_ERR(inode)) {
5871 if (PTR_ERR(inode) == -ENOENT)
5874 return ERR_CAST(inode);
5877 return d_splice_alias(inode, dentry);
5880 unsigned char btrfs_filetype_table[] = {
5881 DT_UNKNOWN, DT_REG, DT_DIR, DT_CHR, DT_BLK, DT_FIFO, DT_SOCK, DT_LNK
5885 * All this infrastructure exists because dir_emit can fault, and we are holding
5886 * the tree lock when doing readdir. For now just allocate a buffer and copy
5887 * our information into that, and then dir_emit from the buffer. This is
5888 * similar to what NFS does, only we don't keep the buffer around in pagecache
5889 * because I'm afraid I'll mess that up. Long term we need to make filldir do
5890 * copy_to_user_inatomic so we don't have to worry about page faulting under the
5893 static int btrfs_opendir(struct inode *inode, struct file *file)
5895 struct btrfs_file_private *private;
5897 private = kzalloc(sizeof(struct btrfs_file_private), GFP_KERNEL);
5900 private->filldir_buf = kzalloc(PAGE_SIZE, GFP_KERNEL);
5901 if (!private->filldir_buf) {
5905 file->private_data = private;
5916 static int btrfs_filldir(void *addr, int entries, struct dir_context *ctx)
5919 struct dir_entry *entry = addr;
5920 char *name = (char *)(entry + 1);
5922 ctx->pos = entry->offset;
5923 if (!dir_emit(ctx, name, entry->name_len, entry->ino,
5926 addr += sizeof(struct dir_entry) + entry->name_len;
5932 static int btrfs_real_readdir(struct file *file, struct dir_context *ctx)
5934 struct inode *inode = file_inode(file);
5935 struct btrfs_root *root = BTRFS_I(inode)->root;
5936 struct btrfs_file_private *private = file->private_data;
5937 struct btrfs_dir_item *di;
5938 struct btrfs_key key;
5939 struct btrfs_key found_key;
5940 struct btrfs_path *path;
5942 struct list_head ins_list;
5943 struct list_head del_list;
5945 struct extent_buffer *leaf;
5952 struct btrfs_key location;
5954 if (!dir_emit_dots(file, ctx))
5957 path = btrfs_alloc_path();
5961 addr = private->filldir_buf;
5962 path->reada = READA_FORWARD;
5964 INIT_LIST_HEAD(&ins_list);
5965 INIT_LIST_HEAD(&del_list);
5966 put = btrfs_readdir_get_delayed_items(inode, &ins_list, &del_list);
5969 key.type = BTRFS_DIR_INDEX_KEY;
5970 key.offset = ctx->pos;
5971 key.objectid = btrfs_ino(BTRFS_I(inode));
5973 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
5978 struct dir_entry *entry;
5980 leaf = path->nodes[0];
5981 slot = path->slots[0];
5982 if (slot >= btrfs_header_nritems(leaf)) {
5983 ret = btrfs_next_leaf(root, path);
5991 btrfs_item_key_to_cpu(leaf, &found_key, slot);
5993 if (found_key.objectid != key.objectid)
5995 if (found_key.type != BTRFS_DIR_INDEX_KEY)
5997 if (found_key.offset < ctx->pos)
5999 if (btrfs_should_delete_dir_index(&del_list, found_key.offset))
6001 di = btrfs_item_ptr(leaf, slot, struct btrfs_dir_item);
6002 name_len = btrfs_dir_name_len(leaf, di);
6003 if ((total_len + sizeof(struct dir_entry) + name_len) >=
6005 btrfs_release_path(path);
6006 ret = btrfs_filldir(private->filldir_buf, entries, ctx);
6009 addr = private->filldir_buf;
6016 entry->name_len = name_len;
6017 name_ptr = (char *)(entry + 1);
6018 read_extent_buffer(leaf, name_ptr, (unsigned long)(di + 1),
6020 entry->type = btrfs_filetype_table[btrfs_dir_type(leaf, di)];
6021 btrfs_dir_item_key_to_cpu(leaf, di, &location);
6022 entry->ino = location.objectid;
6023 entry->offset = found_key.offset;
6025 addr += sizeof(struct dir_entry) + name_len;
6026 total_len += sizeof(struct dir_entry) + name_len;
6030 btrfs_release_path(path);
6032 ret = btrfs_filldir(private->filldir_buf, entries, ctx);
6036 ret = btrfs_readdir_delayed_dir_index(ctx, &ins_list);
6041 * Stop new entries from being returned after we return the last
6044 * New directory entries are assigned a strictly increasing
6045 * offset. This means that new entries created during readdir
6046 * are *guaranteed* to be seen in the future by that readdir.
6047 * This has broken buggy programs which operate on names as
6048 * they're returned by readdir. Until we re-use freed offsets
6049 * we have this hack to stop new entries from being returned
6050 * under the assumption that they'll never reach this huge
6053 * This is being careful not to overflow 32bit loff_t unless the
6054 * last entry requires it because doing so has broken 32bit apps
6057 if (ctx->pos >= INT_MAX)
6058 ctx->pos = LLONG_MAX;
6065 btrfs_readdir_put_delayed_items(inode, &ins_list, &del_list);
6066 btrfs_free_path(path);
6070 int btrfs_write_inode(struct inode *inode, struct writeback_control *wbc)
6072 struct btrfs_root *root = BTRFS_I(inode)->root;
6073 struct btrfs_trans_handle *trans;
6075 bool nolock = false;
6077 if (test_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags))
6080 if (btrfs_fs_closing(root->fs_info) &&
6081 btrfs_is_free_space_inode(BTRFS_I(inode)))
6084 if (wbc->sync_mode == WB_SYNC_ALL) {
6086 trans = btrfs_join_transaction_nolock(root);
6088 trans = btrfs_join_transaction(root);
6090 return PTR_ERR(trans);
6091 ret = btrfs_commit_transaction(trans);
6097 * This is somewhat expensive, updating the tree every time the
6098 * inode changes. But, it is most likely to find the inode in cache.
6099 * FIXME, needs more benchmarking...there are no reasons other than performance
6100 * to keep or drop this code.
6102 static int btrfs_dirty_inode(struct inode *inode)
6104 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
6105 struct btrfs_root *root = BTRFS_I(inode)->root;
6106 struct btrfs_trans_handle *trans;
6109 if (test_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags))
6112 trans = btrfs_join_transaction(root);
6114 return PTR_ERR(trans);
6116 ret = btrfs_update_inode(trans, root, inode);
6117 if (ret && ret == -ENOSPC) {
6118 /* whoops, lets try again with the full transaction */
6119 btrfs_end_transaction(trans);
6120 trans = btrfs_start_transaction(root, 1);
6122 return PTR_ERR(trans);
6124 ret = btrfs_update_inode(trans, root, inode);
6126 btrfs_end_transaction(trans);
6127 if (BTRFS_I(inode)->delayed_node)
6128 btrfs_balance_delayed_items(fs_info);
6134 * This is a copy of file_update_time. We need this so we can return error on
6135 * ENOSPC for updating the inode in the case of file write and mmap writes.
6137 static int btrfs_update_time(struct inode *inode, struct timespec *now,
6140 struct btrfs_root *root = BTRFS_I(inode)->root;
6141 bool dirty = flags & ~S_VERSION;
6143 if (btrfs_root_readonly(root))
6146 if (flags & S_VERSION)
6147 dirty |= inode_maybe_inc_iversion(inode, dirty);
6148 if (flags & S_CTIME)
6149 inode->i_ctime = *now;
6150 if (flags & S_MTIME)
6151 inode->i_mtime = *now;
6152 if (flags & S_ATIME)
6153 inode->i_atime = *now;
6154 return dirty ? btrfs_dirty_inode(inode) : 0;
6158 * find the highest existing sequence number in a directory
6159 * and then set the in-memory index_cnt variable to reflect
6160 * free sequence numbers
6162 static int btrfs_set_inode_index_count(struct btrfs_inode *inode)
6164 struct btrfs_root *root = inode->root;
6165 struct btrfs_key key, found_key;
6166 struct btrfs_path *path;
6167 struct extent_buffer *leaf;
6170 key.objectid = btrfs_ino(inode);
6171 key.type = BTRFS_DIR_INDEX_KEY;
6172 key.offset = (u64)-1;
6174 path = btrfs_alloc_path();
6178 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
6181 /* FIXME: we should be able to handle this */
6187 * MAGIC NUMBER EXPLANATION:
6188 * since we search a directory based on f_pos we have to start at 2
6189 * since '.' and '..' have f_pos of 0 and 1 respectively, so everybody
6190 * else has to start at 2
6192 if (path->slots[0] == 0) {
6193 inode->index_cnt = 2;
6199 leaf = path->nodes[0];
6200 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
6202 if (found_key.objectid != btrfs_ino(inode) ||
6203 found_key.type != BTRFS_DIR_INDEX_KEY) {
6204 inode->index_cnt = 2;
6208 inode->index_cnt = found_key.offset + 1;
6210 btrfs_free_path(path);
6215 * helper to find a free sequence number in a given directory. This current
6216 * code is very simple, later versions will do smarter things in the btree
6218 int btrfs_set_inode_index(struct btrfs_inode *dir, u64 *index)
6222 if (dir->index_cnt == (u64)-1) {
6223 ret = btrfs_inode_delayed_dir_index_count(dir);
6225 ret = btrfs_set_inode_index_count(dir);
6231 *index = dir->index_cnt;
6237 static int btrfs_insert_inode_locked(struct inode *inode)
6239 struct btrfs_iget_args args;
6240 args.location = &BTRFS_I(inode)->location;
6241 args.root = BTRFS_I(inode)->root;
6243 return insert_inode_locked4(inode,
6244 btrfs_inode_hash(inode->i_ino, BTRFS_I(inode)->root),
6245 btrfs_find_actor, &args);
6249 * Inherit flags from the parent inode.
6251 * Currently only the compression flags and the cow flags are inherited.
6253 static void btrfs_inherit_iflags(struct inode *inode, struct inode *dir)
6260 flags = BTRFS_I(dir)->flags;
6262 if (flags & BTRFS_INODE_NOCOMPRESS) {
6263 BTRFS_I(inode)->flags &= ~BTRFS_INODE_COMPRESS;
6264 BTRFS_I(inode)->flags |= BTRFS_INODE_NOCOMPRESS;
6265 } else if (flags & BTRFS_INODE_COMPRESS) {
6266 BTRFS_I(inode)->flags &= ~BTRFS_INODE_NOCOMPRESS;
6267 BTRFS_I(inode)->flags |= BTRFS_INODE_COMPRESS;
6270 if (flags & BTRFS_INODE_NODATACOW) {
6271 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATACOW;
6272 if (S_ISREG(inode->i_mode))
6273 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATASUM;
6276 btrfs_update_iflags(inode);
6279 static struct inode *btrfs_new_inode(struct btrfs_trans_handle *trans,
6280 struct btrfs_root *root,
6282 const char *name, int name_len,
6283 u64 ref_objectid, u64 objectid,
6284 umode_t mode, u64 *index)
6286 struct btrfs_fs_info *fs_info = root->fs_info;
6287 struct inode *inode;
6288 struct btrfs_inode_item *inode_item;
6289 struct btrfs_key *location;
6290 struct btrfs_path *path;
6291 struct btrfs_inode_ref *ref;
6292 struct btrfs_key key[2];
6294 int nitems = name ? 2 : 1;
6298 path = btrfs_alloc_path();
6300 return ERR_PTR(-ENOMEM);
6302 inode = new_inode(fs_info->sb);
6304 btrfs_free_path(path);
6305 return ERR_PTR(-ENOMEM);
6309 * O_TMPFILE, set link count to 0, so that after this point,
6310 * we fill in an inode item with the correct link count.
6313 set_nlink(inode, 0);
6316 * we have to initialize this early, so we can reclaim the inode
6317 * number if we fail afterwards in this function.
6319 inode->i_ino = objectid;
6322 trace_btrfs_inode_request(dir);
6324 ret = btrfs_set_inode_index(BTRFS_I(dir), index);
6326 btrfs_free_path(path);
6328 return ERR_PTR(ret);
6334 * index_cnt is ignored for everything but a dir,
6335 * btrfs_set_inode_index_count has an explanation for the magic
6338 BTRFS_I(inode)->index_cnt = 2;
6339 BTRFS_I(inode)->dir_index = *index;
6340 BTRFS_I(inode)->root = root;
6341 BTRFS_I(inode)->generation = trans->transid;
6342 inode->i_generation = BTRFS_I(inode)->generation;
6345 * We could have gotten an inode number from somebody who was fsynced
6346 * and then removed in this same transaction, so let's just set full
6347 * sync since it will be a full sync anyway and this will blow away the
6348 * old info in the log.
6350 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &BTRFS_I(inode)->runtime_flags);
6352 key[0].objectid = objectid;
6353 key[0].type = BTRFS_INODE_ITEM_KEY;
6356 sizes[0] = sizeof(struct btrfs_inode_item);
6360 * Start new inodes with an inode_ref. This is slightly more
6361 * efficient for small numbers of hard links since they will
6362 * be packed into one item. Extended refs will kick in if we
6363 * add more hard links than can fit in the ref item.
6365 key[1].objectid = objectid;
6366 key[1].type = BTRFS_INODE_REF_KEY;
6367 key[1].offset = ref_objectid;
6369 sizes[1] = name_len + sizeof(*ref);
6372 location = &BTRFS_I(inode)->location;
6373 location->objectid = objectid;
6374 location->offset = 0;
6375 location->type = BTRFS_INODE_ITEM_KEY;
6377 ret = btrfs_insert_inode_locked(inode);
6381 path->leave_spinning = 1;
6382 ret = btrfs_insert_empty_items(trans, root, path, key, sizes, nitems);
6386 inode_init_owner(inode, dir, mode);
6387 inode_set_bytes(inode, 0);
6389 inode->i_mtime = current_time(inode);
6390 inode->i_atime = inode->i_mtime;
6391 inode->i_ctime = inode->i_mtime;
6392 BTRFS_I(inode)->i_otime = inode->i_mtime;
6394 inode_item = btrfs_item_ptr(path->nodes[0], path->slots[0],
6395 struct btrfs_inode_item);
6396 memzero_extent_buffer(path->nodes[0], (unsigned long)inode_item,
6397 sizeof(*inode_item));
6398 fill_inode_item(trans, path->nodes[0], inode_item, inode);
6401 ref = btrfs_item_ptr(path->nodes[0], path->slots[0] + 1,
6402 struct btrfs_inode_ref);
6403 btrfs_set_inode_ref_name_len(path->nodes[0], ref, name_len);
6404 btrfs_set_inode_ref_index(path->nodes[0], ref, *index);
6405 ptr = (unsigned long)(ref + 1);
6406 write_extent_buffer(path->nodes[0], name, ptr, name_len);
6409 btrfs_mark_buffer_dirty(path->nodes[0]);
6410 btrfs_free_path(path);
6412 btrfs_inherit_iflags(inode, dir);
6414 if (S_ISREG(mode)) {
6415 if (btrfs_test_opt(fs_info, NODATASUM))
6416 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATASUM;
6417 if (btrfs_test_opt(fs_info, NODATACOW))
6418 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATACOW |
6419 BTRFS_INODE_NODATASUM;
6422 inode_tree_add(inode);
6424 trace_btrfs_inode_new(inode);
6425 btrfs_set_inode_last_trans(trans, inode);
6427 btrfs_update_root_times(trans, root);
6429 ret = btrfs_inode_inherit_props(trans, inode, dir);
6432 "error inheriting props for ino %llu (root %llu): %d",
6433 btrfs_ino(BTRFS_I(inode)), root->root_key.objectid, ret);
6438 unlock_new_inode(inode);
6441 BTRFS_I(dir)->index_cnt--;
6442 btrfs_free_path(path);
6444 return ERR_PTR(ret);
6447 static inline u8 btrfs_inode_type(struct inode *inode)
6449 return btrfs_type_by_mode[(inode->i_mode & S_IFMT) >> S_SHIFT];
6453 * utility function to add 'inode' into 'parent_inode' with
6454 * a give name and a given sequence number.
6455 * if 'add_backref' is true, also insert a backref from the
6456 * inode to the parent directory.
6458 int btrfs_add_link(struct btrfs_trans_handle *trans,
6459 struct btrfs_inode *parent_inode, struct btrfs_inode *inode,
6460 const char *name, int name_len, int add_backref, u64 index)
6462 struct btrfs_fs_info *fs_info = btrfs_sb(inode->vfs_inode.i_sb);
6464 struct btrfs_key key;
6465 struct btrfs_root *root = parent_inode->root;
6466 u64 ino = btrfs_ino(inode);
6467 u64 parent_ino = btrfs_ino(parent_inode);
6469 if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
6470 memcpy(&key, &inode->root->root_key, sizeof(key));
6473 key.type = BTRFS_INODE_ITEM_KEY;
6477 if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
6478 ret = btrfs_add_root_ref(trans, fs_info, key.objectid,
6479 root->root_key.objectid, parent_ino,
6480 index, name, name_len);
6481 } else if (add_backref) {
6482 ret = btrfs_insert_inode_ref(trans, root, name, name_len, ino,
6486 /* Nothing to clean up yet */
6490 ret = btrfs_insert_dir_item(trans, root, name, name_len,
6492 btrfs_inode_type(&inode->vfs_inode), index);
6493 if (ret == -EEXIST || ret == -EOVERFLOW)
6496 btrfs_abort_transaction(trans, ret);
6500 btrfs_i_size_write(parent_inode, parent_inode->vfs_inode.i_size +
6502 inode_inc_iversion(&parent_inode->vfs_inode);
6503 parent_inode->vfs_inode.i_mtime = parent_inode->vfs_inode.i_ctime =
6504 current_time(&parent_inode->vfs_inode);
6505 ret = btrfs_update_inode(trans, root, &parent_inode->vfs_inode);
6507 btrfs_abort_transaction(trans, ret);
6511 if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
6514 err = btrfs_del_root_ref(trans, fs_info, key.objectid,
6515 root->root_key.objectid, parent_ino,
6516 &local_index, name, name_len);
6518 } else if (add_backref) {
6522 err = btrfs_del_inode_ref(trans, root, name, name_len,
6523 ino, parent_ino, &local_index);
6528 static int btrfs_add_nondir(struct btrfs_trans_handle *trans,
6529 struct btrfs_inode *dir, struct dentry *dentry,
6530 struct btrfs_inode *inode, int backref, u64 index)
6532 int err = btrfs_add_link(trans, dir, inode,
6533 dentry->d_name.name, dentry->d_name.len,
6540 static int btrfs_mknod(struct inode *dir, struct dentry *dentry,
6541 umode_t mode, dev_t rdev)
6543 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
6544 struct btrfs_trans_handle *trans;
6545 struct btrfs_root *root = BTRFS_I(dir)->root;
6546 struct inode *inode = NULL;
6553 * 2 for inode item and ref
6555 * 1 for xattr if selinux is on
6557 trans = btrfs_start_transaction(root, 5);
6559 return PTR_ERR(trans);
6561 err = btrfs_find_free_ino(root, &objectid);
6565 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
6566 dentry->d_name.len, btrfs_ino(BTRFS_I(dir)), objectid,
6568 if (IS_ERR(inode)) {
6569 err = PTR_ERR(inode);
6574 * If the active LSM wants to access the inode during
6575 * d_instantiate it needs these. Smack checks to see
6576 * if the filesystem supports xattrs by looking at the
6579 inode->i_op = &btrfs_special_inode_operations;
6580 init_special_inode(inode, inode->i_mode, rdev);
6582 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
6584 goto out_unlock_inode;
6586 err = btrfs_add_nondir(trans, BTRFS_I(dir), dentry, BTRFS_I(inode),
6589 goto out_unlock_inode;
6591 btrfs_update_inode(trans, root, inode);
6592 unlock_new_inode(inode);
6593 d_instantiate(dentry, inode);
6597 btrfs_end_transaction(trans);
6598 btrfs_btree_balance_dirty(fs_info);
6600 inode_dec_link_count(inode);
6607 unlock_new_inode(inode);
6612 static int btrfs_create(struct inode *dir, struct dentry *dentry,
6613 umode_t mode, bool excl)
6615 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
6616 struct btrfs_trans_handle *trans;
6617 struct btrfs_root *root = BTRFS_I(dir)->root;
6618 struct inode *inode = NULL;
6619 int drop_inode_on_err = 0;
6625 * 2 for inode item and ref
6627 * 1 for xattr if selinux is on
6629 trans = btrfs_start_transaction(root, 5);
6631 return PTR_ERR(trans);
6633 err = btrfs_find_free_ino(root, &objectid);
6637 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
6638 dentry->d_name.len, btrfs_ino(BTRFS_I(dir)), objectid,
6640 if (IS_ERR(inode)) {
6641 err = PTR_ERR(inode);
6644 drop_inode_on_err = 1;
6646 * If the active LSM wants to access the inode during
6647 * d_instantiate it needs these. Smack checks to see
6648 * if the filesystem supports xattrs by looking at the
6651 inode->i_fop = &btrfs_file_operations;
6652 inode->i_op = &btrfs_file_inode_operations;
6653 inode->i_mapping->a_ops = &btrfs_aops;
6655 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
6657 goto out_unlock_inode;
6659 err = btrfs_update_inode(trans, root, inode);
6661 goto out_unlock_inode;
6663 err = btrfs_add_nondir(trans, BTRFS_I(dir), dentry, BTRFS_I(inode),
6666 goto out_unlock_inode;
6668 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
6669 unlock_new_inode(inode);
6670 d_instantiate(dentry, inode);
6673 btrfs_end_transaction(trans);
6674 if (err && drop_inode_on_err) {
6675 inode_dec_link_count(inode);
6678 btrfs_btree_balance_dirty(fs_info);
6682 unlock_new_inode(inode);
6687 static int btrfs_link(struct dentry *old_dentry, struct inode *dir,
6688 struct dentry *dentry)
6690 struct btrfs_trans_handle *trans = NULL;
6691 struct btrfs_root *root = BTRFS_I(dir)->root;
6692 struct inode *inode = d_inode(old_dentry);
6693 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
6698 /* do not allow sys_link's with other subvols of the same device */
6699 if (root->objectid != BTRFS_I(inode)->root->objectid)
6702 if (inode->i_nlink >= BTRFS_LINK_MAX)
6705 err = btrfs_set_inode_index(BTRFS_I(dir), &index);
6710 * 2 items for inode and inode ref
6711 * 2 items for dir items
6712 * 1 item for parent inode
6714 trans = btrfs_start_transaction(root, 5);
6715 if (IS_ERR(trans)) {
6716 err = PTR_ERR(trans);
6721 /* There are several dir indexes for this inode, clear the cache. */
6722 BTRFS_I(inode)->dir_index = 0ULL;
6724 inode_inc_iversion(inode);
6725 inode->i_ctime = current_time(inode);
6727 set_bit(BTRFS_INODE_COPY_EVERYTHING, &BTRFS_I(inode)->runtime_flags);
6729 err = btrfs_add_nondir(trans, BTRFS_I(dir), dentry, BTRFS_I(inode),
6735 struct dentry *parent = dentry->d_parent;
6736 err = btrfs_update_inode(trans, root, inode);
6739 if (inode->i_nlink == 1) {
6741 * If new hard link count is 1, it's a file created
6742 * with open(2) O_TMPFILE flag.
6744 err = btrfs_orphan_del(trans, BTRFS_I(inode));
6748 d_instantiate(dentry, inode);
6749 btrfs_log_new_name(trans, BTRFS_I(inode), NULL, parent);
6754 btrfs_end_transaction(trans);
6756 inode_dec_link_count(inode);
6759 btrfs_btree_balance_dirty(fs_info);
6763 static int btrfs_mkdir(struct inode *dir, struct dentry *dentry, umode_t mode)
6765 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
6766 struct inode *inode = NULL;
6767 struct btrfs_trans_handle *trans;
6768 struct btrfs_root *root = BTRFS_I(dir)->root;
6770 int drop_on_err = 0;
6775 * 2 items for inode and ref
6776 * 2 items for dir items
6777 * 1 for xattr if selinux is on
6779 trans = btrfs_start_transaction(root, 5);
6781 return PTR_ERR(trans);
6783 err = btrfs_find_free_ino(root, &objectid);
6787 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
6788 dentry->d_name.len, btrfs_ino(BTRFS_I(dir)), objectid,
6789 S_IFDIR | mode, &index);
6790 if (IS_ERR(inode)) {
6791 err = PTR_ERR(inode);
6796 /* these must be set before we unlock the inode */
6797 inode->i_op = &btrfs_dir_inode_operations;
6798 inode->i_fop = &btrfs_dir_file_operations;
6800 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
6802 goto out_fail_inode;
6804 btrfs_i_size_write(BTRFS_I(inode), 0);
6805 err = btrfs_update_inode(trans, root, inode);
6807 goto out_fail_inode;
6809 err = btrfs_add_link(trans, BTRFS_I(dir), BTRFS_I(inode),
6810 dentry->d_name.name,
6811 dentry->d_name.len, 0, index);
6813 goto out_fail_inode;
6815 d_instantiate(dentry, inode);
6817 * mkdir is special. We're unlocking after we call d_instantiate
6818 * to avoid a race with nfsd calling d_instantiate.
6820 unlock_new_inode(inode);
6824 btrfs_end_transaction(trans);
6826 inode_dec_link_count(inode);
6829 btrfs_btree_balance_dirty(fs_info);
6833 unlock_new_inode(inode);
6837 static noinline int uncompress_inline(struct btrfs_path *path,
6839 size_t pg_offset, u64 extent_offset,
6840 struct btrfs_file_extent_item *item)
6843 struct extent_buffer *leaf = path->nodes[0];
6846 unsigned long inline_size;
6850 WARN_ON(pg_offset != 0);
6851 compress_type = btrfs_file_extent_compression(leaf, item);
6852 max_size = btrfs_file_extent_ram_bytes(leaf, item);
6853 inline_size = btrfs_file_extent_inline_item_len(leaf,
6854 btrfs_item_nr(path->slots[0]));
6855 tmp = kmalloc(inline_size, GFP_NOFS);
6858 ptr = btrfs_file_extent_inline_start(item);
6860 read_extent_buffer(leaf, tmp, ptr, inline_size);
6862 max_size = min_t(unsigned long, PAGE_SIZE, max_size);
6863 ret = btrfs_decompress(compress_type, tmp, page,
6864 extent_offset, inline_size, max_size);
6867 * decompression code contains a memset to fill in any space between the end
6868 * of the uncompressed data and the end of max_size in case the decompressed
6869 * data ends up shorter than ram_bytes. That doesn't cover the hole between
6870 * the end of an inline extent and the beginning of the next block, so we
6871 * cover that region here.
6874 if (max_size + pg_offset < PAGE_SIZE) {
6875 char *map = kmap(page);
6876 memset(map + pg_offset + max_size, 0, PAGE_SIZE - max_size - pg_offset);
6884 * a bit scary, this does extent mapping from logical file offset to the disk.
6885 * the ugly parts come from merging extents from the disk with the in-ram
6886 * representation. This gets more complex because of the data=ordered code,
6887 * where the in-ram extents might be locked pending data=ordered completion.
6889 * This also copies inline extents directly into the page.
6891 struct extent_map *btrfs_get_extent(struct btrfs_inode *inode,
6893 size_t pg_offset, u64 start, u64 len,
6896 struct btrfs_fs_info *fs_info = btrfs_sb(inode->vfs_inode.i_sb);
6899 u64 extent_start = 0;
6901 u64 objectid = btrfs_ino(inode);
6903 struct btrfs_path *path = NULL;
6904 struct btrfs_root *root = inode->root;
6905 struct btrfs_file_extent_item *item;
6906 struct extent_buffer *leaf;
6907 struct btrfs_key found_key;
6908 struct extent_map *em = NULL;
6909 struct extent_map_tree *em_tree = &inode->extent_tree;
6910 struct extent_io_tree *io_tree = &inode->io_tree;
6911 const bool new_inline = !page || create;
6913 read_lock(&em_tree->lock);
6914 em = lookup_extent_mapping(em_tree, start, len);
6916 em->bdev = fs_info->fs_devices->latest_bdev;
6917 read_unlock(&em_tree->lock);
6920 if (em->start > start || em->start + em->len <= start)
6921 free_extent_map(em);
6922 else if (em->block_start == EXTENT_MAP_INLINE && page)
6923 free_extent_map(em);
6927 em = alloc_extent_map();
6932 em->bdev = fs_info->fs_devices->latest_bdev;
6933 em->start = EXTENT_MAP_HOLE;
6934 em->orig_start = EXTENT_MAP_HOLE;
6936 em->block_len = (u64)-1;
6939 path = btrfs_alloc_path();
6945 * Chances are we'll be called again, so go ahead and do
6948 path->reada = READA_FORWARD;
6951 ret = btrfs_lookup_file_extent(NULL, root, path, objectid, start, 0);
6958 if (path->slots[0] == 0)
6963 leaf = path->nodes[0];
6964 item = btrfs_item_ptr(leaf, path->slots[0],
6965 struct btrfs_file_extent_item);
6966 /* are we inside the extent that was found? */
6967 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
6968 found_type = found_key.type;
6969 if (found_key.objectid != objectid ||
6970 found_type != BTRFS_EXTENT_DATA_KEY) {
6972 * If we backup past the first extent we want to move forward
6973 * and see if there is an extent in front of us, otherwise we'll
6974 * say there is a hole for our whole search range which can
6981 found_type = btrfs_file_extent_type(leaf, item);
6982 extent_start = found_key.offset;
6983 if (found_type == BTRFS_FILE_EXTENT_REG ||
6984 found_type == BTRFS_FILE_EXTENT_PREALLOC) {
6985 extent_end = extent_start +
6986 btrfs_file_extent_num_bytes(leaf, item);
6988 trace_btrfs_get_extent_show_fi_regular(inode, leaf, item,
6990 } else if (found_type == BTRFS_FILE_EXTENT_INLINE) {
6992 size = btrfs_file_extent_inline_len(leaf, path->slots[0], item);
6993 extent_end = ALIGN(extent_start + size,
6994 fs_info->sectorsize);
6996 trace_btrfs_get_extent_show_fi_inline(inode, leaf, item,
7001 if (start >= extent_end) {
7003 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
7004 ret = btrfs_next_leaf(root, path);
7011 leaf = path->nodes[0];
7013 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
7014 if (found_key.objectid != objectid ||
7015 found_key.type != BTRFS_EXTENT_DATA_KEY)
7017 if (start + len <= found_key.offset)
7019 if (start > found_key.offset)
7022 em->orig_start = start;
7023 em->len = found_key.offset - start;
7027 btrfs_extent_item_to_extent_map(inode, path, item,
7030 if (found_type == BTRFS_FILE_EXTENT_REG ||
7031 found_type == BTRFS_FILE_EXTENT_PREALLOC) {
7033 } else if (found_type == BTRFS_FILE_EXTENT_INLINE) {
7037 size_t extent_offset;
7043 size = btrfs_file_extent_inline_len(leaf, path->slots[0], item);
7044 extent_offset = page_offset(page) + pg_offset - extent_start;
7045 copy_size = min_t(u64, PAGE_SIZE - pg_offset,
7046 size - extent_offset);
7047 em->start = extent_start + extent_offset;
7048 em->len = ALIGN(copy_size, fs_info->sectorsize);
7049 em->orig_block_len = em->len;
7050 em->orig_start = em->start;
7051 ptr = btrfs_file_extent_inline_start(item) + extent_offset;
7052 if (!PageUptodate(page)) {
7053 if (btrfs_file_extent_compression(leaf, item) !=
7054 BTRFS_COMPRESS_NONE) {
7055 ret = uncompress_inline(path, page, pg_offset,
7056 extent_offset, item);
7063 read_extent_buffer(leaf, map + pg_offset, ptr,
7065 if (pg_offset + copy_size < PAGE_SIZE) {
7066 memset(map + pg_offset + copy_size, 0,
7067 PAGE_SIZE - pg_offset -
7072 flush_dcache_page(page);
7074 set_extent_uptodate(io_tree, em->start,
7075 extent_map_end(em) - 1, NULL, GFP_NOFS);
7080 em->orig_start = start;
7083 em->block_start = EXTENT_MAP_HOLE;
7085 btrfs_release_path(path);
7086 if (em->start > start || extent_map_end(em) <= start) {
7088 "bad extent! em: [%llu %llu] passed [%llu %llu]",
7089 em->start, em->len, start, len);
7095 write_lock(&em_tree->lock);
7096 err = btrfs_add_extent_mapping(em_tree, &em, start, len);
7097 write_unlock(&em_tree->lock);
7100 trace_btrfs_get_extent(root, inode, em);
7102 btrfs_free_path(path);
7104 free_extent_map(em);
7105 return ERR_PTR(err);
7107 BUG_ON(!em); /* Error is always set */
7111 struct extent_map *btrfs_get_extent_fiemap(struct btrfs_inode *inode,
7113 size_t pg_offset, u64 start, u64 len,
7116 struct extent_map *em;
7117 struct extent_map *hole_em = NULL;
7118 u64 range_start = start;
7124 em = btrfs_get_extent(inode, page, pg_offset, start, len, create);
7128 * If our em maps to:
7130 * - a pre-alloc extent,
7131 * there might actually be delalloc bytes behind it.
7133 if (em->block_start != EXTENT_MAP_HOLE &&
7134 !test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
7139 /* check to see if we've wrapped (len == -1 or similar) */
7148 /* ok, we didn't find anything, lets look for delalloc */
7149 found = count_range_bits(&inode->io_tree, &range_start,
7150 end, len, EXTENT_DELALLOC, 1);
7151 found_end = range_start + found;
7152 if (found_end < range_start)
7153 found_end = (u64)-1;
7156 * we didn't find anything useful, return
7157 * the original results from get_extent()
7159 if (range_start > end || found_end <= start) {
7165 /* adjust the range_start to make sure it doesn't
7166 * go backwards from the start they passed in
7168 range_start = max(start, range_start);
7169 found = found_end - range_start;
7172 u64 hole_start = start;
7175 em = alloc_extent_map();
7181 * when btrfs_get_extent can't find anything it
7182 * returns one huge hole
7184 * make sure what it found really fits our range, and
7185 * adjust to make sure it is based on the start from
7189 u64 calc_end = extent_map_end(hole_em);
7191 if (calc_end <= start || (hole_em->start > end)) {
7192 free_extent_map(hole_em);
7195 hole_start = max(hole_em->start, start);
7196 hole_len = calc_end - hole_start;
7200 if (hole_em && range_start > hole_start) {
7201 /* our hole starts before our delalloc, so we
7202 * have to return just the parts of the hole
7203 * that go until the delalloc starts
7205 em->len = min(hole_len,
7206 range_start - hole_start);
7207 em->start = hole_start;
7208 em->orig_start = hole_start;
7210 * don't adjust block start at all,
7211 * it is fixed at EXTENT_MAP_HOLE
7213 em->block_start = hole_em->block_start;
7214 em->block_len = hole_len;
7215 if (test_bit(EXTENT_FLAG_PREALLOC, &hole_em->flags))
7216 set_bit(EXTENT_FLAG_PREALLOC, &em->flags);
7218 em->start = range_start;
7220 em->orig_start = range_start;
7221 em->block_start = EXTENT_MAP_DELALLOC;
7222 em->block_len = found;
7229 free_extent_map(hole_em);
7231 free_extent_map(em);
7232 return ERR_PTR(err);
7237 static struct extent_map *btrfs_create_dio_extent(struct inode *inode,
7240 const u64 orig_start,
7241 const u64 block_start,
7242 const u64 block_len,
7243 const u64 orig_block_len,
7244 const u64 ram_bytes,
7247 struct extent_map *em = NULL;
7250 if (type != BTRFS_ORDERED_NOCOW) {
7251 em = create_io_em(inode, start, len, orig_start,
7252 block_start, block_len, orig_block_len,
7254 BTRFS_COMPRESS_NONE, /* compress_type */
7259 ret = btrfs_add_ordered_extent_dio(inode, start, block_start,
7260 len, block_len, type);
7263 free_extent_map(em);
7264 btrfs_drop_extent_cache(BTRFS_I(inode), start,
7265 start + len - 1, 0);
7274 static struct extent_map *btrfs_new_extent_direct(struct inode *inode,
7277 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7278 struct btrfs_root *root = BTRFS_I(inode)->root;
7279 struct extent_map *em;
7280 struct btrfs_key ins;
7284 alloc_hint = get_extent_allocation_hint(inode, start, len);
7285 ret = btrfs_reserve_extent(root, len, len, fs_info->sectorsize,
7286 0, alloc_hint, &ins, 1, 1);
7288 return ERR_PTR(ret);
7290 em = btrfs_create_dio_extent(inode, start, ins.offset, start,
7291 ins.objectid, ins.offset, ins.offset,
7292 ins.offset, BTRFS_ORDERED_REGULAR);
7293 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
7295 btrfs_free_reserved_extent(fs_info, ins.objectid,
7302 * returns 1 when the nocow is safe, < 1 on error, 0 if the
7303 * block must be cow'd
7305 noinline int can_nocow_extent(struct inode *inode, u64 offset, u64 *len,
7306 u64 *orig_start, u64 *orig_block_len,
7309 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7310 struct btrfs_path *path;
7312 struct extent_buffer *leaf;
7313 struct btrfs_root *root = BTRFS_I(inode)->root;
7314 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
7315 struct btrfs_file_extent_item *fi;
7316 struct btrfs_key key;
7323 bool nocow = (BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW);
7325 path = btrfs_alloc_path();
7329 ret = btrfs_lookup_file_extent(NULL, root, path,
7330 btrfs_ino(BTRFS_I(inode)), offset, 0);
7334 slot = path->slots[0];
7337 /* can't find the item, must cow */
7344 leaf = path->nodes[0];
7345 btrfs_item_key_to_cpu(leaf, &key, slot);
7346 if (key.objectid != btrfs_ino(BTRFS_I(inode)) ||
7347 key.type != BTRFS_EXTENT_DATA_KEY) {
7348 /* not our file or wrong item type, must cow */
7352 if (key.offset > offset) {
7353 /* Wrong offset, must cow */
7357 fi = btrfs_item_ptr(leaf, slot, struct btrfs_file_extent_item);
7358 found_type = btrfs_file_extent_type(leaf, fi);
7359 if (found_type != BTRFS_FILE_EXTENT_REG &&
7360 found_type != BTRFS_FILE_EXTENT_PREALLOC) {
7361 /* not a regular extent, must cow */
7365 if (!nocow && found_type == BTRFS_FILE_EXTENT_REG)
7368 extent_end = key.offset + btrfs_file_extent_num_bytes(leaf, fi);
7369 if (extent_end <= offset)
7372 disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
7373 if (disk_bytenr == 0)
7376 if (btrfs_file_extent_compression(leaf, fi) ||
7377 btrfs_file_extent_encryption(leaf, fi) ||
7378 btrfs_file_extent_other_encoding(leaf, fi))
7381 backref_offset = btrfs_file_extent_offset(leaf, fi);
7384 *orig_start = key.offset - backref_offset;
7385 *orig_block_len = btrfs_file_extent_disk_num_bytes(leaf, fi);
7386 *ram_bytes = btrfs_file_extent_ram_bytes(leaf, fi);
7389 if (btrfs_extent_readonly(fs_info, disk_bytenr))
7392 num_bytes = min(offset + *len, extent_end) - offset;
7393 if (!nocow && found_type == BTRFS_FILE_EXTENT_PREALLOC) {
7396 range_end = round_up(offset + num_bytes,
7397 root->fs_info->sectorsize) - 1;
7398 ret = test_range_bit(io_tree, offset, range_end,
7399 EXTENT_DELALLOC, 0, NULL);
7406 btrfs_release_path(path);
7409 * look for other files referencing this extent, if we
7410 * find any we must cow
7413 ret = btrfs_cross_ref_exist(root, btrfs_ino(BTRFS_I(inode)),
7414 key.offset - backref_offset, disk_bytenr);
7421 * adjust disk_bytenr and num_bytes to cover just the bytes
7422 * in this extent we are about to write. If there
7423 * are any csums in that range we have to cow in order
7424 * to keep the csums correct
7426 disk_bytenr += backref_offset;
7427 disk_bytenr += offset - key.offset;
7428 if (csum_exist_in_range(fs_info, disk_bytenr, num_bytes))
7431 * all of the above have passed, it is safe to overwrite this extent
7437 btrfs_free_path(path);
7441 bool btrfs_page_exists_in_range(struct inode *inode, loff_t start, loff_t end)
7443 struct radix_tree_root *root = &inode->i_mapping->page_tree;
7445 void **pagep = NULL;
7446 struct page *page = NULL;
7447 unsigned long start_idx;
7448 unsigned long end_idx;
7450 start_idx = start >> PAGE_SHIFT;
7453 * end is the last byte in the last page. end == start is legal
7455 end_idx = end >> PAGE_SHIFT;
7459 /* Most of the code in this while loop is lifted from
7460 * find_get_page. It's been modified to begin searching from a
7461 * page and return just the first page found in that range. If the
7462 * found idx is less than or equal to the end idx then we know that
7463 * a page exists. If no pages are found or if those pages are
7464 * outside of the range then we're fine (yay!) */
7465 while (page == NULL &&
7466 radix_tree_gang_lookup_slot(root, &pagep, NULL, start_idx, 1)) {
7467 page = radix_tree_deref_slot(pagep);
7468 if (unlikely(!page))
7471 if (radix_tree_exception(page)) {
7472 if (radix_tree_deref_retry(page)) {
7477 * Otherwise, shmem/tmpfs must be storing a swap entry
7478 * here as an exceptional entry: so return it without
7479 * attempting to raise page count.
7482 break; /* TODO: Is this relevant for this use case? */
7485 if (!page_cache_get_speculative(page)) {
7491 * Has the page moved?
7492 * This is part of the lockless pagecache protocol. See
7493 * include/linux/pagemap.h for details.
7495 if (unlikely(page != *pagep)) {
7502 if (page->index <= end_idx)
7511 static int lock_extent_direct(struct inode *inode, u64 lockstart, u64 lockend,
7512 struct extent_state **cached_state, int writing)
7514 struct btrfs_ordered_extent *ordered;
7518 lock_extent_bits(&BTRFS_I(inode)->io_tree, lockstart, lockend,
7521 * We're concerned with the entire range that we're going to be
7522 * doing DIO to, so we need to make sure there's no ordered
7523 * extents in this range.
7525 ordered = btrfs_lookup_ordered_range(BTRFS_I(inode), lockstart,
7526 lockend - lockstart + 1);
7529 * We need to make sure there are no buffered pages in this
7530 * range either, we could have raced between the invalidate in
7531 * generic_file_direct_write and locking the extent. The
7532 * invalidate needs to happen so that reads after a write do not
7537 !btrfs_page_exists_in_range(inode, lockstart, lockend)))
7540 unlock_extent_cached(&BTRFS_I(inode)->io_tree, lockstart, lockend,
7545 * If we are doing a DIO read and the ordered extent we
7546 * found is for a buffered write, we can not wait for it
7547 * to complete and retry, because if we do so we can
7548 * deadlock with concurrent buffered writes on page
7549 * locks. This happens only if our DIO read covers more
7550 * than one extent map, if at this point has already
7551 * created an ordered extent for a previous extent map
7552 * and locked its range in the inode's io tree, and a
7553 * concurrent write against that previous extent map's
7554 * range and this range started (we unlock the ranges
7555 * in the io tree only when the bios complete and
7556 * buffered writes always lock pages before attempting
7557 * to lock range in the io tree).
7560 test_bit(BTRFS_ORDERED_DIRECT, &ordered->flags))
7561 btrfs_start_ordered_extent(inode, ordered, 1);
7564 btrfs_put_ordered_extent(ordered);
7567 * We could trigger writeback for this range (and wait
7568 * for it to complete) and then invalidate the pages for
7569 * this range (through invalidate_inode_pages2_range()),
7570 * but that can lead us to a deadlock with a concurrent
7571 * call to readpages() (a buffered read or a defrag call
7572 * triggered a readahead) on a page lock due to an
7573 * ordered dio extent we created before but did not have
7574 * yet a corresponding bio submitted (whence it can not
7575 * complete), which makes readpages() wait for that
7576 * ordered extent to complete while holding a lock on
7591 /* The callers of this must take lock_extent() */
7592 static struct extent_map *create_io_em(struct inode *inode, u64 start, u64 len,
7593 u64 orig_start, u64 block_start,
7594 u64 block_len, u64 orig_block_len,
7595 u64 ram_bytes, int compress_type,
7598 struct extent_map_tree *em_tree;
7599 struct extent_map *em;
7600 struct btrfs_root *root = BTRFS_I(inode)->root;
7603 ASSERT(type == BTRFS_ORDERED_PREALLOC ||
7604 type == BTRFS_ORDERED_COMPRESSED ||
7605 type == BTRFS_ORDERED_NOCOW ||
7606 type == BTRFS_ORDERED_REGULAR);
7608 em_tree = &BTRFS_I(inode)->extent_tree;
7609 em = alloc_extent_map();
7611 return ERR_PTR(-ENOMEM);
7614 em->orig_start = orig_start;
7616 em->block_len = block_len;
7617 em->block_start = block_start;
7618 em->bdev = root->fs_info->fs_devices->latest_bdev;
7619 em->orig_block_len = orig_block_len;
7620 em->ram_bytes = ram_bytes;
7621 em->generation = -1;
7622 set_bit(EXTENT_FLAG_PINNED, &em->flags);
7623 if (type == BTRFS_ORDERED_PREALLOC) {
7624 set_bit(EXTENT_FLAG_FILLING, &em->flags);
7625 } else if (type == BTRFS_ORDERED_COMPRESSED) {
7626 set_bit(EXTENT_FLAG_COMPRESSED, &em->flags);
7627 em->compress_type = compress_type;
7631 btrfs_drop_extent_cache(BTRFS_I(inode), em->start,
7632 em->start + em->len - 1, 0);
7633 write_lock(&em_tree->lock);
7634 ret = add_extent_mapping(em_tree, em, 1);
7635 write_unlock(&em_tree->lock);
7637 * The caller has taken lock_extent(), who could race with us
7640 } while (ret == -EEXIST);
7643 free_extent_map(em);
7644 return ERR_PTR(ret);
7647 /* em got 2 refs now, callers needs to do free_extent_map once. */
7651 static int btrfs_get_blocks_direct(struct inode *inode, sector_t iblock,
7652 struct buffer_head *bh_result, int create)
7654 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7655 struct extent_map *em;
7656 struct extent_state *cached_state = NULL;
7657 struct btrfs_dio_data *dio_data = NULL;
7658 u64 start = iblock << inode->i_blkbits;
7659 u64 lockstart, lockend;
7660 u64 len = bh_result->b_size;
7661 int unlock_bits = EXTENT_LOCKED;
7665 unlock_bits |= EXTENT_DIRTY;
7667 len = min_t(u64, len, fs_info->sectorsize);
7670 lockend = start + len - 1;
7672 if (current->journal_info) {
7674 * Need to pull our outstanding extents and set journal_info to NULL so
7675 * that anything that needs to check if there's a transaction doesn't get
7678 dio_data = current->journal_info;
7679 current->journal_info = NULL;
7683 * If this errors out it's because we couldn't invalidate pagecache for
7684 * this range and we need to fallback to buffered.
7686 if (lock_extent_direct(inode, lockstart, lockend, &cached_state,
7692 em = btrfs_get_extent(BTRFS_I(inode), NULL, 0, start, len, 0);
7699 * Ok for INLINE and COMPRESSED extents we need to fallback on buffered
7700 * io. INLINE is special, and we could probably kludge it in here, but
7701 * it's still buffered so for safety lets just fall back to the generic
7704 * For COMPRESSED we _have_ to read the entire extent in so we can
7705 * decompress it, so there will be buffering required no matter what we
7706 * do, so go ahead and fallback to buffered.
7708 * We return -ENOTBLK because that's what makes DIO go ahead and go back
7709 * to buffered IO. Don't blame me, this is the price we pay for using
7712 if (test_bit(EXTENT_FLAG_COMPRESSED, &em->flags) ||
7713 em->block_start == EXTENT_MAP_INLINE) {
7714 free_extent_map(em);
7719 /* Just a good old fashioned hole, return */
7720 if (!create && (em->block_start == EXTENT_MAP_HOLE ||
7721 test_bit(EXTENT_FLAG_PREALLOC, &em->flags))) {
7722 free_extent_map(em);
7727 * We don't allocate a new extent in the following cases
7729 * 1) The inode is marked as NODATACOW. In this case we'll just use the
7731 * 2) The extent is marked as PREALLOC. We're good to go here and can
7732 * just use the extent.
7736 len = min(len, em->len - (start - em->start));
7737 lockstart = start + len;
7741 if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags) ||
7742 ((BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW) &&
7743 em->block_start != EXTENT_MAP_HOLE)) {
7745 u64 block_start, orig_start, orig_block_len, ram_bytes;
7747 if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
7748 type = BTRFS_ORDERED_PREALLOC;
7750 type = BTRFS_ORDERED_NOCOW;
7751 len = min(len, em->len - (start - em->start));
7752 block_start = em->block_start + (start - em->start);
7754 if (can_nocow_extent(inode, start, &len, &orig_start,
7755 &orig_block_len, &ram_bytes) == 1 &&
7756 btrfs_inc_nocow_writers(fs_info, block_start)) {
7757 struct extent_map *em2;
7759 em2 = btrfs_create_dio_extent(inode, start, len,
7760 orig_start, block_start,
7761 len, orig_block_len,
7763 btrfs_dec_nocow_writers(fs_info, block_start);
7764 if (type == BTRFS_ORDERED_PREALLOC) {
7765 free_extent_map(em);
7768 if (em2 && IS_ERR(em2)) {
7773 * For inode marked NODATACOW or extent marked PREALLOC,
7774 * use the existing or preallocated extent, so does not
7775 * need to adjust btrfs_space_info's bytes_may_use.
7777 btrfs_free_reserved_data_space_noquota(inode,
7784 * this will cow the extent, reset the len in case we changed
7787 len = bh_result->b_size;
7788 free_extent_map(em);
7789 em = btrfs_new_extent_direct(inode, start, len);
7794 len = min(len, em->len - (start - em->start));
7796 bh_result->b_blocknr = (em->block_start + (start - em->start)) >>
7798 bh_result->b_size = len;
7799 bh_result->b_bdev = em->bdev;
7800 set_buffer_mapped(bh_result);
7802 if (!test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
7803 set_buffer_new(bh_result);
7806 * Need to update the i_size under the extent lock so buffered
7807 * readers will get the updated i_size when we unlock.
7809 if (!dio_data->overwrite && start + len > i_size_read(inode))
7810 i_size_write(inode, start + len);
7812 WARN_ON(dio_data->reserve < len);
7813 dio_data->reserve -= len;
7814 dio_data->unsubmitted_oe_range_end = start + len;
7815 current->journal_info = dio_data;
7819 * In the case of write we need to clear and unlock the entire range,
7820 * in the case of read we need to unlock only the end area that we
7821 * aren't using if there is any left over space.
7823 if (lockstart < lockend) {
7824 clear_extent_bit(&BTRFS_I(inode)->io_tree, lockstart,
7825 lockend, unlock_bits, 1, 0,
7828 free_extent_state(cached_state);
7831 free_extent_map(em);
7836 clear_extent_bit(&BTRFS_I(inode)->io_tree, lockstart, lockend,
7837 unlock_bits, 1, 0, &cached_state);
7840 current->journal_info = dio_data;
7844 static inline blk_status_t submit_dio_repair_bio(struct inode *inode,
7848 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7851 BUG_ON(bio_op(bio) == REQ_OP_WRITE);
7853 ret = btrfs_bio_wq_end_io(fs_info, bio, BTRFS_WQ_ENDIO_DIO_REPAIR);
7857 ret = btrfs_map_bio(fs_info, bio, mirror_num, 0);
7862 static int btrfs_check_dio_repairable(struct inode *inode,
7863 struct bio *failed_bio,
7864 struct io_failure_record *failrec,
7867 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7870 num_copies = btrfs_num_copies(fs_info, failrec->logical, failrec->len);
7871 if (num_copies == 1) {
7873 * we only have a single copy of the data, so don't bother with
7874 * all the retry and error correction code that follows. no
7875 * matter what the error is, it is very likely to persist.
7877 btrfs_debug(fs_info,
7878 "Check DIO Repairable: cannot repair, num_copies=%d, next_mirror %d, failed_mirror %d",
7879 num_copies, failrec->this_mirror, failed_mirror);
7883 failrec->failed_mirror = failed_mirror;
7884 failrec->this_mirror++;
7885 if (failrec->this_mirror == failed_mirror)
7886 failrec->this_mirror++;
7888 if (failrec->this_mirror > num_copies) {
7889 btrfs_debug(fs_info,
7890 "Check DIO Repairable: (fail) num_copies=%d, next_mirror %d, failed_mirror %d",
7891 num_copies, failrec->this_mirror, failed_mirror);
7898 static blk_status_t dio_read_error(struct inode *inode, struct bio *failed_bio,
7899 struct page *page, unsigned int pgoff,
7900 u64 start, u64 end, int failed_mirror,
7901 bio_end_io_t *repair_endio, void *repair_arg)
7903 struct io_failure_record *failrec;
7904 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
7905 struct extent_io_tree *failure_tree = &BTRFS_I(inode)->io_failure_tree;
7908 unsigned int read_mode = 0;
7911 blk_status_t status;
7912 struct bio_vec bvec;
7914 BUG_ON(bio_op(failed_bio) == REQ_OP_WRITE);
7916 ret = btrfs_get_io_failure_record(inode, start, end, &failrec);
7918 return errno_to_blk_status(ret);
7920 ret = btrfs_check_dio_repairable(inode, failed_bio, failrec,
7923 free_io_failure(failure_tree, io_tree, failrec);
7924 return BLK_STS_IOERR;
7927 segs = bio_segments(failed_bio);
7928 bio_get_first_bvec(failed_bio, &bvec);
7930 (bvec.bv_len > btrfs_inode_sectorsize(inode)))
7931 read_mode |= REQ_FAILFAST_DEV;
7933 isector = start - btrfs_io_bio(failed_bio)->logical;
7934 isector >>= inode->i_sb->s_blocksize_bits;
7935 bio = btrfs_create_repair_bio(inode, failed_bio, failrec, page,
7936 pgoff, isector, repair_endio, repair_arg);
7937 bio_set_op_attrs(bio, REQ_OP_READ, read_mode);
7939 btrfs_debug(BTRFS_I(inode)->root->fs_info,
7940 "repair DIO read error: submitting new dio read[%#x] to this_mirror=%d, in_validation=%d",
7941 read_mode, failrec->this_mirror, failrec->in_validation);
7943 status = submit_dio_repair_bio(inode, bio, failrec->this_mirror);
7945 free_io_failure(failure_tree, io_tree, failrec);
7952 struct btrfs_retry_complete {
7953 struct completion done;
7954 struct inode *inode;
7959 static void btrfs_retry_endio_nocsum(struct bio *bio)
7961 struct btrfs_retry_complete *done = bio->bi_private;
7962 struct inode *inode = done->inode;
7963 struct bio_vec *bvec;
7964 struct extent_io_tree *io_tree, *failure_tree;
7970 ASSERT(bio->bi_vcnt == 1);
7971 io_tree = &BTRFS_I(inode)->io_tree;
7972 failure_tree = &BTRFS_I(inode)->io_failure_tree;
7973 ASSERT(bio_first_bvec_all(bio)->bv_len == btrfs_inode_sectorsize(inode));
7976 ASSERT(!bio_flagged(bio, BIO_CLONED));
7977 bio_for_each_segment_all(bvec, bio, i)
7978 clean_io_failure(BTRFS_I(inode)->root->fs_info, failure_tree,
7979 io_tree, done->start, bvec->bv_page,
7980 btrfs_ino(BTRFS_I(inode)), 0);
7982 complete(&done->done);
7986 static blk_status_t __btrfs_correct_data_nocsum(struct inode *inode,
7987 struct btrfs_io_bio *io_bio)
7989 struct btrfs_fs_info *fs_info;
7990 struct bio_vec bvec;
7991 struct bvec_iter iter;
7992 struct btrfs_retry_complete done;
7998 blk_status_t err = BLK_STS_OK;
8000 fs_info = BTRFS_I(inode)->root->fs_info;
8001 sectorsize = fs_info->sectorsize;
8003 start = io_bio->logical;
8005 io_bio->bio.bi_iter = io_bio->iter;
8007 bio_for_each_segment(bvec, &io_bio->bio, iter) {
8008 nr_sectors = BTRFS_BYTES_TO_BLKS(fs_info, bvec.bv_len);
8009 pgoff = bvec.bv_offset;
8011 next_block_or_try_again:
8014 init_completion(&done.done);
8016 ret = dio_read_error(inode, &io_bio->bio, bvec.bv_page,
8017 pgoff, start, start + sectorsize - 1,
8019 btrfs_retry_endio_nocsum, &done);
8025 wait_for_completion_io(&done.done);
8027 if (!done.uptodate) {
8028 /* We might have another mirror, so try again */
8029 goto next_block_or_try_again;
8033 start += sectorsize;
8037 pgoff += sectorsize;
8038 ASSERT(pgoff < PAGE_SIZE);
8039 goto next_block_or_try_again;
8046 static void btrfs_retry_endio(struct bio *bio)
8048 struct btrfs_retry_complete *done = bio->bi_private;
8049 struct btrfs_io_bio *io_bio = btrfs_io_bio(bio);
8050 struct extent_io_tree *io_tree, *failure_tree;
8051 struct inode *inode = done->inode;
8052 struct bio_vec *bvec;
8062 ASSERT(bio->bi_vcnt == 1);
8063 ASSERT(bio_first_bvec_all(bio)->bv_len == btrfs_inode_sectorsize(done->inode));
8065 io_tree = &BTRFS_I(inode)->io_tree;
8066 failure_tree = &BTRFS_I(inode)->io_failure_tree;
8068 ASSERT(!bio_flagged(bio, BIO_CLONED));
8069 bio_for_each_segment_all(bvec, bio, i) {
8070 ret = __readpage_endio_check(inode, io_bio, i, bvec->bv_page,
8071 bvec->bv_offset, done->start,
8074 clean_io_failure(BTRFS_I(inode)->root->fs_info,
8075 failure_tree, io_tree, done->start,
8077 btrfs_ino(BTRFS_I(inode)),
8083 done->uptodate = uptodate;
8085 complete(&done->done);
8089 static blk_status_t __btrfs_subio_endio_read(struct inode *inode,
8090 struct btrfs_io_bio *io_bio, blk_status_t err)
8092 struct btrfs_fs_info *fs_info;
8093 struct bio_vec bvec;
8094 struct bvec_iter iter;
8095 struct btrfs_retry_complete done;
8102 bool uptodate = (err == 0);
8104 blk_status_t status;
8106 fs_info = BTRFS_I(inode)->root->fs_info;
8107 sectorsize = fs_info->sectorsize;
8110 start = io_bio->logical;
8112 io_bio->bio.bi_iter = io_bio->iter;
8114 bio_for_each_segment(bvec, &io_bio->bio, iter) {
8115 nr_sectors = BTRFS_BYTES_TO_BLKS(fs_info, bvec.bv_len);
8117 pgoff = bvec.bv_offset;
8120 csum_pos = BTRFS_BYTES_TO_BLKS(fs_info, offset);
8121 ret = __readpage_endio_check(inode, io_bio, csum_pos,
8122 bvec.bv_page, pgoff, start, sectorsize);
8129 init_completion(&done.done);
8131 status = dio_read_error(inode, &io_bio->bio, bvec.bv_page,
8132 pgoff, start, start + sectorsize - 1,
8133 io_bio->mirror_num, btrfs_retry_endio,
8140 wait_for_completion_io(&done.done);
8142 if (!done.uptodate) {
8143 /* We might have another mirror, so try again */
8147 offset += sectorsize;
8148 start += sectorsize;
8154 pgoff += sectorsize;
8155 ASSERT(pgoff < PAGE_SIZE);
8163 static blk_status_t btrfs_subio_endio_read(struct inode *inode,
8164 struct btrfs_io_bio *io_bio, blk_status_t err)
8166 bool skip_csum = BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM;
8170 return __btrfs_correct_data_nocsum(inode, io_bio);
8174 return __btrfs_subio_endio_read(inode, io_bio, err);
8178 static void btrfs_endio_direct_read(struct bio *bio)
8180 struct btrfs_dio_private *dip = bio->bi_private;
8181 struct inode *inode = dip->inode;
8182 struct bio *dio_bio;
8183 struct btrfs_io_bio *io_bio = btrfs_io_bio(bio);
8184 blk_status_t err = bio->bi_status;
8186 if (dip->flags & BTRFS_DIO_ORIG_BIO_SUBMITTED)
8187 err = btrfs_subio_endio_read(inode, io_bio, err);
8189 unlock_extent(&BTRFS_I(inode)->io_tree, dip->logical_offset,
8190 dip->logical_offset + dip->bytes - 1);
8191 dio_bio = dip->dio_bio;
8195 dio_bio->bi_status = err;
8196 dio_end_io(dio_bio);
8199 io_bio->end_io(io_bio, blk_status_to_errno(err));
8203 static void __endio_write_update_ordered(struct inode *inode,
8204 const u64 offset, const u64 bytes,
8205 const bool uptodate)
8207 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
8208 struct btrfs_ordered_extent *ordered = NULL;
8209 struct btrfs_workqueue *wq;
8210 btrfs_work_func_t func;
8211 u64 ordered_offset = offset;
8212 u64 ordered_bytes = bytes;
8216 if (btrfs_is_free_space_inode(BTRFS_I(inode))) {
8217 wq = fs_info->endio_freespace_worker;
8218 func = btrfs_freespace_write_helper;
8220 wq = fs_info->endio_write_workers;
8221 func = btrfs_endio_write_helper;
8225 last_offset = ordered_offset;
8226 ret = btrfs_dec_test_first_ordered_pending(inode, &ordered,
8233 btrfs_init_work(&ordered->work, func, finish_ordered_fn, NULL, NULL);
8234 btrfs_queue_work(wq, &ordered->work);
8237 * If btrfs_dec_test_ordered_pending does not find any ordered extent
8238 * in the range, we can exit.
8240 if (ordered_offset == last_offset)
8243 * our bio might span multiple ordered extents. If we haven't
8244 * completed the accounting for the whole dio, go back and try again
8246 if (ordered_offset < offset + bytes) {
8247 ordered_bytes = offset + bytes - ordered_offset;
8253 static void btrfs_endio_direct_write(struct bio *bio)
8255 struct btrfs_dio_private *dip = bio->bi_private;
8256 struct bio *dio_bio = dip->dio_bio;
8258 __endio_write_update_ordered(dip->inode, dip->logical_offset,
8259 dip->bytes, !bio->bi_status);
8263 dio_bio->bi_status = bio->bi_status;
8264 dio_end_io(dio_bio);
8268 static blk_status_t __btrfs_submit_bio_start_direct_io(void *private_data,
8269 struct bio *bio, int mirror_num,
8270 unsigned long bio_flags, u64 offset)
8272 struct inode *inode = private_data;
8274 ret = btrfs_csum_one_bio(inode, bio, offset, 1);
8275 BUG_ON(ret); /* -ENOMEM */
8279 static void btrfs_end_dio_bio(struct bio *bio)
8281 struct btrfs_dio_private *dip = bio->bi_private;
8282 blk_status_t err = bio->bi_status;
8285 btrfs_warn(BTRFS_I(dip->inode)->root->fs_info,
8286 "direct IO failed ino %llu rw %d,%u sector %#Lx len %u err no %d",
8287 btrfs_ino(BTRFS_I(dip->inode)), bio_op(bio),
8289 (unsigned long long)bio->bi_iter.bi_sector,
8290 bio->bi_iter.bi_size, err);
8292 if (dip->subio_endio)
8293 err = dip->subio_endio(dip->inode, btrfs_io_bio(bio), err);
8299 * before atomic variable goto zero, we must make sure
8300 * dip->errors is perceived to be set.
8302 smp_mb__before_atomic();
8305 /* if there are more bios still pending for this dio, just exit */
8306 if (!atomic_dec_and_test(&dip->pending_bios))
8310 bio_io_error(dip->orig_bio);
8312 dip->dio_bio->bi_status = BLK_STS_OK;
8313 bio_endio(dip->orig_bio);
8319 static inline blk_status_t btrfs_lookup_and_bind_dio_csum(struct inode *inode,
8320 struct btrfs_dio_private *dip,
8324 struct btrfs_io_bio *io_bio = btrfs_io_bio(bio);
8325 struct btrfs_io_bio *orig_io_bio = btrfs_io_bio(dip->orig_bio);
8329 * We load all the csum data we need when we submit
8330 * the first bio to reduce the csum tree search and
8333 if (dip->logical_offset == file_offset) {
8334 ret = btrfs_lookup_bio_sums_dio(inode, dip->orig_bio,
8340 if (bio == dip->orig_bio)
8343 file_offset -= dip->logical_offset;
8344 file_offset >>= inode->i_sb->s_blocksize_bits;
8345 io_bio->csum = (u8 *)(((u32 *)orig_io_bio->csum) + file_offset);
8350 static inline blk_status_t
8351 __btrfs_submit_dio_bio(struct bio *bio, struct inode *inode, u64 file_offset,
8354 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
8355 struct btrfs_dio_private *dip = bio->bi_private;
8356 bool write = bio_op(bio) == REQ_OP_WRITE;
8359 /* Check btrfs_submit_bio_hook() for rules about async submit. */
8361 async_submit = !atomic_read(&BTRFS_I(inode)->sync_writers);
8364 ret = btrfs_bio_wq_end_io(fs_info, bio, BTRFS_WQ_ENDIO_DATA);
8369 if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)
8372 if (write && async_submit) {
8373 ret = btrfs_wq_submit_bio(fs_info, bio, 0, 0,
8375 __btrfs_submit_bio_start_direct_io,
8376 __btrfs_submit_bio_done);
8380 * If we aren't doing async submit, calculate the csum of the
8383 ret = btrfs_csum_one_bio(inode, bio, file_offset, 1);
8387 ret = btrfs_lookup_and_bind_dio_csum(inode, dip, bio,
8393 ret = btrfs_map_bio(fs_info, bio, 0, 0);
8398 static int btrfs_submit_direct_hook(struct btrfs_dio_private *dip)
8400 struct inode *inode = dip->inode;
8401 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
8403 struct bio *orig_bio = dip->orig_bio;
8404 u64 start_sector = orig_bio->bi_iter.bi_sector;
8405 u64 file_offset = dip->logical_offset;
8407 int async_submit = 0;
8409 int clone_offset = 0;
8412 blk_status_t status;
8414 map_length = orig_bio->bi_iter.bi_size;
8415 submit_len = map_length;
8416 ret = btrfs_map_block(fs_info, btrfs_op(orig_bio), start_sector << 9,
8417 &map_length, NULL, 0);
8421 if (map_length >= submit_len) {
8423 dip->flags |= BTRFS_DIO_ORIG_BIO_SUBMITTED;
8427 /* async crcs make it difficult to collect full stripe writes. */
8428 if (btrfs_data_alloc_profile(fs_info) & BTRFS_BLOCK_GROUP_RAID56_MASK)
8434 ASSERT(map_length <= INT_MAX);
8435 atomic_inc(&dip->pending_bios);
8437 clone_len = min_t(int, submit_len, map_length);
8440 * This will never fail as it's passing GPF_NOFS and
8441 * the allocation is backed by btrfs_bioset.
8443 bio = btrfs_bio_clone_partial(orig_bio, clone_offset,
8445 bio->bi_private = dip;
8446 bio->bi_end_io = btrfs_end_dio_bio;
8447 btrfs_io_bio(bio)->logical = file_offset;
8449 ASSERT(submit_len >= clone_len);
8450 submit_len -= clone_len;
8451 if (submit_len == 0)
8455 * Increase the count before we submit the bio so we know
8456 * the end IO handler won't happen before we increase the
8457 * count. Otherwise, the dip might get freed before we're
8458 * done setting it up.
8460 atomic_inc(&dip->pending_bios);
8462 status = __btrfs_submit_dio_bio(bio, inode, file_offset,
8466 atomic_dec(&dip->pending_bios);
8470 clone_offset += clone_len;
8471 start_sector += clone_len >> 9;
8472 file_offset += clone_len;
8474 map_length = submit_len;
8475 ret = btrfs_map_block(fs_info, btrfs_op(orig_bio),
8476 start_sector << 9, &map_length, NULL, 0);
8479 } while (submit_len > 0);
8482 status = __btrfs_submit_dio_bio(bio, inode, file_offset, async_submit);
8490 * before atomic variable goto zero, we must
8491 * make sure dip->errors is perceived to be set.
8493 smp_mb__before_atomic();
8494 if (atomic_dec_and_test(&dip->pending_bios))
8495 bio_io_error(dip->orig_bio);
8497 /* bio_end_io() will handle error, so we needn't return it */
8501 static void btrfs_submit_direct(struct bio *dio_bio, struct inode *inode,
8504 struct btrfs_dio_private *dip = NULL;
8505 struct bio *bio = NULL;
8506 struct btrfs_io_bio *io_bio;
8507 bool write = (bio_op(dio_bio) == REQ_OP_WRITE);
8510 bio = btrfs_bio_clone(dio_bio);
8512 dip = kzalloc(sizeof(*dip), GFP_NOFS);
8518 dip->private = dio_bio->bi_private;
8520 dip->logical_offset = file_offset;
8521 dip->bytes = dio_bio->bi_iter.bi_size;
8522 dip->disk_bytenr = (u64)dio_bio->bi_iter.bi_sector << 9;
8523 bio->bi_private = dip;
8524 dip->orig_bio = bio;
8525 dip->dio_bio = dio_bio;
8526 atomic_set(&dip->pending_bios, 0);
8527 io_bio = btrfs_io_bio(bio);
8528 io_bio->logical = file_offset;
8531 bio->bi_end_io = btrfs_endio_direct_write;
8533 bio->bi_end_io = btrfs_endio_direct_read;
8534 dip->subio_endio = btrfs_subio_endio_read;
8538 * Reset the range for unsubmitted ordered extents (to a 0 length range)
8539 * even if we fail to submit a bio, because in such case we do the
8540 * corresponding error handling below and it must not be done a second
8541 * time by btrfs_direct_IO().
8544 struct btrfs_dio_data *dio_data = current->journal_info;
8546 dio_data->unsubmitted_oe_range_end = dip->logical_offset +
8548 dio_data->unsubmitted_oe_range_start =
8549 dio_data->unsubmitted_oe_range_end;
8552 ret = btrfs_submit_direct_hook(dip);
8557 io_bio->end_io(io_bio, ret);
8561 * If we arrived here it means either we failed to submit the dip
8562 * or we either failed to clone the dio_bio or failed to allocate the
8563 * dip. If we cloned the dio_bio and allocated the dip, we can just
8564 * call bio_endio against our io_bio so that we get proper resource
8565 * cleanup if we fail to submit the dip, otherwise, we must do the
8566 * same as btrfs_endio_direct_[write|read] because we can't call these
8567 * callbacks - they require an allocated dip and a clone of dio_bio.
8572 * The end io callbacks free our dip, do the final put on bio
8573 * and all the cleanup and final put for dio_bio (through
8580 __endio_write_update_ordered(inode,
8582 dio_bio->bi_iter.bi_size,
8585 unlock_extent(&BTRFS_I(inode)->io_tree, file_offset,
8586 file_offset + dio_bio->bi_iter.bi_size - 1);
8588 dio_bio->bi_status = BLK_STS_IOERR;
8590 * Releases and cleans up our dio_bio, no need to bio_put()
8591 * nor bio_endio()/bio_io_error() against dio_bio.
8593 dio_end_io(dio_bio);
8600 static ssize_t check_direct_IO(struct btrfs_fs_info *fs_info,
8601 const struct iov_iter *iter, loff_t offset)
8605 unsigned int blocksize_mask = fs_info->sectorsize - 1;
8606 ssize_t retval = -EINVAL;
8608 if (offset & blocksize_mask)
8611 if (iov_iter_alignment(iter) & blocksize_mask)
8614 /* If this is a write we don't need to check anymore */
8615 if (iov_iter_rw(iter) != READ || !iter_is_iovec(iter))
8618 * Check to make sure we don't have duplicate iov_base's in this
8619 * iovec, if so return EINVAL, otherwise we'll get csum errors
8620 * when reading back.
8622 for (seg = 0; seg < iter->nr_segs; seg++) {
8623 for (i = seg + 1; i < iter->nr_segs; i++) {
8624 if (iter->iov[seg].iov_base == iter->iov[i].iov_base)
8633 static ssize_t btrfs_direct_IO(struct kiocb *iocb, struct iov_iter *iter)
8635 struct file *file = iocb->ki_filp;
8636 struct inode *inode = file->f_mapping->host;
8637 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
8638 struct btrfs_dio_data dio_data = { 0 };
8639 struct extent_changeset *data_reserved = NULL;
8640 loff_t offset = iocb->ki_pos;
8644 bool relock = false;
8647 if (check_direct_IO(fs_info, iter, offset))
8650 inode_dio_begin(inode);
8653 * The generic stuff only does filemap_write_and_wait_range, which
8654 * isn't enough if we've written compressed pages to this area, so
8655 * we need to flush the dirty pages again to make absolutely sure
8656 * that any outstanding dirty pages are on disk.
8658 count = iov_iter_count(iter);
8659 if (test_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
8660 &BTRFS_I(inode)->runtime_flags))
8661 filemap_fdatawrite_range(inode->i_mapping, offset,
8662 offset + count - 1);
8664 if (iov_iter_rw(iter) == WRITE) {
8666 * If the write DIO is beyond the EOF, we need update
8667 * the isize, but it is protected by i_mutex. So we can
8668 * not unlock the i_mutex at this case.
8670 if (offset + count <= inode->i_size) {
8671 dio_data.overwrite = 1;
8672 inode_unlock(inode);
8674 } else if (iocb->ki_flags & IOCB_NOWAIT) {
8678 ret = btrfs_delalloc_reserve_space(inode, &data_reserved,
8684 * We need to know how many extents we reserved so that we can
8685 * do the accounting properly if we go over the number we
8686 * originally calculated. Abuse current->journal_info for this.
8688 dio_data.reserve = round_up(count,
8689 fs_info->sectorsize);
8690 dio_data.unsubmitted_oe_range_start = (u64)offset;
8691 dio_data.unsubmitted_oe_range_end = (u64)offset;
8692 current->journal_info = &dio_data;
8693 down_read(&BTRFS_I(inode)->dio_sem);
8694 } else if (test_bit(BTRFS_INODE_READDIO_NEED_LOCK,
8695 &BTRFS_I(inode)->runtime_flags)) {
8696 inode_dio_end(inode);
8697 flags = DIO_LOCKING | DIO_SKIP_HOLES;
8701 ret = __blockdev_direct_IO(iocb, inode,
8702 fs_info->fs_devices->latest_bdev,
8703 iter, btrfs_get_blocks_direct, NULL,
8704 btrfs_submit_direct, flags);
8705 if (iov_iter_rw(iter) == WRITE) {
8706 up_read(&BTRFS_I(inode)->dio_sem);
8707 current->journal_info = NULL;
8708 if (ret < 0 && ret != -EIOCBQUEUED) {
8709 if (dio_data.reserve)
8710 btrfs_delalloc_release_space(inode, data_reserved,
8711 offset, dio_data.reserve);
8713 * On error we might have left some ordered extents
8714 * without submitting corresponding bios for them, so
8715 * cleanup them up to avoid other tasks getting them
8716 * and waiting for them to complete forever.
8718 if (dio_data.unsubmitted_oe_range_start <
8719 dio_data.unsubmitted_oe_range_end)
8720 __endio_write_update_ordered(inode,
8721 dio_data.unsubmitted_oe_range_start,
8722 dio_data.unsubmitted_oe_range_end -
8723 dio_data.unsubmitted_oe_range_start,
8725 } else if (ret >= 0 && (size_t)ret < count)
8726 btrfs_delalloc_release_space(inode, data_reserved,
8727 offset, count - (size_t)ret);
8728 btrfs_delalloc_release_extents(BTRFS_I(inode), count);
8732 inode_dio_end(inode);
8736 extent_changeset_free(data_reserved);
8740 #define BTRFS_FIEMAP_FLAGS (FIEMAP_FLAG_SYNC)
8742 static int btrfs_fiemap(struct inode *inode, struct fiemap_extent_info *fieinfo,
8743 __u64 start, __u64 len)
8747 ret = fiemap_check_flags(fieinfo, BTRFS_FIEMAP_FLAGS);
8751 return extent_fiemap(inode, fieinfo, start, len);
8754 int btrfs_readpage(struct file *file, struct page *page)
8756 struct extent_io_tree *tree;
8757 tree = &BTRFS_I(page->mapping->host)->io_tree;
8758 return extent_read_full_page(tree, page, btrfs_get_extent, 0);
8761 static int btrfs_writepage(struct page *page, struct writeback_control *wbc)
8763 struct inode *inode = page->mapping->host;
8766 if (current->flags & PF_MEMALLOC) {
8767 redirty_page_for_writepage(wbc, page);
8773 * If we are under memory pressure we will call this directly from the
8774 * VM, we need to make sure we have the inode referenced for the ordered
8775 * extent. If not just return like we didn't do anything.
8777 if (!igrab(inode)) {
8778 redirty_page_for_writepage(wbc, page);
8779 return AOP_WRITEPAGE_ACTIVATE;
8781 ret = extent_write_full_page(page, wbc);
8782 btrfs_add_delayed_iput(inode);
8786 static int btrfs_writepages(struct address_space *mapping,
8787 struct writeback_control *wbc)
8789 struct extent_io_tree *tree;
8791 tree = &BTRFS_I(mapping->host)->io_tree;
8792 return extent_writepages(tree, mapping, wbc);
8796 btrfs_readpages(struct file *file, struct address_space *mapping,
8797 struct list_head *pages, unsigned nr_pages)
8799 struct extent_io_tree *tree;
8800 tree = &BTRFS_I(mapping->host)->io_tree;
8801 return extent_readpages(tree, mapping, pages, nr_pages);
8803 static int __btrfs_releasepage(struct page *page, gfp_t gfp_flags)
8805 struct extent_io_tree *tree;
8806 struct extent_map_tree *map;
8809 tree = &BTRFS_I(page->mapping->host)->io_tree;
8810 map = &BTRFS_I(page->mapping->host)->extent_tree;
8811 ret = try_release_extent_mapping(map, tree, page, gfp_flags);
8813 ClearPagePrivate(page);
8814 set_page_private(page, 0);
8820 static int btrfs_releasepage(struct page *page, gfp_t gfp_flags)
8822 if (PageWriteback(page) || PageDirty(page))
8824 return __btrfs_releasepage(page, gfp_flags);
8827 static void btrfs_invalidatepage(struct page *page, unsigned int offset,
8828 unsigned int length)
8830 struct inode *inode = page->mapping->host;
8831 struct extent_io_tree *tree;
8832 struct btrfs_ordered_extent *ordered;
8833 struct extent_state *cached_state = NULL;
8834 u64 page_start = page_offset(page);
8835 u64 page_end = page_start + PAGE_SIZE - 1;
8838 int inode_evicting = inode->i_state & I_FREEING;
8841 * we have the page locked, so new writeback can't start,
8842 * and the dirty bit won't be cleared while we are here.
8844 * Wait for IO on this page so that we can safely clear
8845 * the PagePrivate2 bit and do ordered accounting
8847 wait_on_page_writeback(page);
8849 tree = &BTRFS_I(inode)->io_tree;
8851 btrfs_releasepage(page, GFP_NOFS);
8855 if (!inode_evicting)
8856 lock_extent_bits(tree, page_start, page_end, &cached_state);
8859 ordered = btrfs_lookup_ordered_range(BTRFS_I(inode), start,
8860 page_end - start + 1);
8862 end = min(page_end, ordered->file_offset + ordered->len - 1);
8864 * IO on this page will never be started, so we need
8865 * to account for any ordered extents now
8867 if (!inode_evicting)
8868 clear_extent_bit(tree, start, end,
8869 EXTENT_DIRTY | EXTENT_DELALLOC |
8870 EXTENT_DELALLOC_NEW |
8871 EXTENT_LOCKED | EXTENT_DO_ACCOUNTING |
8872 EXTENT_DEFRAG, 1, 0, &cached_state);
8874 * whoever cleared the private bit is responsible
8875 * for the finish_ordered_io
8877 if (TestClearPagePrivate2(page)) {
8878 struct btrfs_ordered_inode_tree *tree;
8881 tree = &BTRFS_I(inode)->ordered_tree;
8883 spin_lock_irq(&tree->lock);
8884 set_bit(BTRFS_ORDERED_TRUNCATED, &ordered->flags);
8885 new_len = start - ordered->file_offset;
8886 if (new_len < ordered->truncated_len)
8887 ordered->truncated_len = new_len;
8888 spin_unlock_irq(&tree->lock);
8890 if (btrfs_dec_test_ordered_pending(inode, &ordered,
8892 end - start + 1, 1))
8893 btrfs_finish_ordered_io(ordered);
8895 btrfs_put_ordered_extent(ordered);
8896 if (!inode_evicting) {
8897 cached_state = NULL;
8898 lock_extent_bits(tree, start, end,
8903 if (start < page_end)
8908 * Qgroup reserved space handler
8909 * Page here will be either
8910 * 1) Already written to disk
8911 * In this case, its reserved space is released from data rsv map
8912 * and will be freed by delayed_ref handler finally.
8913 * So even we call qgroup_free_data(), it won't decrease reserved
8915 * 2) Not written to disk
8916 * This means the reserved space should be freed here. However,
8917 * if a truncate invalidates the page (by clearing PageDirty)
8918 * and the page is accounted for while allocating extent
8919 * in btrfs_check_data_free_space() we let delayed_ref to
8920 * free the entire extent.
8922 if (PageDirty(page))
8923 btrfs_qgroup_free_data(inode, NULL, page_start, PAGE_SIZE);
8924 if (!inode_evicting) {
8925 clear_extent_bit(tree, page_start, page_end,
8926 EXTENT_LOCKED | EXTENT_DIRTY |
8927 EXTENT_DELALLOC | EXTENT_DELALLOC_NEW |
8928 EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG, 1, 1,
8931 __btrfs_releasepage(page, GFP_NOFS);
8934 ClearPageChecked(page);
8935 if (PagePrivate(page)) {
8936 ClearPagePrivate(page);
8937 set_page_private(page, 0);
8943 * btrfs_page_mkwrite() is not allowed to change the file size as it gets
8944 * called from a page fault handler when a page is first dirtied. Hence we must
8945 * be careful to check for EOF conditions here. We set the page up correctly
8946 * for a written page which means we get ENOSPC checking when writing into
8947 * holes and correct delalloc and unwritten extent mapping on filesystems that
8948 * support these features.
8950 * We are not allowed to take the i_mutex here so we have to play games to
8951 * protect against truncate races as the page could now be beyond EOF. Because
8952 * vmtruncate() writes the inode size before removing pages, once we have the
8953 * page lock we can determine safely if the page is beyond EOF. If it is not
8954 * beyond EOF, then the page is guaranteed safe against truncation until we
8957 int btrfs_page_mkwrite(struct vm_fault *vmf)
8959 struct page *page = vmf->page;
8960 struct inode *inode = file_inode(vmf->vma->vm_file);
8961 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
8962 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
8963 struct btrfs_ordered_extent *ordered;
8964 struct extent_state *cached_state = NULL;
8965 struct extent_changeset *data_reserved = NULL;
8967 unsigned long zero_start;
8976 reserved_space = PAGE_SIZE;
8978 sb_start_pagefault(inode->i_sb);
8979 page_start = page_offset(page);
8980 page_end = page_start + PAGE_SIZE - 1;
8984 * Reserving delalloc space after obtaining the page lock can lead to
8985 * deadlock. For example, if a dirty page is locked by this function
8986 * and the call to btrfs_delalloc_reserve_space() ends up triggering
8987 * dirty page write out, then the btrfs_writepage() function could
8988 * end up waiting indefinitely to get a lock on the page currently
8989 * being processed by btrfs_page_mkwrite() function.
8991 ret = btrfs_delalloc_reserve_space(inode, &data_reserved, page_start,
8994 ret = file_update_time(vmf->vma->vm_file);
9000 else /* -ENOSPC, -EIO, etc */
9001 ret = VM_FAULT_SIGBUS;
9007 ret = VM_FAULT_NOPAGE; /* make the VM retry the fault */
9010 size = i_size_read(inode);
9012 if ((page->mapping != inode->i_mapping) ||
9013 (page_start >= size)) {
9014 /* page got truncated out from underneath us */
9017 wait_on_page_writeback(page);
9019 lock_extent_bits(io_tree, page_start, page_end, &cached_state);
9020 set_page_extent_mapped(page);
9023 * we can't set the delalloc bits if there are pending ordered
9024 * extents. Drop our locks and wait for them to finish
9026 ordered = btrfs_lookup_ordered_range(BTRFS_I(inode), page_start,
9029 unlock_extent_cached(io_tree, page_start, page_end,
9032 btrfs_start_ordered_extent(inode, ordered, 1);
9033 btrfs_put_ordered_extent(ordered);
9037 if (page->index == ((size - 1) >> PAGE_SHIFT)) {
9038 reserved_space = round_up(size - page_start,
9039 fs_info->sectorsize);
9040 if (reserved_space < PAGE_SIZE) {
9041 end = page_start + reserved_space - 1;
9042 btrfs_delalloc_release_space(inode, data_reserved,
9043 page_start, PAGE_SIZE - reserved_space);
9048 * page_mkwrite gets called when the page is firstly dirtied after it's
9049 * faulted in, but write(2) could also dirty a page and set delalloc
9050 * bits, thus in this case for space account reason, we still need to
9051 * clear any delalloc bits within this page range since we have to
9052 * reserve data&meta space before lock_page() (see above comments).
9054 clear_extent_bit(&BTRFS_I(inode)->io_tree, page_start, end,
9055 EXTENT_DIRTY | EXTENT_DELALLOC |
9056 EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG,
9057 0, 0, &cached_state);
9059 ret = btrfs_set_extent_delalloc(inode, page_start, end, 0,
9062 unlock_extent_cached(io_tree, page_start, page_end,
9064 ret = VM_FAULT_SIGBUS;
9069 /* page is wholly or partially inside EOF */
9070 if (page_start + PAGE_SIZE > size)
9071 zero_start = size & ~PAGE_MASK;
9073 zero_start = PAGE_SIZE;
9075 if (zero_start != PAGE_SIZE) {
9077 memset(kaddr + zero_start, 0, PAGE_SIZE - zero_start);
9078 flush_dcache_page(page);
9081 ClearPageChecked(page);
9082 set_page_dirty(page);
9083 SetPageUptodate(page);
9085 BTRFS_I(inode)->last_trans = fs_info->generation;
9086 BTRFS_I(inode)->last_sub_trans = BTRFS_I(inode)->root->log_transid;
9087 BTRFS_I(inode)->last_log_commit = BTRFS_I(inode)->root->last_log_commit;
9089 unlock_extent_cached(io_tree, page_start, page_end, &cached_state);
9093 btrfs_delalloc_release_extents(BTRFS_I(inode), PAGE_SIZE);
9094 sb_end_pagefault(inode->i_sb);
9095 extent_changeset_free(data_reserved);
9096 return VM_FAULT_LOCKED;
9100 btrfs_delalloc_release_extents(BTRFS_I(inode), PAGE_SIZE);
9101 btrfs_delalloc_release_space(inode, data_reserved, page_start,
9104 sb_end_pagefault(inode->i_sb);
9105 extent_changeset_free(data_reserved);
9109 static int btrfs_truncate(struct inode *inode)
9111 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
9112 struct btrfs_root *root = BTRFS_I(inode)->root;
9113 struct btrfs_block_rsv *rsv;
9116 struct btrfs_trans_handle *trans;
9117 u64 mask = fs_info->sectorsize - 1;
9118 u64 min_size = btrfs_calc_trunc_metadata_size(fs_info, 1);
9120 ret = btrfs_wait_ordered_range(inode, inode->i_size & (~mask),
9126 * Yes ladies and gentlemen, this is indeed ugly. The fact is we have
9127 * 3 things going on here
9129 * 1) We need to reserve space for our orphan item and the space to
9130 * delete our orphan item. Lord knows we don't want to have a dangling
9131 * orphan item because we didn't reserve space to remove it.
9133 * 2) We need to reserve space to update our inode.
9135 * 3) We need to have something to cache all the space that is going to
9136 * be free'd up by the truncate operation, but also have some slack
9137 * space reserved in case it uses space during the truncate (thank you
9138 * very much snapshotting).
9140 * And we need these to all be separate. The fact is we can use a lot of
9141 * space doing the truncate, and we have no earthly idea how much space
9142 * we will use, so we need the truncate reservation to be separate so it
9143 * doesn't end up using space reserved for updating the inode or
9144 * removing the orphan item. We also need to be able to stop the
9145 * transaction and start a new one, which means we need to be able to
9146 * update the inode several times, and we have no idea of knowing how
9147 * many times that will be, so we can't just reserve 1 item for the
9148 * entirety of the operation, so that has to be done separately as well.
9149 * Then there is the orphan item, which does indeed need to be held on
9150 * to for the whole operation, and we need nobody to touch this reserved
9151 * space except the orphan code.
9153 * So that leaves us with
9155 * 1) root->orphan_block_rsv - for the orphan deletion.
9156 * 2) rsv - for the truncate reservation, which we will steal from the
9157 * transaction reservation.
9158 * 3) fs_info->trans_block_rsv - this will have 1 items worth left for
9159 * updating the inode.
9161 rsv = btrfs_alloc_block_rsv(fs_info, BTRFS_BLOCK_RSV_TEMP);
9164 rsv->size = min_size;
9168 * 1 for the truncate slack space
9169 * 1 for updating the inode.
9171 trans = btrfs_start_transaction(root, 2);
9172 if (IS_ERR(trans)) {
9173 err = PTR_ERR(trans);
9177 /* Migrate the slack space for the truncate to our reserve */
9178 ret = btrfs_block_rsv_migrate(&fs_info->trans_block_rsv, rsv,
9183 * So if we truncate and then write and fsync we normally would just
9184 * write the extents that changed, which is a problem if we need to
9185 * first truncate that entire inode. So set this flag so we write out
9186 * all of the extents in the inode to the sync log so we're completely
9189 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &BTRFS_I(inode)->runtime_flags);
9190 trans->block_rsv = rsv;
9193 ret = btrfs_truncate_inode_items(trans, root, inode,
9195 BTRFS_EXTENT_DATA_KEY);
9196 trans->block_rsv = &fs_info->trans_block_rsv;
9197 if (ret != -ENOSPC && ret != -EAGAIN) {
9202 ret = btrfs_update_inode(trans, root, inode);
9208 btrfs_end_transaction(trans);
9209 btrfs_btree_balance_dirty(fs_info);
9211 trans = btrfs_start_transaction(root, 2);
9212 if (IS_ERR(trans)) {
9213 ret = err = PTR_ERR(trans);
9218 btrfs_block_rsv_release(fs_info, rsv, -1);
9219 ret = btrfs_block_rsv_migrate(&fs_info->trans_block_rsv,
9221 BUG_ON(ret); /* shouldn't happen */
9222 trans->block_rsv = rsv;
9226 * We can't call btrfs_truncate_block inside a trans handle as we could
9227 * deadlock with freeze, if we got NEED_TRUNCATE_BLOCK then we know
9228 * we've truncated everything except the last little bit, and can do
9229 * btrfs_truncate_block and then update the disk_i_size.
9231 if (ret == NEED_TRUNCATE_BLOCK) {
9232 btrfs_end_transaction(trans);
9233 btrfs_btree_balance_dirty(fs_info);
9235 ret = btrfs_truncate_block(inode, inode->i_size, 0, 0);
9238 trans = btrfs_start_transaction(root, 1);
9239 if (IS_ERR(trans)) {
9240 ret = PTR_ERR(trans);
9243 btrfs_ordered_update_i_size(inode, inode->i_size, NULL);
9246 if (ret == 0 && inode->i_nlink > 0) {
9247 trans->block_rsv = root->orphan_block_rsv;
9248 ret = btrfs_orphan_del(trans, BTRFS_I(inode));
9254 trans->block_rsv = &fs_info->trans_block_rsv;
9255 ret = btrfs_update_inode(trans, root, inode);
9259 ret = btrfs_end_transaction(trans);
9260 btrfs_btree_balance_dirty(fs_info);
9263 btrfs_free_block_rsv(fs_info, rsv);
9272 * create a new subvolume directory/inode (helper for the ioctl).
9274 int btrfs_create_subvol_root(struct btrfs_trans_handle *trans,
9275 struct btrfs_root *new_root,
9276 struct btrfs_root *parent_root,
9279 struct inode *inode;
9283 inode = btrfs_new_inode(trans, new_root, NULL, "..", 2,
9284 new_dirid, new_dirid,
9285 S_IFDIR | (~current_umask() & S_IRWXUGO),
9288 return PTR_ERR(inode);
9289 inode->i_op = &btrfs_dir_inode_operations;
9290 inode->i_fop = &btrfs_dir_file_operations;
9292 set_nlink(inode, 1);
9293 btrfs_i_size_write(BTRFS_I(inode), 0);
9294 unlock_new_inode(inode);
9296 err = btrfs_subvol_inherit_props(trans, new_root, parent_root);
9298 btrfs_err(new_root->fs_info,
9299 "error inheriting subvolume %llu properties: %d",
9300 new_root->root_key.objectid, err);
9302 err = btrfs_update_inode(trans, new_root, inode);
9308 struct inode *btrfs_alloc_inode(struct super_block *sb)
9310 struct btrfs_fs_info *fs_info = btrfs_sb(sb);
9311 struct btrfs_inode *ei;
9312 struct inode *inode;
9314 ei = kmem_cache_alloc(btrfs_inode_cachep, GFP_KERNEL);
9321 ei->last_sub_trans = 0;
9322 ei->logged_trans = 0;
9323 ei->delalloc_bytes = 0;
9324 ei->new_delalloc_bytes = 0;
9325 ei->defrag_bytes = 0;
9326 ei->disk_i_size = 0;
9329 ei->index_cnt = (u64)-1;
9331 ei->last_unlink_trans = 0;
9332 ei->last_log_commit = 0;
9333 ei->delayed_iput_count = 0;
9335 spin_lock_init(&ei->lock);
9336 ei->outstanding_extents = 0;
9337 if (sb->s_magic != BTRFS_TEST_MAGIC)
9338 btrfs_init_metadata_block_rsv(fs_info, &ei->block_rsv,
9339 BTRFS_BLOCK_RSV_DELALLOC);
9340 ei->runtime_flags = 0;
9341 ei->prop_compress = BTRFS_COMPRESS_NONE;
9342 ei->defrag_compress = BTRFS_COMPRESS_NONE;
9344 ei->delayed_node = NULL;
9346 ei->i_otime.tv_sec = 0;
9347 ei->i_otime.tv_nsec = 0;
9349 inode = &ei->vfs_inode;
9350 extent_map_tree_init(&ei->extent_tree);
9351 extent_io_tree_init(&ei->io_tree, inode);
9352 extent_io_tree_init(&ei->io_failure_tree, inode);
9353 ei->io_tree.track_uptodate = 1;
9354 ei->io_failure_tree.track_uptodate = 1;
9355 atomic_set(&ei->sync_writers, 0);
9356 mutex_init(&ei->log_mutex);
9357 mutex_init(&ei->delalloc_mutex);
9358 btrfs_ordered_inode_tree_init(&ei->ordered_tree);
9359 INIT_LIST_HEAD(&ei->delalloc_inodes);
9360 INIT_LIST_HEAD(&ei->delayed_iput);
9361 RB_CLEAR_NODE(&ei->rb_node);
9362 init_rwsem(&ei->dio_sem);
9367 #ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
9368 void btrfs_test_destroy_inode(struct inode *inode)
9370 btrfs_drop_extent_cache(BTRFS_I(inode), 0, (u64)-1, 0);
9371 kmem_cache_free(btrfs_inode_cachep, BTRFS_I(inode));
9375 static void btrfs_i_callback(struct rcu_head *head)
9377 struct inode *inode = container_of(head, struct inode, i_rcu);
9378 kmem_cache_free(btrfs_inode_cachep, BTRFS_I(inode));
9381 void btrfs_destroy_inode(struct inode *inode)
9383 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
9384 struct btrfs_ordered_extent *ordered;
9385 struct btrfs_root *root = BTRFS_I(inode)->root;
9387 WARN_ON(!hlist_empty(&inode->i_dentry));
9388 WARN_ON(inode->i_data.nrpages);
9389 WARN_ON(BTRFS_I(inode)->block_rsv.reserved);
9390 WARN_ON(BTRFS_I(inode)->block_rsv.size);
9391 WARN_ON(BTRFS_I(inode)->outstanding_extents);
9392 WARN_ON(BTRFS_I(inode)->delalloc_bytes);
9393 WARN_ON(BTRFS_I(inode)->new_delalloc_bytes);
9394 WARN_ON(BTRFS_I(inode)->csum_bytes);
9395 WARN_ON(BTRFS_I(inode)->defrag_bytes);
9398 * This can happen where we create an inode, but somebody else also
9399 * created the same inode and we need to destroy the one we already
9405 if (test_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
9406 &BTRFS_I(inode)->runtime_flags)) {
9407 btrfs_info(fs_info, "inode %llu still on the orphan list",
9408 btrfs_ino(BTRFS_I(inode)));
9409 atomic_dec(&root->orphan_inodes);
9413 ordered = btrfs_lookup_first_ordered_extent(inode, (u64)-1);
9418 "found ordered extent %llu %llu on inode cleanup",
9419 ordered->file_offset, ordered->len);
9420 btrfs_remove_ordered_extent(inode, ordered);
9421 btrfs_put_ordered_extent(ordered);
9422 btrfs_put_ordered_extent(ordered);
9425 btrfs_qgroup_check_reserved_leak(inode);
9426 inode_tree_del(inode);
9427 btrfs_drop_extent_cache(BTRFS_I(inode), 0, (u64)-1, 0);
9429 call_rcu(&inode->i_rcu, btrfs_i_callback);
9432 int btrfs_drop_inode(struct inode *inode)
9434 struct btrfs_root *root = BTRFS_I(inode)->root;
9439 /* the snap/subvol tree is on deleting */
9440 if (btrfs_root_refs(&root->root_item) == 0)
9443 return generic_drop_inode(inode);
9446 static void init_once(void *foo)
9448 struct btrfs_inode *ei = (struct btrfs_inode *) foo;
9450 inode_init_once(&ei->vfs_inode);
9453 void btrfs_destroy_cachep(void)
9456 * Make sure all delayed rcu free inodes are flushed before we
9460 kmem_cache_destroy(btrfs_inode_cachep);
9461 kmem_cache_destroy(btrfs_trans_handle_cachep);
9462 kmem_cache_destroy(btrfs_path_cachep);
9463 kmem_cache_destroy(btrfs_free_space_cachep);
9466 int __init btrfs_init_cachep(void)
9468 btrfs_inode_cachep = kmem_cache_create("btrfs_inode",
9469 sizeof(struct btrfs_inode), 0,
9470 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD | SLAB_ACCOUNT,
9472 if (!btrfs_inode_cachep)
9475 btrfs_trans_handle_cachep = kmem_cache_create("btrfs_trans_handle",
9476 sizeof(struct btrfs_trans_handle), 0,
9477 SLAB_TEMPORARY | SLAB_MEM_SPREAD, NULL);
9478 if (!btrfs_trans_handle_cachep)
9481 btrfs_path_cachep = kmem_cache_create("btrfs_path",
9482 sizeof(struct btrfs_path), 0,
9483 SLAB_MEM_SPREAD, NULL);
9484 if (!btrfs_path_cachep)
9487 btrfs_free_space_cachep = kmem_cache_create("btrfs_free_space",
9488 sizeof(struct btrfs_free_space), 0,
9489 SLAB_MEM_SPREAD, NULL);
9490 if (!btrfs_free_space_cachep)
9495 btrfs_destroy_cachep();
9499 static int btrfs_getattr(const struct path *path, struct kstat *stat,
9500 u32 request_mask, unsigned int flags)
9503 struct inode *inode = d_inode(path->dentry);
9504 u32 blocksize = inode->i_sb->s_blocksize;
9505 u32 bi_flags = BTRFS_I(inode)->flags;
9507 stat->result_mask |= STATX_BTIME;
9508 stat->btime.tv_sec = BTRFS_I(inode)->i_otime.tv_sec;
9509 stat->btime.tv_nsec = BTRFS_I(inode)->i_otime.tv_nsec;
9510 if (bi_flags & BTRFS_INODE_APPEND)
9511 stat->attributes |= STATX_ATTR_APPEND;
9512 if (bi_flags & BTRFS_INODE_COMPRESS)
9513 stat->attributes |= STATX_ATTR_COMPRESSED;
9514 if (bi_flags & BTRFS_INODE_IMMUTABLE)
9515 stat->attributes |= STATX_ATTR_IMMUTABLE;
9516 if (bi_flags & BTRFS_INODE_NODUMP)
9517 stat->attributes |= STATX_ATTR_NODUMP;
9519 stat->attributes_mask |= (STATX_ATTR_APPEND |
9520 STATX_ATTR_COMPRESSED |
9521 STATX_ATTR_IMMUTABLE |
9524 generic_fillattr(inode, stat);
9525 stat->dev = BTRFS_I(inode)->root->anon_dev;
9527 spin_lock(&BTRFS_I(inode)->lock);
9528 delalloc_bytes = BTRFS_I(inode)->new_delalloc_bytes;
9529 spin_unlock(&BTRFS_I(inode)->lock);
9530 stat->blocks = (ALIGN(inode_get_bytes(inode), blocksize) +
9531 ALIGN(delalloc_bytes, blocksize)) >> 9;
9535 static int btrfs_rename_exchange(struct inode *old_dir,
9536 struct dentry *old_dentry,
9537 struct inode *new_dir,
9538 struct dentry *new_dentry)
9540 struct btrfs_fs_info *fs_info = btrfs_sb(old_dir->i_sb);
9541 struct btrfs_trans_handle *trans;
9542 struct btrfs_root *root = BTRFS_I(old_dir)->root;
9543 struct btrfs_root *dest = BTRFS_I(new_dir)->root;
9544 struct inode *new_inode = new_dentry->d_inode;
9545 struct inode *old_inode = old_dentry->d_inode;
9546 struct timespec ctime = current_time(old_inode);
9547 struct dentry *parent;
9548 u64 old_ino = btrfs_ino(BTRFS_I(old_inode));
9549 u64 new_ino = btrfs_ino(BTRFS_I(new_inode));
9554 bool root_log_pinned = false;
9555 bool dest_log_pinned = false;
9557 /* we only allow rename subvolume link between subvolumes */
9558 if (old_ino != BTRFS_FIRST_FREE_OBJECTID && root != dest)
9561 /* close the race window with snapshot create/destroy ioctl */
9562 if (old_ino == BTRFS_FIRST_FREE_OBJECTID)
9563 down_read(&fs_info->subvol_sem);
9564 if (new_ino == BTRFS_FIRST_FREE_OBJECTID)
9565 down_read(&fs_info->subvol_sem);
9568 * We want to reserve the absolute worst case amount of items. So if
9569 * both inodes are subvols and we need to unlink them then that would
9570 * require 4 item modifications, but if they are both normal inodes it
9571 * would require 5 item modifications, so we'll assume their normal
9572 * inodes. So 5 * 2 is 10, plus 2 for the new links, so 12 total items
9573 * should cover the worst case number of items we'll modify.
9575 trans = btrfs_start_transaction(root, 12);
9576 if (IS_ERR(trans)) {
9577 ret = PTR_ERR(trans);
9582 * We need to find a free sequence number both in the source and
9583 * in the destination directory for the exchange.
9585 ret = btrfs_set_inode_index(BTRFS_I(new_dir), &old_idx);
9588 ret = btrfs_set_inode_index(BTRFS_I(old_dir), &new_idx);
9592 BTRFS_I(old_inode)->dir_index = 0ULL;
9593 BTRFS_I(new_inode)->dir_index = 0ULL;
9595 /* Reference for the source. */
9596 if (old_ino == BTRFS_FIRST_FREE_OBJECTID) {
9597 /* force full log commit if subvolume involved. */
9598 btrfs_set_log_full_commit(fs_info, trans);
9600 btrfs_pin_log_trans(root);
9601 root_log_pinned = true;
9602 ret = btrfs_insert_inode_ref(trans, dest,
9603 new_dentry->d_name.name,
9604 new_dentry->d_name.len,
9606 btrfs_ino(BTRFS_I(new_dir)),
9612 /* And now for the dest. */
9613 if (new_ino == BTRFS_FIRST_FREE_OBJECTID) {
9614 /* force full log commit if subvolume involved. */
9615 btrfs_set_log_full_commit(fs_info, trans);
9617 btrfs_pin_log_trans(dest);
9618 dest_log_pinned = true;
9619 ret = btrfs_insert_inode_ref(trans, root,
9620 old_dentry->d_name.name,
9621 old_dentry->d_name.len,
9623 btrfs_ino(BTRFS_I(old_dir)),
9629 /* Update inode version and ctime/mtime. */
9630 inode_inc_iversion(old_dir);
9631 inode_inc_iversion(new_dir);
9632 inode_inc_iversion(old_inode);
9633 inode_inc_iversion(new_inode);
9634 old_dir->i_ctime = old_dir->i_mtime = ctime;
9635 new_dir->i_ctime = new_dir->i_mtime = ctime;
9636 old_inode->i_ctime = ctime;
9637 new_inode->i_ctime = ctime;
9639 if (old_dentry->d_parent != new_dentry->d_parent) {
9640 btrfs_record_unlink_dir(trans, BTRFS_I(old_dir),
9641 BTRFS_I(old_inode), 1);
9642 btrfs_record_unlink_dir(trans, BTRFS_I(new_dir),
9643 BTRFS_I(new_inode), 1);
9646 /* src is a subvolume */
9647 if (old_ino == BTRFS_FIRST_FREE_OBJECTID) {
9648 root_objectid = BTRFS_I(old_inode)->root->root_key.objectid;
9649 ret = btrfs_unlink_subvol(trans, root, old_dir,
9651 old_dentry->d_name.name,
9652 old_dentry->d_name.len);
9653 } else { /* src is an inode */
9654 ret = __btrfs_unlink_inode(trans, root, BTRFS_I(old_dir),
9655 BTRFS_I(old_dentry->d_inode),
9656 old_dentry->d_name.name,
9657 old_dentry->d_name.len);
9659 ret = btrfs_update_inode(trans, root, old_inode);
9662 btrfs_abort_transaction(trans, ret);
9666 /* dest is a subvolume */
9667 if (new_ino == BTRFS_FIRST_FREE_OBJECTID) {
9668 root_objectid = BTRFS_I(new_inode)->root->root_key.objectid;
9669 ret = btrfs_unlink_subvol(trans, dest, new_dir,
9671 new_dentry->d_name.name,
9672 new_dentry->d_name.len);
9673 } else { /* dest is an inode */
9674 ret = __btrfs_unlink_inode(trans, dest, BTRFS_I(new_dir),
9675 BTRFS_I(new_dentry->d_inode),
9676 new_dentry->d_name.name,
9677 new_dentry->d_name.len);
9679 ret = btrfs_update_inode(trans, dest, new_inode);
9682 btrfs_abort_transaction(trans, ret);
9686 ret = btrfs_add_link(trans, BTRFS_I(new_dir), BTRFS_I(old_inode),
9687 new_dentry->d_name.name,
9688 new_dentry->d_name.len, 0, old_idx);
9690 btrfs_abort_transaction(trans, ret);
9694 ret = btrfs_add_link(trans, BTRFS_I(old_dir), BTRFS_I(new_inode),
9695 old_dentry->d_name.name,
9696 old_dentry->d_name.len, 0, new_idx);
9698 btrfs_abort_transaction(trans, ret);
9702 if (old_inode->i_nlink == 1)
9703 BTRFS_I(old_inode)->dir_index = old_idx;
9704 if (new_inode->i_nlink == 1)
9705 BTRFS_I(new_inode)->dir_index = new_idx;
9707 if (root_log_pinned) {
9708 parent = new_dentry->d_parent;
9709 btrfs_log_new_name(trans, BTRFS_I(old_inode), BTRFS_I(old_dir),
9711 btrfs_end_log_trans(root);
9712 root_log_pinned = false;
9714 if (dest_log_pinned) {
9715 parent = old_dentry->d_parent;
9716 btrfs_log_new_name(trans, BTRFS_I(new_inode), BTRFS_I(new_dir),
9718 btrfs_end_log_trans(dest);
9719 dest_log_pinned = false;
9723 * If we have pinned a log and an error happened, we unpin tasks
9724 * trying to sync the log and force them to fallback to a transaction
9725 * commit if the log currently contains any of the inodes involved in
9726 * this rename operation (to ensure we do not persist a log with an
9727 * inconsistent state for any of these inodes or leading to any
9728 * inconsistencies when replayed). If the transaction was aborted, the
9729 * abortion reason is propagated to userspace when attempting to commit
9730 * the transaction. If the log does not contain any of these inodes, we
9731 * allow the tasks to sync it.
9733 if (ret && (root_log_pinned || dest_log_pinned)) {
9734 if (btrfs_inode_in_log(BTRFS_I(old_dir), fs_info->generation) ||
9735 btrfs_inode_in_log(BTRFS_I(new_dir), fs_info->generation) ||
9736 btrfs_inode_in_log(BTRFS_I(old_inode), fs_info->generation) ||
9738 btrfs_inode_in_log(BTRFS_I(new_inode), fs_info->generation)))
9739 btrfs_set_log_full_commit(fs_info, trans);
9741 if (root_log_pinned) {
9742 btrfs_end_log_trans(root);
9743 root_log_pinned = false;
9745 if (dest_log_pinned) {
9746 btrfs_end_log_trans(dest);
9747 dest_log_pinned = false;
9750 ret = btrfs_end_transaction(trans);
9752 if (new_ino == BTRFS_FIRST_FREE_OBJECTID)
9753 up_read(&fs_info->subvol_sem);
9754 if (old_ino == BTRFS_FIRST_FREE_OBJECTID)
9755 up_read(&fs_info->subvol_sem);
9760 static int btrfs_whiteout_for_rename(struct btrfs_trans_handle *trans,
9761 struct btrfs_root *root,
9763 struct dentry *dentry)
9766 struct inode *inode;
9770 ret = btrfs_find_free_ino(root, &objectid);
9774 inode = btrfs_new_inode(trans, root, dir,
9775 dentry->d_name.name,
9777 btrfs_ino(BTRFS_I(dir)),
9779 S_IFCHR | WHITEOUT_MODE,
9782 if (IS_ERR(inode)) {
9783 ret = PTR_ERR(inode);
9787 inode->i_op = &btrfs_special_inode_operations;
9788 init_special_inode(inode, inode->i_mode,
9791 ret = btrfs_init_inode_security(trans, inode, dir,
9796 ret = btrfs_add_nondir(trans, BTRFS_I(dir), dentry,
9797 BTRFS_I(inode), 0, index);
9801 ret = btrfs_update_inode(trans, root, inode);
9803 unlock_new_inode(inode);
9805 inode_dec_link_count(inode);
9811 static int btrfs_rename(struct inode *old_dir, struct dentry *old_dentry,
9812 struct inode *new_dir, struct dentry *new_dentry,
9815 struct btrfs_fs_info *fs_info = btrfs_sb(old_dir->i_sb);
9816 struct btrfs_trans_handle *trans;
9817 unsigned int trans_num_items;
9818 struct btrfs_root *root = BTRFS_I(old_dir)->root;
9819 struct btrfs_root *dest = BTRFS_I(new_dir)->root;
9820 struct inode *new_inode = d_inode(new_dentry);
9821 struct inode *old_inode = d_inode(old_dentry);
9825 u64 old_ino = btrfs_ino(BTRFS_I(old_inode));
9826 bool log_pinned = false;
9828 if (btrfs_ino(BTRFS_I(new_dir)) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)
9831 /* we only allow rename subvolume link between subvolumes */
9832 if (old_ino != BTRFS_FIRST_FREE_OBJECTID && root != dest)
9835 if (old_ino == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID ||
9836 (new_inode && btrfs_ino(BTRFS_I(new_inode)) == BTRFS_FIRST_FREE_OBJECTID))
9839 if (S_ISDIR(old_inode->i_mode) && new_inode &&
9840 new_inode->i_size > BTRFS_EMPTY_DIR_SIZE)
9844 /* check for collisions, even if the name isn't there */
9845 ret = btrfs_check_dir_item_collision(dest, new_dir->i_ino,
9846 new_dentry->d_name.name,
9847 new_dentry->d_name.len);
9850 if (ret == -EEXIST) {
9852 * eexist without a new_inode */
9853 if (WARN_ON(!new_inode)) {
9857 /* maybe -EOVERFLOW */
9864 * we're using rename to replace one file with another. Start IO on it
9865 * now so we don't add too much work to the end of the transaction
9867 if (new_inode && S_ISREG(old_inode->i_mode) && new_inode->i_size)
9868 filemap_flush(old_inode->i_mapping);
9870 /* close the racy window with snapshot create/destroy ioctl */
9871 if (old_ino == BTRFS_FIRST_FREE_OBJECTID)
9872 down_read(&fs_info->subvol_sem);
9874 * We want to reserve the absolute worst case amount of items. So if
9875 * both inodes are subvols and we need to unlink them then that would
9876 * require 4 item modifications, but if they are both normal inodes it
9877 * would require 5 item modifications, so we'll assume they are normal
9878 * inodes. So 5 * 2 is 10, plus 1 for the new link, so 11 total items
9879 * should cover the worst case number of items we'll modify.
9880 * If our rename has the whiteout flag, we need more 5 units for the
9881 * new inode (1 inode item, 1 inode ref, 2 dir items and 1 xattr item
9882 * when selinux is enabled).
9884 trans_num_items = 11;
9885 if (flags & RENAME_WHITEOUT)
9886 trans_num_items += 5;
9887 trans = btrfs_start_transaction(root, trans_num_items);
9888 if (IS_ERR(trans)) {
9889 ret = PTR_ERR(trans);
9894 btrfs_record_root_in_trans(trans, dest);
9896 ret = btrfs_set_inode_index(BTRFS_I(new_dir), &index);
9900 BTRFS_I(old_inode)->dir_index = 0ULL;
9901 if (unlikely(old_ino == BTRFS_FIRST_FREE_OBJECTID)) {
9902 /* force full log commit if subvolume involved. */
9903 btrfs_set_log_full_commit(fs_info, trans);
9905 btrfs_pin_log_trans(root);
9907 ret = btrfs_insert_inode_ref(trans, dest,
9908 new_dentry->d_name.name,
9909 new_dentry->d_name.len,
9911 btrfs_ino(BTRFS_I(new_dir)), index);
9916 inode_inc_iversion(old_dir);
9917 inode_inc_iversion(new_dir);
9918 inode_inc_iversion(old_inode);
9919 old_dir->i_ctime = old_dir->i_mtime =
9920 new_dir->i_ctime = new_dir->i_mtime =
9921 old_inode->i_ctime = current_time(old_dir);
9923 if (old_dentry->d_parent != new_dentry->d_parent)
9924 btrfs_record_unlink_dir(trans, BTRFS_I(old_dir),
9925 BTRFS_I(old_inode), 1);
9927 if (unlikely(old_ino == BTRFS_FIRST_FREE_OBJECTID)) {
9928 root_objectid = BTRFS_I(old_inode)->root->root_key.objectid;
9929 ret = btrfs_unlink_subvol(trans, root, old_dir, root_objectid,
9930 old_dentry->d_name.name,
9931 old_dentry->d_name.len);
9933 ret = __btrfs_unlink_inode(trans, root, BTRFS_I(old_dir),
9934 BTRFS_I(d_inode(old_dentry)),
9935 old_dentry->d_name.name,
9936 old_dentry->d_name.len);
9938 ret = btrfs_update_inode(trans, root, old_inode);
9941 btrfs_abort_transaction(trans, ret);
9946 inode_inc_iversion(new_inode);
9947 new_inode->i_ctime = current_time(new_inode);
9948 if (unlikely(btrfs_ino(BTRFS_I(new_inode)) ==
9949 BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)) {
9950 root_objectid = BTRFS_I(new_inode)->location.objectid;
9951 ret = btrfs_unlink_subvol(trans, dest, new_dir,
9953 new_dentry->d_name.name,
9954 new_dentry->d_name.len);
9955 BUG_ON(new_inode->i_nlink == 0);
9957 ret = btrfs_unlink_inode(trans, dest, BTRFS_I(new_dir),
9958 BTRFS_I(d_inode(new_dentry)),
9959 new_dentry->d_name.name,
9960 new_dentry->d_name.len);
9962 if (!ret && new_inode->i_nlink == 0)
9963 ret = btrfs_orphan_add(trans,
9964 BTRFS_I(d_inode(new_dentry)));
9966 btrfs_abort_transaction(trans, ret);
9971 ret = btrfs_add_link(trans, BTRFS_I(new_dir), BTRFS_I(old_inode),
9972 new_dentry->d_name.name,
9973 new_dentry->d_name.len, 0, index);
9975 btrfs_abort_transaction(trans, ret);
9979 if (old_inode->i_nlink == 1)
9980 BTRFS_I(old_inode)->dir_index = index;
9983 struct dentry *parent = new_dentry->d_parent;
9985 btrfs_log_new_name(trans, BTRFS_I(old_inode), BTRFS_I(old_dir),
9987 btrfs_end_log_trans(root);
9991 if (flags & RENAME_WHITEOUT) {
9992 ret = btrfs_whiteout_for_rename(trans, root, old_dir,
9996 btrfs_abort_transaction(trans, ret);
10002 * If we have pinned the log and an error happened, we unpin tasks
10003 * trying to sync the log and force them to fallback to a transaction
10004 * commit if the log currently contains any of the inodes involved in
10005 * this rename operation (to ensure we do not persist a log with an
10006 * inconsistent state for any of these inodes or leading to any
10007 * inconsistencies when replayed). If the transaction was aborted, the
10008 * abortion reason is propagated to userspace when attempting to commit
10009 * the transaction. If the log does not contain any of these inodes, we
10010 * allow the tasks to sync it.
10012 if (ret && log_pinned) {
10013 if (btrfs_inode_in_log(BTRFS_I(old_dir), fs_info->generation) ||
10014 btrfs_inode_in_log(BTRFS_I(new_dir), fs_info->generation) ||
10015 btrfs_inode_in_log(BTRFS_I(old_inode), fs_info->generation) ||
10017 btrfs_inode_in_log(BTRFS_I(new_inode), fs_info->generation)))
10018 btrfs_set_log_full_commit(fs_info, trans);
10020 btrfs_end_log_trans(root);
10021 log_pinned = false;
10023 btrfs_end_transaction(trans);
10025 if (old_ino == BTRFS_FIRST_FREE_OBJECTID)
10026 up_read(&fs_info->subvol_sem);
10031 static int btrfs_rename2(struct inode *old_dir, struct dentry *old_dentry,
10032 struct inode *new_dir, struct dentry *new_dentry,
10033 unsigned int flags)
10035 if (flags & ~(RENAME_NOREPLACE | RENAME_EXCHANGE | RENAME_WHITEOUT))
10038 if (flags & RENAME_EXCHANGE)
10039 return btrfs_rename_exchange(old_dir, old_dentry, new_dir,
10042 return btrfs_rename(old_dir, old_dentry, new_dir, new_dentry, flags);
10045 static void btrfs_run_delalloc_work(struct btrfs_work *work)
10047 struct btrfs_delalloc_work *delalloc_work;
10048 struct inode *inode;
10050 delalloc_work = container_of(work, struct btrfs_delalloc_work,
10052 inode = delalloc_work->inode;
10053 filemap_flush(inode->i_mapping);
10054 if (test_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
10055 &BTRFS_I(inode)->runtime_flags))
10056 filemap_flush(inode->i_mapping);
10058 if (delalloc_work->delay_iput)
10059 btrfs_add_delayed_iput(inode);
10062 complete(&delalloc_work->completion);
10065 struct btrfs_delalloc_work *btrfs_alloc_delalloc_work(struct inode *inode,
10068 struct btrfs_delalloc_work *work;
10070 work = kmalloc(sizeof(*work), GFP_NOFS);
10074 init_completion(&work->completion);
10075 INIT_LIST_HEAD(&work->list);
10076 work->inode = inode;
10077 work->delay_iput = delay_iput;
10078 WARN_ON_ONCE(!inode);
10079 btrfs_init_work(&work->work, btrfs_flush_delalloc_helper,
10080 btrfs_run_delalloc_work, NULL, NULL);
10085 void btrfs_wait_and_free_delalloc_work(struct btrfs_delalloc_work *work)
10087 wait_for_completion(&work->completion);
10092 * some fairly slow code that needs optimization. This walks the list
10093 * of all the inodes with pending delalloc and forces them to disk.
10095 static int __start_delalloc_inodes(struct btrfs_root *root, int delay_iput,
10098 struct btrfs_inode *binode;
10099 struct inode *inode;
10100 struct btrfs_delalloc_work *work, *next;
10101 struct list_head works;
10102 struct list_head splice;
10105 INIT_LIST_HEAD(&works);
10106 INIT_LIST_HEAD(&splice);
10108 mutex_lock(&root->delalloc_mutex);
10109 spin_lock(&root->delalloc_lock);
10110 list_splice_init(&root->delalloc_inodes, &splice);
10111 while (!list_empty(&splice)) {
10112 binode = list_entry(splice.next, struct btrfs_inode,
10115 list_move_tail(&binode->delalloc_inodes,
10116 &root->delalloc_inodes);
10117 inode = igrab(&binode->vfs_inode);
10119 cond_resched_lock(&root->delalloc_lock);
10122 spin_unlock(&root->delalloc_lock);
10124 work = btrfs_alloc_delalloc_work(inode, delay_iput);
10127 btrfs_add_delayed_iput(inode);
10133 list_add_tail(&work->list, &works);
10134 btrfs_queue_work(root->fs_info->flush_workers,
10137 if (nr != -1 && ret >= nr)
10140 spin_lock(&root->delalloc_lock);
10142 spin_unlock(&root->delalloc_lock);
10145 list_for_each_entry_safe(work, next, &works, list) {
10146 list_del_init(&work->list);
10147 btrfs_wait_and_free_delalloc_work(work);
10150 if (!list_empty_careful(&splice)) {
10151 spin_lock(&root->delalloc_lock);
10152 list_splice_tail(&splice, &root->delalloc_inodes);
10153 spin_unlock(&root->delalloc_lock);
10155 mutex_unlock(&root->delalloc_mutex);
10159 int btrfs_start_delalloc_inodes(struct btrfs_root *root, int delay_iput)
10161 struct btrfs_fs_info *fs_info = root->fs_info;
10164 if (test_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state))
10167 ret = __start_delalloc_inodes(root, delay_iput, -1);
10173 int btrfs_start_delalloc_roots(struct btrfs_fs_info *fs_info, int delay_iput,
10176 struct btrfs_root *root;
10177 struct list_head splice;
10180 if (test_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state))
10183 INIT_LIST_HEAD(&splice);
10185 mutex_lock(&fs_info->delalloc_root_mutex);
10186 spin_lock(&fs_info->delalloc_root_lock);
10187 list_splice_init(&fs_info->delalloc_roots, &splice);
10188 while (!list_empty(&splice) && nr) {
10189 root = list_first_entry(&splice, struct btrfs_root,
10191 root = btrfs_grab_fs_root(root);
10193 list_move_tail(&root->delalloc_root,
10194 &fs_info->delalloc_roots);
10195 spin_unlock(&fs_info->delalloc_root_lock);
10197 ret = __start_delalloc_inodes(root, delay_iput, nr);
10198 btrfs_put_fs_root(root);
10206 spin_lock(&fs_info->delalloc_root_lock);
10208 spin_unlock(&fs_info->delalloc_root_lock);
10212 if (!list_empty_careful(&splice)) {
10213 spin_lock(&fs_info->delalloc_root_lock);
10214 list_splice_tail(&splice, &fs_info->delalloc_roots);
10215 spin_unlock(&fs_info->delalloc_root_lock);
10217 mutex_unlock(&fs_info->delalloc_root_mutex);
10221 static int btrfs_symlink(struct inode *dir, struct dentry *dentry,
10222 const char *symname)
10224 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
10225 struct btrfs_trans_handle *trans;
10226 struct btrfs_root *root = BTRFS_I(dir)->root;
10227 struct btrfs_path *path;
10228 struct btrfs_key key;
10229 struct inode *inode = NULL;
10231 int drop_inode = 0;
10237 struct btrfs_file_extent_item *ei;
10238 struct extent_buffer *leaf;
10240 name_len = strlen(symname);
10241 if (name_len > BTRFS_MAX_INLINE_DATA_SIZE(fs_info))
10242 return -ENAMETOOLONG;
10245 * 2 items for inode item and ref
10246 * 2 items for dir items
10247 * 1 item for updating parent inode item
10248 * 1 item for the inline extent item
10249 * 1 item for xattr if selinux is on
10251 trans = btrfs_start_transaction(root, 7);
10253 return PTR_ERR(trans);
10255 err = btrfs_find_free_ino(root, &objectid);
10259 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
10260 dentry->d_name.len, btrfs_ino(BTRFS_I(dir)),
10261 objectid, S_IFLNK|S_IRWXUGO, &index);
10262 if (IS_ERR(inode)) {
10263 err = PTR_ERR(inode);
10268 * If the active LSM wants to access the inode during
10269 * d_instantiate it needs these. Smack checks to see
10270 * if the filesystem supports xattrs by looking at the
10273 inode->i_fop = &btrfs_file_operations;
10274 inode->i_op = &btrfs_file_inode_operations;
10275 inode->i_mapping->a_ops = &btrfs_aops;
10276 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
10278 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
10280 goto out_unlock_inode;
10282 path = btrfs_alloc_path();
10285 goto out_unlock_inode;
10287 key.objectid = btrfs_ino(BTRFS_I(inode));
10289 key.type = BTRFS_EXTENT_DATA_KEY;
10290 datasize = btrfs_file_extent_calc_inline_size(name_len);
10291 err = btrfs_insert_empty_item(trans, root, path, &key,
10294 btrfs_free_path(path);
10295 goto out_unlock_inode;
10297 leaf = path->nodes[0];
10298 ei = btrfs_item_ptr(leaf, path->slots[0],
10299 struct btrfs_file_extent_item);
10300 btrfs_set_file_extent_generation(leaf, ei, trans->transid);
10301 btrfs_set_file_extent_type(leaf, ei,
10302 BTRFS_FILE_EXTENT_INLINE);
10303 btrfs_set_file_extent_encryption(leaf, ei, 0);
10304 btrfs_set_file_extent_compression(leaf, ei, 0);
10305 btrfs_set_file_extent_other_encoding(leaf, ei, 0);
10306 btrfs_set_file_extent_ram_bytes(leaf, ei, name_len);
10308 ptr = btrfs_file_extent_inline_start(ei);
10309 write_extent_buffer(leaf, symname, ptr, name_len);
10310 btrfs_mark_buffer_dirty(leaf);
10311 btrfs_free_path(path);
10313 inode->i_op = &btrfs_symlink_inode_operations;
10314 inode_nohighmem(inode);
10315 inode->i_mapping->a_ops = &btrfs_symlink_aops;
10316 inode_set_bytes(inode, name_len);
10317 btrfs_i_size_write(BTRFS_I(inode), name_len);
10318 err = btrfs_update_inode(trans, root, inode);
10320 * Last step, add directory indexes for our symlink inode. This is the
10321 * last step to avoid extra cleanup of these indexes if an error happens
10325 err = btrfs_add_nondir(trans, BTRFS_I(dir), dentry,
10326 BTRFS_I(inode), 0, index);
10329 goto out_unlock_inode;
10332 unlock_new_inode(inode);
10333 d_instantiate(dentry, inode);
10336 btrfs_end_transaction(trans);
10338 inode_dec_link_count(inode);
10341 btrfs_btree_balance_dirty(fs_info);
10346 unlock_new_inode(inode);
10350 static int __btrfs_prealloc_file_range(struct inode *inode, int mode,
10351 u64 start, u64 num_bytes, u64 min_size,
10352 loff_t actual_len, u64 *alloc_hint,
10353 struct btrfs_trans_handle *trans)
10355 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
10356 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
10357 struct extent_map *em;
10358 struct btrfs_root *root = BTRFS_I(inode)->root;
10359 struct btrfs_key ins;
10360 u64 cur_offset = start;
10363 u64 last_alloc = (u64)-1;
10365 bool own_trans = true;
10366 u64 end = start + num_bytes - 1;
10370 while (num_bytes > 0) {
10372 trans = btrfs_start_transaction(root, 3);
10373 if (IS_ERR(trans)) {
10374 ret = PTR_ERR(trans);
10379 cur_bytes = min_t(u64, num_bytes, SZ_256M);
10380 cur_bytes = max(cur_bytes, min_size);
10382 * If we are severely fragmented we could end up with really
10383 * small allocations, so if the allocator is returning small
10384 * chunks lets make its job easier by only searching for those
10387 cur_bytes = min(cur_bytes, last_alloc);
10388 ret = btrfs_reserve_extent(root, cur_bytes, cur_bytes,
10389 min_size, 0, *alloc_hint, &ins, 1, 0);
10392 btrfs_end_transaction(trans);
10395 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
10397 last_alloc = ins.offset;
10398 ret = insert_reserved_file_extent(trans, inode,
10399 cur_offset, ins.objectid,
10400 ins.offset, ins.offset,
10401 ins.offset, 0, 0, 0,
10402 BTRFS_FILE_EXTENT_PREALLOC);
10404 btrfs_free_reserved_extent(fs_info, ins.objectid,
10406 btrfs_abort_transaction(trans, ret);
10408 btrfs_end_transaction(trans);
10412 btrfs_drop_extent_cache(BTRFS_I(inode), cur_offset,
10413 cur_offset + ins.offset -1, 0);
10415 em = alloc_extent_map();
10417 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
10418 &BTRFS_I(inode)->runtime_flags);
10422 em->start = cur_offset;
10423 em->orig_start = cur_offset;
10424 em->len = ins.offset;
10425 em->block_start = ins.objectid;
10426 em->block_len = ins.offset;
10427 em->orig_block_len = ins.offset;
10428 em->ram_bytes = ins.offset;
10429 em->bdev = fs_info->fs_devices->latest_bdev;
10430 set_bit(EXTENT_FLAG_PREALLOC, &em->flags);
10431 em->generation = trans->transid;
10434 write_lock(&em_tree->lock);
10435 ret = add_extent_mapping(em_tree, em, 1);
10436 write_unlock(&em_tree->lock);
10437 if (ret != -EEXIST)
10439 btrfs_drop_extent_cache(BTRFS_I(inode), cur_offset,
10440 cur_offset + ins.offset - 1,
10443 free_extent_map(em);
10445 num_bytes -= ins.offset;
10446 cur_offset += ins.offset;
10447 *alloc_hint = ins.objectid + ins.offset;
10449 inode_inc_iversion(inode);
10450 inode->i_ctime = current_time(inode);
10451 BTRFS_I(inode)->flags |= BTRFS_INODE_PREALLOC;
10452 if (!(mode & FALLOC_FL_KEEP_SIZE) &&
10453 (actual_len > inode->i_size) &&
10454 (cur_offset > inode->i_size)) {
10455 if (cur_offset > actual_len)
10456 i_size = actual_len;
10458 i_size = cur_offset;
10459 i_size_write(inode, i_size);
10460 btrfs_ordered_update_i_size(inode, i_size, NULL);
10463 ret = btrfs_update_inode(trans, root, inode);
10466 btrfs_abort_transaction(trans, ret);
10468 btrfs_end_transaction(trans);
10473 btrfs_end_transaction(trans);
10475 if (cur_offset < end)
10476 btrfs_free_reserved_data_space(inode, NULL, cur_offset,
10477 end - cur_offset + 1);
10481 int btrfs_prealloc_file_range(struct inode *inode, int mode,
10482 u64 start, u64 num_bytes, u64 min_size,
10483 loff_t actual_len, u64 *alloc_hint)
10485 return __btrfs_prealloc_file_range(inode, mode, start, num_bytes,
10486 min_size, actual_len, alloc_hint,
10490 int btrfs_prealloc_file_range_trans(struct inode *inode,
10491 struct btrfs_trans_handle *trans, int mode,
10492 u64 start, u64 num_bytes, u64 min_size,
10493 loff_t actual_len, u64 *alloc_hint)
10495 return __btrfs_prealloc_file_range(inode, mode, start, num_bytes,
10496 min_size, actual_len, alloc_hint, trans);
10499 static int btrfs_set_page_dirty(struct page *page)
10501 return __set_page_dirty_nobuffers(page);
10504 static int btrfs_permission(struct inode *inode, int mask)
10506 struct btrfs_root *root = BTRFS_I(inode)->root;
10507 umode_t mode = inode->i_mode;
10509 if (mask & MAY_WRITE &&
10510 (S_ISREG(mode) || S_ISDIR(mode) || S_ISLNK(mode))) {
10511 if (btrfs_root_readonly(root))
10513 if (BTRFS_I(inode)->flags & BTRFS_INODE_READONLY)
10516 return generic_permission(inode, mask);
10519 static int btrfs_tmpfile(struct inode *dir, struct dentry *dentry, umode_t mode)
10521 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
10522 struct btrfs_trans_handle *trans;
10523 struct btrfs_root *root = BTRFS_I(dir)->root;
10524 struct inode *inode = NULL;
10530 * 5 units required for adding orphan entry
10532 trans = btrfs_start_transaction(root, 5);
10534 return PTR_ERR(trans);
10536 ret = btrfs_find_free_ino(root, &objectid);
10540 inode = btrfs_new_inode(trans, root, dir, NULL, 0,
10541 btrfs_ino(BTRFS_I(dir)), objectid, mode, &index);
10542 if (IS_ERR(inode)) {
10543 ret = PTR_ERR(inode);
10548 inode->i_fop = &btrfs_file_operations;
10549 inode->i_op = &btrfs_file_inode_operations;
10551 inode->i_mapping->a_ops = &btrfs_aops;
10552 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
10554 ret = btrfs_init_inode_security(trans, inode, dir, NULL);
10558 ret = btrfs_update_inode(trans, root, inode);
10561 ret = btrfs_orphan_add(trans, BTRFS_I(inode));
10566 * We set number of links to 0 in btrfs_new_inode(), and here we set
10567 * it to 1 because d_tmpfile() will issue a warning if the count is 0,
10570 * d_tmpfile() -> inode_dec_link_count() -> drop_nlink()
10572 set_nlink(inode, 1);
10573 unlock_new_inode(inode);
10574 d_tmpfile(dentry, inode);
10575 mark_inode_dirty(inode);
10578 btrfs_end_transaction(trans);
10581 btrfs_btree_balance_dirty(fs_info);
10585 unlock_new_inode(inode);
10590 __attribute__((const))
10591 static int btrfs_readpage_io_failed_hook(struct page *page, int failed_mirror)
10596 static struct btrfs_fs_info *iotree_fs_info(void *private_data)
10598 struct inode *inode = private_data;
10599 return btrfs_sb(inode->i_sb);
10602 static void btrfs_check_extent_io_range(void *private_data, const char *caller,
10603 u64 start, u64 end)
10605 struct inode *inode = private_data;
10608 isize = i_size_read(inode);
10609 if (end >= PAGE_SIZE && (end % 2) == 0 && end != isize - 1) {
10610 btrfs_debug_rl(BTRFS_I(inode)->root->fs_info,
10611 "%s: ino %llu isize %llu odd range [%llu,%llu]",
10612 caller, btrfs_ino(BTRFS_I(inode)), isize, start, end);
10616 void btrfs_set_range_writeback(void *private_data, u64 start, u64 end)
10618 struct inode *inode = private_data;
10619 unsigned long index = start >> PAGE_SHIFT;
10620 unsigned long end_index = end >> PAGE_SHIFT;
10623 while (index <= end_index) {
10624 page = find_get_page(inode->i_mapping, index);
10625 ASSERT(page); /* Pages should be in the extent_io_tree */
10626 set_page_writeback(page);
10632 static const struct inode_operations btrfs_dir_inode_operations = {
10633 .getattr = btrfs_getattr,
10634 .lookup = btrfs_lookup,
10635 .create = btrfs_create,
10636 .unlink = btrfs_unlink,
10637 .link = btrfs_link,
10638 .mkdir = btrfs_mkdir,
10639 .rmdir = btrfs_rmdir,
10640 .rename = btrfs_rename2,
10641 .symlink = btrfs_symlink,
10642 .setattr = btrfs_setattr,
10643 .mknod = btrfs_mknod,
10644 .listxattr = btrfs_listxattr,
10645 .permission = btrfs_permission,
10646 .get_acl = btrfs_get_acl,
10647 .set_acl = btrfs_set_acl,
10648 .update_time = btrfs_update_time,
10649 .tmpfile = btrfs_tmpfile,
10651 static const struct inode_operations btrfs_dir_ro_inode_operations = {
10652 .lookup = btrfs_lookup,
10653 .permission = btrfs_permission,
10654 .update_time = btrfs_update_time,
10657 static const struct file_operations btrfs_dir_file_operations = {
10658 .llseek = generic_file_llseek,
10659 .read = generic_read_dir,
10660 .iterate_shared = btrfs_real_readdir,
10661 .open = btrfs_opendir,
10662 .unlocked_ioctl = btrfs_ioctl,
10663 #ifdef CONFIG_COMPAT
10664 .compat_ioctl = btrfs_compat_ioctl,
10666 .release = btrfs_release_file,
10667 .fsync = btrfs_sync_file,
10670 static const struct extent_io_ops btrfs_extent_io_ops = {
10671 /* mandatory callbacks */
10672 .submit_bio_hook = btrfs_submit_bio_hook,
10673 .readpage_end_io_hook = btrfs_readpage_end_io_hook,
10674 .merge_bio_hook = btrfs_merge_bio_hook,
10675 .readpage_io_failed_hook = btrfs_readpage_io_failed_hook,
10676 .tree_fs_info = iotree_fs_info,
10677 .set_range_writeback = btrfs_set_range_writeback,
10679 /* optional callbacks */
10680 .fill_delalloc = run_delalloc_range,
10681 .writepage_end_io_hook = btrfs_writepage_end_io_hook,
10682 .writepage_start_hook = btrfs_writepage_start_hook,
10683 .set_bit_hook = btrfs_set_bit_hook,
10684 .clear_bit_hook = btrfs_clear_bit_hook,
10685 .merge_extent_hook = btrfs_merge_extent_hook,
10686 .split_extent_hook = btrfs_split_extent_hook,
10687 .check_extent_io_range = btrfs_check_extent_io_range,
10691 * btrfs doesn't support the bmap operation because swapfiles
10692 * use bmap to make a mapping of extents in the file. They assume
10693 * these extents won't change over the life of the file and they
10694 * use the bmap result to do IO directly to the drive.
10696 * the btrfs bmap call would return logical addresses that aren't
10697 * suitable for IO and they also will change frequently as COW
10698 * operations happen. So, swapfile + btrfs == corruption.
10700 * For now we're avoiding this by dropping bmap.
10702 static const struct address_space_operations btrfs_aops = {
10703 .readpage = btrfs_readpage,
10704 .writepage = btrfs_writepage,
10705 .writepages = btrfs_writepages,
10706 .readpages = btrfs_readpages,
10707 .direct_IO = btrfs_direct_IO,
10708 .invalidatepage = btrfs_invalidatepage,
10709 .releasepage = btrfs_releasepage,
10710 .set_page_dirty = btrfs_set_page_dirty,
10711 .error_remove_page = generic_error_remove_page,
10714 static const struct address_space_operations btrfs_symlink_aops = {
10715 .readpage = btrfs_readpage,
10716 .writepage = btrfs_writepage,
10717 .invalidatepage = btrfs_invalidatepage,
10718 .releasepage = btrfs_releasepage,
10721 static const struct inode_operations btrfs_file_inode_operations = {
10722 .getattr = btrfs_getattr,
10723 .setattr = btrfs_setattr,
10724 .listxattr = btrfs_listxattr,
10725 .permission = btrfs_permission,
10726 .fiemap = btrfs_fiemap,
10727 .get_acl = btrfs_get_acl,
10728 .set_acl = btrfs_set_acl,
10729 .update_time = btrfs_update_time,
10731 static const struct inode_operations btrfs_special_inode_operations = {
10732 .getattr = btrfs_getattr,
10733 .setattr = btrfs_setattr,
10734 .permission = btrfs_permission,
10735 .listxattr = btrfs_listxattr,
10736 .get_acl = btrfs_get_acl,
10737 .set_acl = btrfs_set_acl,
10738 .update_time = btrfs_update_time,
10740 static const struct inode_operations btrfs_symlink_inode_operations = {
10741 .get_link = page_get_link,
10742 .getattr = btrfs_getattr,
10743 .setattr = btrfs_setattr,
10744 .permission = btrfs_permission,
10745 .listxattr = btrfs_listxattr,
10746 .update_time = btrfs_update_time,
10749 const struct dentry_operations btrfs_dentry_operations = {
10750 .d_delete = btrfs_dentry_delete,
10751 .d_release = btrfs_dentry_release,