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>
48 #include "transaction.h"
49 #include "btrfs_inode.h"
50 #include "print-tree.h"
51 #include "ordered-data.h"
55 #include "compression.h"
57 #include "free-space-cache.h"
58 #include "inode-map.h"
65 struct btrfs_iget_args {
66 struct btrfs_key *location;
67 struct btrfs_root *root;
70 struct btrfs_dio_data {
72 u64 unsubmitted_oe_range_start;
73 u64 unsubmitted_oe_range_end;
77 static const struct inode_operations btrfs_dir_inode_operations;
78 static const struct inode_operations btrfs_symlink_inode_operations;
79 static const struct inode_operations btrfs_dir_ro_inode_operations;
80 static const struct inode_operations btrfs_special_inode_operations;
81 static const struct inode_operations btrfs_file_inode_operations;
82 static const struct address_space_operations btrfs_aops;
83 static const struct address_space_operations btrfs_symlink_aops;
84 static const struct file_operations btrfs_dir_file_operations;
85 static const struct extent_io_ops btrfs_extent_io_ops;
87 static struct kmem_cache *btrfs_inode_cachep;
88 struct kmem_cache *btrfs_trans_handle_cachep;
89 struct kmem_cache *btrfs_path_cachep;
90 struct kmem_cache *btrfs_free_space_cachep;
93 static const unsigned char btrfs_type_by_mode[S_IFMT >> S_SHIFT] = {
94 [S_IFREG >> S_SHIFT] = BTRFS_FT_REG_FILE,
95 [S_IFDIR >> S_SHIFT] = BTRFS_FT_DIR,
96 [S_IFCHR >> S_SHIFT] = BTRFS_FT_CHRDEV,
97 [S_IFBLK >> S_SHIFT] = BTRFS_FT_BLKDEV,
98 [S_IFIFO >> S_SHIFT] = BTRFS_FT_FIFO,
99 [S_IFSOCK >> S_SHIFT] = BTRFS_FT_SOCK,
100 [S_IFLNK >> S_SHIFT] = BTRFS_FT_SYMLINK,
103 static int btrfs_setsize(struct inode *inode, struct iattr *attr);
104 static int btrfs_truncate(struct inode *inode);
105 static int btrfs_finish_ordered_io(struct btrfs_ordered_extent *ordered_extent);
106 static noinline int cow_file_range(struct inode *inode,
107 struct page *locked_page,
108 u64 start, u64 end, u64 delalloc_end,
109 int *page_started, unsigned long *nr_written,
110 int unlock, struct btrfs_dedupe_hash *hash);
111 static struct extent_map *create_io_em(struct inode *inode, u64 start, u64 len,
112 u64 orig_start, u64 block_start,
113 u64 block_len, u64 orig_block_len,
114 u64 ram_bytes, int compress_type,
117 static void __endio_write_update_ordered(struct inode *inode,
118 const u64 offset, const u64 bytes,
119 const bool uptodate);
122 * Cleanup all submitted ordered extents in specified range to handle errors
123 * from the fill_dellaloc() callback.
125 * NOTE: caller must ensure that when an error happens, it can not call
126 * extent_clear_unlock_delalloc() to clear both the bits EXTENT_DO_ACCOUNTING
127 * and EXTENT_DELALLOC simultaneously, because that causes the reserved metadata
128 * to be released, which we want to happen only when finishing the ordered
129 * extent (btrfs_finish_ordered_io()). Also note that the caller of the
130 * fill_delalloc() callback already does proper cleanup for the first page of
131 * the range, that is, it invokes the callback writepage_end_io_hook() for the
132 * range of the first page.
134 static inline void btrfs_cleanup_ordered_extents(struct inode *inode,
138 unsigned long index = offset >> PAGE_SHIFT;
139 unsigned long end_index = (offset + bytes - 1) >> PAGE_SHIFT;
142 while (index <= end_index) {
143 page = find_get_page(inode->i_mapping, index);
147 ClearPagePrivate2(page);
150 return __endio_write_update_ordered(inode, offset + PAGE_SIZE,
151 bytes - PAGE_SIZE, false);
154 static int btrfs_dirty_inode(struct inode *inode);
156 #ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
157 void btrfs_test_inode_set_ops(struct inode *inode)
159 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
163 static int btrfs_init_inode_security(struct btrfs_trans_handle *trans,
164 struct inode *inode, struct inode *dir,
165 const struct qstr *qstr)
169 err = btrfs_init_acl(trans, inode, dir);
171 err = btrfs_xattr_security_init(trans, inode, dir, qstr);
176 * this does all the hard work for inserting an inline extent into
177 * the btree. The caller should have done a btrfs_drop_extents so that
178 * no overlapping inline items exist in the btree
180 static int insert_inline_extent(struct btrfs_trans_handle *trans,
181 struct btrfs_path *path, int extent_inserted,
182 struct btrfs_root *root, struct inode *inode,
183 u64 start, size_t size, size_t compressed_size,
185 struct page **compressed_pages)
187 struct extent_buffer *leaf;
188 struct page *page = NULL;
191 struct btrfs_file_extent_item *ei;
193 size_t cur_size = size;
194 unsigned long offset;
196 if (compressed_size && compressed_pages)
197 cur_size = compressed_size;
199 inode_add_bytes(inode, size);
201 if (!extent_inserted) {
202 struct btrfs_key key;
205 key.objectid = btrfs_ino(BTRFS_I(inode));
207 key.type = BTRFS_EXTENT_DATA_KEY;
209 datasize = btrfs_file_extent_calc_inline_size(cur_size);
210 path->leave_spinning = 1;
211 ret = btrfs_insert_empty_item(trans, root, path, &key,
216 leaf = path->nodes[0];
217 ei = btrfs_item_ptr(leaf, path->slots[0],
218 struct btrfs_file_extent_item);
219 btrfs_set_file_extent_generation(leaf, ei, trans->transid);
220 btrfs_set_file_extent_type(leaf, ei, BTRFS_FILE_EXTENT_INLINE);
221 btrfs_set_file_extent_encryption(leaf, ei, 0);
222 btrfs_set_file_extent_other_encoding(leaf, ei, 0);
223 btrfs_set_file_extent_ram_bytes(leaf, ei, size);
224 ptr = btrfs_file_extent_inline_start(ei);
226 if (compress_type != BTRFS_COMPRESS_NONE) {
229 while (compressed_size > 0) {
230 cpage = compressed_pages[i];
231 cur_size = min_t(unsigned long, compressed_size,
234 kaddr = kmap_atomic(cpage);
235 write_extent_buffer(leaf, kaddr, ptr, cur_size);
236 kunmap_atomic(kaddr);
240 compressed_size -= cur_size;
242 btrfs_set_file_extent_compression(leaf, ei,
245 page = find_get_page(inode->i_mapping,
246 start >> PAGE_SHIFT);
247 btrfs_set_file_extent_compression(leaf, ei, 0);
248 kaddr = kmap_atomic(page);
249 offset = start & (PAGE_SIZE - 1);
250 write_extent_buffer(leaf, kaddr + offset, ptr, size);
251 kunmap_atomic(kaddr);
254 btrfs_mark_buffer_dirty(leaf);
255 btrfs_release_path(path);
258 * we're an inline extent, so nobody can
259 * extend the file past i_size without locking
260 * a page we already have locked.
262 * We must do any isize and inode updates
263 * before we unlock the pages. Otherwise we
264 * could end up racing with unlink.
266 BTRFS_I(inode)->disk_i_size = inode->i_size;
267 ret = btrfs_update_inode(trans, root, inode);
275 * conditionally insert an inline extent into the file. This
276 * does the checks required to make sure the data is small enough
277 * to fit as an inline extent.
279 static noinline int cow_file_range_inline(struct btrfs_root *root,
280 struct inode *inode, u64 start,
281 u64 end, size_t compressed_size,
283 struct page **compressed_pages)
285 struct btrfs_fs_info *fs_info = root->fs_info;
286 struct btrfs_trans_handle *trans;
287 u64 isize = i_size_read(inode);
288 u64 actual_end = min(end + 1, isize);
289 u64 inline_len = actual_end - start;
290 u64 aligned_end = ALIGN(end, fs_info->sectorsize);
291 u64 data_len = inline_len;
293 struct btrfs_path *path;
294 int extent_inserted = 0;
295 u32 extent_item_size;
298 data_len = compressed_size;
301 actual_end > fs_info->sectorsize ||
302 data_len > BTRFS_MAX_INLINE_DATA_SIZE(fs_info) ||
304 (actual_end & (fs_info->sectorsize - 1)) == 0) ||
306 data_len > fs_info->max_inline) {
310 path = btrfs_alloc_path();
314 trans = btrfs_join_transaction(root);
316 btrfs_free_path(path);
317 return PTR_ERR(trans);
319 trans->block_rsv = &BTRFS_I(inode)->block_rsv;
321 if (compressed_size && compressed_pages)
322 extent_item_size = btrfs_file_extent_calc_inline_size(
325 extent_item_size = btrfs_file_extent_calc_inline_size(
328 ret = __btrfs_drop_extents(trans, root, inode, path,
329 start, aligned_end, NULL,
330 1, 1, extent_item_size, &extent_inserted);
332 btrfs_abort_transaction(trans, ret);
336 if (isize > actual_end)
337 inline_len = min_t(u64, isize, actual_end);
338 ret = insert_inline_extent(trans, path, extent_inserted,
340 inline_len, compressed_size,
341 compress_type, compressed_pages);
342 if (ret && ret != -ENOSPC) {
343 btrfs_abort_transaction(trans, ret);
345 } else if (ret == -ENOSPC) {
350 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &BTRFS_I(inode)->runtime_flags);
351 btrfs_drop_extent_cache(BTRFS_I(inode), start, aligned_end - 1, 0);
354 * Don't forget to free the reserved space, as for inlined extent
355 * it won't count as data extent, free them directly here.
356 * And at reserve time, it's always aligned to page size, so
357 * just free one page here.
359 btrfs_qgroup_free_data(inode, NULL, 0, PAGE_SIZE);
360 btrfs_free_path(path);
361 btrfs_end_transaction(trans);
365 struct async_extent {
370 unsigned long nr_pages;
372 struct list_head list;
377 struct btrfs_root *root;
378 struct page *locked_page;
381 struct list_head extents;
382 struct btrfs_work work;
385 static noinline int add_async_extent(struct async_cow *cow,
386 u64 start, u64 ram_size,
389 unsigned long nr_pages,
392 struct async_extent *async_extent;
394 async_extent = kmalloc(sizeof(*async_extent), GFP_NOFS);
395 BUG_ON(!async_extent); /* -ENOMEM */
396 async_extent->start = start;
397 async_extent->ram_size = ram_size;
398 async_extent->compressed_size = compressed_size;
399 async_extent->pages = pages;
400 async_extent->nr_pages = nr_pages;
401 async_extent->compress_type = compress_type;
402 list_add_tail(&async_extent->list, &cow->extents);
406 static inline int inode_need_compress(struct inode *inode, u64 start, u64 end)
408 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
411 if (btrfs_test_opt(fs_info, FORCE_COMPRESS))
414 if (BTRFS_I(inode)->defrag_compress)
416 /* bad compression ratios */
417 if (BTRFS_I(inode)->flags & BTRFS_INODE_NOCOMPRESS)
419 if (btrfs_test_opt(fs_info, COMPRESS) ||
420 BTRFS_I(inode)->flags & BTRFS_INODE_COMPRESS ||
421 BTRFS_I(inode)->prop_compress)
422 return btrfs_compress_heuristic(inode, start, end);
426 static inline void inode_should_defrag(struct btrfs_inode *inode,
427 u64 start, u64 end, u64 num_bytes, u64 small_write)
429 /* If this is a small write inside eof, kick off a defrag */
430 if (num_bytes < small_write &&
431 (start > 0 || end + 1 < inode->disk_i_size))
432 btrfs_add_inode_defrag(NULL, inode);
436 * we create compressed extents in two phases. The first
437 * phase compresses a range of pages that have already been
438 * locked (both pages and state bits are locked).
440 * This is done inside an ordered work queue, and the compression
441 * is spread across many cpus. The actual IO submission is step
442 * two, and the ordered work queue takes care of making sure that
443 * happens in the same order things were put onto the queue by
444 * writepages and friends.
446 * If this code finds it can't get good compression, it puts an
447 * entry onto the work queue to write the uncompressed bytes. This
448 * makes sure that both compressed inodes and uncompressed inodes
449 * are written in the same order that the flusher thread sent them
452 static noinline void compress_file_range(struct inode *inode,
453 struct page *locked_page,
455 struct async_cow *async_cow,
458 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
459 struct btrfs_root *root = BTRFS_I(inode)->root;
460 u64 blocksize = fs_info->sectorsize;
462 u64 isize = i_size_read(inode);
464 struct page **pages = NULL;
465 unsigned long nr_pages;
466 unsigned long total_compressed = 0;
467 unsigned long total_in = 0;
470 int compress_type = fs_info->compress_type;
473 inode_should_defrag(BTRFS_I(inode), start, end, end - start + 1,
476 actual_end = min_t(u64, isize, end + 1);
479 nr_pages = (end >> PAGE_SHIFT) - (start >> PAGE_SHIFT) + 1;
480 BUILD_BUG_ON((BTRFS_MAX_COMPRESSED % PAGE_SIZE) != 0);
481 nr_pages = min_t(unsigned long, nr_pages,
482 BTRFS_MAX_COMPRESSED / PAGE_SIZE);
485 * we don't want to send crud past the end of i_size through
486 * compression, that's just a waste of CPU time. So, if the
487 * end of the file is before the start of our current
488 * requested range of bytes, we bail out to the uncompressed
489 * cleanup code that can deal with all of this.
491 * It isn't really the fastest way to fix things, but this is a
492 * very uncommon corner.
494 if (actual_end <= start)
495 goto cleanup_and_bail_uncompressed;
497 total_compressed = actual_end - start;
500 * skip compression for a small file range(<=blocksize) that
501 * isn't an inline extent, since it doesn't save disk space at all.
503 if (total_compressed <= blocksize &&
504 (start > 0 || end + 1 < BTRFS_I(inode)->disk_i_size))
505 goto cleanup_and_bail_uncompressed;
507 total_compressed = min_t(unsigned long, total_compressed,
508 BTRFS_MAX_UNCOMPRESSED);
513 * we do compression for mount -o compress and when the
514 * inode has not been flagged as nocompress. This flag can
515 * change at any time if we discover bad compression ratios.
517 if (inode_need_compress(inode, start, end)) {
519 pages = kcalloc(nr_pages, sizeof(struct page *), GFP_NOFS);
521 /* just bail out to the uncompressed code */
525 if (BTRFS_I(inode)->defrag_compress)
526 compress_type = BTRFS_I(inode)->defrag_compress;
527 else if (BTRFS_I(inode)->prop_compress)
528 compress_type = BTRFS_I(inode)->prop_compress;
531 * we need to call clear_page_dirty_for_io on each
532 * page in the range. Otherwise applications with the file
533 * mmap'd can wander in and change the page contents while
534 * we are compressing them.
536 * If the compression fails for any reason, we set the pages
537 * dirty again later on.
539 extent_range_clear_dirty_for_io(inode, start, end);
542 /* Compression level is applied here and only here */
543 ret = btrfs_compress_pages(
544 compress_type | (fs_info->compress_level << 4),
545 inode->i_mapping, start,
552 unsigned long offset = total_compressed &
554 struct page *page = pages[nr_pages - 1];
557 /* zero the tail end of the last page, we might be
558 * sending it down to disk
561 kaddr = kmap_atomic(page);
562 memset(kaddr + offset, 0,
564 kunmap_atomic(kaddr);
571 /* lets try to make an inline extent */
572 if (ret || total_in < actual_end) {
573 /* we didn't compress the entire range, try
574 * to make an uncompressed inline extent.
576 ret = cow_file_range_inline(root, inode, start, end,
577 0, BTRFS_COMPRESS_NONE, NULL);
579 /* try making a compressed inline extent */
580 ret = cow_file_range_inline(root, inode, start, end,
582 compress_type, pages);
585 unsigned long clear_flags = EXTENT_DELALLOC |
586 EXTENT_DELALLOC_NEW | EXTENT_DEFRAG |
587 EXTENT_DO_ACCOUNTING;
588 unsigned long page_error_op;
590 page_error_op = ret < 0 ? PAGE_SET_ERROR : 0;
593 * inline extent creation worked or returned error,
594 * we don't need to create any more async work items.
595 * Unlock and free up our temp pages.
597 * We use DO_ACCOUNTING here because we need the
598 * delalloc_release_metadata to be done _after_ we drop
599 * our outstanding extent for clearing delalloc for this
602 extent_clear_unlock_delalloc(inode, start, end, end,
615 * we aren't doing an inline extent round the compressed size
616 * up to a block size boundary so the allocator does sane
619 total_compressed = ALIGN(total_compressed, blocksize);
622 * one last check to make sure the compression is really a
623 * win, compare the page count read with the blocks on disk,
624 * compression must free at least one sector size
626 total_in = ALIGN(total_in, PAGE_SIZE);
627 if (total_compressed + blocksize <= total_in) {
631 * The async work queues will take care of doing actual
632 * allocation on disk for these compressed pages, and
633 * will submit them to the elevator.
635 add_async_extent(async_cow, start, total_in,
636 total_compressed, pages, nr_pages,
639 if (start + total_in < end) {
650 * the compression code ran but failed to make things smaller,
651 * free any pages it allocated and our page pointer array
653 for (i = 0; i < nr_pages; i++) {
654 WARN_ON(pages[i]->mapping);
659 total_compressed = 0;
662 /* flag the file so we don't compress in the future */
663 if (!btrfs_test_opt(fs_info, FORCE_COMPRESS) &&
664 !(BTRFS_I(inode)->prop_compress)) {
665 BTRFS_I(inode)->flags |= BTRFS_INODE_NOCOMPRESS;
668 cleanup_and_bail_uncompressed:
670 * No compression, but we still need to write the pages in the file
671 * we've been given so far. redirty the locked page if it corresponds
672 * to our extent and set things up for the async work queue to run
673 * cow_file_range to do the normal delalloc dance.
675 if (page_offset(locked_page) >= start &&
676 page_offset(locked_page) <= end)
677 __set_page_dirty_nobuffers(locked_page);
678 /* unlocked later on in the async handlers */
681 extent_range_redirty_for_io(inode, start, end);
682 add_async_extent(async_cow, start, end - start + 1, 0, NULL, 0,
683 BTRFS_COMPRESS_NONE);
689 for (i = 0; i < nr_pages; i++) {
690 WARN_ON(pages[i]->mapping);
696 static void free_async_extent_pages(struct async_extent *async_extent)
700 if (!async_extent->pages)
703 for (i = 0; i < async_extent->nr_pages; i++) {
704 WARN_ON(async_extent->pages[i]->mapping);
705 put_page(async_extent->pages[i]);
707 kfree(async_extent->pages);
708 async_extent->nr_pages = 0;
709 async_extent->pages = NULL;
713 * phase two of compressed writeback. This is the ordered portion
714 * of the code, which only gets called in the order the work was
715 * queued. We walk all the async extents created by compress_file_range
716 * and send them down to the disk.
718 static noinline void submit_compressed_extents(struct inode *inode,
719 struct async_cow *async_cow)
721 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
722 struct async_extent *async_extent;
724 struct btrfs_key ins;
725 struct extent_map *em;
726 struct btrfs_root *root = BTRFS_I(inode)->root;
727 struct extent_io_tree *io_tree;
731 while (!list_empty(&async_cow->extents)) {
732 async_extent = list_entry(async_cow->extents.next,
733 struct async_extent, list);
734 list_del(&async_extent->list);
736 io_tree = &BTRFS_I(inode)->io_tree;
739 /* did the compression code fall back to uncompressed IO? */
740 if (!async_extent->pages) {
741 int page_started = 0;
742 unsigned long nr_written = 0;
744 lock_extent(io_tree, async_extent->start,
745 async_extent->start +
746 async_extent->ram_size - 1);
748 /* allocate blocks */
749 ret = cow_file_range(inode, async_cow->locked_page,
751 async_extent->start +
752 async_extent->ram_size - 1,
753 async_extent->start +
754 async_extent->ram_size - 1,
755 &page_started, &nr_written, 0,
761 * if page_started, cow_file_range inserted an
762 * inline extent and took care of all the unlocking
763 * and IO for us. Otherwise, we need to submit
764 * all those pages down to the drive.
766 if (!page_started && !ret)
767 extent_write_locked_range(io_tree,
768 inode, async_extent->start,
769 async_extent->start +
770 async_extent->ram_size - 1,
774 unlock_page(async_cow->locked_page);
780 lock_extent(io_tree, async_extent->start,
781 async_extent->start + async_extent->ram_size - 1);
783 ret = btrfs_reserve_extent(root, async_extent->ram_size,
784 async_extent->compressed_size,
785 async_extent->compressed_size,
786 0, alloc_hint, &ins, 1, 1);
788 free_async_extent_pages(async_extent);
790 if (ret == -ENOSPC) {
791 unlock_extent(io_tree, async_extent->start,
792 async_extent->start +
793 async_extent->ram_size - 1);
796 * we need to redirty the pages if we decide to
797 * fallback to uncompressed IO, otherwise we
798 * will not submit these pages down to lower
801 extent_range_redirty_for_io(inode,
803 async_extent->start +
804 async_extent->ram_size - 1);
811 * here we're doing allocation and writeback of the
814 em = create_io_em(inode, async_extent->start,
815 async_extent->ram_size, /* len */
816 async_extent->start, /* orig_start */
817 ins.objectid, /* block_start */
818 ins.offset, /* block_len */
819 ins.offset, /* orig_block_len */
820 async_extent->ram_size, /* ram_bytes */
821 async_extent->compress_type,
822 BTRFS_ORDERED_COMPRESSED);
824 /* ret value is not necessary due to void function */
825 goto out_free_reserve;
828 ret = btrfs_add_ordered_extent_compress(inode,
831 async_extent->ram_size,
833 BTRFS_ORDERED_COMPRESSED,
834 async_extent->compress_type);
836 btrfs_drop_extent_cache(BTRFS_I(inode),
838 async_extent->start +
839 async_extent->ram_size - 1, 0);
840 goto out_free_reserve;
842 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
845 * clear dirty, set writeback and unlock the pages.
847 extent_clear_unlock_delalloc(inode, async_extent->start,
848 async_extent->start +
849 async_extent->ram_size - 1,
850 async_extent->start +
851 async_extent->ram_size - 1,
852 NULL, EXTENT_LOCKED | EXTENT_DELALLOC,
853 PAGE_UNLOCK | PAGE_CLEAR_DIRTY |
855 if (btrfs_submit_compressed_write(inode,
857 async_extent->ram_size,
859 ins.offset, async_extent->pages,
860 async_extent->nr_pages)) {
861 struct extent_io_tree *tree = &BTRFS_I(inode)->io_tree;
862 struct page *p = async_extent->pages[0];
863 const u64 start = async_extent->start;
864 const u64 end = start + async_extent->ram_size - 1;
866 p->mapping = inode->i_mapping;
867 tree->ops->writepage_end_io_hook(p, start, end,
870 extent_clear_unlock_delalloc(inode, start, end, end,
874 free_async_extent_pages(async_extent);
876 alloc_hint = ins.objectid + ins.offset;
882 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
883 btrfs_free_reserved_extent(fs_info, ins.objectid, ins.offset, 1);
885 extent_clear_unlock_delalloc(inode, async_extent->start,
886 async_extent->start +
887 async_extent->ram_size - 1,
888 async_extent->start +
889 async_extent->ram_size - 1,
890 NULL, EXTENT_LOCKED | EXTENT_DELALLOC |
891 EXTENT_DELALLOC_NEW |
892 EXTENT_DEFRAG | EXTENT_DO_ACCOUNTING,
893 PAGE_UNLOCK | PAGE_CLEAR_DIRTY |
894 PAGE_SET_WRITEBACK | PAGE_END_WRITEBACK |
896 free_async_extent_pages(async_extent);
901 static u64 get_extent_allocation_hint(struct inode *inode, u64 start,
904 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
905 struct extent_map *em;
908 read_lock(&em_tree->lock);
909 em = search_extent_mapping(em_tree, start, num_bytes);
912 * if block start isn't an actual block number then find the
913 * first block in this inode and use that as a hint. If that
914 * block is also bogus then just don't worry about it.
916 if (em->block_start >= EXTENT_MAP_LAST_BYTE) {
918 em = search_extent_mapping(em_tree, 0, 0);
919 if (em && em->block_start < EXTENT_MAP_LAST_BYTE)
920 alloc_hint = em->block_start;
924 alloc_hint = em->block_start;
928 read_unlock(&em_tree->lock);
934 * when extent_io.c finds a delayed allocation range in the file,
935 * the call backs end up in this code. The basic idea is to
936 * allocate extents on disk for the range, and create ordered data structs
937 * in ram to track those extents.
939 * locked_page is the page that writepage had locked already. We use
940 * it to make sure we don't do extra locks or unlocks.
942 * *page_started is set to one if we unlock locked_page and do everything
943 * required to start IO on it. It may be clean and already done with
946 static noinline int cow_file_range(struct inode *inode,
947 struct page *locked_page,
948 u64 start, u64 end, u64 delalloc_end,
949 int *page_started, unsigned long *nr_written,
950 int unlock, struct btrfs_dedupe_hash *hash)
952 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
953 struct btrfs_root *root = BTRFS_I(inode)->root;
956 unsigned long ram_size;
958 u64 cur_alloc_size = 0;
959 u64 blocksize = fs_info->sectorsize;
960 struct btrfs_key ins;
961 struct extent_map *em;
963 unsigned long page_ops;
964 bool extent_reserved = false;
967 if (btrfs_is_free_space_inode(BTRFS_I(inode))) {
973 num_bytes = ALIGN(end - start + 1, blocksize);
974 num_bytes = max(blocksize, num_bytes);
975 disk_num_bytes = num_bytes;
977 inode_should_defrag(BTRFS_I(inode), start, end, num_bytes, SZ_64K);
980 /* lets try to make an inline extent */
981 ret = cow_file_range_inline(root, inode, start, end, 0,
982 BTRFS_COMPRESS_NONE, NULL);
985 * We use DO_ACCOUNTING here because we need the
986 * delalloc_release_metadata to be run _after_ we drop
987 * our outstanding extent for clearing delalloc for this
990 extent_clear_unlock_delalloc(inode, start, end,
992 EXTENT_LOCKED | EXTENT_DELALLOC |
993 EXTENT_DELALLOC_NEW | EXTENT_DEFRAG |
994 EXTENT_DO_ACCOUNTING, PAGE_UNLOCK |
995 PAGE_CLEAR_DIRTY | PAGE_SET_WRITEBACK |
997 *nr_written = *nr_written +
998 (end - start + PAGE_SIZE) / PAGE_SIZE;
1001 } else if (ret < 0) {
1006 BUG_ON(disk_num_bytes >
1007 btrfs_super_total_bytes(fs_info->super_copy));
1009 alloc_hint = get_extent_allocation_hint(inode, start, num_bytes);
1010 btrfs_drop_extent_cache(BTRFS_I(inode), start,
1011 start + num_bytes - 1, 0);
1013 while (disk_num_bytes > 0) {
1014 cur_alloc_size = disk_num_bytes;
1015 ret = btrfs_reserve_extent(root, cur_alloc_size, cur_alloc_size,
1016 fs_info->sectorsize, 0, alloc_hint,
1020 cur_alloc_size = ins.offset;
1021 extent_reserved = true;
1023 ram_size = ins.offset;
1024 em = create_io_em(inode, start, ins.offset, /* len */
1025 start, /* orig_start */
1026 ins.objectid, /* block_start */
1027 ins.offset, /* block_len */
1028 ins.offset, /* orig_block_len */
1029 ram_size, /* ram_bytes */
1030 BTRFS_COMPRESS_NONE, /* compress_type */
1031 BTRFS_ORDERED_REGULAR /* type */);
1034 free_extent_map(em);
1036 ret = btrfs_add_ordered_extent(inode, start, ins.objectid,
1037 ram_size, cur_alloc_size, 0);
1039 goto out_drop_extent_cache;
1041 if (root->root_key.objectid ==
1042 BTRFS_DATA_RELOC_TREE_OBJECTID) {
1043 ret = btrfs_reloc_clone_csums(inode, start,
1046 * Only drop cache here, and process as normal.
1048 * We must not allow extent_clear_unlock_delalloc()
1049 * at out_unlock label to free meta of this ordered
1050 * extent, as its meta should be freed by
1051 * btrfs_finish_ordered_io().
1053 * So we must continue until @start is increased to
1054 * skip current ordered extent.
1057 btrfs_drop_extent_cache(BTRFS_I(inode), start,
1058 start + ram_size - 1, 0);
1061 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
1063 /* we're not doing compressed IO, don't unlock the first
1064 * page (which the caller expects to stay locked), don't
1065 * clear any dirty bits and don't set any writeback bits
1067 * Do set the Private2 bit so we know this page was properly
1068 * setup for writepage
1070 page_ops = unlock ? PAGE_UNLOCK : 0;
1071 page_ops |= PAGE_SET_PRIVATE2;
1073 extent_clear_unlock_delalloc(inode, start,
1074 start + ram_size - 1,
1075 delalloc_end, locked_page,
1076 EXTENT_LOCKED | EXTENT_DELALLOC,
1078 if (disk_num_bytes < cur_alloc_size)
1081 disk_num_bytes -= cur_alloc_size;
1082 num_bytes -= cur_alloc_size;
1083 alloc_hint = ins.objectid + ins.offset;
1084 start += cur_alloc_size;
1085 extent_reserved = false;
1088 * btrfs_reloc_clone_csums() error, since start is increased
1089 * extent_clear_unlock_delalloc() at out_unlock label won't
1090 * free metadata of current ordered extent, we're OK to exit.
1098 out_drop_extent_cache:
1099 btrfs_drop_extent_cache(BTRFS_I(inode), start, start + ram_size - 1, 0);
1101 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
1102 btrfs_free_reserved_extent(fs_info, ins.objectid, ins.offset, 1);
1104 clear_bits = EXTENT_LOCKED | EXTENT_DELALLOC | EXTENT_DELALLOC_NEW |
1105 EXTENT_DEFRAG | EXTENT_CLEAR_META_RESV;
1106 page_ops = PAGE_UNLOCK | PAGE_CLEAR_DIRTY | PAGE_SET_WRITEBACK |
1109 * If we reserved an extent for our delalloc range (or a subrange) and
1110 * failed to create the respective ordered extent, then it means that
1111 * when we reserved the extent we decremented the extent's size from
1112 * the data space_info's bytes_may_use counter and incremented the
1113 * space_info's bytes_reserved counter by the same amount. We must make
1114 * sure extent_clear_unlock_delalloc() does not try to decrement again
1115 * the data space_info's bytes_may_use counter, therefore we do not pass
1116 * it the flag EXTENT_CLEAR_DATA_RESV.
1118 if (extent_reserved) {
1119 extent_clear_unlock_delalloc(inode, start,
1120 start + cur_alloc_size,
1121 start + cur_alloc_size,
1125 start += cur_alloc_size;
1129 extent_clear_unlock_delalloc(inode, start, end, delalloc_end,
1131 clear_bits | EXTENT_CLEAR_DATA_RESV,
1137 * work queue call back to started compression on a file and pages
1139 static noinline void async_cow_start(struct btrfs_work *work)
1141 struct async_cow *async_cow;
1143 async_cow = container_of(work, struct async_cow, work);
1145 compress_file_range(async_cow->inode, async_cow->locked_page,
1146 async_cow->start, async_cow->end, async_cow,
1148 if (num_added == 0) {
1149 btrfs_add_delayed_iput(async_cow->inode);
1150 async_cow->inode = NULL;
1155 * work queue call back to submit previously compressed pages
1157 static noinline void async_cow_submit(struct btrfs_work *work)
1159 struct btrfs_fs_info *fs_info;
1160 struct async_cow *async_cow;
1161 struct btrfs_root *root;
1162 unsigned long nr_pages;
1164 async_cow = container_of(work, struct async_cow, work);
1166 root = async_cow->root;
1167 fs_info = root->fs_info;
1168 nr_pages = (async_cow->end - async_cow->start + PAGE_SIZE) >>
1172 * atomic_sub_return implies a barrier for waitqueue_active
1174 if (atomic_sub_return(nr_pages, &fs_info->async_delalloc_pages) <
1176 waitqueue_active(&fs_info->async_submit_wait))
1177 wake_up(&fs_info->async_submit_wait);
1179 if (async_cow->inode)
1180 submit_compressed_extents(async_cow->inode, async_cow);
1183 static noinline void async_cow_free(struct btrfs_work *work)
1185 struct async_cow *async_cow;
1186 async_cow = container_of(work, struct async_cow, work);
1187 if (async_cow->inode)
1188 btrfs_add_delayed_iput(async_cow->inode);
1192 static int cow_file_range_async(struct inode *inode, struct page *locked_page,
1193 u64 start, u64 end, int *page_started,
1194 unsigned long *nr_written)
1196 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1197 struct async_cow *async_cow;
1198 struct btrfs_root *root = BTRFS_I(inode)->root;
1199 unsigned long nr_pages;
1202 clear_extent_bit(&BTRFS_I(inode)->io_tree, start, end, EXTENT_LOCKED,
1203 1, 0, NULL, GFP_NOFS);
1204 while (start < end) {
1205 async_cow = kmalloc(sizeof(*async_cow), GFP_NOFS);
1206 BUG_ON(!async_cow); /* -ENOMEM */
1207 async_cow->inode = igrab(inode);
1208 async_cow->root = root;
1209 async_cow->locked_page = locked_page;
1210 async_cow->start = start;
1212 if (BTRFS_I(inode)->flags & BTRFS_INODE_NOCOMPRESS &&
1213 !btrfs_test_opt(fs_info, FORCE_COMPRESS))
1216 cur_end = min(end, start + SZ_512K - 1);
1218 async_cow->end = cur_end;
1219 INIT_LIST_HEAD(&async_cow->extents);
1221 btrfs_init_work(&async_cow->work,
1222 btrfs_delalloc_helper,
1223 async_cow_start, async_cow_submit,
1226 nr_pages = (cur_end - start + PAGE_SIZE) >>
1228 atomic_add(nr_pages, &fs_info->async_delalloc_pages);
1230 btrfs_queue_work(fs_info->delalloc_workers, &async_cow->work);
1232 *nr_written += nr_pages;
1233 start = cur_end + 1;
1239 static noinline int csum_exist_in_range(struct btrfs_fs_info *fs_info,
1240 u64 bytenr, u64 num_bytes)
1243 struct btrfs_ordered_sum *sums;
1246 ret = btrfs_lookup_csums_range(fs_info->csum_root, bytenr,
1247 bytenr + num_bytes - 1, &list, 0);
1248 if (ret == 0 && list_empty(&list))
1251 while (!list_empty(&list)) {
1252 sums = list_entry(list.next, struct btrfs_ordered_sum, list);
1253 list_del(&sums->list);
1260 * when nowcow writeback call back. This checks for snapshots or COW copies
1261 * of the extents that exist in the file, and COWs the file as required.
1263 * If no cow copies or snapshots exist, we write directly to the existing
1266 static noinline int run_delalloc_nocow(struct inode *inode,
1267 struct page *locked_page,
1268 u64 start, u64 end, int *page_started, int force,
1269 unsigned long *nr_written)
1271 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1272 struct btrfs_root *root = BTRFS_I(inode)->root;
1273 struct extent_buffer *leaf;
1274 struct btrfs_path *path;
1275 struct btrfs_file_extent_item *fi;
1276 struct btrfs_key found_key;
1277 struct extent_map *em;
1292 u64 ino = btrfs_ino(BTRFS_I(inode));
1294 path = btrfs_alloc_path();
1296 extent_clear_unlock_delalloc(inode, start, end, end,
1298 EXTENT_LOCKED | EXTENT_DELALLOC |
1299 EXTENT_DO_ACCOUNTING |
1300 EXTENT_DEFRAG, PAGE_UNLOCK |
1302 PAGE_SET_WRITEBACK |
1303 PAGE_END_WRITEBACK);
1307 nolock = btrfs_is_free_space_inode(BTRFS_I(inode));
1309 cow_start = (u64)-1;
1312 ret = btrfs_lookup_file_extent(NULL, root, path, ino,
1316 if (ret > 0 && path->slots[0] > 0 && check_prev) {
1317 leaf = path->nodes[0];
1318 btrfs_item_key_to_cpu(leaf, &found_key,
1319 path->slots[0] - 1);
1320 if (found_key.objectid == ino &&
1321 found_key.type == BTRFS_EXTENT_DATA_KEY)
1326 leaf = path->nodes[0];
1327 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
1328 ret = btrfs_next_leaf(root, path);
1333 leaf = path->nodes[0];
1339 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
1341 if (found_key.objectid > ino)
1343 if (WARN_ON_ONCE(found_key.objectid < ino) ||
1344 found_key.type < BTRFS_EXTENT_DATA_KEY) {
1348 if (found_key.type > BTRFS_EXTENT_DATA_KEY ||
1349 found_key.offset > end)
1352 if (found_key.offset > cur_offset) {
1353 extent_end = found_key.offset;
1358 fi = btrfs_item_ptr(leaf, path->slots[0],
1359 struct btrfs_file_extent_item);
1360 extent_type = btrfs_file_extent_type(leaf, fi);
1362 ram_bytes = btrfs_file_extent_ram_bytes(leaf, fi);
1363 if (extent_type == BTRFS_FILE_EXTENT_REG ||
1364 extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
1365 disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
1366 extent_offset = btrfs_file_extent_offset(leaf, fi);
1367 extent_end = found_key.offset +
1368 btrfs_file_extent_num_bytes(leaf, fi);
1370 btrfs_file_extent_disk_num_bytes(leaf, fi);
1371 if (extent_end <= start) {
1375 if (disk_bytenr == 0)
1377 if (btrfs_file_extent_compression(leaf, fi) ||
1378 btrfs_file_extent_encryption(leaf, fi) ||
1379 btrfs_file_extent_other_encoding(leaf, fi))
1381 if (extent_type == BTRFS_FILE_EXTENT_REG && !force)
1383 if (btrfs_extent_readonly(fs_info, disk_bytenr))
1385 if (btrfs_cross_ref_exist(root, ino,
1387 extent_offset, disk_bytenr))
1389 disk_bytenr += extent_offset;
1390 disk_bytenr += cur_offset - found_key.offset;
1391 num_bytes = min(end + 1, extent_end) - cur_offset;
1393 * if there are pending snapshots for this root,
1394 * we fall into common COW way.
1397 err = btrfs_start_write_no_snapshotting(root);
1402 * force cow if csum exists in the range.
1403 * this ensure that csum for a given extent are
1404 * either valid or do not exist.
1406 if (csum_exist_in_range(fs_info, disk_bytenr,
1409 btrfs_end_write_no_snapshotting(root);
1412 if (!btrfs_inc_nocow_writers(fs_info, disk_bytenr)) {
1414 btrfs_end_write_no_snapshotting(root);
1418 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
1419 extent_end = found_key.offset +
1420 btrfs_file_extent_inline_len(leaf,
1421 path->slots[0], fi);
1422 extent_end = ALIGN(extent_end,
1423 fs_info->sectorsize);
1428 if (extent_end <= start) {
1430 if (!nolock && nocow)
1431 btrfs_end_write_no_snapshotting(root);
1433 btrfs_dec_nocow_writers(fs_info, disk_bytenr);
1437 if (cow_start == (u64)-1)
1438 cow_start = cur_offset;
1439 cur_offset = extent_end;
1440 if (cur_offset > end)
1446 btrfs_release_path(path);
1447 if (cow_start != (u64)-1) {
1448 ret = cow_file_range(inode, locked_page,
1449 cow_start, found_key.offset - 1,
1450 end, page_started, nr_written, 1,
1453 if (!nolock && nocow)
1454 btrfs_end_write_no_snapshotting(root);
1456 btrfs_dec_nocow_writers(fs_info,
1460 cow_start = (u64)-1;
1463 if (extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
1464 u64 orig_start = found_key.offset - extent_offset;
1466 em = create_io_em(inode, cur_offset, num_bytes,
1468 disk_bytenr, /* block_start */
1469 num_bytes, /* block_len */
1470 disk_num_bytes, /* orig_block_len */
1471 ram_bytes, BTRFS_COMPRESS_NONE,
1472 BTRFS_ORDERED_PREALLOC);
1474 if (!nolock && nocow)
1475 btrfs_end_write_no_snapshotting(root);
1477 btrfs_dec_nocow_writers(fs_info,
1482 free_extent_map(em);
1485 if (extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
1486 type = BTRFS_ORDERED_PREALLOC;
1488 type = BTRFS_ORDERED_NOCOW;
1491 ret = btrfs_add_ordered_extent(inode, cur_offset, disk_bytenr,
1492 num_bytes, num_bytes, type);
1494 btrfs_dec_nocow_writers(fs_info, disk_bytenr);
1495 BUG_ON(ret); /* -ENOMEM */
1497 if (root->root_key.objectid ==
1498 BTRFS_DATA_RELOC_TREE_OBJECTID)
1500 * Error handled later, as we must prevent
1501 * extent_clear_unlock_delalloc() in error handler
1502 * from freeing metadata of created ordered extent.
1504 ret = btrfs_reloc_clone_csums(inode, cur_offset,
1507 extent_clear_unlock_delalloc(inode, cur_offset,
1508 cur_offset + num_bytes - 1, end,
1509 locked_page, EXTENT_LOCKED |
1511 EXTENT_CLEAR_DATA_RESV,
1512 PAGE_UNLOCK | PAGE_SET_PRIVATE2);
1514 if (!nolock && nocow)
1515 btrfs_end_write_no_snapshotting(root);
1516 cur_offset = extent_end;
1519 * btrfs_reloc_clone_csums() error, now we're OK to call error
1520 * handler, as metadata for created ordered extent will only
1521 * be freed by btrfs_finish_ordered_io().
1525 if (cur_offset > end)
1528 btrfs_release_path(path);
1530 if (cur_offset <= end && cow_start == (u64)-1) {
1531 cow_start = cur_offset;
1535 if (cow_start != (u64)-1) {
1536 ret = cow_file_range(inode, locked_page, cow_start, end, end,
1537 page_started, nr_written, 1, NULL);
1543 if (ret && cur_offset < end)
1544 extent_clear_unlock_delalloc(inode, cur_offset, end, end,
1545 locked_page, EXTENT_LOCKED |
1546 EXTENT_DELALLOC | EXTENT_DEFRAG |
1547 EXTENT_DO_ACCOUNTING, PAGE_UNLOCK |
1549 PAGE_SET_WRITEBACK |
1550 PAGE_END_WRITEBACK);
1551 btrfs_free_path(path);
1555 static inline int need_force_cow(struct inode *inode, u64 start, u64 end)
1558 if (!(BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW) &&
1559 !(BTRFS_I(inode)->flags & BTRFS_INODE_PREALLOC))
1563 * @defrag_bytes is a hint value, no spinlock held here,
1564 * if is not zero, it means the file is defragging.
1565 * Force cow if given extent needs to be defragged.
1567 if (BTRFS_I(inode)->defrag_bytes &&
1568 test_range_bit(&BTRFS_I(inode)->io_tree, start, end,
1569 EXTENT_DEFRAG, 0, NULL))
1576 * extent_io.c call back to do delayed allocation processing
1578 static int run_delalloc_range(void *private_data, struct page *locked_page,
1579 u64 start, u64 end, int *page_started,
1580 unsigned long *nr_written)
1582 struct inode *inode = private_data;
1584 int force_cow = need_force_cow(inode, start, end);
1586 if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW && !force_cow) {
1587 ret = run_delalloc_nocow(inode, locked_page, start, end,
1588 page_started, 1, nr_written);
1589 } else if (BTRFS_I(inode)->flags & BTRFS_INODE_PREALLOC && !force_cow) {
1590 ret = run_delalloc_nocow(inode, locked_page, start, end,
1591 page_started, 0, nr_written);
1592 } else if (!inode_need_compress(inode, start, end)) {
1593 ret = cow_file_range(inode, locked_page, start, end, end,
1594 page_started, nr_written, 1, NULL);
1596 set_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
1597 &BTRFS_I(inode)->runtime_flags);
1598 ret = cow_file_range_async(inode, locked_page, start, end,
1599 page_started, nr_written);
1602 btrfs_cleanup_ordered_extents(inode, start, end - start + 1);
1606 static void btrfs_split_extent_hook(void *private_data,
1607 struct extent_state *orig, u64 split)
1609 struct inode *inode = private_data;
1612 /* not delalloc, ignore it */
1613 if (!(orig->state & EXTENT_DELALLOC))
1616 size = orig->end - orig->start + 1;
1617 if (size > BTRFS_MAX_EXTENT_SIZE) {
1622 * See the explanation in btrfs_merge_extent_hook, the same
1623 * applies here, just in reverse.
1625 new_size = orig->end - split + 1;
1626 num_extents = count_max_extents(new_size);
1627 new_size = split - orig->start;
1628 num_extents += count_max_extents(new_size);
1629 if (count_max_extents(size) >= num_extents)
1633 spin_lock(&BTRFS_I(inode)->lock);
1634 btrfs_mod_outstanding_extents(BTRFS_I(inode), 1);
1635 spin_unlock(&BTRFS_I(inode)->lock);
1639 * extent_io.c merge_extent_hook, used to track merged delayed allocation
1640 * extents so we can keep track of new extents that are just merged onto old
1641 * extents, such as when we are doing sequential writes, so we can properly
1642 * account for the metadata space we'll need.
1644 static void btrfs_merge_extent_hook(void *private_data,
1645 struct extent_state *new,
1646 struct extent_state *other)
1648 struct inode *inode = private_data;
1649 u64 new_size, old_size;
1652 /* not delalloc, ignore it */
1653 if (!(other->state & EXTENT_DELALLOC))
1656 if (new->start > other->start)
1657 new_size = new->end - other->start + 1;
1659 new_size = other->end - new->start + 1;
1661 /* we're not bigger than the max, unreserve the space and go */
1662 if (new_size <= BTRFS_MAX_EXTENT_SIZE) {
1663 spin_lock(&BTRFS_I(inode)->lock);
1664 btrfs_mod_outstanding_extents(BTRFS_I(inode), -1);
1665 spin_unlock(&BTRFS_I(inode)->lock);
1670 * We have to add up either side to figure out how many extents were
1671 * accounted for before we merged into one big extent. If the number of
1672 * extents we accounted for is <= the amount we need for the new range
1673 * then we can return, otherwise drop. Think of it like this
1677 * So we've grown the extent by a MAX_SIZE extent, this would mean we
1678 * need 2 outstanding extents, on one side we have 1 and the other side
1679 * we have 1 so they are == and we can return. But in this case
1681 * [MAX_SIZE+4k][MAX_SIZE+4k]
1683 * Each range on their own accounts for 2 extents, but merged together
1684 * they are only 3 extents worth of accounting, so we need to drop in
1687 old_size = other->end - other->start + 1;
1688 num_extents = count_max_extents(old_size);
1689 old_size = new->end - new->start + 1;
1690 num_extents += count_max_extents(old_size);
1691 if (count_max_extents(new_size) >= num_extents)
1694 spin_lock(&BTRFS_I(inode)->lock);
1695 btrfs_mod_outstanding_extents(BTRFS_I(inode), -1);
1696 spin_unlock(&BTRFS_I(inode)->lock);
1699 static void btrfs_add_delalloc_inodes(struct btrfs_root *root,
1700 struct inode *inode)
1702 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1704 spin_lock(&root->delalloc_lock);
1705 if (list_empty(&BTRFS_I(inode)->delalloc_inodes)) {
1706 list_add_tail(&BTRFS_I(inode)->delalloc_inodes,
1707 &root->delalloc_inodes);
1708 set_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1709 &BTRFS_I(inode)->runtime_flags);
1710 root->nr_delalloc_inodes++;
1711 if (root->nr_delalloc_inodes == 1) {
1712 spin_lock(&fs_info->delalloc_root_lock);
1713 BUG_ON(!list_empty(&root->delalloc_root));
1714 list_add_tail(&root->delalloc_root,
1715 &fs_info->delalloc_roots);
1716 spin_unlock(&fs_info->delalloc_root_lock);
1719 spin_unlock(&root->delalloc_lock);
1722 static void btrfs_del_delalloc_inode(struct btrfs_root *root,
1723 struct btrfs_inode *inode)
1725 struct btrfs_fs_info *fs_info = btrfs_sb(inode->vfs_inode.i_sb);
1727 spin_lock(&root->delalloc_lock);
1728 if (!list_empty(&inode->delalloc_inodes)) {
1729 list_del_init(&inode->delalloc_inodes);
1730 clear_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1731 &inode->runtime_flags);
1732 root->nr_delalloc_inodes--;
1733 if (!root->nr_delalloc_inodes) {
1734 spin_lock(&fs_info->delalloc_root_lock);
1735 BUG_ON(list_empty(&root->delalloc_root));
1736 list_del_init(&root->delalloc_root);
1737 spin_unlock(&fs_info->delalloc_root_lock);
1740 spin_unlock(&root->delalloc_lock);
1744 * extent_io.c set_bit_hook, used to track delayed allocation
1745 * bytes in this file, and to maintain the list of inodes that
1746 * have pending delalloc work to be done.
1748 static void btrfs_set_bit_hook(void *private_data,
1749 struct extent_state *state, unsigned *bits)
1751 struct inode *inode = private_data;
1753 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1755 if ((*bits & EXTENT_DEFRAG) && !(*bits & EXTENT_DELALLOC))
1758 * set_bit and clear bit hooks normally require _irqsave/restore
1759 * but in this case, we are only testing for the DELALLOC
1760 * bit, which is only set or cleared with irqs on
1762 if (!(state->state & EXTENT_DELALLOC) && (*bits & EXTENT_DELALLOC)) {
1763 struct btrfs_root *root = BTRFS_I(inode)->root;
1764 u64 len = state->end + 1 - state->start;
1765 u32 num_extents = count_max_extents(len);
1766 bool do_list = !btrfs_is_free_space_inode(BTRFS_I(inode));
1768 spin_lock(&BTRFS_I(inode)->lock);
1769 btrfs_mod_outstanding_extents(BTRFS_I(inode), num_extents);
1770 spin_unlock(&BTRFS_I(inode)->lock);
1772 /* For sanity tests */
1773 if (btrfs_is_testing(fs_info))
1776 percpu_counter_add_batch(&fs_info->delalloc_bytes, len,
1777 fs_info->delalloc_batch);
1778 spin_lock(&BTRFS_I(inode)->lock);
1779 BTRFS_I(inode)->delalloc_bytes += len;
1780 if (*bits & EXTENT_DEFRAG)
1781 BTRFS_I(inode)->defrag_bytes += len;
1782 if (do_list && !test_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1783 &BTRFS_I(inode)->runtime_flags))
1784 btrfs_add_delalloc_inodes(root, inode);
1785 spin_unlock(&BTRFS_I(inode)->lock);
1788 if (!(state->state & EXTENT_DELALLOC_NEW) &&
1789 (*bits & EXTENT_DELALLOC_NEW)) {
1790 spin_lock(&BTRFS_I(inode)->lock);
1791 BTRFS_I(inode)->new_delalloc_bytes += state->end + 1 -
1793 spin_unlock(&BTRFS_I(inode)->lock);
1798 * extent_io.c clear_bit_hook, see set_bit_hook for why
1800 static void btrfs_clear_bit_hook(void *private_data,
1801 struct extent_state *state,
1804 struct btrfs_inode *inode = BTRFS_I((struct inode *)private_data);
1805 struct btrfs_fs_info *fs_info = btrfs_sb(inode->vfs_inode.i_sb);
1806 u64 len = state->end + 1 - state->start;
1807 u32 num_extents = count_max_extents(len);
1809 if ((state->state & EXTENT_DEFRAG) && (*bits & EXTENT_DEFRAG)) {
1810 spin_lock(&inode->lock);
1811 inode->defrag_bytes -= len;
1812 spin_unlock(&inode->lock);
1816 * set_bit and clear bit hooks normally require _irqsave/restore
1817 * but in this case, we are only testing for the DELALLOC
1818 * bit, which is only set or cleared with irqs on
1820 if ((state->state & EXTENT_DELALLOC) && (*bits & EXTENT_DELALLOC)) {
1821 struct btrfs_root *root = inode->root;
1822 bool do_list = !btrfs_is_free_space_inode(inode);
1824 spin_lock(&inode->lock);
1825 btrfs_mod_outstanding_extents(inode, -num_extents);
1826 spin_unlock(&inode->lock);
1829 * We don't reserve metadata space for space cache inodes so we
1830 * don't need to call dellalloc_release_metadata if there is an
1833 if (*bits & EXTENT_CLEAR_META_RESV &&
1834 root != fs_info->tree_root)
1835 btrfs_delalloc_release_metadata(inode, len);
1837 /* For sanity tests. */
1838 if (btrfs_is_testing(fs_info))
1841 if (root->root_key.objectid != BTRFS_DATA_RELOC_TREE_OBJECTID &&
1842 do_list && !(state->state & EXTENT_NORESERVE) &&
1843 (*bits & EXTENT_CLEAR_DATA_RESV))
1844 btrfs_free_reserved_data_space_noquota(
1848 percpu_counter_add_batch(&fs_info->delalloc_bytes, -len,
1849 fs_info->delalloc_batch);
1850 spin_lock(&inode->lock);
1851 inode->delalloc_bytes -= len;
1852 if (do_list && inode->delalloc_bytes == 0 &&
1853 test_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1854 &inode->runtime_flags))
1855 btrfs_del_delalloc_inode(root, inode);
1856 spin_unlock(&inode->lock);
1859 if ((state->state & EXTENT_DELALLOC_NEW) &&
1860 (*bits & EXTENT_DELALLOC_NEW)) {
1861 spin_lock(&inode->lock);
1862 ASSERT(inode->new_delalloc_bytes >= len);
1863 inode->new_delalloc_bytes -= len;
1864 spin_unlock(&inode->lock);
1869 * extent_io.c merge_bio_hook, this must check the chunk tree to make sure
1870 * we don't create bios that span stripes or chunks
1872 * return 1 if page cannot be merged to bio
1873 * return 0 if page can be merged to bio
1874 * return error otherwise
1876 int btrfs_merge_bio_hook(struct page *page, unsigned long offset,
1877 size_t size, struct bio *bio,
1878 unsigned long bio_flags)
1880 struct inode *inode = page->mapping->host;
1881 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1882 u64 logical = (u64)bio->bi_iter.bi_sector << 9;
1887 if (bio_flags & EXTENT_BIO_COMPRESSED)
1890 length = bio->bi_iter.bi_size;
1891 map_length = length;
1892 ret = btrfs_map_block(fs_info, btrfs_op(bio), logical, &map_length,
1896 if (map_length < length + size)
1902 * in order to insert checksums into the metadata in large chunks,
1903 * we wait until bio submission time. All the pages in the bio are
1904 * checksummed and sums are attached onto the ordered extent record.
1906 * At IO completion time the cums attached on the ordered extent record
1907 * are inserted into the btree
1909 static blk_status_t __btrfs_submit_bio_start(void *private_data, struct bio *bio,
1910 int mirror_num, unsigned long bio_flags,
1913 struct inode *inode = private_data;
1914 blk_status_t ret = 0;
1916 ret = btrfs_csum_one_bio(inode, bio, 0, 0);
1917 BUG_ON(ret); /* -ENOMEM */
1922 * in order to insert checksums into the metadata in large chunks,
1923 * we wait until bio submission time. All the pages in the bio are
1924 * checksummed and sums are attached onto the ordered extent record.
1926 * At IO completion time the cums attached on the ordered extent record
1927 * are inserted into the btree
1929 static blk_status_t __btrfs_submit_bio_done(void *private_data, struct bio *bio,
1930 int mirror_num, unsigned long bio_flags,
1933 struct inode *inode = private_data;
1934 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1937 ret = btrfs_map_bio(fs_info, bio, mirror_num, 1);
1939 bio->bi_status = ret;
1946 * extent_io.c submission hook. This does the right thing for csum calculation
1947 * on write, or reading the csums from the tree before a read
1949 static blk_status_t btrfs_submit_bio_hook(void *private_data, struct bio *bio,
1950 int mirror_num, unsigned long bio_flags,
1953 struct inode *inode = private_data;
1954 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1955 struct btrfs_root *root = BTRFS_I(inode)->root;
1956 enum btrfs_wq_endio_type metadata = BTRFS_WQ_ENDIO_DATA;
1957 blk_status_t ret = 0;
1959 int async = !atomic_read(&BTRFS_I(inode)->sync_writers);
1961 skip_sum = BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM;
1963 if (btrfs_is_free_space_inode(BTRFS_I(inode)))
1964 metadata = BTRFS_WQ_ENDIO_FREE_SPACE;
1966 if (bio_op(bio) != REQ_OP_WRITE) {
1967 ret = btrfs_bio_wq_end_io(fs_info, bio, metadata);
1971 if (bio_flags & EXTENT_BIO_COMPRESSED) {
1972 ret = btrfs_submit_compressed_read(inode, bio,
1976 } else if (!skip_sum) {
1977 ret = btrfs_lookup_bio_sums(inode, bio, NULL);
1982 } else if (async && !skip_sum) {
1983 /* csum items have already been cloned */
1984 if (root->root_key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID)
1986 /* we're doing a write, do the async checksumming */
1987 ret = btrfs_wq_submit_bio(fs_info, bio, mirror_num, bio_flags,
1989 __btrfs_submit_bio_start,
1990 __btrfs_submit_bio_done);
1992 } else if (!skip_sum) {
1993 ret = btrfs_csum_one_bio(inode, bio, 0, 0);
1999 ret = btrfs_map_bio(fs_info, bio, mirror_num, 0);
2003 bio->bi_status = ret;
2010 * given a list of ordered sums record them in the inode. This happens
2011 * at IO completion time based on sums calculated at bio submission time.
2013 static noinline int add_pending_csums(struct btrfs_trans_handle *trans,
2014 struct inode *inode, struct list_head *list)
2016 struct btrfs_ordered_sum *sum;
2018 list_for_each_entry(sum, list, list) {
2019 trans->adding_csums = 1;
2020 btrfs_csum_file_blocks(trans,
2021 BTRFS_I(inode)->root->fs_info->csum_root, sum);
2022 trans->adding_csums = 0;
2027 int btrfs_set_extent_delalloc(struct inode *inode, u64 start, u64 end,
2028 struct extent_state **cached_state, int dedupe)
2030 WARN_ON((end & (PAGE_SIZE - 1)) == 0);
2031 return set_extent_delalloc(&BTRFS_I(inode)->io_tree, start, end,
2035 /* see btrfs_writepage_start_hook for details on why this is required */
2036 struct btrfs_writepage_fixup {
2038 struct btrfs_work work;
2041 static void btrfs_writepage_fixup_worker(struct btrfs_work *work)
2043 struct btrfs_writepage_fixup *fixup;
2044 struct btrfs_ordered_extent *ordered;
2045 struct extent_state *cached_state = NULL;
2046 struct extent_changeset *data_reserved = NULL;
2048 struct inode *inode;
2053 fixup = container_of(work, struct btrfs_writepage_fixup, work);
2057 if (!page->mapping || !PageDirty(page) || !PageChecked(page)) {
2058 ClearPageChecked(page);
2062 inode = page->mapping->host;
2063 page_start = page_offset(page);
2064 page_end = page_offset(page) + PAGE_SIZE - 1;
2066 lock_extent_bits(&BTRFS_I(inode)->io_tree, page_start, page_end,
2069 /* already ordered? We're done */
2070 if (PagePrivate2(page))
2073 ordered = btrfs_lookup_ordered_range(BTRFS_I(inode), page_start,
2076 unlock_extent_cached(&BTRFS_I(inode)->io_tree, page_start,
2077 page_end, &cached_state, GFP_NOFS);
2079 btrfs_start_ordered_extent(inode, ordered, 1);
2080 btrfs_put_ordered_extent(ordered);
2084 ret = btrfs_delalloc_reserve_space(inode, &data_reserved, page_start,
2087 mapping_set_error(page->mapping, ret);
2088 end_extent_writepage(page, ret, page_start, page_end);
2089 ClearPageChecked(page);
2093 btrfs_set_extent_delalloc(inode, page_start, page_end, &cached_state,
2095 ClearPageChecked(page);
2096 set_page_dirty(page);
2097 btrfs_delalloc_release_extents(BTRFS_I(inode), PAGE_SIZE);
2099 unlock_extent_cached(&BTRFS_I(inode)->io_tree, page_start, page_end,
2100 &cached_state, GFP_NOFS);
2105 extent_changeset_free(data_reserved);
2109 * There are a few paths in the higher layers of the kernel that directly
2110 * set the page dirty bit without asking the filesystem if it is a
2111 * good idea. This causes problems because we want to make sure COW
2112 * properly happens and the data=ordered rules are followed.
2114 * In our case any range that doesn't have the ORDERED bit set
2115 * hasn't been properly setup for IO. We kick off an async process
2116 * to fix it up. The async helper will wait for ordered extents, set
2117 * the delalloc bit and make it safe to write the page.
2119 static int btrfs_writepage_start_hook(struct page *page, u64 start, u64 end)
2121 struct inode *inode = page->mapping->host;
2122 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2123 struct btrfs_writepage_fixup *fixup;
2125 /* this page is properly in the ordered list */
2126 if (TestClearPagePrivate2(page))
2129 if (PageChecked(page))
2132 fixup = kzalloc(sizeof(*fixup), GFP_NOFS);
2136 SetPageChecked(page);
2138 btrfs_init_work(&fixup->work, btrfs_fixup_helper,
2139 btrfs_writepage_fixup_worker, NULL, NULL);
2141 btrfs_queue_work(fs_info->fixup_workers, &fixup->work);
2145 static int insert_reserved_file_extent(struct btrfs_trans_handle *trans,
2146 struct inode *inode, u64 file_pos,
2147 u64 disk_bytenr, u64 disk_num_bytes,
2148 u64 num_bytes, u64 ram_bytes,
2149 u8 compression, u8 encryption,
2150 u16 other_encoding, int extent_type)
2152 struct btrfs_root *root = BTRFS_I(inode)->root;
2153 struct btrfs_file_extent_item *fi;
2154 struct btrfs_path *path;
2155 struct extent_buffer *leaf;
2156 struct btrfs_key ins;
2158 int extent_inserted = 0;
2161 path = btrfs_alloc_path();
2166 * we may be replacing one extent in the tree with another.
2167 * The new extent is pinned in the extent map, and we don't want
2168 * to drop it from the cache until it is completely in the btree.
2170 * So, tell btrfs_drop_extents to leave this extent in the cache.
2171 * the caller is expected to unpin it and allow it to be merged
2174 ret = __btrfs_drop_extents(trans, root, inode, path, file_pos,
2175 file_pos + num_bytes, NULL, 0,
2176 1, sizeof(*fi), &extent_inserted);
2180 if (!extent_inserted) {
2181 ins.objectid = btrfs_ino(BTRFS_I(inode));
2182 ins.offset = file_pos;
2183 ins.type = BTRFS_EXTENT_DATA_KEY;
2185 path->leave_spinning = 1;
2186 ret = btrfs_insert_empty_item(trans, root, path, &ins,
2191 leaf = path->nodes[0];
2192 fi = btrfs_item_ptr(leaf, path->slots[0],
2193 struct btrfs_file_extent_item);
2194 btrfs_set_file_extent_generation(leaf, fi, trans->transid);
2195 btrfs_set_file_extent_type(leaf, fi, extent_type);
2196 btrfs_set_file_extent_disk_bytenr(leaf, fi, disk_bytenr);
2197 btrfs_set_file_extent_disk_num_bytes(leaf, fi, disk_num_bytes);
2198 btrfs_set_file_extent_offset(leaf, fi, 0);
2199 btrfs_set_file_extent_num_bytes(leaf, fi, num_bytes);
2200 btrfs_set_file_extent_ram_bytes(leaf, fi, ram_bytes);
2201 btrfs_set_file_extent_compression(leaf, fi, compression);
2202 btrfs_set_file_extent_encryption(leaf, fi, encryption);
2203 btrfs_set_file_extent_other_encoding(leaf, fi, other_encoding);
2205 btrfs_mark_buffer_dirty(leaf);
2206 btrfs_release_path(path);
2208 inode_add_bytes(inode, num_bytes);
2210 ins.objectid = disk_bytenr;
2211 ins.offset = disk_num_bytes;
2212 ins.type = BTRFS_EXTENT_ITEM_KEY;
2215 * Release the reserved range from inode dirty range map, as it is
2216 * already moved into delayed_ref_head
2218 ret = btrfs_qgroup_release_data(inode, file_pos, ram_bytes);
2222 ret = btrfs_alloc_reserved_file_extent(trans, root,
2223 btrfs_ino(BTRFS_I(inode)),
2224 file_pos, qg_released, &ins);
2226 btrfs_free_path(path);
2231 /* snapshot-aware defrag */
2232 struct sa_defrag_extent_backref {
2233 struct rb_node node;
2234 struct old_sa_defrag_extent *old;
2243 struct old_sa_defrag_extent {
2244 struct list_head list;
2245 struct new_sa_defrag_extent *new;
2254 struct new_sa_defrag_extent {
2255 struct rb_root root;
2256 struct list_head head;
2257 struct btrfs_path *path;
2258 struct inode *inode;
2266 static int backref_comp(struct sa_defrag_extent_backref *b1,
2267 struct sa_defrag_extent_backref *b2)
2269 if (b1->root_id < b2->root_id)
2271 else if (b1->root_id > b2->root_id)
2274 if (b1->inum < b2->inum)
2276 else if (b1->inum > b2->inum)
2279 if (b1->file_pos < b2->file_pos)
2281 else if (b1->file_pos > b2->file_pos)
2285 * [------------------------------] ===> (a range of space)
2286 * |<--->| |<---->| =============> (fs/file tree A)
2287 * |<---------------------------->| ===> (fs/file tree B)
2289 * A range of space can refer to two file extents in one tree while
2290 * refer to only one file extent in another tree.
2292 * So we may process a disk offset more than one time(two extents in A)
2293 * and locate at the same extent(one extent in B), then insert two same
2294 * backrefs(both refer to the extent in B).
2299 static void backref_insert(struct rb_root *root,
2300 struct sa_defrag_extent_backref *backref)
2302 struct rb_node **p = &root->rb_node;
2303 struct rb_node *parent = NULL;
2304 struct sa_defrag_extent_backref *entry;
2309 entry = rb_entry(parent, struct sa_defrag_extent_backref, node);
2311 ret = backref_comp(backref, entry);
2315 p = &(*p)->rb_right;
2318 rb_link_node(&backref->node, parent, p);
2319 rb_insert_color(&backref->node, root);
2323 * Note the backref might has changed, and in this case we just return 0.
2325 static noinline int record_one_backref(u64 inum, u64 offset, u64 root_id,
2328 struct btrfs_file_extent_item *extent;
2329 struct old_sa_defrag_extent *old = ctx;
2330 struct new_sa_defrag_extent *new = old->new;
2331 struct btrfs_path *path = new->path;
2332 struct btrfs_key key;
2333 struct btrfs_root *root;
2334 struct sa_defrag_extent_backref *backref;
2335 struct extent_buffer *leaf;
2336 struct inode *inode = new->inode;
2337 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2343 if (BTRFS_I(inode)->root->root_key.objectid == root_id &&
2344 inum == btrfs_ino(BTRFS_I(inode)))
2347 key.objectid = root_id;
2348 key.type = BTRFS_ROOT_ITEM_KEY;
2349 key.offset = (u64)-1;
2351 root = btrfs_read_fs_root_no_name(fs_info, &key);
2353 if (PTR_ERR(root) == -ENOENT)
2356 btrfs_debug(fs_info, "inum=%llu, offset=%llu, root_id=%llu",
2357 inum, offset, root_id);
2358 return PTR_ERR(root);
2361 key.objectid = inum;
2362 key.type = BTRFS_EXTENT_DATA_KEY;
2363 if (offset > (u64)-1 << 32)
2366 key.offset = offset;
2368 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2369 if (WARN_ON(ret < 0))
2376 leaf = path->nodes[0];
2377 slot = path->slots[0];
2379 if (slot >= btrfs_header_nritems(leaf)) {
2380 ret = btrfs_next_leaf(root, path);
2383 } else if (ret > 0) {
2392 btrfs_item_key_to_cpu(leaf, &key, slot);
2394 if (key.objectid > inum)
2397 if (key.objectid < inum || key.type != BTRFS_EXTENT_DATA_KEY)
2400 extent = btrfs_item_ptr(leaf, slot,
2401 struct btrfs_file_extent_item);
2403 if (btrfs_file_extent_disk_bytenr(leaf, extent) != old->bytenr)
2407 * 'offset' refers to the exact key.offset,
2408 * NOT the 'offset' field in btrfs_extent_data_ref, ie.
2409 * (key.offset - extent_offset).
2411 if (key.offset != offset)
2414 extent_offset = btrfs_file_extent_offset(leaf, extent);
2415 num_bytes = btrfs_file_extent_num_bytes(leaf, extent);
2417 if (extent_offset >= old->extent_offset + old->offset +
2418 old->len || extent_offset + num_bytes <=
2419 old->extent_offset + old->offset)
2424 backref = kmalloc(sizeof(*backref), GFP_NOFS);
2430 backref->root_id = root_id;
2431 backref->inum = inum;
2432 backref->file_pos = offset;
2433 backref->num_bytes = num_bytes;
2434 backref->extent_offset = extent_offset;
2435 backref->generation = btrfs_file_extent_generation(leaf, extent);
2437 backref_insert(&new->root, backref);
2440 btrfs_release_path(path);
2445 static noinline bool record_extent_backrefs(struct btrfs_path *path,
2446 struct new_sa_defrag_extent *new)
2448 struct btrfs_fs_info *fs_info = btrfs_sb(new->inode->i_sb);
2449 struct old_sa_defrag_extent *old, *tmp;
2454 list_for_each_entry_safe(old, tmp, &new->head, list) {
2455 ret = iterate_inodes_from_logical(old->bytenr +
2456 old->extent_offset, fs_info,
2457 path, record_one_backref,
2459 if (ret < 0 && ret != -ENOENT)
2462 /* no backref to be processed for this extent */
2464 list_del(&old->list);
2469 if (list_empty(&new->head))
2475 static int relink_is_mergable(struct extent_buffer *leaf,
2476 struct btrfs_file_extent_item *fi,
2477 struct new_sa_defrag_extent *new)
2479 if (btrfs_file_extent_disk_bytenr(leaf, fi) != new->bytenr)
2482 if (btrfs_file_extent_type(leaf, fi) != BTRFS_FILE_EXTENT_REG)
2485 if (btrfs_file_extent_compression(leaf, fi) != new->compress_type)
2488 if (btrfs_file_extent_encryption(leaf, fi) ||
2489 btrfs_file_extent_other_encoding(leaf, fi))
2496 * Note the backref might has changed, and in this case we just return 0.
2498 static noinline int relink_extent_backref(struct btrfs_path *path,
2499 struct sa_defrag_extent_backref *prev,
2500 struct sa_defrag_extent_backref *backref)
2502 struct btrfs_file_extent_item *extent;
2503 struct btrfs_file_extent_item *item;
2504 struct btrfs_ordered_extent *ordered;
2505 struct btrfs_trans_handle *trans;
2506 struct btrfs_root *root;
2507 struct btrfs_key key;
2508 struct extent_buffer *leaf;
2509 struct old_sa_defrag_extent *old = backref->old;
2510 struct new_sa_defrag_extent *new = old->new;
2511 struct btrfs_fs_info *fs_info = btrfs_sb(new->inode->i_sb);
2512 struct inode *inode;
2513 struct extent_state *cached = NULL;
2522 if (prev && prev->root_id == backref->root_id &&
2523 prev->inum == backref->inum &&
2524 prev->file_pos + prev->num_bytes == backref->file_pos)
2527 /* step 1: get root */
2528 key.objectid = backref->root_id;
2529 key.type = BTRFS_ROOT_ITEM_KEY;
2530 key.offset = (u64)-1;
2532 index = srcu_read_lock(&fs_info->subvol_srcu);
2534 root = btrfs_read_fs_root_no_name(fs_info, &key);
2536 srcu_read_unlock(&fs_info->subvol_srcu, index);
2537 if (PTR_ERR(root) == -ENOENT)
2539 return PTR_ERR(root);
2542 if (btrfs_root_readonly(root)) {
2543 srcu_read_unlock(&fs_info->subvol_srcu, index);
2547 /* step 2: get inode */
2548 key.objectid = backref->inum;
2549 key.type = BTRFS_INODE_ITEM_KEY;
2552 inode = btrfs_iget(fs_info->sb, &key, root, NULL);
2553 if (IS_ERR(inode)) {
2554 srcu_read_unlock(&fs_info->subvol_srcu, index);
2558 srcu_read_unlock(&fs_info->subvol_srcu, index);
2560 /* step 3: relink backref */
2561 lock_start = backref->file_pos;
2562 lock_end = backref->file_pos + backref->num_bytes - 1;
2563 lock_extent_bits(&BTRFS_I(inode)->io_tree, lock_start, lock_end,
2566 ordered = btrfs_lookup_first_ordered_extent(inode, lock_end);
2568 btrfs_put_ordered_extent(ordered);
2572 trans = btrfs_join_transaction(root);
2573 if (IS_ERR(trans)) {
2574 ret = PTR_ERR(trans);
2578 key.objectid = backref->inum;
2579 key.type = BTRFS_EXTENT_DATA_KEY;
2580 key.offset = backref->file_pos;
2582 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2585 } else if (ret > 0) {
2590 extent = btrfs_item_ptr(path->nodes[0], path->slots[0],
2591 struct btrfs_file_extent_item);
2593 if (btrfs_file_extent_generation(path->nodes[0], extent) !=
2594 backref->generation)
2597 btrfs_release_path(path);
2599 start = backref->file_pos;
2600 if (backref->extent_offset < old->extent_offset + old->offset)
2601 start += old->extent_offset + old->offset -
2602 backref->extent_offset;
2604 len = min(backref->extent_offset + backref->num_bytes,
2605 old->extent_offset + old->offset + old->len);
2606 len -= max(backref->extent_offset, old->extent_offset + old->offset);
2608 ret = btrfs_drop_extents(trans, root, inode, start,
2613 key.objectid = btrfs_ino(BTRFS_I(inode));
2614 key.type = BTRFS_EXTENT_DATA_KEY;
2617 path->leave_spinning = 1;
2619 struct btrfs_file_extent_item *fi;
2621 struct btrfs_key found_key;
2623 ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
2628 leaf = path->nodes[0];
2629 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
2631 fi = btrfs_item_ptr(leaf, path->slots[0],
2632 struct btrfs_file_extent_item);
2633 extent_len = btrfs_file_extent_num_bytes(leaf, fi);
2635 if (extent_len + found_key.offset == start &&
2636 relink_is_mergable(leaf, fi, new)) {
2637 btrfs_set_file_extent_num_bytes(leaf, fi,
2639 btrfs_mark_buffer_dirty(leaf);
2640 inode_add_bytes(inode, len);
2646 btrfs_release_path(path);
2651 ret = btrfs_insert_empty_item(trans, root, path, &key,
2654 btrfs_abort_transaction(trans, ret);
2658 leaf = path->nodes[0];
2659 item = btrfs_item_ptr(leaf, path->slots[0],
2660 struct btrfs_file_extent_item);
2661 btrfs_set_file_extent_disk_bytenr(leaf, item, new->bytenr);
2662 btrfs_set_file_extent_disk_num_bytes(leaf, item, new->disk_len);
2663 btrfs_set_file_extent_offset(leaf, item, start - new->file_pos);
2664 btrfs_set_file_extent_num_bytes(leaf, item, len);
2665 btrfs_set_file_extent_ram_bytes(leaf, item, new->len);
2666 btrfs_set_file_extent_generation(leaf, item, trans->transid);
2667 btrfs_set_file_extent_type(leaf, item, BTRFS_FILE_EXTENT_REG);
2668 btrfs_set_file_extent_compression(leaf, item, new->compress_type);
2669 btrfs_set_file_extent_encryption(leaf, item, 0);
2670 btrfs_set_file_extent_other_encoding(leaf, item, 0);
2672 btrfs_mark_buffer_dirty(leaf);
2673 inode_add_bytes(inode, len);
2674 btrfs_release_path(path);
2676 ret = btrfs_inc_extent_ref(trans, root, new->bytenr,
2678 backref->root_id, backref->inum,
2679 new->file_pos); /* start - extent_offset */
2681 btrfs_abort_transaction(trans, ret);
2687 btrfs_release_path(path);
2688 path->leave_spinning = 0;
2689 btrfs_end_transaction(trans);
2691 unlock_extent_cached(&BTRFS_I(inode)->io_tree, lock_start, lock_end,
2697 static void free_sa_defrag_extent(struct new_sa_defrag_extent *new)
2699 struct old_sa_defrag_extent *old, *tmp;
2704 list_for_each_entry_safe(old, tmp, &new->head, list) {
2710 static void relink_file_extents(struct new_sa_defrag_extent *new)
2712 struct btrfs_fs_info *fs_info = btrfs_sb(new->inode->i_sb);
2713 struct btrfs_path *path;
2714 struct sa_defrag_extent_backref *backref;
2715 struct sa_defrag_extent_backref *prev = NULL;
2716 struct inode *inode;
2717 struct btrfs_root *root;
2718 struct rb_node *node;
2722 root = BTRFS_I(inode)->root;
2724 path = btrfs_alloc_path();
2728 if (!record_extent_backrefs(path, new)) {
2729 btrfs_free_path(path);
2732 btrfs_release_path(path);
2735 node = rb_first(&new->root);
2738 rb_erase(node, &new->root);
2740 backref = rb_entry(node, struct sa_defrag_extent_backref, node);
2742 ret = relink_extent_backref(path, prev, backref);
2755 btrfs_free_path(path);
2757 free_sa_defrag_extent(new);
2759 atomic_dec(&fs_info->defrag_running);
2760 wake_up(&fs_info->transaction_wait);
2763 static struct new_sa_defrag_extent *
2764 record_old_file_extents(struct inode *inode,
2765 struct btrfs_ordered_extent *ordered)
2767 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2768 struct btrfs_root *root = BTRFS_I(inode)->root;
2769 struct btrfs_path *path;
2770 struct btrfs_key key;
2771 struct old_sa_defrag_extent *old;
2772 struct new_sa_defrag_extent *new;
2775 new = kmalloc(sizeof(*new), GFP_NOFS);
2780 new->file_pos = ordered->file_offset;
2781 new->len = ordered->len;
2782 new->bytenr = ordered->start;
2783 new->disk_len = ordered->disk_len;
2784 new->compress_type = ordered->compress_type;
2785 new->root = RB_ROOT;
2786 INIT_LIST_HEAD(&new->head);
2788 path = btrfs_alloc_path();
2792 key.objectid = btrfs_ino(BTRFS_I(inode));
2793 key.type = BTRFS_EXTENT_DATA_KEY;
2794 key.offset = new->file_pos;
2796 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2799 if (ret > 0 && path->slots[0] > 0)
2802 /* find out all the old extents for the file range */
2804 struct btrfs_file_extent_item *extent;
2805 struct extent_buffer *l;
2814 slot = path->slots[0];
2816 if (slot >= btrfs_header_nritems(l)) {
2817 ret = btrfs_next_leaf(root, path);
2825 btrfs_item_key_to_cpu(l, &key, slot);
2827 if (key.objectid != btrfs_ino(BTRFS_I(inode)))
2829 if (key.type != BTRFS_EXTENT_DATA_KEY)
2831 if (key.offset >= new->file_pos + new->len)
2834 extent = btrfs_item_ptr(l, slot, struct btrfs_file_extent_item);
2836 num_bytes = btrfs_file_extent_num_bytes(l, extent);
2837 if (key.offset + num_bytes < new->file_pos)
2840 disk_bytenr = btrfs_file_extent_disk_bytenr(l, extent);
2844 extent_offset = btrfs_file_extent_offset(l, extent);
2846 old = kmalloc(sizeof(*old), GFP_NOFS);
2850 offset = max(new->file_pos, key.offset);
2851 end = min(new->file_pos + new->len, key.offset + num_bytes);
2853 old->bytenr = disk_bytenr;
2854 old->extent_offset = extent_offset;
2855 old->offset = offset - key.offset;
2856 old->len = end - offset;
2859 list_add_tail(&old->list, &new->head);
2865 btrfs_free_path(path);
2866 atomic_inc(&fs_info->defrag_running);
2871 btrfs_free_path(path);
2873 free_sa_defrag_extent(new);
2877 static void btrfs_release_delalloc_bytes(struct btrfs_fs_info *fs_info,
2880 struct btrfs_block_group_cache *cache;
2882 cache = btrfs_lookup_block_group(fs_info, start);
2885 spin_lock(&cache->lock);
2886 cache->delalloc_bytes -= len;
2887 spin_unlock(&cache->lock);
2889 btrfs_put_block_group(cache);
2892 /* as ordered data IO finishes, this gets called so we can finish
2893 * an ordered extent if the range of bytes in the file it covers are
2896 static int btrfs_finish_ordered_io(struct btrfs_ordered_extent *ordered_extent)
2898 struct inode *inode = ordered_extent->inode;
2899 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2900 struct btrfs_root *root = BTRFS_I(inode)->root;
2901 struct btrfs_trans_handle *trans = NULL;
2902 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
2903 struct extent_state *cached_state = NULL;
2904 struct new_sa_defrag_extent *new = NULL;
2905 int compress_type = 0;
2907 u64 logical_len = ordered_extent->len;
2909 bool truncated = false;
2910 bool range_locked = false;
2911 bool clear_new_delalloc_bytes = false;
2913 if (!test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags) &&
2914 !test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags) &&
2915 !test_bit(BTRFS_ORDERED_DIRECT, &ordered_extent->flags))
2916 clear_new_delalloc_bytes = true;
2918 nolock = btrfs_is_free_space_inode(BTRFS_I(inode));
2920 if (test_bit(BTRFS_ORDERED_IOERR, &ordered_extent->flags)) {
2925 btrfs_free_io_failure_record(BTRFS_I(inode),
2926 ordered_extent->file_offset,
2927 ordered_extent->file_offset +
2928 ordered_extent->len - 1);
2930 if (test_bit(BTRFS_ORDERED_TRUNCATED, &ordered_extent->flags)) {
2932 logical_len = ordered_extent->truncated_len;
2933 /* Truncated the entire extent, don't bother adding */
2938 if (test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags)) {
2939 BUG_ON(!list_empty(&ordered_extent->list)); /* Logic error */
2942 * For mwrite(mmap + memset to write) case, we still reserve
2943 * space for NOCOW range.
2944 * As NOCOW won't cause a new delayed ref, just free the space
2946 btrfs_qgroup_free_data(inode, NULL, ordered_extent->file_offset,
2947 ordered_extent->len);
2948 btrfs_ordered_update_i_size(inode, 0, ordered_extent);
2950 trans = btrfs_join_transaction_nolock(root);
2952 trans = btrfs_join_transaction(root);
2953 if (IS_ERR(trans)) {
2954 ret = PTR_ERR(trans);
2958 trans->block_rsv = &BTRFS_I(inode)->block_rsv;
2959 ret = btrfs_update_inode_fallback(trans, root, inode);
2960 if (ret) /* -ENOMEM or corruption */
2961 btrfs_abort_transaction(trans, ret);
2965 range_locked = true;
2966 lock_extent_bits(io_tree, ordered_extent->file_offset,
2967 ordered_extent->file_offset + ordered_extent->len - 1,
2970 ret = test_range_bit(io_tree, ordered_extent->file_offset,
2971 ordered_extent->file_offset + ordered_extent->len - 1,
2972 EXTENT_DEFRAG, 0, cached_state);
2974 u64 last_snapshot = btrfs_root_last_snapshot(&root->root_item);
2975 if (0 && last_snapshot >= BTRFS_I(inode)->generation)
2976 /* the inode is shared */
2977 new = record_old_file_extents(inode, ordered_extent);
2979 clear_extent_bit(io_tree, ordered_extent->file_offset,
2980 ordered_extent->file_offset + ordered_extent->len - 1,
2981 EXTENT_DEFRAG, 0, 0, &cached_state, GFP_NOFS);
2985 trans = btrfs_join_transaction_nolock(root);
2987 trans = btrfs_join_transaction(root);
2988 if (IS_ERR(trans)) {
2989 ret = PTR_ERR(trans);
2994 trans->block_rsv = &BTRFS_I(inode)->block_rsv;
2996 if (test_bit(BTRFS_ORDERED_COMPRESSED, &ordered_extent->flags))
2997 compress_type = ordered_extent->compress_type;
2998 if (test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags)) {
2999 BUG_ON(compress_type);
3000 ret = btrfs_mark_extent_written(trans, BTRFS_I(inode),
3001 ordered_extent->file_offset,
3002 ordered_extent->file_offset +
3005 BUG_ON(root == fs_info->tree_root);
3006 ret = insert_reserved_file_extent(trans, inode,
3007 ordered_extent->file_offset,
3008 ordered_extent->start,
3009 ordered_extent->disk_len,
3010 logical_len, logical_len,
3011 compress_type, 0, 0,
3012 BTRFS_FILE_EXTENT_REG);
3014 btrfs_release_delalloc_bytes(fs_info,
3015 ordered_extent->start,
3016 ordered_extent->disk_len);
3018 unpin_extent_cache(&BTRFS_I(inode)->extent_tree,
3019 ordered_extent->file_offset, ordered_extent->len,
3022 btrfs_abort_transaction(trans, ret);
3026 add_pending_csums(trans, inode, &ordered_extent->list);
3028 btrfs_ordered_update_i_size(inode, 0, ordered_extent);
3029 ret = btrfs_update_inode_fallback(trans, root, inode);
3030 if (ret) { /* -ENOMEM or corruption */
3031 btrfs_abort_transaction(trans, ret);
3036 if (range_locked || clear_new_delalloc_bytes) {
3037 unsigned int clear_bits = 0;
3040 clear_bits |= EXTENT_LOCKED;
3041 if (clear_new_delalloc_bytes)
3042 clear_bits |= EXTENT_DELALLOC_NEW;
3043 clear_extent_bit(&BTRFS_I(inode)->io_tree,
3044 ordered_extent->file_offset,
3045 ordered_extent->file_offset +
3046 ordered_extent->len - 1,
3048 (clear_bits & EXTENT_LOCKED) ? 1 : 0,
3049 0, &cached_state, GFP_NOFS);
3053 btrfs_end_transaction(trans);
3055 if (ret || truncated) {
3059 start = ordered_extent->file_offset + logical_len;
3061 start = ordered_extent->file_offset;
3062 end = ordered_extent->file_offset + ordered_extent->len - 1;
3063 clear_extent_uptodate(io_tree, start, end, NULL, GFP_NOFS);
3065 /* Drop the cache for the part of the extent we didn't write. */
3066 btrfs_drop_extent_cache(BTRFS_I(inode), start, end, 0);
3069 * If the ordered extent had an IOERR or something else went
3070 * wrong we need to return the space for this ordered extent
3071 * back to the allocator. We only free the extent in the
3072 * truncated case if we didn't write out the extent at all.
3074 if ((ret || !logical_len) &&
3075 !test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags) &&
3076 !test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags))
3077 btrfs_free_reserved_extent(fs_info,
3078 ordered_extent->start,
3079 ordered_extent->disk_len, 1);
3084 * This needs to be done to make sure anybody waiting knows we are done
3085 * updating everything for this ordered extent.
3087 btrfs_remove_ordered_extent(inode, ordered_extent);
3089 /* for snapshot-aware defrag */
3092 free_sa_defrag_extent(new);
3093 atomic_dec(&fs_info->defrag_running);
3095 relink_file_extents(new);
3100 btrfs_put_ordered_extent(ordered_extent);
3101 /* once for the tree */
3102 btrfs_put_ordered_extent(ordered_extent);
3107 static void finish_ordered_fn(struct btrfs_work *work)
3109 struct btrfs_ordered_extent *ordered_extent;
3110 ordered_extent = container_of(work, struct btrfs_ordered_extent, work);
3111 btrfs_finish_ordered_io(ordered_extent);
3114 static void btrfs_writepage_end_io_hook(struct page *page, u64 start, u64 end,
3115 struct extent_state *state, int uptodate)
3117 struct inode *inode = page->mapping->host;
3118 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
3119 struct btrfs_ordered_extent *ordered_extent = NULL;
3120 struct btrfs_workqueue *wq;
3121 btrfs_work_func_t func;
3123 trace_btrfs_writepage_end_io_hook(page, start, end, uptodate);
3125 ClearPagePrivate2(page);
3126 if (!btrfs_dec_test_ordered_pending(inode, &ordered_extent, start,
3127 end - start + 1, uptodate))
3130 if (btrfs_is_free_space_inode(BTRFS_I(inode))) {
3131 wq = fs_info->endio_freespace_worker;
3132 func = btrfs_freespace_write_helper;
3134 wq = fs_info->endio_write_workers;
3135 func = btrfs_endio_write_helper;
3138 btrfs_init_work(&ordered_extent->work, func, finish_ordered_fn, NULL,
3140 btrfs_queue_work(wq, &ordered_extent->work);
3143 static int __readpage_endio_check(struct inode *inode,
3144 struct btrfs_io_bio *io_bio,
3145 int icsum, struct page *page,
3146 int pgoff, u64 start, size_t len)
3152 csum_expected = *(((u32 *)io_bio->csum) + icsum);
3154 kaddr = kmap_atomic(page);
3155 csum = btrfs_csum_data(kaddr + pgoff, csum, len);
3156 btrfs_csum_final(csum, (u8 *)&csum);
3157 if (csum != csum_expected)
3160 kunmap_atomic(kaddr);
3163 btrfs_print_data_csum_error(BTRFS_I(inode), start, csum, csum_expected,
3164 io_bio->mirror_num);
3165 memset(kaddr + pgoff, 1, len);
3166 flush_dcache_page(page);
3167 kunmap_atomic(kaddr);
3172 * when reads are done, we need to check csums to verify the data is correct
3173 * if there's a match, we allow the bio to finish. If not, the code in
3174 * extent_io.c will try to find good copies for us.
3176 static int btrfs_readpage_end_io_hook(struct btrfs_io_bio *io_bio,
3177 u64 phy_offset, struct page *page,
3178 u64 start, u64 end, int mirror)
3180 size_t offset = start - page_offset(page);
3181 struct inode *inode = page->mapping->host;
3182 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
3183 struct btrfs_root *root = BTRFS_I(inode)->root;
3185 if (PageChecked(page)) {
3186 ClearPageChecked(page);
3190 if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)
3193 if (root->root_key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID &&
3194 test_range_bit(io_tree, start, end, EXTENT_NODATASUM, 1, NULL)) {
3195 clear_extent_bits(io_tree, start, end, EXTENT_NODATASUM);
3199 phy_offset >>= inode->i_sb->s_blocksize_bits;
3200 return __readpage_endio_check(inode, io_bio, phy_offset, page, offset,
3201 start, (size_t)(end - start + 1));
3204 void btrfs_add_delayed_iput(struct inode *inode)
3206 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
3207 struct btrfs_inode *binode = BTRFS_I(inode);
3209 if (atomic_add_unless(&inode->i_count, -1, 1))
3212 spin_lock(&fs_info->delayed_iput_lock);
3213 if (binode->delayed_iput_count == 0) {
3214 ASSERT(list_empty(&binode->delayed_iput));
3215 list_add_tail(&binode->delayed_iput, &fs_info->delayed_iputs);
3217 binode->delayed_iput_count++;
3219 spin_unlock(&fs_info->delayed_iput_lock);
3222 void btrfs_run_delayed_iputs(struct btrfs_fs_info *fs_info)
3225 spin_lock(&fs_info->delayed_iput_lock);
3226 while (!list_empty(&fs_info->delayed_iputs)) {
3227 struct btrfs_inode *inode;
3229 inode = list_first_entry(&fs_info->delayed_iputs,
3230 struct btrfs_inode, delayed_iput);
3231 if (inode->delayed_iput_count) {
3232 inode->delayed_iput_count--;
3233 list_move_tail(&inode->delayed_iput,
3234 &fs_info->delayed_iputs);
3236 list_del_init(&inode->delayed_iput);
3238 spin_unlock(&fs_info->delayed_iput_lock);
3239 iput(&inode->vfs_inode);
3240 spin_lock(&fs_info->delayed_iput_lock);
3242 spin_unlock(&fs_info->delayed_iput_lock);
3246 * This is called in transaction commit time. If there are no orphan
3247 * files in the subvolume, it removes orphan item and frees block_rsv
3250 void btrfs_orphan_commit_root(struct btrfs_trans_handle *trans,
3251 struct btrfs_root *root)
3253 struct btrfs_fs_info *fs_info = root->fs_info;
3254 struct btrfs_block_rsv *block_rsv;
3257 if (atomic_read(&root->orphan_inodes) ||
3258 root->orphan_cleanup_state != ORPHAN_CLEANUP_DONE)
3261 spin_lock(&root->orphan_lock);
3262 if (atomic_read(&root->orphan_inodes)) {
3263 spin_unlock(&root->orphan_lock);
3267 if (root->orphan_cleanup_state != ORPHAN_CLEANUP_DONE) {
3268 spin_unlock(&root->orphan_lock);
3272 block_rsv = root->orphan_block_rsv;
3273 root->orphan_block_rsv = NULL;
3274 spin_unlock(&root->orphan_lock);
3276 if (test_bit(BTRFS_ROOT_ORPHAN_ITEM_INSERTED, &root->state) &&
3277 btrfs_root_refs(&root->root_item) > 0) {
3278 ret = btrfs_del_orphan_item(trans, fs_info->tree_root,
3279 root->root_key.objectid);
3281 btrfs_abort_transaction(trans, ret);
3283 clear_bit(BTRFS_ROOT_ORPHAN_ITEM_INSERTED,
3288 WARN_ON(block_rsv->size > 0);
3289 btrfs_free_block_rsv(fs_info, block_rsv);
3294 * This creates an orphan entry for the given inode in case something goes
3295 * wrong in the middle of an unlink/truncate.
3297 * NOTE: caller of this function should reserve 5 units of metadata for
3300 int btrfs_orphan_add(struct btrfs_trans_handle *trans,
3301 struct btrfs_inode *inode)
3303 struct btrfs_fs_info *fs_info = btrfs_sb(inode->vfs_inode.i_sb);
3304 struct btrfs_root *root = inode->root;
3305 struct btrfs_block_rsv *block_rsv = NULL;
3310 if (!root->orphan_block_rsv) {
3311 block_rsv = btrfs_alloc_block_rsv(fs_info,
3312 BTRFS_BLOCK_RSV_TEMP);
3317 spin_lock(&root->orphan_lock);
3318 if (!root->orphan_block_rsv) {
3319 root->orphan_block_rsv = block_rsv;
3320 } else if (block_rsv) {
3321 btrfs_free_block_rsv(fs_info, block_rsv);
3325 if (!test_and_set_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
3326 &inode->runtime_flags)) {
3329 * For proper ENOSPC handling, we should do orphan
3330 * cleanup when mounting. But this introduces backward
3331 * compatibility issue.
3333 if (!xchg(&root->orphan_item_inserted, 1))
3339 atomic_inc(&root->orphan_inodes);
3342 if (!test_and_set_bit(BTRFS_INODE_ORPHAN_META_RESERVED,
3343 &inode->runtime_flags))
3345 spin_unlock(&root->orphan_lock);
3347 /* grab metadata reservation from transaction handle */
3349 ret = btrfs_orphan_reserve_metadata(trans, inode);
3352 atomic_dec(&root->orphan_inodes);
3353 clear_bit(BTRFS_INODE_ORPHAN_META_RESERVED,
3354 &inode->runtime_flags);
3356 clear_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
3357 &inode->runtime_flags);
3362 /* insert an orphan item to track this unlinked/truncated file */
3364 ret = btrfs_insert_orphan_item(trans, root, btrfs_ino(inode));
3366 atomic_dec(&root->orphan_inodes);
3368 clear_bit(BTRFS_INODE_ORPHAN_META_RESERVED,
3369 &inode->runtime_flags);
3370 btrfs_orphan_release_metadata(inode);
3372 if (ret != -EEXIST) {
3373 clear_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
3374 &inode->runtime_flags);
3375 btrfs_abort_transaction(trans, ret);
3382 /* insert an orphan item to track subvolume contains orphan files */
3384 ret = btrfs_insert_orphan_item(trans, fs_info->tree_root,
3385 root->root_key.objectid);
3386 if (ret && ret != -EEXIST) {
3387 btrfs_abort_transaction(trans, ret);
3395 * We have done the truncate/delete so we can go ahead and remove the orphan
3396 * item for this particular inode.
3398 static int btrfs_orphan_del(struct btrfs_trans_handle *trans,
3399 struct btrfs_inode *inode)
3401 struct btrfs_root *root = inode->root;
3402 int delete_item = 0;
3403 int release_rsv = 0;
3406 spin_lock(&root->orphan_lock);
3407 if (test_and_clear_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
3408 &inode->runtime_flags))
3411 if (test_and_clear_bit(BTRFS_INODE_ORPHAN_META_RESERVED,
3412 &inode->runtime_flags))
3414 spin_unlock(&root->orphan_lock);
3417 atomic_dec(&root->orphan_inodes);
3419 ret = btrfs_del_orphan_item(trans, root,
3424 btrfs_orphan_release_metadata(inode);
3430 * this cleans up any orphans that may be left on the list from the last use
3433 int btrfs_orphan_cleanup(struct btrfs_root *root)
3435 struct btrfs_fs_info *fs_info = root->fs_info;
3436 struct btrfs_path *path;
3437 struct extent_buffer *leaf;
3438 struct btrfs_key key, found_key;
3439 struct btrfs_trans_handle *trans;
3440 struct inode *inode;
3441 u64 last_objectid = 0;
3442 int ret = 0, nr_unlink = 0, nr_truncate = 0;
3444 if (cmpxchg(&root->orphan_cleanup_state, 0, ORPHAN_CLEANUP_STARTED))
3447 path = btrfs_alloc_path();
3452 path->reada = READA_BACK;
3454 key.objectid = BTRFS_ORPHAN_OBJECTID;
3455 key.type = BTRFS_ORPHAN_ITEM_KEY;
3456 key.offset = (u64)-1;
3459 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
3464 * if ret == 0 means we found what we were searching for, which
3465 * is weird, but possible, so only screw with path if we didn't
3466 * find the key and see if we have stuff that matches
3470 if (path->slots[0] == 0)
3475 /* pull out the item */
3476 leaf = path->nodes[0];
3477 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
3479 /* make sure the item matches what we want */
3480 if (found_key.objectid != BTRFS_ORPHAN_OBJECTID)
3482 if (found_key.type != BTRFS_ORPHAN_ITEM_KEY)
3485 /* release the path since we're done with it */
3486 btrfs_release_path(path);
3489 * this is where we are basically btrfs_lookup, without the
3490 * crossing root thing. we store the inode number in the
3491 * offset of the orphan item.
3494 if (found_key.offset == last_objectid) {
3496 "Error removing orphan entry, stopping orphan cleanup");
3501 last_objectid = found_key.offset;
3503 found_key.objectid = found_key.offset;
3504 found_key.type = BTRFS_INODE_ITEM_KEY;
3505 found_key.offset = 0;
3506 inode = btrfs_iget(fs_info->sb, &found_key, root, NULL);
3507 ret = PTR_ERR_OR_ZERO(inode);
3508 if (ret && ret != -ENOENT)
3511 if (ret == -ENOENT && root == fs_info->tree_root) {
3512 struct btrfs_root *dead_root;
3513 struct btrfs_fs_info *fs_info = root->fs_info;
3514 int is_dead_root = 0;
3517 * this is an orphan in the tree root. Currently these
3518 * could come from 2 sources:
3519 * a) a snapshot deletion in progress
3520 * b) a free space cache inode
3521 * We need to distinguish those two, as the snapshot
3522 * orphan must not get deleted.
3523 * find_dead_roots already ran before us, so if this
3524 * is a snapshot deletion, we should find the root
3525 * in the dead_roots list
3527 spin_lock(&fs_info->trans_lock);
3528 list_for_each_entry(dead_root, &fs_info->dead_roots,
3530 if (dead_root->root_key.objectid ==
3531 found_key.objectid) {
3536 spin_unlock(&fs_info->trans_lock);
3538 /* prevent this orphan from being found again */
3539 key.offset = found_key.objectid - 1;
3544 * Inode is already gone but the orphan item is still there,
3545 * kill the orphan item.
3547 if (ret == -ENOENT) {
3548 trans = btrfs_start_transaction(root, 1);
3549 if (IS_ERR(trans)) {
3550 ret = PTR_ERR(trans);
3553 btrfs_debug(fs_info, "auto deleting %Lu",
3554 found_key.objectid);
3555 ret = btrfs_del_orphan_item(trans, root,
3556 found_key.objectid);
3557 btrfs_end_transaction(trans);
3564 * add this inode to the orphan list so btrfs_orphan_del does
3565 * the proper thing when we hit it
3567 set_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
3568 &BTRFS_I(inode)->runtime_flags);
3569 atomic_inc(&root->orphan_inodes);
3571 /* if we have links, this was a truncate, lets do that */
3572 if (inode->i_nlink) {
3573 if (WARN_ON(!S_ISREG(inode->i_mode))) {
3579 /* 1 for the orphan item deletion. */
3580 trans = btrfs_start_transaction(root, 1);
3581 if (IS_ERR(trans)) {
3583 ret = PTR_ERR(trans);
3586 ret = btrfs_orphan_add(trans, BTRFS_I(inode));
3587 btrfs_end_transaction(trans);
3593 ret = btrfs_truncate(inode);
3595 btrfs_orphan_del(NULL, BTRFS_I(inode));
3600 /* this will do delete_inode and everything for us */
3605 /* release the path since we're done with it */
3606 btrfs_release_path(path);
3608 root->orphan_cleanup_state = ORPHAN_CLEANUP_DONE;
3610 if (root->orphan_block_rsv)
3611 btrfs_block_rsv_release(fs_info, root->orphan_block_rsv,
3614 if (root->orphan_block_rsv ||
3615 test_bit(BTRFS_ROOT_ORPHAN_ITEM_INSERTED, &root->state)) {
3616 trans = btrfs_join_transaction(root);
3618 btrfs_end_transaction(trans);
3622 btrfs_debug(fs_info, "unlinked %d orphans", nr_unlink);
3624 btrfs_debug(fs_info, "truncated %d orphans", nr_truncate);
3628 btrfs_err(fs_info, "could not do orphan cleanup %d", ret);
3629 btrfs_free_path(path);
3634 * very simple check to peek ahead in the leaf looking for xattrs. If we
3635 * don't find any xattrs, we know there can't be any acls.
3637 * slot is the slot the inode is in, objectid is the objectid of the inode
3639 static noinline int acls_after_inode_item(struct extent_buffer *leaf,
3640 int slot, u64 objectid,
3641 int *first_xattr_slot)
3643 u32 nritems = btrfs_header_nritems(leaf);
3644 struct btrfs_key found_key;
3645 static u64 xattr_access = 0;
3646 static u64 xattr_default = 0;
3649 if (!xattr_access) {
3650 xattr_access = btrfs_name_hash(XATTR_NAME_POSIX_ACL_ACCESS,
3651 strlen(XATTR_NAME_POSIX_ACL_ACCESS));
3652 xattr_default = btrfs_name_hash(XATTR_NAME_POSIX_ACL_DEFAULT,
3653 strlen(XATTR_NAME_POSIX_ACL_DEFAULT));
3657 *first_xattr_slot = -1;
3658 while (slot < nritems) {
3659 btrfs_item_key_to_cpu(leaf, &found_key, slot);
3661 /* we found a different objectid, there must not be acls */
3662 if (found_key.objectid != objectid)
3665 /* we found an xattr, assume we've got an acl */
3666 if (found_key.type == BTRFS_XATTR_ITEM_KEY) {
3667 if (*first_xattr_slot == -1)
3668 *first_xattr_slot = slot;
3669 if (found_key.offset == xattr_access ||
3670 found_key.offset == xattr_default)
3675 * we found a key greater than an xattr key, there can't
3676 * be any acls later on
3678 if (found_key.type > BTRFS_XATTR_ITEM_KEY)
3685 * it goes inode, inode backrefs, xattrs, extents,
3686 * so if there are a ton of hard links to an inode there can
3687 * be a lot of backrefs. Don't waste time searching too hard,
3688 * this is just an optimization
3693 /* we hit the end of the leaf before we found an xattr or
3694 * something larger than an xattr. We have to assume the inode
3697 if (*first_xattr_slot == -1)
3698 *first_xattr_slot = slot;
3703 * read an inode from the btree into the in-memory inode
3705 static int btrfs_read_locked_inode(struct inode *inode)
3707 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
3708 struct btrfs_path *path;
3709 struct extent_buffer *leaf;
3710 struct btrfs_inode_item *inode_item;
3711 struct btrfs_root *root = BTRFS_I(inode)->root;
3712 struct btrfs_key location;
3717 bool filled = false;
3718 int first_xattr_slot;
3720 ret = btrfs_fill_inode(inode, &rdev);
3724 path = btrfs_alloc_path();
3730 memcpy(&location, &BTRFS_I(inode)->location, sizeof(location));
3732 ret = btrfs_lookup_inode(NULL, root, path, &location, 0);
3739 leaf = path->nodes[0];
3744 inode_item = btrfs_item_ptr(leaf, path->slots[0],
3745 struct btrfs_inode_item);
3746 inode->i_mode = btrfs_inode_mode(leaf, inode_item);
3747 set_nlink(inode, btrfs_inode_nlink(leaf, inode_item));
3748 i_uid_write(inode, btrfs_inode_uid(leaf, inode_item));
3749 i_gid_write(inode, btrfs_inode_gid(leaf, inode_item));
3750 btrfs_i_size_write(BTRFS_I(inode), btrfs_inode_size(leaf, inode_item));
3752 inode->i_atime.tv_sec = btrfs_timespec_sec(leaf, &inode_item->atime);
3753 inode->i_atime.tv_nsec = btrfs_timespec_nsec(leaf, &inode_item->atime);
3755 inode->i_mtime.tv_sec = btrfs_timespec_sec(leaf, &inode_item->mtime);
3756 inode->i_mtime.tv_nsec = btrfs_timespec_nsec(leaf, &inode_item->mtime);
3758 inode->i_ctime.tv_sec = btrfs_timespec_sec(leaf, &inode_item->ctime);
3759 inode->i_ctime.tv_nsec = btrfs_timespec_nsec(leaf, &inode_item->ctime);
3761 BTRFS_I(inode)->i_otime.tv_sec =
3762 btrfs_timespec_sec(leaf, &inode_item->otime);
3763 BTRFS_I(inode)->i_otime.tv_nsec =
3764 btrfs_timespec_nsec(leaf, &inode_item->otime);
3766 inode_set_bytes(inode, btrfs_inode_nbytes(leaf, inode_item));
3767 BTRFS_I(inode)->generation = btrfs_inode_generation(leaf, inode_item);
3768 BTRFS_I(inode)->last_trans = btrfs_inode_transid(leaf, inode_item);
3770 inode->i_version = btrfs_inode_sequence(leaf, inode_item);
3771 inode->i_generation = BTRFS_I(inode)->generation;
3773 rdev = btrfs_inode_rdev(leaf, inode_item);
3775 BTRFS_I(inode)->index_cnt = (u64)-1;
3776 BTRFS_I(inode)->flags = btrfs_inode_flags(leaf, inode_item);
3780 * If we were modified in the current generation and evicted from memory
3781 * and then re-read we need to do a full sync since we don't have any
3782 * idea about which extents were modified before we were evicted from
3785 * This is required for both inode re-read from disk and delayed inode
3786 * in delayed_nodes_tree.
3788 if (BTRFS_I(inode)->last_trans == fs_info->generation)
3789 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
3790 &BTRFS_I(inode)->runtime_flags);
3793 * We don't persist the id of the transaction where an unlink operation
3794 * against the inode was last made. So here we assume the inode might
3795 * have been evicted, and therefore the exact value of last_unlink_trans
3796 * lost, and set it to last_trans to avoid metadata inconsistencies
3797 * between the inode and its parent if the inode is fsync'ed and the log
3798 * replayed. For example, in the scenario:
3801 * ln mydir/foo mydir/bar
3804 * echo 2 > /proc/sys/vm/drop_caches # evicts inode
3805 * xfs_io -c fsync mydir/foo
3807 * mount fs, triggers fsync log replay
3809 * We must make sure that when we fsync our inode foo we also log its
3810 * parent inode, otherwise after log replay the parent still has the
3811 * dentry with the "bar" name but our inode foo has a link count of 1
3812 * and doesn't have an inode ref with the name "bar" anymore.
3814 * Setting last_unlink_trans to last_trans is a pessimistic approach,
3815 * but it guarantees correctness at the expense of occasional full
3816 * transaction commits on fsync if our inode is a directory, or if our
3817 * inode is not a directory, logging its parent unnecessarily.
3819 BTRFS_I(inode)->last_unlink_trans = BTRFS_I(inode)->last_trans;
3822 if (inode->i_nlink != 1 ||
3823 path->slots[0] >= btrfs_header_nritems(leaf))
3826 btrfs_item_key_to_cpu(leaf, &location, path->slots[0]);
3827 if (location.objectid != btrfs_ino(BTRFS_I(inode)))
3830 ptr = btrfs_item_ptr_offset(leaf, path->slots[0]);
3831 if (location.type == BTRFS_INODE_REF_KEY) {
3832 struct btrfs_inode_ref *ref;
3834 ref = (struct btrfs_inode_ref *)ptr;
3835 BTRFS_I(inode)->dir_index = btrfs_inode_ref_index(leaf, ref);
3836 } else if (location.type == BTRFS_INODE_EXTREF_KEY) {
3837 struct btrfs_inode_extref *extref;
3839 extref = (struct btrfs_inode_extref *)ptr;
3840 BTRFS_I(inode)->dir_index = btrfs_inode_extref_index(leaf,
3845 * try to precache a NULL acl entry for files that don't have
3846 * any xattrs or acls
3848 maybe_acls = acls_after_inode_item(leaf, path->slots[0],
3849 btrfs_ino(BTRFS_I(inode)), &first_xattr_slot);
3850 if (first_xattr_slot != -1) {
3851 path->slots[0] = first_xattr_slot;
3852 ret = btrfs_load_inode_props(inode, path);
3855 "error loading props for ino %llu (root %llu): %d",
3856 btrfs_ino(BTRFS_I(inode)),
3857 root->root_key.objectid, ret);
3859 btrfs_free_path(path);
3862 cache_no_acl(inode);
3864 switch (inode->i_mode & S_IFMT) {
3866 inode->i_mapping->a_ops = &btrfs_aops;
3867 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
3868 inode->i_fop = &btrfs_file_operations;
3869 inode->i_op = &btrfs_file_inode_operations;
3872 inode->i_fop = &btrfs_dir_file_operations;
3873 inode->i_op = &btrfs_dir_inode_operations;
3876 inode->i_op = &btrfs_symlink_inode_operations;
3877 inode_nohighmem(inode);
3878 inode->i_mapping->a_ops = &btrfs_symlink_aops;
3881 inode->i_op = &btrfs_special_inode_operations;
3882 init_special_inode(inode, inode->i_mode, rdev);
3886 btrfs_update_iflags(inode);
3890 btrfs_free_path(path);
3891 make_bad_inode(inode);
3896 * given a leaf and an inode, copy the inode fields into the leaf
3898 static void fill_inode_item(struct btrfs_trans_handle *trans,
3899 struct extent_buffer *leaf,
3900 struct btrfs_inode_item *item,
3901 struct inode *inode)
3903 struct btrfs_map_token token;
3905 btrfs_init_map_token(&token);
3907 btrfs_set_token_inode_uid(leaf, item, i_uid_read(inode), &token);
3908 btrfs_set_token_inode_gid(leaf, item, i_gid_read(inode), &token);
3909 btrfs_set_token_inode_size(leaf, item, BTRFS_I(inode)->disk_i_size,
3911 btrfs_set_token_inode_mode(leaf, item, inode->i_mode, &token);
3912 btrfs_set_token_inode_nlink(leaf, item, inode->i_nlink, &token);
3914 btrfs_set_token_timespec_sec(leaf, &item->atime,
3915 inode->i_atime.tv_sec, &token);
3916 btrfs_set_token_timespec_nsec(leaf, &item->atime,
3917 inode->i_atime.tv_nsec, &token);
3919 btrfs_set_token_timespec_sec(leaf, &item->mtime,
3920 inode->i_mtime.tv_sec, &token);
3921 btrfs_set_token_timespec_nsec(leaf, &item->mtime,
3922 inode->i_mtime.tv_nsec, &token);
3924 btrfs_set_token_timespec_sec(leaf, &item->ctime,
3925 inode->i_ctime.tv_sec, &token);
3926 btrfs_set_token_timespec_nsec(leaf, &item->ctime,
3927 inode->i_ctime.tv_nsec, &token);
3929 btrfs_set_token_timespec_sec(leaf, &item->otime,
3930 BTRFS_I(inode)->i_otime.tv_sec, &token);
3931 btrfs_set_token_timespec_nsec(leaf, &item->otime,
3932 BTRFS_I(inode)->i_otime.tv_nsec, &token);
3934 btrfs_set_token_inode_nbytes(leaf, item, inode_get_bytes(inode),
3936 btrfs_set_token_inode_generation(leaf, item, BTRFS_I(inode)->generation,
3938 btrfs_set_token_inode_sequence(leaf, item, inode->i_version, &token);
3939 btrfs_set_token_inode_transid(leaf, item, trans->transid, &token);
3940 btrfs_set_token_inode_rdev(leaf, item, inode->i_rdev, &token);
3941 btrfs_set_token_inode_flags(leaf, item, BTRFS_I(inode)->flags, &token);
3942 btrfs_set_token_inode_block_group(leaf, item, 0, &token);
3946 * copy everything in the in-memory inode into the btree.
3948 static noinline int btrfs_update_inode_item(struct btrfs_trans_handle *trans,
3949 struct btrfs_root *root, struct inode *inode)
3951 struct btrfs_inode_item *inode_item;
3952 struct btrfs_path *path;
3953 struct extent_buffer *leaf;
3956 path = btrfs_alloc_path();
3960 path->leave_spinning = 1;
3961 ret = btrfs_lookup_inode(trans, root, path, &BTRFS_I(inode)->location,
3969 leaf = path->nodes[0];
3970 inode_item = btrfs_item_ptr(leaf, path->slots[0],
3971 struct btrfs_inode_item);
3973 fill_inode_item(trans, leaf, inode_item, inode);
3974 btrfs_mark_buffer_dirty(leaf);
3975 btrfs_set_inode_last_trans(trans, inode);
3978 btrfs_free_path(path);
3983 * copy everything in the in-memory inode into the btree.
3985 noinline int btrfs_update_inode(struct btrfs_trans_handle *trans,
3986 struct btrfs_root *root, struct inode *inode)
3988 struct btrfs_fs_info *fs_info = root->fs_info;
3992 * If the inode is a free space inode, we can deadlock during commit
3993 * if we put it into the delayed code.
3995 * The data relocation inode should also be directly updated
3998 if (!btrfs_is_free_space_inode(BTRFS_I(inode))
3999 && root->root_key.objectid != BTRFS_DATA_RELOC_TREE_OBJECTID
4000 && !test_bit(BTRFS_FS_LOG_RECOVERING, &fs_info->flags)) {
4001 btrfs_update_root_times(trans, root);
4003 ret = btrfs_delayed_update_inode(trans, root, inode);
4005 btrfs_set_inode_last_trans(trans, inode);
4009 return btrfs_update_inode_item(trans, root, inode);
4012 noinline int btrfs_update_inode_fallback(struct btrfs_trans_handle *trans,
4013 struct btrfs_root *root,
4014 struct inode *inode)
4018 ret = btrfs_update_inode(trans, root, inode);
4020 return btrfs_update_inode_item(trans, root, inode);
4025 * unlink helper that gets used here in inode.c and in the tree logging
4026 * recovery code. It remove a link in a directory with a given name, and
4027 * also drops the back refs in the inode to the directory
4029 static int __btrfs_unlink_inode(struct btrfs_trans_handle *trans,
4030 struct btrfs_root *root,
4031 struct btrfs_inode *dir,
4032 struct btrfs_inode *inode,
4033 const char *name, int name_len)
4035 struct btrfs_fs_info *fs_info = root->fs_info;
4036 struct btrfs_path *path;
4038 struct extent_buffer *leaf;
4039 struct btrfs_dir_item *di;
4040 struct btrfs_key key;
4042 u64 ino = btrfs_ino(inode);
4043 u64 dir_ino = btrfs_ino(dir);
4045 path = btrfs_alloc_path();
4051 path->leave_spinning = 1;
4052 di = btrfs_lookup_dir_item(trans, root, path, dir_ino,
4053 name, name_len, -1);
4062 leaf = path->nodes[0];
4063 btrfs_dir_item_key_to_cpu(leaf, di, &key);
4064 ret = btrfs_delete_one_dir_name(trans, root, path, di);
4067 btrfs_release_path(path);
4070 * If we don't have dir index, we have to get it by looking up
4071 * the inode ref, since we get the inode ref, remove it directly,
4072 * it is unnecessary to do delayed deletion.
4074 * But if we have dir index, needn't search inode ref to get it.
4075 * Since the inode ref is close to the inode item, it is better
4076 * that we delay to delete it, and just do this deletion when
4077 * we update the inode item.
4079 if (inode->dir_index) {
4080 ret = btrfs_delayed_delete_inode_ref(inode);
4082 index = inode->dir_index;
4087 ret = btrfs_del_inode_ref(trans, root, name, name_len, ino,
4091 "failed to delete reference to %.*s, inode %llu parent %llu",
4092 name_len, name, ino, dir_ino);
4093 btrfs_abort_transaction(trans, ret);
4097 ret = btrfs_delete_delayed_dir_index(trans, fs_info, dir, index);
4099 btrfs_abort_transaction(trans, ret);
4103 ret = btrfs_del_inode_ref_in_log(trans, root, name, name_len, inode,
4105 if (ret != 0 && ret != -ENOENT) {
4106 btrfs_abort_transaction(trans, ret);
4110 ret = btrfs_del_dir_entries_in_log(trans, root, name, name_len, dir,
4115 btrfs_abort_transaction(trans, ret);
4117 btrfs_free_path(path);
4121 btrfs_i_size_write(dir, dir->vfs_inode.i_size - name_len * 2);
4122 inode_inc_iversion(&inode->vfs_inode);
4123 inode_inc_iversion(&dir->vfs_inode);
4124 inode->vfs_inode.i_ctime = dir->vfs_inode.i_mtime =
4125 dir->vfs_inode.i_ctime = current_time(&inode->vfs_inode);
4126 ret = btrfs_update_inode(trans, root, &dir->vfs_inode);
4131 int btrfs_unlink_inode(struct btrfs_trans_handle *trans,
4132 struct btrfs_root *root,
4133 struct btrfs_inode *dir, struct btrfs_inode *inode,
4134 const char *name, int name_len)
4137 ret = __btrfs_unlink_inode(trans, root, dir, inode, name, name_len);
4139 drop_nlink(&inode->vfs_inode);
4140 ret = btrfs_update_inode(trans, root, &inode->vfs_inode);
4146 * helper to start transaction for unlink and rmdir.
4148 * unlink and rmdir are special in btrfs, they do not always free space, so
4149 * if we cannot make our reservations the normal way try and see if there is
4150 * plenty of slack room in the global reserve to migrate, otherwise we cannot
4151 * allow the unlink to occur.
4153 static struct btrfs_trans_handle *__unlink_start_trans(struct inode *dir)
4155 struct btrfs_root *root = BTRFS_I(dir)->root;
4158 * 1 for the possible orphan item
4159 * 1 for the dir item
4160 * 1 for the dir index
4161 * 1 for the inode ref
4164 return btrfs_start_transaction_fallback_global_rsv(root, 5, 5);
4167 static int btrfs_unlink(struct inode *dir, struct dentry *dentry)
4169 struct btrfs_root *root = BTRFS_I(dir)->root;
4170 struct btrfs_trans_handle *trans;
4171 struct inode *inode = d_inode(dentry);
4174 trans = __unlink_start_trans(dir);
4176 return PTR_ERR(trans);
4178 btrfs_record_unlink_dir(trans, BTRFS_I(dir), BTRFS_I(d_inode(dentry)),
4181 ret = btrfs_unlink_inode(trans, root, BTRFS_I(dir),
4182 BTRFS_I(d_inode(dentry)), dentry->d_name.name,
4183 dentry->d_name.len);
4187 if (inode->i_nlink == 0) {
4188 ret = btrfs_orphan_add(trans, BTRFS_I(inode));
4194 btrfs_end_transaction(trans);
4195 btrfs_btree_balance_dirty(root->fs_info);
4199 int btrfs_unlink_subvol(struct btrfs_trans_handle *trans,
4200 struct btrfs_root *root,
4201 struct inode *dir, u64 objectid,
4202 const char *name, int name_len)
4204 struct btrfs_fs_info *fs_info = root->fs_info;
4205 struct btrfs_path *path;
4206 struct extent_buffer *leaf;
4207 struct btrfs_dir_item *di;
4208 struct btrfs_key key;
4211 u64 dir_ino = btrfs_ino(BTRFS_I(dir));
4213 path = btrfs_alloc_path();
4217 di = btrfs_lookup_dir_item(trans, root, path, dir_ino,
4218 name, name_len, -1);
4219 if (IS_ERR_OR_NULL(di)) {
4227 leaf = path->nodes[0];
4228 btrfs_dir_item_key_to_cpu(leaf, di, &key);
4229 WARN_ON(key.type != BTRFS_ROOT_ITEM_KEY || key.objectid != objectid);
4230 ret = btrfs_delete_one_dir_name(trans, root, path, di);
4232 btrfs_abort_transaction(trans, ret);
4235 btrfs_release_path(path);
4237 ret = btrfs_del_root_ref(trans, fs_info, objectid,
4238 root->root_key.objectid, dir_ino,
4239 &index, name, name_len);
4241 if (ret != -ENOENT) {
4242 btrfs_abort_transaction(trans, ret);
4245 di = btrfs_search_dir_index_item(root, path, dir_ino,
4247 if (IS_ERR_OR_NULL(di)) {
4252 btrfs_abort_transaction(trans, ret);
4256 leaf = path->nodes[0];
4257 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
4258 btrfs_release_path(path);
4261 btrfs_release_path(path);
4263 ret = btrfs_delete_delayed_dir_index(trans, fs_info, BTRFS_I(dir), index);
4265 btrfs_abort_transaction(trans, ret);
4269 btrfs_i_size_write(BTRFS_I(dir), dir->i_size - name_len * 2);
4270 inode_inc_iversion(dir);
4271 dir->i_mtime = dir->i_ctime = current_time(dir);
4272 ret = btrfs_update_inode_fallback(trans, root, dir);
4274 btrfs_abort_transaction(trans, ret);
4276 btrfs_free_path(path);
4280 static int btrfs_rmdir(struct inode *dir, struct dentry *dentry)
4282 struct inode *inode = d_inode(dentry);
4284 struct btrfs_root *root = BTRFS_I(dir)->root;
4285 struct btrfs_trans_handle *trans;
4286 u64 last_unlink_trans;
4288 if (inode->i_size > BTRFS_EMPTY_DIR_SIZE)
4290 if (btrfs_ino(BTRFS_I(inode)) == BTRFS_FIRST_FREE_OBJECTID)
4293 trans = __unlink_start_trans(dir);
4295 return PTR_ERR(trans);
4297 if (unlikely(btrfs_ino(BTRFS_I(inode)) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)) {
4298 err = btrfs_unlink_subvol(trans, root, dir,
4299 BTRFS_I(inode)->location.objectid,
4300 dentry->d_name.name,
4301 dentry->d_name.len);
4305 err = btrfs_orphan_add(trans, BTRFS_I(inode));
4309 last_unlink_trans = BTRFS_I(inode)->last_unlink_trans;
4311 /* now the directory is empty */
4312 err = btrfs_unlink_inode(trans, root, BTRFS_I(dir),
4313 BTRFS_I(d_inode(dentry)), dentry->d_name.name,
4314 dentry->d_name.len);
4316 btrfs_i_size_write(BTRFS_I(inode), 0);
4318 * Propagate the last_unlink_trans value of the deleted dir to
4319 * its parent directory. This is to prevent an unrecoverable
4320 * log tree in the case we do something like this:
4322 * 2) create snapshot under dir foo
4323 * 3) delete the snapshot
4326 * 6) fsync foo or some file inside foo
4328 if (last_unlink_trans >= trans->transid)
4329 BTRFS_I(dir)->last_unlink_trans = last_unlink_trans;
4332 btrfs_end_transaction(trans);
4333 btrfs_btree_balance_dirty(root->fs_info);
4338 static int truncate_space_check(struct btrfs_trans_handle *trans,
4339 struct btrfs_root *root,
4342 struct btrfs_fs_info *fs_info = root->fs_info;
4346 * This is only used to apply pressure to the enospc system, we don't
4347 * intend to use this reservation at all.
4349 bytes_deleted = btrfs_csum_bytes_to_leaves(fs_info, bytes_deleted);
4350 bytes_deleted *= fs_info->nodesize;
4351 ret = btrfs_block_rsv_add(root, &fs_info->trans_block_rsv,
4352 bytes_deleted, BTRFS_RESERVE_NO_FLUSH);
4354 trace_btrfs_space_reservation(fs_info, "transaction",
4357 trans->bytes_reserved += bytes_deleted;
4364 * Return this if we need to call truncate_block for the last bit of the
4367 #define NEED_TRUNCATE_BLOCK 1
4370 * this can truncate away extent items, csum items and directory items.
4371 * It starts at a high offset and removes keys until it can't find
4372 * any higher than new_size
4374 * csum items that cross the new i_size are truncated to the new size
4377 * min_type is the minimum key type to truncate down to. If set to 0, this
4378 * will kill all the items on this inode, including the INODE_ITEM_KEY.
4380 int btrfs_truncate_inode_items(struct btrfs_trans_handle *trans,
4381 struct btrfs_root *root,
4382 struct inode *inode,
4383 u64 new_size, u32 min_type)
4385 struct btrfs_fs_info *fs_info = root->fs_info;
4386 struct btrfs_path *path;
4387 struct extent_buffer *leaf;
4388 struct btrfs_file_extent_item *fi;
4389 struct btrfs_key key;
4390 struct btrfs_key found_key;
4391 u64 extent_start = 0;
4392 u64 extent_num_bytes = 0;
4393 u64 extent_offset = 0;
4395 u64 last_size = new_size;
4396 u32 found_type = (u8)-1;
4399 int pending_del_nr = 0;
4400 int pending_del_slot = 0;
4401 int extent_type = -1;
4404 u64 ino = btrfs_ino(BTRFS_I(inode));
4405 u64 bytes_deleted = 0;
4406 bool be_nice = false;
4407 bool should_throttle = false;
4408 bool should_end = false;
4410 BUG_ON(new_size > 0 && min_type != BTRFS_EXTENT_DATA_KEY);
4413 * for non-free space inodes and ref cows, we want to back off from
4416 if (!btrfs_is_free_space_inode(BTRFS_I(inode)) &&
4417 test_bit(BTRFS_ROOT_REF_COWS, &root->state))
4420 path = btrfs_alloc_path();
4423 path->reada = READA_BACK;
4426 * We want to drop from the next block forward in case this new size is
4427 * not block aligned since we will be keeping the last block of the
4428 * extent just the way it is.
4430 if (test_bit(BTRFS_ROOT_REF_COWS, &root->state) ||
4431 root == fs_info->tree_root)
4432 btrfs_drop_extent_cache(BTRFS_I(inode), ALIGN(new_size,
4433 fs_info->sectorsize),
4437 * This function is also used to drop the items in the log tree before
4438 * we relog the inode, so if root != BTRFS_I(inode)->root, it means
4439 * it is used to drop the loged items. So we shouldn't kill the delayed
4442 if (min_type == 0 && root == BTRFS_I(inode)->root)
4443 btrfs_kill_delayed_inode_items(BTRFS_I(inode));
4446 key.offset = (u64)-1;
4451 * with a 16K leaf size and 128MB extents, you can actually queue
4452 * up a huge file in a single leaf. Most of the time that
4453 * bytes_deleted is > 0, it will be huge by the time we get here
4455 if (be_nice && bytes_deleted > SZ_32M) {
4456 if (btrfs_should_end_transaction(trans)) {
4463 path->leave_spinning = 1;
4464 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
4471 /* there are no items in the tree for us to truncate, we're
4474 if (path->slots[0] == 0)
4481 leaf = path->nodes[0];
4482 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
4483 found_type = found_key.type;
4485 if (found_key.objectid != ino)
4488 if (found_type < min_type)
4491 item_end = found_key.offset;
4492 if (found_type == BTRFS_EXTENT_DATA_KEY) {
4493 fi = btrfs_item_ptr(leaf, path->slots[0],
4494 struct btrfs_file_extent_item);
4495 extent_type = btrfs_file_extent_type(leaf, fi);
4496 if (extent_type != BTRFS_FILE_EXTENT_INLINE) {
4498 btrfs_file_extent_num_bytes(leaf, fi);
4500 trace_btrfs_truncate_show_fi_regular(
4501 BTRFS_I(inode), leaf, fi,
4503 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
4504 item_end += btrfs_file_extent_inline_len(leaf,
4505 path->slots[0], fi);
4507 trace_btrfs_truncate_show_fi_inline(
4508 BTRFS_I(inode), leaf, fi, path->slots[0],
4513 if (found_type > min_type) {
4516 if (item_end < new_size)
4518 if (found_key.offset >= new_size)
4524 /* FIXME, shrink the extent if the ref count is only 1 */
4525 if (found_type != BTRFS_EXTENT_DATA_KEY)
4528 if (extent_type != BTRFS_FILE_EXTENT_INLINE) {
4530 extent_start = btrfs_file_extent_disk_bytenr(leaf, fi);
4532 u64 orig_num_bytes =
4533 btrfs_file_extent_num_bytes(leaf, fi);
4534 extent_num_bytes = ALIGN(new_size -
4536 fs_info->sectorsize);
4537 btrfs_set_file_extent_num_bytes(leaf, fi,
4539 num_dec = (orig_num_bytes -
4541 if (test_bit(BTRFS_ROOT_REF_COWS,
4544 inode_sub_bytes(inode, num_dec);
4545 btrfs_mark_buffer_dirty(leaf);
4548 btrfs_file_extent_disk_num_bytes(leaf,
4550 extent_offset = found_key.offset -
4551 btrfs_file_extent_offset(leaf, fi);
4553 /* FIXME blocksize != 4096 */
4554 num_dec = btrfs_file_extent_num_bytes(leaf, fi);
4555 if (extent_start != 0) {
4557 if (test_bit(BTRFS_ROOT_REF_COWS,
4559 inode_sub_bytes(inode, num_dec);
4562 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
4564 * we can't truncate inline items that have had
4568 btrfs_file_extent_encryption(leaf, fi) == 0 &&
4569 btrfs_file_extent_other_encoding(leaf, fi) == 0 &&
4570 btrfs_file_extent_compression(leaf, fi) == 0) {
4571 u32 size = (u32)(new_size - found_key.offset);
4573 btrfs_set_file_extent_ram_bytes(leaf, fi, size);
4574 size = btrfs_file_extent_calc_inline_size(size);
4575 btrfs_truncate_item(root->fs_info, path, size, 1);
4576 } else if (!del_item) {
4578 * We have to bail so the last_size is set to
4579 * just before this extent.
4581 err = NEED_TRUNCATE_BLOCK;
4585 if (test_bit(BTRFS_ROOT_REF_COWS, &root->state))
4586 inode_sub_bytes(inode, item_end + 1 - new_size);
4590 last_size = found_key.offset;
4592 last_size = new_size;
4594 if (!pending_del_nr) {
4595 /* no pending yet, add ourselves */
4596 pending_del_slot = path->slots[0];
4598 } else if (pending_del_nr &&
4599 path->slots[0] + 1 == pending_del_slot) {
4600 /* hop on the pending chunk */
4602 pending_del_slot = path->slots[0];
4609 should_throttle = false;
4612 (test_bit(BTRFS_ROOT_REF_COWS, &root->state) ||
4613 root == fs_info->tree_root)) {
4614 btrfs_set_path_blocking(path);
4615 bytes_deleted += extent_num_bytes;
4616 ret = btrfs_free_extent(trans, root, extent_start,
4617 extent_num_bytes, 0,
4618 btrfs_header_owner(leaf),
4619 ino, extent_offset);
4621 if (btrfs_should_throttle_delayed_refs(trans, fs_info))
4622 btrfs_async_run_delayed_refs(fs_info,
4623 trans->delayed_ref_updates * 2,
4626 if (truncate_space_check(trans, root,
4627 extent_num_bytes)) {
4630 if (btrfs_should_throttle_delayed_refs(trans,
4632 should_throttle = true;
4636 if (found_type == BTRFS_INODE_ITEM_KEY)
4639 if (path->slots[0] == 0 ||
4640 path->slots[0] != pending_del_slot ||
4641 should_throttle || should_end) {
4642 if (pending_del_nr) {
4643 ret = btrfs_del_items(trans, root, path,
4647 btrfs_abort_transaction(trans, ret);
4652 btrfs_release_path(path);
4653 if (should_throttle) {
4654 unsigned long updates = trans->delayed_ref_updates;
4656 trans->delayed_ref_updates = 0;
4657 ret = btrfs_run_delayed_refs(trans,
4665 * if we failed to refill our space rsv, bail out
4666 * and let the transaction restart
4678 if (pending_del_nr) {
4679 ret = btrfs_del_items(trans, root, path, pending_del_slot,
4682 btrfs_abort_transaction(trans, ret);
4685 if (root->root_key.objectid != BTRFS_TREE_LOG_OBJECTID) {
4686 ASSERT(last_size >= new_size);
4687 if (!err && last_size > new_size)
4688 last_size = new_size;
4689 btrfs_ordered_update_i_size(inode, last_size, NULL);
4692 btrfs_free_path(path);
4694 if (be_nice && bytes_deleted > SZ_32M) {
4695 unsigned long updates = trans->delayed_ref_updates;
4697 trans->delayed_ref_updates = 0;
4698 ret = btrfs_run_delayed_refs(trans, fs_info,
4708 * btrfs_truncate_block - read, zero a chunk and write a block
4709 * @inode - inode that we're zeroing
4710 * @from - the offset to start zeroing
4711 * @len - the length to zero, 0 to zero the entire range respective to the
4713 * @front - zero up to the offset instead of from the offset on
4715 * This will find the block for the "from" offset and cow the block and zero the
4716 * part we want to zero. This is used with truncate and hole punching.
4718 int btrfs_truncate_block(struct inode *inode, loff_t from, loff_t len,
4721 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
4722 struct address_space *mapping = inode->i_mapping;
4723 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
4724 struct btrfs_ordered_extent *ordered;
4725 struct extent_state *cached_state = NULL;
4726 struct extent_changeset *data_reserved = NULL;
4728 u32 blocksize = fs_info->sectorsize;
4729 pgoff_t index = from >> PAGE_SHIFT;
4730 unsigned offset = from & (blocksize - 1);
4732 gfp_t mask = btrfs_alloc_write_mask(mapping);
4737 if ((offset & (blocksize - 1)) == 0 &&
4738 (!len || ((len & (blocksize - 1)) == 0)))
4741 block_start = round_down(from, blocksize);
4742 block_end = block_start + blocksize - 1;
4744 ret = btrfs_delalloc_reserve_space(inode, &data_reserved,
4745 block_start, blocksize);
4750 page = find_or_create_page(mapping, index, mask);
4752 btrfs_delalloc_release_space(inode, data_reserved,
4753 block_start, blocksize);
4754 btrfs_delalloc_release_extents(BTRFS_I(inode), blocksize);
4759 if (!PageUptodate(page)) {
4760 ret = btrfs_readpage(NULL, page);
4762 if (page->mapping != mapping) {
4767 if (!PageUptodate(page)) {
4772 wait_on_page_writeback(page);
4774 lock_extent_bits(io_tree, block_start, block_end, &cached_state);
4775 set_page_extent_mapped(page);
4777 ordered = btrfs_lookup_ordered_extent(inode, block_start);
4779 unlock_extent_cached(io_tree, block_start, block_end,
4780 &cached_state, GFP_NOFS);
4783 btrfs_start_ordered_extent(inode, ordered, 1);
4784 btrfs_put_ordered_extent(ordered);
4788 clear_extent_bit(&BTRFS_I(inode)->io_tree, block_start, block_end,
4789 EXTENT_DIRTY | EXTENT_DELALLOC |
4790 EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG,
4791 0, 0, &cached_state, GFP_NOFS);
4793 ret = btrfs_set_extent_delalloc(inode, block_start, block_end,
4796 unlock_extent_cached(io_tree, block_start, block_end,
4797 &cached_state, GFP_NOFS);
4801 if (offset != blocksize) {
4803 len = blocksize - offset;
4806 memset(kaddr + (block_start - page_offset(page)),
4809 memset(kaddr + (block_start - page_offset(page)) + offset,
4811 flush_dcache_page(page);
4814 ClearPageChecked(page);
4815 set_page_dirty(page);
4816 unlock_extent_cached(io_tree, block_start, block_end, &cached_state,
4821 btrfs_delalloc_release_space(inode, data_reserved, block_start,
4823 btrfs_delalloc_release_extents(BTRFS_I(inode), blocksize);
4827 extent_changeset_free(data_reserved);
4831 static int maybe_insert_hole(struct btrfs_root *root, struct inode *inode,
4832 u64 offset, u64 len)
4834 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
4835 struct btrfs_trans_handle *trans;
4839 * Still need to make sure the inode looks like it's been updated so
4840 * that any holes get logged if we fsync.
4842 if (btrfs_fs_incompat(fs_info, NO_HOLES)) {
4843 BTRFS_I(inode)->last_trans = fs_info->generation;
4844 BTRFS_I(inode)->last_sub_trans = root->log_transid;
4845 BTRFS_I(inode)->last_log_commit = root->last_log_commit;
4850 * 1 - for the one we're dropping
4851 * 1 - for the one we're adding
4852 * 1 - for updating the inode.
4854 trans = btrfs_start_transaction(root, 3);
4856 return PTR_ERR(trans);
4858 ret = btrfs_drop_extents(trans, root, inode, offset, offset + len, 1);
4860 btrfs_abort_transaction(trans, ret);
4861 btrfs_end_transaction(trans);
4865 ret = btrfs_insert_file_extent(trans, root, btrfs_ino(BTRFS_I(inode)),
4866 offset, 0, 0, len, 0, len, 0, 0, 0);
4868 btrfs_abort_transaction(trans, ret);
4870 btrfs_update_inode(trans, root, inode);
4871 btrfs_end_transaction(trans);
4876 * This function puts in dummy file extents for the area we're creating a hole
4877 * for. So if we are truncating this file to a larger size we need to insert
4878 * these file extents so that btrfs_get_extent will return a EXTENT_MAP_HOLE for
4879 * the range between oldsize and size
4881 int btrfs_cont_expand(struct inode *inode, loff_t oldsize, loff_t size)
4883 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
4884 struct btrfs_root *root = BTRFS_I(inode)->root;
4885 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
4886 struct extent_map *em = NULL;
4887 struct extent_state *cached_state = NULL;
4888 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
4889 u64 hole_start = ALIGN(oldsize, fs_info->sectorsize);
4890 u64 block_end = ALIGN(size, fs_info->sectorsize);
4897 * If our size started in the middle of a block we need to zero out the
4898 * rest of the block before we expand the i_size, otherwise we could
4899 * expose stale data.
4901 err = btrfs_truncate_block(inode, oldsize, 0, 0);
4905 if (size <= hole_start)
4909 struct btrfs_ordered_extent *ordered;
4911 lock_extent_bits(io_tree, hole_start, block_end - 1,
4913 ordered = btrfs_lookup_ordered_range(BTRFS_I(inode), hole_start,
4914 block_end - hole_start);
4917 unlock_extent_cached(io_tree, hole_start, block_end - 1,
4918 &cached_state, GFP_NOFS);
4919 btrfs_start_ordered_extent(inode, ordered, 1);
4920 btrfs_put_ordered_extent(ordered);
4923 cur_offset = hole_start;
4925 em = btrfs_get_extent(BTRFS_I(inode), NULL, 0, cur_offset,
4926 block_end - cur_offset, 0);
4932 last_byte = min(extent_map_end(em), block_end);
4933 last_byte = ALIGN(last_byte, fs_info->sectorsize);
4934 if (!test_bit(EXTENT_FLAG_PREALLOC, &em->flags)) {
4935 struct extent_map *hole_em;
4936 hole_size = last_byte - cur_offset;
4938 err = maybe_insert_hole(root, inode, cur_offset,
4942 btrfs_drop_extent_cache(BTRFS_I(inode), cur_offset,
4943 cur_offset + hole_size - 1, 0);
4944 hole_em = alloc_extent_map();
4946 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
4947 &BTRFS_I(inode)->runtime_flags);
4950 hole_em->start = cur_offset;
4951 hole_em->len = hole_size;
4952 hole_em->orig_start = cur_offset;
4954 hole_em->block_start = EXTENT_MAP_HOLE;
4955 hole_em->block_len = 0;
4956 hole_em->orig_block_len = 0;
4957 hole_em->ram_bytes = hole_size;
4958 hole_em->bdev = fs_info->fs_devices->latest_bdev;
4959 hole_em->compress_type = BTRFS_COMPRESS_NONE;
4960 hole_em->generation = fs_info->generation;
4963 write_lock(&em_tree->lock);
4964 err = add_extent_mapping(em_tree, hole_em, 1);
4965 write_unlock(&em_tree->lock);
4968 btrfs_drop_extent_cache(BTRFS_I(inode),
4973 free_extent_map(hole_em);
4976 free_extent_map(em);
4978 cur_offset = last_byte;
4979 if (cur_offset >= block_end)
4982 free_extent_map(em);
4983 unlock_extent_cached(io_tree, hole_start, block_end - 1, &cached_state,
4988 static int btrfs_setsize(struct inode *inode, struct iattr *attr)
4990 struct btrfs_root *root = BTRFS_I(inode)->root;
4991 struct btrfs_trans_handle *trans;
4992 loff_t oldsize = i_size_read(inode);
4993 loff_t newsize = attr->ia_size;
4994 int mask = attr->ia_valid;
4998 * The regular truncate() case without ATTR_CTIME and ATTR_MTIME is a
4999 * special case where we need to update the times despite not having
5000 * these flags set. For all other operations the VFS set these flags
5001 * explicitly if it wants a timestamp update.
5003 if (newsize != oldsize) {
5004 inode_inc_iversion(inode);
5005 if (!(mask & (ATTR_CTIME | ATTR_MTIME)))
5006 inode->i_ctime = inode->i_mtime =
5007 current_time(inode);
5010 if (newsize > oldsize) {
5012 * Don't do an expanding truncate while snapshotting is ongoing.
5013 * This is to ensure the snapshot captures a fully consistent
5014 * state of this file - if the snapshot captures this expanding
5015 * truncation, it must capture all writes that happened before
5018 btrfs_wait_for_snapshot_creation(root);
5019 ret = btrfs_cont_expand(inode, oldsize, newsize);
5021 btrfs_end_write_no_snapshotting(root);
5025 trans = btrfs_start_transaction(root, 1);
5026 if (IS_ERR(trans)) {
5027 btrfs_end_write_no_snapshotting(root);
5028 return PTR_ERR(trans);
5031 i_size_write(inode, newsize);
5032 btrfs_ordered_update_i_size(inode, i_size_read(inode), NULL);
5033 pagecache_isize_extended(inode, oldsize, newsize);
5034 ret = btrfs_update_inode(trans, root, inode);
5035 btrfs_end_write_no_snapshotting(root);
5036 btrfs_end_transaction(trans);
5040 * We're truncating a file that used to have good data down to
5041 * zero. Make sure it gets into the ordered flush list so that
5042 * any new writes get down to disk quickly.
5045 set_bit(BTRFS_INODE_ORDERED_DATA_CLOSE,
5046 &BTRFS_I(inode)->runtime_flags);
5049 * 1 for the orphan item we're going to add
5050 * 1 for the orphan item deletion.
5052 trans = btrfs_start_transaction(root, 2);
5054 return PTR_ERR(trans);
5057 * We need to do this in case we fail at _any_ point during the
5058 * actual truncate. Once we do the truncate_setsize we could
5059 * invalidate pages which forces any outstanding ordered io to
5060 * be instantly completed which will give us extents that need
5061 * to be truncated. If we fail to get an orphan inode down we
5062 * could have left over extents that were never meant to live,
5063 * so we need to guarantee from this point on that everything
5064 * will be consistent.
5066 ret = btrfs_orphan_add(trans, BTRFS_I(inode));
5067 btrfs_end_transaction(trans);
5071 /* we don't support swapfiles, so vmtruncate shouldn't fail */
5072 truncate_setsize(inode, newsize);
5074 /* Disable nonlocked read DIO to avoid the end less truncate */
5075 btrfs_inode_block_unlocked_dio(BTRFS_I(inode));
5076 inode_dio_wait(inode);
5077 btrfs_inode_resume_unlocked_dio(BTRFS_I(inode));
5079 ret = btrfs_truncate(inode);
5080 if (ret && inode->i_nlink) {
5083 /* To get a stable disk_i_size */
5084 err = btrfs_wait_ordered_range(inode, 0, (u64)-1);
5086 btrfs_orphan_del(NULL, BTRFS_I(inode));
5091 * failed to truncate, disk_i_size is only adjusted down
5092 * as we remove extents, so it should represent the true
5093 * size of the inode, so reset the in memory size and
5094 * delete our orphan entry.
5096 trans = btrfs_join_transaction(root);
5097 if (IS_ERR(trans)) {
5098 btrfs_orphan_del(NULL, BTRFS_I(inode));
5101 i_size_write(inode, BTRFS_I(inode)->disk_i_size);
5102 err = btrfs_orphan_del(trans, BTRFS_I(inode));
5104 btrfs_abort_transaction(trans, err);
5105 btrfs_end_transaction(trans);
5112 static int btrfs_setattr(struct dentry *dentry, struct iattr *attr)
5114 struct inode *inode = d_inode(dentry);
5115 struct btrfs_root *root = BTRFS_I(inode)->root;
5118 if (btrfs_root_readonly(root))
5121 err = setattr_prepare(dentry, attr);
5125 if (S_ISREG(inode->i_mode) && (attr->ia_valid & ATTR_SIZE)) {
5126 err = btrfs_setsize(inode, attr);
5131 if (attr->ia_valid) {
5132 setattr_copy(inode, attr);
5133 inode_inc_iversion(inode);
5134 err = btrfs_dirty_inode(inode);
5136 if (!err && attr->ia_valid & ATTR_MODE)
5137 err = posix_acl_chmod(inode, inode->i_mode);
5144 * While truncating the inode pages during eviction, we get the VFS calling
5145 * btrfs_invalidatepage() against each page of the inode. This is slow because
5146 * the calls to btrfs_invalidatepage() result in a huge amount of calls to
5147 * lock_extent_bits() and clear_extent_bit(), which keep merging and splitting
5148 * extent_state structures over and over, wasting lots of time.
5150 * Therefore if the inode is being evicted, let btrfs_invalidatepage() skip all
5151 * those expensive operations on a per page basis and do only the ordered io
5152 * finishing, while we release here the extent_map and extent_state structures,
5153 * without the excessive merging and splitting.
5155 static void evict_inode_truncate_pages(struct inode *inode)
5157 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
5158 struct extent_map_tree *map_tree = &BTRFS_I(inode)->extent_tree;
5159 struct rb_node *node;
5161 ASSERT(inode->i_state & I_FREEING);
5162 truncate_inode_pages_final(&inode->i_data);
5164 write_lock(&map_tree->lock);
5165 while (!RB_EMPTY_ROOT(&map_tree->map)) {
5166 struct extent_map *em;
5168 node = rb_first(&map_tree->map);
5169 em = rb_entry(node, struct extent_map, rb_node);
5170 clear_bit(EXTENT_FLAG_PINNED, &em->flags);
5171 clear_bit(EXTENT_FLAG_LOGGING, &em->flags);
5172 remove_extent_mapping(map_tree, em);
5173 free_extent_map(em);
5174 if (need_resched()) {
5175 write_unlock(&map_tree->lock);
5177 write_lock(&map_tree->lock);
5180 write_unlock(&map_tree->lock);
5183 * Keep looping until we have no more ranges in the io tree.
5184 * We can have ongoing bios started by readpages (called from readahead)
5185 * that have their endio callback (extent_io.c:end_bio_extent_readpage)
5186 * still in progress (unlocked the pages in the bio but did not yet
5187 * unlocked the ranges in the io tree). Therefore this means some
5188 * ranges can still be locked and eviction started because before
5189 * submitting those bios, which are executed by a separate task (work
5190 * queue kthread), inode references (inode->i_count) were not taken
5191 * (which would be dropped in the end io callback of each bio).
5192 * Therefore here we effectively end up waiting for those bios and
5193 * anyone else holding locked ranges without having bumped the inode's
5194 * reference count - if we don't do it, when they access the inode's
5195 * io_tree to unlock a range it may be too late, leading to an
5196 * use-after-free issue.
5198 spin_lock(&io_tree->lock);
5199 while (!RB_EMPTY_ROOT(&io_tree->state)) {
5200 struct extent_state *state;
5201 struct extent_state *cached_state = NULL;
5205 node = rb_first(&io_tree->state);
5206 state = rb_entry(node, struct extent_state, rb_node);
5207 start = state->start;
5209 spin_unlock(&io_tree->lock);
5211 lock_extent_bits(io_tree, start, end, &cached_state);
5214 * If still has DELALLOC flag, the extent didn't reach disk,
5215 * and its reserved space won't be freed by delayed_ref.
5216 * So we need to free its reserved space here.
5217 * (Refer to comment in btrfs_invalidatepage, case 2)
5219 * Note, end is the bytenr of last byte, so we need + 1 here.
5221 if (state->state & EXTENT_DELALLOC)
5222 btrfs_qgroup_free_data(inode, NULL, start, end - start + 1);
5224 clear_extent_bit(io_tree, start, end,
5225 EXTENT_LOCKED | EXTENT_DIRTY |
5226 EXTENT_DELALLOC | EXTENT_DO_ACCOUNTING |
5227 EXTENT_DEFRAG, 1, 1,
5228 &cached_state, GFP_NOFS);
5231 spin_lock(&io_tree->lock);
5233 spin_unlock(&io_tree->lock);
5236 void btrfs_evict_inode(struct inode *inode)
5238 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
5239 struct btrfs_trans_handle *trans;
5240 struct btrfs_root *root = BTRFS_I(inode)->root;
5241 struct btrfs_block_rsv *rsv, *global_rsv;
5242 int steal_from_global = 0;
5246 trace_btrfs_inode_evict(inode);
5249 kmem_cache_free(btrfs_inode_cachep, BTRFS_I(inode));
5253 min_size = btrfs_calc_trunc_metadata_size(fs_info, 1);
5255 evict_inode_truncate_pages(inode);
5257 if (inode->i_nlink &&
5258 ((btrfs_root_refs(&root->root_item) != 0 &&
5259 root->root_key.objectid != BTRFS_ROOT_TREE_OBJECTID) ||
5260 btrfs_is_free_space_inode(BTRFS_I(inode))))
5263 if (is_bad_inode(inode)) {
5264 btrfs_orphan_del(NULL, BTRFS_I(inode));
5267 /* do we really want it for ->i_nlink > 0 and zero btrfs_root_refs? */
5268 if (!special_file(inode->i_mode))
5269 btrfs_wait_ordered_range(inode, 0, (u64)-1);
5271 btrfs_free_io_failure_record(BTRFS_I(inode), 0, (u64)-1);
5273 if (test_bit(BTRFS_FS_LOG_RECOVERING, &fs_info->flags)) {
5274 BUG_ON(test_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
5275 &BTRFS_I(inode)->runtime_flags));
5279 if (inode->i_nlink > 0) {
5280 BUG_ON(btrfs_root_refs(&root->root_item) != 0 &&
5281 root->root_key.objectid != BTRFS_ROOT_TREE_OBJECTID);
5285 ret = btrfs_commit_inode_delayed_inode(BTRFS_I(inode));
5287 btrfs_orphan_del(NULL, BTRFS_I(inode));
5291 rsv = btrfs_alloc_block_rsv(fs_info, BTRFS_BLOCK_RSV_TEMP);
5293 btrfs_orphan_del(NULL, BTRFS_I(inode));
5296 rsv->size = min_size;
5298 global_rsv = &fs_info->global_block_rsv;
5300 btrfs_i_size_write(BTRFS_I(inode), 0);
5303 * This is a bit simpler than btrfs_truncate since we've already
5304 * reserved our space for our orphan item in the unlink, so we just
5305 * need to reserve some slack space in case we add bytes and update
5306 * inode item when doing the truncate.
5309 ret = btrfs_block_rsv_refill(root, rsv, min_size,
5310 BTRFS_RESERVE_FLUSH_LIMIT);
5313 * Try and steal from the global reserve since we will
5314 * likely not use this space anyway, we want to try as
5315 * hard as possible to get this to work.
5318 steal_from_global++;
5320 steal_from_global = 0;
5324 * steal_from_global == 0: we reserved stuff, hooray!
5325 * steal_from_global == 1: we didn't reserve stuff, boo!
5326 * steal_from_global == 2: we've committed, still not a lot of
5327 * room but maybe we'll have room in the global reserve this
5329 * steal_from_global == 3: abandon all hope!
5331 if (steal_from_global > 2) {
5333 "Could not get space for a delete, will truncate on mount %d",
5335 btrfs_orphan_del(NULL, BTRFS_I(inode));
5336 btrfs_free_block_rsv(fs_info, rsv);
5340 trans = btrfs_join_transaction(root);
5341 if (IS_ERR(trans)) {
5342 btrfs_orphan_del(NULL, BTRFS_I(inode));
5343 btrfs_free_block_rsv(fs_info, rsv);
5348 * We can't just steal from the global reserve, we need to make
5349 * sure there is room to do it, if not we need to commit and try
5352 if (steal_from_global) {
5353 if (!btrfs_check_space_for_delayed_refs(trans, fs_info))
5354 ret = btrfs_block_rsv_migrate(global_rsv, rsv,
5361 * Couldn't steal from the global reserve, we have too much
5362 * pending stuff built up, commit the transaction and try it
5366 ret = btrfs_commit_transaction(trans);
5368 btrfs_orphan_del(NULL, BTRFS_I(inode));
5369 btrfs_free_block_rsv(fs_info, rsv);
5374 steal_from_global = 0;
5377 trans->block_rsv = rsv;
5379 ret = btrfs_truncate_inode_items(trans, root, inode, 0, 0);
5380 if (ret != -ENOSPC && ret != -EAGAIN)
5383 trans->block_rsv = &fs_info->trans_block_rsv;
5384 btrfs_end_transaction(trans);
5386 btrfs_btree_balance_dirty(fs_info);
5389 btrfs_free_block_rsv(fs_info, rsv);
5392 * Errors here aren't a big deal, it just means we leave orphan items
5393 * in the tree. They will be cleaned up on the next mount.
5396 trans->block_rsv = root->orphan_block_rsv;
5397 btrfs_orphan_del(trans, BTRFS_I(inode));
5399 btrfs_orphan_del(NULL, BTRFS_I(inode));
5402 trans->block_rsv = &fs_info->trans_block_rsv;
5403 if (!(root == fs_info->tree_root ||
5404 root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID))
5405 btrfs_return_ino(root, btrfs_ino(BTRFS_I(inode)));
5407 btrfs_end_transaction(trans);
5408 btrfs_btree_balance_dirty(fs_info);
5410 btrfs_remove_delayed_node(BTRFS_I(inode));
5415 * this returns the key found in the dir entry in the location pointer.
5416 * If no dir entries were found, location->objectid is 0.
5418 static int btrfs_inode_by_name(struct inode *dir, struct dentry *dentry,
5419 struct btrfs_key *location)
5421 const char *name = dentry->d_name.name;
5422 int namelen = dentry->d_name.len;
5423 struct btrfs_dir_item *di;
5424 struct btrfs_path *path;
5425 struct btrfs_root *root = BTRFS_I(dir)->root;
5428 path = btrfs_alloc_path();
5432 di = btrfs_lookup_dir_item(NULL, root, path, btrfs_ino(BTRFS_I(dir)),
5437 if (IS_ERR_OR_NULL(di))
5440 btrfs_dir_item_key_to_cpu(path->nodes[0], di, location);
5442 btrfs_free_path(path);
5445 location->objectid = 0;
5450 * when we hit a tree root in a directory, the btrfs part of the inode
5451 * needs to be changed to reflect the root directory of the tree root. This
5452 * is kind of like crossing a mount point.
5454 static int fixup_tree_root_location(struct btrfs_fs_info *fs_info,
5456 struct dentry *dentry,
5457 struct btrfs_key *location,
5458 struct btrfs_root **sub_root)
5460 struct btrfs_path *path;
5461 struct btrfs_root *new_root;
5462 struct btrfs_root_ref *ref;
5463 struct extent_buffer *leaf;
5464 struct btrfs_key key;
5468 path = btrfs_alloc_path();
5475 key.objectid = BTRFS_I(dir)->root->root_key.objectid;
5476 key.type = BTRFS_ROOT_REF_KEY;
5477 key.offset = location->objectid;
5479 ret = btrfs_search_slot(NULL, fs_info->tree_root, &key, path, 0, 0);
5486 leaf = path->nodes[0];
5487 ref = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_root_ref);
5488 if (btrfs_root_ref_dirid(leaf, ref) != btrfs_ino(BTRFS_I(dir)) ||
5489 btrfs_root_ref_name_len(leaf, ref) != dentry->d_name.len)
5492 ret = memcmp_extent_buffer(leaf, dentry->d_name.name,
5493 (unsigned long)(ref + 1),
5494 dentry->d_name.len);
5498 btrfs_release_path(path);
5500 new_root = btrfs_read_fs_root_no_name(fs_info, location);
5501 if (IS_ERR(new_root)) {
5502 err = PTR_ERR(new_root);
5506 *sub_root = new_root;
5507 location->objectid = btrfs_root_dirid(&new_root->root_item);
5508 location->type = BTRFS_INODE_ITEM_KEY;
5509 location->offset = 0;
5512 btrfs_free_path(path);
5516 static void inode_tree_add(struct inode *inode)
5518 struct btrfs_root *root = BTRFS_I(inode)->root;
5519 struct btrfs_inode *entry;
5521 struct rb_node *parent;
5522 struct rb_node *new = &BTRFS_I(inode)->rb_node;
5523 u64 ino = btrfs_ino(BTRFS_I(inode));
5525 if (inode_unhashed(inode))
5528 spin_lock(&root->inode_lock);
5529 p = &root->inode_tree.rb_node;
5532 entry = rb_entry(parent, struct btrfs_inode, rb_node);
5534 if (ino < btrfs_ino(BTRFS_I(&entry->vfs_inode)))
5535 p = &parent->rb_left;
5536 else if (ino > btrfs_ino(BTRFS_I(&entry->vfs_inode)))
5537 p = &parent->rb_right;
5539 WARN_ON(!(entry->vfs_inode.i_state &
5540 (I_WILL_FREE | I_FREEING)));
5541 rb_replace_node(parent, new, &root->inode_tree);
5542 RB_CLEAR_NODE(parent);
5543 spin_unlock(&root->inode_lock);
5547 rb_link_node(new, parent, p);
5548 rb_insert_color(new, &root->inode_tree);
5549 spin_unlock(&root->inode_lock);
5552 static void inode_tree_del(struct inode *inode)
5554 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
5555 struct btrfs_root *root = BTRFS_I(inode)->root;
5558 spin_lock(&root->inode_lock);
5559 if (!RB_EMPTY_NODE(&BTRFS_I(inode)->rb_node)) {
5560 rb_erase(&BTRFS_I(inode)->rb_node, &root->inode_tree);
5561 RB_CLEAR_NODE(&BTRFS_I(inode)->rb_node);
5562 empty = RB_EMPTY_ROOT(&root->inode_tree);
5564 spin_unlock(&root->inode_lock);
5566 if (empty && btrfs_root_refs(&root->root_item) == 0) {
5567 synchronize_srcu(&fs_info->subvol_srcu);
5568 spin_lock(&root->inode_lock);
5569 empty = RB_EMPTY_ROOT(&root->inode_tree);
5570 spin_unlock(&root->inode_lock);
5572 btrfs_add_dead_root(root);
5576 void btrfs_invalidate_inodes(struct btrfs_root *root)
5578 struct btrfs_fs_info *fs_info = root->fs_info;
5579 struct rb_node *node;
5580 struct rb_node *prev;
5581 struct btrfs_inode *entry;
5582 struct inode *inode;
5585 if (!test_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state))
5586 WARN_ON(btrfs_root_refs(&root->root_item) != 0);
5588 spin_lock(&root->inode_lock);
5590 node = root->inode_tree.rb_node;
5594 entry = rb_entry(node, struct btrfs_inode, rb_node);
5596 if (objectid < btrfs_ino(BTRFS_I(&entry->vfs_inode)))
5597 node = node->rb_left;
5598 else if (objectid > btrfs_ino(BTRFS_I(&entry->vfs_inode)))
5599 node = node->rb_right;
5605 entry = rb_entry(prev, struct btrfs_inode, rb_node);
5606 if (objectid <= btrfs_ino(BTRFS_I(&entry->vfs_inode))) {
5610 prev = rb_next(prev);
5614 entry = rb_entry(node, struct btrfs_inode, rb_node);
5615 objectid = btrfs_ino(BTRFS_I(&entry->vfs_inode)) + 1;
5616 inode = igrab(&entry->vfs_inode);
5618 spin_unlock(&root->inode_lock);
5619 if (atomic_read(&inode->i_count) > 1)
5620 d_prune_aliases(inode);
5622 * btrfs_drop_inode will have it removed from
5623 * the inode cache when its usage count
5628 spin_lock(&root->inode_lock);
5632 if (cond_resched_lock(&root->inode_lock))
5635 node = rb_next(node);
5637 spin_unlock(&root->inode_lock);
5640 static int btrfs_init_locked_inode(struct inode *inode, void *p)
5642 struct btrfs_iget_args *args = p;
5643 inode->i_ino = args->location->objectid;
5644 memcpy(&BTRFS_I(inode)->location, args->location,
5645 sizeof(*args->location));
5646 BTRFS_I(inode)->root = args->root;
5650 static int btrfs_find_actor(struct inode *inode, void *opaque)
5652 struct btrfs_iget_args *args = opaque;
5653 return args->location->objectid == BTRFS_I(inode)->location.objectid &&
5654 args->root == BTRFS_I(inode)->root;
5657 static struct inode *btrfs_iget_locked(struct super_block *s,
5658 struct btrfs_key *location,
5659 struct btrfs_root *root)
5661 struct inode *inode;
5662 struct btrfs_iget_args args;
5663 unsigned long hashval = btrfs_inode_hash(location->objectid, root);
5665 args.location = location;
5668 inode = iget5_locked(s, hashval, btrfs_find_actor,
5669 btrfs_init_locked_inode,
5674 /* Get an inode object given its location and corresponding root.
5675 * Returns in *is_new if the inode was read from disk
5677 struct inode *btrfs_iget(struct super_block *s, struct btrfs_key *location,
5678 struct btrfs_root *root, int *new)
5680 struct inode *inode;
5682 inode = btrfs_iget_locked(s, location, root);
5684 return ERR_PTR(-ENOMEM);
5686 if (inode->i_state & I_NEW) {
5689 ret = btrfs_read_locked_inode(inode);
5690 if (!is_bad_inode(inode)) {
5691 inode_tree_add(inode);
5692 unlock_new_inode(inode);
5696 unlock_new_inode(inode);
5699 inode = ERR_PTR(ret < 0 ? ret : -ESTALE);
5706 static struct inode *new_simple_dir(struct super_block *s,
5707 struct btrfs_key *key,
5708 struct btrfs_root *root)
5710 struct inode *inode = new_inode(s);
5713 return ERR_PTR(-ENOMEM);
5715 BTRFS_I(inode)->root = root;
5716 memcpy(&BTRFS_I(inode)->location, key, sizeof(*key));
5717 set_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags);
5719 inode->i_ino = BTRFS_EMPTY_SUBVOL_DIR_OBJECTID;
5720 inode->i_op = &btrfs_dir_ro_inode_operations;
5721 inode->i_opflags &= ~IOP_XATTR;
5722 inode->i_fop = &simple_dir_operations;
5723 inode->i_mode = S_IFDIR | S_IRUGO | S_IWUSR | S_IXUGO;
5724 inode->i_mtime = current_time(inode);
5725 inode->i_atime = inode->i_mtime;
5726 inode->i_ctime = inode->i_mtime;
5727 BTRFS_I(inode)->i_otime = inode->i_mtime;
5732 struct inode *btrfs_lookup_dentry(struct inode *dir, struct dentry *dentry)
5734 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
5735 struct inode *inode;
5736 struct btrfs_root *root = BTRFS_I(dir)->root;
5737 struct btrfs_root *sub_root = root;
5738 struct btrfs_key location;
5742 if (dentry->d_name.len > BTRFS_NAME_LEN)
5743 return ERR_PTR(-ENAMETOOLONG);
5745 ret = btrfs_inode_by_name(dir, dentry, &location);
5747 return ERR_PTR(ret);
5749 if (location.objectid == 0)
5750 return ERR_PTR(-ENOENT);
5752 if (location.type == BTRFS_INODE_ITEM_KEY) {
5753 inode = btrfs_iget(dir->i_sb, &location, root, NULL);
5757 BUG_ON(location.type != BTRFS_ROOT_ITEM_KEY);
5759 index = srcu_read_lock(&fs_info->subvol_srcu);
5760 ret = fixup_tree_root_location(fs_info, dir, dentry,
5761 &location, &sub_root);
5764 inode = ERR_PTR(ret);
5766 inode = new_simple_dir(dir->i_sb, &location, sub_root);
5768 inode = btrfs_iget(dir->i_sb, &location, sub_root, NULL);
5770 srcu_read_unlock(&fs_info->subvol_srcu, index);
5772 if (!IS_ERR(inode) && root != sub_root) {
5773 down_read(&fs_info->cleanup_work_sem);
5774 if (!sb_rdonly(inode->i_sb))
5775 ret = btrfs_orphan_cleanup(sub_root);
5776 up_read(&fs_info->cleanup_work_sem);
5779 inode = ERR_PTR(ret);
5786 static int btrfs_dentry_delete(const struct dentry *dentry)
5788 struct btrfs_root *root;
5789 struct inode *inode = d_inode(dentry);
5791 if (!inode && !IS_ROOT(dentry))
5792 inode = d_inode(dentry->d_parent);
5795 root = BTRFS_I(inode)->root;
5796 if (btrfs_root_refs(&root->root_item) == 0)
5799 if (btrfs_ino(BTRFS_I(inode)) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)
5805 static void btrfs_dentry_release(struct dentry *dentry)
5807 kfree(dentry->d_fsdata);
5810 static struct dentry *btrfs_lookup(struct inode *dir, struct dentry *dentry,
5813 struct inode *inode;
5815 inode = btrfs_lookup_dentry(dir, dentry);
5816 if (IS_ERR(inode)) {
5817 if (PTR_ERR(inode) == -ENOENT)
5820 return ERR_CAST(inode);
5823 return d_splice_alias(inode, dentry);
5826 unsigned char btrfs_filetype_table[] = {
5827 DT_UNKNOWN, DT_REG, DT_DIR, DT_CHR, DT_BLK, DT_FIFO, DT_SOCK, DT_LNK
5831 * All this infrastructure exists because dir_emit can fault, and we are holding
5832 * the tree lock when doing readdir. For now just allocate a buffer and copy
5833 * our information into that, and then dir_emit from the buffer. This is
5834 * similar to what NFS does, only we don't keep the buffer around in pagecache
5835 * because I'm afraid I'll mess that up. Long term we need to make filldir do
5836 * copy_to_user_inatomic so we don't have to worry about page faulting under the
5839 static int btrfs_opendir(struct inode *inode, struct file *file)
5841 struct btrfs_file_private *private;
5843 private = kzalloc(sizeof(struct btrfs_file_private), GFP_KERNEL);
5846 private->filldir_buf = kzalloc(PAGE_SIZE, GFP_KERNEL);
5847 if (!private->filldir_buf) {
5851 file->private_data = private;
5862 static int btrfs_filldir(void *addr, int entries, struct dir_context *ctx)
5865 struct dir_entry *entry = addr;
5866 char *name = (char *)(entry + 1);
5868 ctx->pos = entry->offset;
5869 if (!dir_emit(ctx, name, entry->name_len, entry->ino,
5872 addr += sizeof(struct dir_entry) + entry->name_len;
5878 static int btrfs_real_readdir(struct file *file, struct dir_context *ctx)
5880 struct inode *inode = file_inode(file);
5881 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
5882 struct btrfs_root *root = BTRFS_I(inode)->root;
5883 struct btrfs_file_private *private = file->private_data;
5884 struct btrfs_dir_item *di;
5885 struct btrfs_key key;
5886 struct btrfs_key found_key;
5887 struct btrfs_path *path;
5889 struct list_head ins_list;
5890 struct list_head del_list;
5892 struct extent_buffer *leaf;
5899 struct btrfs_key location;
5901 if (!dir_emit_dots(file, ctx))
5904 path = btrfs_alloc_path();
5908 addr = private->filldir_buf;
5909 path->reada = READA_FORWARD;
5911 INIT_LIST_HEAD(&ins_list);
5912 INIT_LIST_HEAD(&del_list);
5913 put = btrfs_readdir_get_delayed_items(inode, &ins_list, &del_list);
5916 key.type = BTRFS_DIR_INDEX_KEY;
5917 key.offset = ctx->pos;
5918 key.objectid = btrfs_ino(BTRFS_I(inode));
5920 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
5925 struct dir_entry *entry;
5927 leaf = path->nodes[0];
5928 slot = path->slots[0];
5929 if (slot >= btrfs_header_nritems(leaf)) {
5930 ret = btrfs_next_leaf(root, path);
5938 btrfs_item_key_to_cpu(leaf, &found_key, slot);
5940 if (found_key.objectid != key.objectid)
5942 if (found_key.type != BTRFS_DIR_INDEX_KEY)
5944 if (found_key.offset < ctx->pos)
5946 if (btrfs_should_delete_dir_index(&del_list, found_key.offset))
5948 di = btrfs_item_ptr(leaf, slot, struct btrfs_dir_item);
5949 if (verify_dir_item(fs_info, leaf, slot, di))
5952 name_len = btrfs_dir_name_len(leaf, di);
5953 if ((total_len + sizeof(struct dir_entry) + name_len) >=
5955 btrfs_release_path(path);
5956 ret = btrfs_filldir(private->filldir_buf, entries, ctx);
5959 addr = private->filldir_buf;
5966 entry->name_len = name_len;
5967 name_ptr = (char *)(entry + 1);
5968 read_extent_buffer(leaf, name_ptr, (unsigned long)(di + 1),
5970 entry->type = btrfs_filetype_table[btrfs_dir_type(leaf, di)];
5971 btrfs_dir_item_key_to_cpu(leaf, di, &location);
5972 entry->ino = location.objectid;
5973 entry->offset = found_key.offset;
5975 addr += sizeof(struct dir_entry) + name_len;
5976 total_len += sizeof(struct dir_entry) + name_len;
5980 btrfs_release_path(path);
5982 ret = btrfs_filldir(private->filldir_buf, entries, ctx);
5986 ret = btrfs_readdir_delayed_dir_index(ctx, &ins_list);
5991 * Stop new entries from being returned after we return the last
5994 * New directory entries are assigned a strictly increasing
5995 * offset. This means that new entries created during readdir
5996 * are *guaranteed* to be seen in the future by that readdir.
5997 * This has broken buggy programs which operate on names as
5998 * they're returned by readdir. Until we re-use freed offsets
5999 * we have this hack to stop new entries from being returned
6000 * under the assumption that they'll never reach this huge
6003 * This is being careful not to overflow 32bit loff_t unless the
6004 * last entry requires it because doing so has broken 32bit apps
6007 if (ctx->pos >= INT_MAX)
6008 ctx->pos = LLONG_MAX;
6015 btrfs_readdir_put_delayed_items(inode, &ins_list, &del_list);
6016 btrfs_free_path(path);
6020 int btrfs_write_inode(struct inode *inode, struct writeback_control *wbc)
6022 struct btrfs_root *root = BTRFS_I(inode)->root;
6023 struct btrfs_trans_handle *trans;
6025 bool nolock = false;
6027 if (test_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags))
6030 if (btrfs_fs_closing(root->fs_info) &&
6031 btrfs_is_free_space_inode(BTRFS_I(inode)))
6034 if (wbc->sync_mode == WB_SYNC_ALL) {
6036 trans = btrfs_join_transaction_nolock(root);
6038 trans = btrfs_join_transaction(root);
6040 return PTR_ERR(trans);
6041 ret = btrfs_commit_transaction(trans);
6047 * This is somewhat expensive, updating the tree every time the
6048 * inode changes. But, it is most likely to find the inode in cache.
6049 * FIXME, needs more benchmarking...there are no reasons other than performance
6050 * to keep or drop this code.
6052 static int btrfs_dirty_inode(struct inode *inode)
6054 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
6055 struct btrfs_root *root = BTRFS_I(inode)->root;
6056 struct btrfs_trans_handle *trans;
6059 if (test_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags))
6062 trans = btrfs_join_transaction(root);
6064 return PTR_ERR(trans);
6066 ret = btrfs_update_inode(trans, root, inode);
6067 if (ret && ret == -ENOSPC) {
6068 /* whoops, lets try again with the full transaction */
6069 btrfs_end_transaction(trans);
6070 trans = btrfs_start_transaction(root, 1);
6072 return PTR_ERR(trans);
6074 ret = btrfs_update_inode(trans, root, inode);
6076 btrfs_end_transaction(trans);
6077 if (BTRFS_I(inode)->delayed_node)
6078 btrfs_balance_delayed_items(fs_info);
6084 * This is a copy of file_update_time. We need this so we can return error on
6085 * ENOSPC for updating the inode in the case of file write and mmap writes.
6087 static int btrfs_update_time(struct inode *inode, struct timespec *now,
6090 struct btrfs_root *root = BTRFS_I(inode)->root;
6092 if (btrfs_root_readonly(root))
6095 if (flags & S_VERSION)
6096 inode_inc_iversion(inode);
6097 if (flags & S_CTIME)
6098 inode->i_ctime = *now;
6099 if (flags & S_MTIME)
6100 inode->i_mtime = *now;
6101 if (flags & S_ATIME)
6102 inode->i_atime = *now;
6103 return btrfs_dirty_inode(inode);
6107 * find the highest existing sequence number in a directory
6108 * and then set the in-memory index_cnt variable to reflect
6109 * free sequence numbers
6111 static int btrfs_set_inode_index_count(struct btrfs_inode *inode)
6113 struct btrfs_root *root = inode->root;
6114 struct btrfs_key key, found_key;
6115 struct btrfs_path *path;
6116 struct extent_buffer *leaf;
6119 key.objectid = btrfs_ino(inode);
6120 key.type = BTRFS_DIR_INDEX_KEY;
6121 key.offset = (u64)-1;
6123 path = btrfs_alloc_path();
6127 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
6130 /* FIXME: we should be able to handle this */
6136 * MAGIC NUMBER EXPLANATION:
6137 * since we search a directory based on f_pos we have to start at 2
6138 * since '.' and '..' have f_pos of 0 and 1 respectively, so everybody
6139 * else has to start at 2
6141 if (path->slots[0] == 0) {
6142 inode->index_cnt = 2;
6148 leaf = path->nodes[0];
6149 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
6151 if (found_key.objectid != btrfs_ino(inode) ||
6152 found_key.type != BTRFS_DIR_INDEX_KEY) {
6153 inode->index_cnt = 2;
6157 inode->index_cnt = found_key.offset + 1;
6159 btrfs_free_path(path);
6164 * helper to find a free sequence number in a given directory. This current
6165 * code is very simple, later versions will do smarter things in the btree
6167 int btrfs_set_inode_index(struct btrfs_inode *dir, u64 *index)
6171 if (dir->index_cnt == (u64)-1) {
6172 ret = btrfs_inode_delayed_dir_index_count(dir);
6174 ret = btrfs_set_inode_index_count(dir);
6180 *index = dir->index_cnt;
6186 static int btrfs_insert_inode_locked(struct inode *inode)
6188 struct btrfs_iget_args args;
6189 args.location = &BTRFS_I(inode)->location;
6190 args.root = BTRFS_I(inode)->root;
6192 return insert_inode_locked4(inode,
6193 btrfs_inode_hash(inode->i_ino, BTRFS_I(inode)->root),
6194 btrfs_find_actor, &args);
6198 * Inherit flags from the parent inode.
6200 * Currently only the compression flags and the cow flags are inherited.
6202 static void btrfs_inherit_iflags(struct inode *inode, struct inode *dir)
6209 flags = BTRFS_I(dir)->flags;
6211 if (flags & BTRFS_INODE_NOCOMPRESS) {
6212 BTRFS_I(inode)->flags &= ~BTRFS_INODE_COMPRESS;
6213 BTRFS_I(inode)->flags |= BTRFS_INODE_NOCOMPRESS;
6214 } else if (flags & BTRFS_INODE_COMPRESS) {
6215 BTRFS_I(inode)->flags &= ~BTRFS_INODE_NOCOMPRESS;
6216 BTRFS_I(inode)->flags |= BTRFS_INODE_COMPRESS;
6219 if (flags & BTRFS_INODE_NODATACOW) {
6220 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATACOW;
6221 if (S_ISREG(inode->i_mode))
6222 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATASUM;
6225 btrfs_update_iflags(inode);
6228 static struct inode *btrfs_new_inode(struct btrfs_trans_handle *trans,
6229 struct btrfs_root *root,
6231 const char *name, int name_len,
6232 u64 ref_objectid, u64 objectid,
6233 umode_t mode, u64 *index)
6235 struct btrfs_fs_info *fs_info = root->fs_info;
6236 struct inode *inode;
6237 struct btrfs_inode_item *inode_item;
6238 struct btrfs_key *location;
6239 struct btrfs_path *path;
6240 struct btrfs_inode_ref *ref;
6241 struct btrfs_key key[2];
6243 int nitems = name ? 2 : 1;
6247 path = btrfs_alloc_path();
6249 return ERR_PTR(-ENOMEM);
6251 inode = new_inode(fs_info->sb);
6253 btrfs_free_path(path);
6254 return ERR_PTR(-ENOMEM);
6258 * O_TMPFILE, set link count to 0, so that after this point,
6259 * we fill in an inode item with the correct link count.
6262 set_nlink(inode, 0);
6265 * we have to initialize this early, so we can reclaim the inode
6266 * number if we fail afterwards in this function.
6268 inode->i_ino = objectid;
6271 trace_btrfs_inode_request(dir);
6273 ret = btrfs_set_inode_index(BTRFS_I(dir), index);
6275 btrfs_free_path(path);
6277 return ERR_PTR(ret);
6283 * index_cnt is ignored for everything but a dir,
6284 * btrfs_get_inode_index_count has an explanation for the magic
6287 BTRFS_I(inode)->index_cnt = 2;
6288 BTRFS_I(inode)->dir_index = *index;
6289 BTRFS_I(inode)->root = root;
6290 BTRFS_I(inode)->generation = trans->transid;
6291 inode->i_generation = BTRFS_I(inode)->generation;
6294 * We could have gotten an inode number from somebody who was fsynced
6295 * and then removed in this same transaction, so let's just set full
6296 * sync since it will be a full sync anyway and this will blow away the
6297 * old info in the log.
6299 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &BTRFS_I(inode)->runtime_flags);
6301 key[0].objectid = objectid;
6302 key[0].type = BTRFS_INODE_ITEM_KEY;
6305 sizes[0] = sizeof(struct btrfs_inode_item);
6309 * Start new inodes with an inode_ref. This is slightly more
6310 * efficient for small numbers of hard links since they will
6311 * be packed into one item. Extended refs will kick in if we
6312 * add more hard links than can fit in the ref item.
6314 key[1].objectid = objectid;
6315 key[1].type = BTRFS_INODE_REF_KEY;
6316 key[1].offset = ref_objectid;
6318 sizes[1] = name_len + sizeof(*ref);
6321 location = &BTRFS_I(inode)->location;
6322 location->objectid = objectid;
6323 location->offset = 0;
6324 location->type = BTRFS_INODE_ITEM_KEY;
6326 ret = btrfs_insert_inode_locked(inode);
6330 path->leave_spinning = 1;
6331 ret = btrfs_insert_empty_items(trans, root, path, key, sizes, nitems);
6335 inode_init_owner(inode, dir, mode);
6336 inode_set_bytes(inode, 0);
6338 inode->i_mtime = current_time(inode);
6339 inode->i_atime = inode->i_mtime;
6340 inode->i_ctime = inode->i_mtime;
6341 BTRFS_I(inode)->i_otime = inode->i_mtime;
6343 inode_item = btrfs_item_ptr(path->nodes[0], path->slots[0],
6344 struct btrfs_inode_item);
6345 memzero_extent_buffer(path->nodes[0], (unsigned long)inode_item,
6346 sizeof(*inode_item));
6347 fill_inode_item(trans, path->nodes[0], inode_item, inode);
6350 ref = btrfs_item_ptr(path->nodes[0], path->slots[0] + 1,
6351 struct btrfs_inode_ref);
6352 btrfs_set_inode_ref_name_len(path->nodes[0], ref, name_len);
6353 btrfs_set_inode_ref_index(path->nodes[0], ref, *index);
6354 ptr = (unsigned long)(ref + 1);
6355 write_extent_buffer(path->nodes[0], name, ptr, name_len);
6358 btrfs_mark_buffer_dirty(path->nodes[0]);
6359 btrfs_free_path(path);
6361 btrfs_inherit_iflags(inode, dir);
6363 if (S_ISREG(mode)) {
6364 if (btrfs_test_opt(fs_info, NODATASUM))
6365 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATASUM;
6366 if (btrfs_test_opt(fs_info, NODATACOW))
6367 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATACOW |
6368 BTRFS_INODE_NODATASUM;
6371 inode_tree_add(inode);
6373 trace_btrfs_inode_new(inode);
6374 btrfs_set_inode_last_trans(trans, inode);
6376 btrfs_update_root_times(trans, root);
6378 ret = btrfs_inode_inherit_props(trans, inode, dir);
6381 "error inheriting props for ino %llu (root %llu): %d",
6382 btrfs_ino(BTRFS_I(inode)), root->root_key.objectid, ret);
6387 unlock_new_inode(inode);
6390 BTRFS_I(dir)->index_cnt--;
6391 btrfs_free_path(path);
6393 return ERR_PTR(ret);
6396 static inline u8 btrfs_inode_type(struct inode *inode)
6398 return btrfs_type_by_mode[(inode->i_mode & S_IFMT) >> S_SHIFT];
6402 * utility function to add 'inode' into 'parent_inode' with
6403 * a give name and a given sequence number.
6404 * if 'add_backref' is true, also insert a backref from the
6405 * inode to the parent directory.
6407 int btrfs_add_link(struct btrfs_trans_handle *trans,
6408 struct btrfs_inode *parent_inode, struct btrfs_inode *inode,
6409 const char *name, int name_len, int add_backref, u64 index)
6411 struct btrfs_fs_info *fs_info = btrfs_sb(inode->vfs_inode.i_sb);
6413 struct btrfs_key key;
6414 struct btrfs_root *root = parent_inode->root;
6415 u64 ino = btrfs_ino(inode);
6416 u64 parent_ino = btrfs_ino(parent_inode);
6418 if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
6419 memcpy(&key, &inode->root->root_key, sizeof(key));
6422 key.type = BTRFS_INODE_ITEM_KEY;
6426 if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
6427 ret = btrfs_add_root_ref(trans, fs_info, key.objectid,
6428 root->root_key.objectid, parent_ino,
6429 index, name, name_len);
6430 } else if (add_backref) {
6431 ret = btrfs_insert_inode_ref(trans, root, name, name_len, ino,
6435 /* Nothing to clean up yet */
6439 ret = btrfs_insert_dir_item(trans, root, name, name_len,
6441 btrfs_inode_type(&inode->vfs_inode), index);
6442 if (ret == -EEXIST || ret == -EOVERFLOW)
6445 btrfs_abort_transaction(trans, ret);
6449 btrfs_i_size_write(parent_inode, parent_inode->vfs_inode.i_size +
6451 inode_inc_iversion(&parent_inode->vfs_inode);
6452 parent_inode->vfs_inode.i_mtime = parent_inode->vfs_inode.i_ctime =
6453 current_time(&parent_inode->vfs_inode);
6454 ret = btrfs_update_inode(trans, root, &parent_inode->vfs_inode);
6456 btrfs_abort_transaction(trans, ret);
6460 if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
6463 err = btrfs_del_root_ref(trans, fs_info, key.objectid,
6464 root->root_key.objectid, parent_ino,
6465 &local_index, name, name_len);
6467 } else if (add_backref) {
6471 err = btrfs_del_inode_ref(trans, root, name, name_len,
6472 ino, parent_ino, &local_index);
6477 static int btrfs_add_nondir(struct btrfs_trans_handle *trans,
6478 struct btrfs_inode *dir, struct dentry *dentry,
6479 struct btrfs_inode *inode, int backref, u64 index)
6481 int err = btrfs_add_link(trans, dir, inode,
6482 dentry->d_name.name, dentry->d_name.len,
6489 static int btrfs_mknod(struct inode *dir, struct dentry *dentry,
6490 umode_t mode, dev_t rdev)
6492 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
6493 struct btrfs_trans_handle *trans;
6494 struct btrfs_root *root = BTRFS_I(dir)->root;
6495 struct inode *inode = NULL;
6502 * 2 for inode item and ref
6504 * 1 for xattr if selinux is on
6506 trans = btrfs_start_transaction(root, 5);
6508 return PTR_ERR(trans);
6510 err = btrfs_find_free_ino(root, &objectid);
6514 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
6515 dentry->d_name.len, btrfs_ino(BTRFS_I(dir)), objectid,
6517 if (IS_ERR(inode)) {
6518 err = PTR_ERR(inode);
6523 * If the active LSM wants to access the inode during
6524 * d_instantiate it needs these. Smack checks to see
6525 * if the filesystem supports xattrs by looking at the
6528 inode->i_op = &btrfs_special_inode_operations;
6529 init_special_inode(inode, inode->i_mode, rdev);
6531 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
6533 goto out_unlock_inode;
6535 err = btrfs_add_nondir(trans, BTRFS_I(dir), dentry, BTRFS_I(inode),
6538 goto out_unlock_inode;
6540 btrfs_update_inode(trans, root, inode);
6541 unlock_new_inode(inode);
6542 d_instantiate(dentry, inode);
6546 btrfs_end_transaction(trans);
6547 btrfs_balance_delayed_items(fs_info);
6548 btrfs_btree_balance_dirty(fs_info);
6550 inode_dec_link_count(inode);
6557 unlock_new_inode(inode);
6562 static int btrfs_create(struct inode *dir, struct dentry *dentry,
6563 umode_t mode, bool excl)
6565 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
6566 struct btrfs_trans_handle *trans;
6567 struct btrfs_root *root = BTRFS_I(dir)->root;
6568 struct inode *inode = NULL;
6569 int drop_inode_on_err = 0;
6575 * 2 for inode item and ref
6577 * 1 for xattr if selinux is on
6579 trans = btrfs_start_transaction(root, 5);
6581 return PTR_ERR(trans);
6583 err = btrfs_find_free_ino(root, &objectid);
6587 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
6588 dentry->d_name.len, btrfs_ino(BTRFS_I(dir)), objectid,
6590 if (IS_ERR(inode)) {
6591 err = PTR_ERR(inode);
6594 drop_inode_on_err = 1;
6596 * If the active LSM wants to access the inode during
6597 * d_instantiate it needs these. Smack checks to see
6598 * if the filesystem supports xattrs by looking at the
6601 inode->i_fop = &btrfs_file_operations;
6602 inode->i_op = &btrfs_file_inode_operations;
6603 inode->i_mapping->a_ops = &btrfs_aops;
6605 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
6607 goto out_unlock_inode;
6609 err = btrfs_update_inode(trans, root, inode);
6611 goto out_unlock_inode;
6613 err = btrfs_add_nondir(trans, BTRFS_I(dir), dentry, BTRFS_I(inode),
6616 goto out_unlock_inode;
6618 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
6619 unlock_new_inode(inode);
6620 d_instantiate(dentry, inode);
6623 btrfs_end_transaction(trans);
6624 if (err && drop_inode_on_err) {
6625 inode_dec_link_count(inode);
6628 btrfs_balance_delayed_items(fs_info);
6629 btrfs_btree_balance_dirty(fs_info);
6633 unlock_new_inode(inode);
6638 static int btrfs_link(struct dentry *old_dentry, struct inode *dir,
6639 struct dentry *dentry)
6641 struct btrfs_trans_handle *trans = NULL;
6642 struct btrfs_root *root = BTRFS_I(dir)->root;
6643 struct inode *inode = d_inode(old_dentry);
6644 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
6649 /* do not allow sys_link's with other subvols of the same device */
6650 if (root->objectid != BTRFS_I(inode)->root->objectid)
6653 if (inode->i_nlink >= BTRFS_LINK_MAX)
6656 err = btrfs_set_inode_index(BTRFS_I(dir), &index);
6661 * 2 items for inode and inode ref
6662 * 2 items for dir items
6663 * 1 item for parent inode
6665 trans = btrfs_start_transaction(root, 5);
6666 if (IS_ERR(trans)) {
6667 err = PTR_ERR(trans);
6672 /* There are several dir indexes for this inode, clear the cache. */
6673 BTRFS_I(inode)->dir_index = 0ULL;
6675 inode_inc_iversion(inode);
6676 inode->i_ctime = current_time(inode);
6678 set_bit(BTRFS_INODE_COPY_EVERYTHING, &BTRFS_I(inode)->runtime_flags);
6680 err = btrfs_add_nondir(trans, BTRFS_I(dir), dentry, BTRFS_I(inode),
6686 struct dentry *parent = dentry->d_parent;
6687 err = btrfs_update_inode(trans, root, inode);
6690 if (inode->i_nlink == 1) {
6692 * If new hard link count is 1, it's a file created
6693 * with open(2) O_TMPFILE flag.
6695 err = btrfs_orphan_del(trans, BTRFS_I(inode));
6699 d_instantiate(dentry, inode);
6700 btrfs_log_new_name(trans, BTRFS_I(inode), NULL, parent);
6703 btrfs_balance_delayed_items(fs_info);
6706 btrfs_end_transaction(trans);
6708 inode_dec_link_count(inode);
6711 btrfs_btree_balance_dirty(fs_info);
6715 static int btrfs_mkdir(struct inode *dir, struct dentry *dentry, umode_t mode)
6717 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
6718 struct inode *inode = NULL;
6719 struct btrfs_trans_handle *trans;
6720 struct btrfs_root *root = BTRFS_I(dir)->root;
6722 int drop_on_err = 0;
6727 * 2 items for inode and ref
6728 * 2 items for dir items
6729 * 1 for xattr if selinux is on
6731 trans = btrfs_start_transaction(root, 5);
6733 return PTR_ERR(trans);
6735 err = btrfs_find_free_ino(root, &objectid);
6739 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
6740 dentry->d_name.len, btrfs_ino(BTRFS_I(dir)), objectid,
6741 S_IFDIR | mode, &index);
6742 if (IS_ERR(inode)) {
6743 err = PTR_ERR(inode);
6748 /* these must be set before we unlock the inode */
6749 inode->i_op = &btrfs_dir_inode_operations;
6750 inode->i_fop = &btrfs_dir_file_operations;
6752 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
6754 goto out_fail_inode;
6756 btrfs_i_size_write(BTRFS_I(inode), 0);
6757 err = btrfs_update_inode(trans, root, inode);
6759 goto out_fail_inode;
6761 err = btrfs_add_link(trans, BTRFS_I(dir), BTRFS_I(inode),
6762 dentry->d_name.name,
6763 dentry->d_name.len, 0, index);
6765 goto out_fail_inode;
6767 d_instantiate(dentry, inode);
6769 * mkdir is special. We're unlocking after we call d_instantiate
6770 * to avoid a race with nfsd calling d_instantiate.
6772 unlock_new_inode(inode);
6776 btrfs_end_transaction(trans);
6778 inode_dec_link_count(inode);
6781 btrfs_balance_delayed_items(fs_info);
6782 btrfs_btree_balance_dirty(fs_info);
6786 unlock_new_inode(inode);
6790 /* Find next extent map of a given extent map, caller needs to ensure locks */
6791 static struct extent_map *next_extent_map(struct extent_map *em)
6793 struct rb_node *next;
6795 next = rb_next(&em->rb_node);
6798 return container_of(next, struct extent_map, rb_node);
6801 static struct extent_map *prev_extent_map(struct extent_map *em)
6803 struct rb_node *prev;
6805 prev = rb_prev(&em->rb_node);
6808 return container_of(prev, struct extent_map, rb_node);
6811 /* helper for btfs_get_extent. Given an existing extent in the tree,
6812 * the existing extent is the nearest extent to map_start,
6813 * and an extent that you want to insert, deal with overlap and insert
6814 * the best fitted new extent into the tree.
6816 static int merge_extent_mapping(struct extent_map_tree *em_tree,
6817 struct extent_map *existing,
6818 struct extent_map *em,
6821 struct extent_map *prev;
6822 struct extent_map *next;
6827 BUG_ON(map_start < em->start || map_start >= extent_map_end(em));
6829 if (existing->start > map_start) {
6831 prev = prev_extent_map(next);
6834 next = next_extent_map(prev);
6837 start = prev ? extent_map_end(prev) : em->start;
6838 start = max_t(u64, start, em->start);
6839 end = next ? next->start : extent_map_end(em);
6840 end = min_t(u64, end, extent_map_end(em));
6841 start_diff = start - em->start;
6843 em->len = end - start;
6844 if (em->block_start < EXTENT_MAP_LAST_BYTE &&
6845 !test_bit(EXTENT_FLAG_COMPRESSED, &em->flags)) {
6846 em->block_start += start_diff;
6847 em->block_len -= start_diff;
6849 return add_extent_mapping(em_tree, em, 0);
6852 static noinline int uncompress_inline(struct btrfs_path *path,
6854 size_t pg_offset, u64 extent_offset,
6855 struct btrfs_file_extent_item *item)
6858 struct extent_buffer *leaf = path->nodes[0];
6861 unsigned long inline_size;
6865 WARN_ON(pg_offset != 0);
6866 compress_type = btrfs_file_extent_compression(leaf, item);
6867 max_size = btrfs_file_extent_ram_bytes(leaf, item);
6868 inline_size = btrfs_file_extent_inline_item_len(leaf,
6869 btrfs_item_nr(path->slots[0]));
6870 tmp = kmalloc(inline_size, GFP_NOFS);
6873 ptr = btrfs_file_extent_inline_start(item);
6875 read_extent_buffer(leaf, tmp, ptr, inline_size);
6877 max_size = min_t(unsigned long, PAGE_SIZE, max_size);
6878 ret = btrfs_decompress(compress_type, tmp, page,
6879 extent_offset, inline_size, max_size);
6882 * decompression code contains a memset to fill in any space between the end
6883 * of the uncompressed data and the end of max_size in case the decompressed
6884 * data ends up shorter than ram_bytes. That doesn't cover the hole between
6885 * the end of an inline extent and the beginning of the next block, so we
6886 * cover that region here.
6889 if (max_size + pg_offset < PAGE_SIZE) {
6890 char *map = kmap(page);
6891 memset(map + pg_offset + max_size, 0, PAGE_SIZE - max_size - pg_offset);
6899 * a bit scary, this does extent mapping from logical file offset to the disk.
6900 * the ugly parts come from merging extents from the disk with the in-ram
6901 * representation. This gets more complex because of the data=ordered code,
6902 * where the in-ram extents might be locked pending data=ordered completion.
6904 * This also copies inline extents directly into the page.
6906 struct extent_map *btrfs_get_extent(struct btrfs_inode *inode,
6908 size_t pg_offset, u64 start, u64 len,
6911 struct btrfs_fs_info *fs_info = btrfs_sb(inode->vfs_inode.i_sb);
6914 u64 extent_start = 0;
6916 u64 objectid = btrfs_ino(inode);
6918 struct btrfs_path *path = NULL;
6919 struct btrfs_root *root = inode->root;
6920 struct btrfs_file_extent_item *item;
6921 struct extent_buffer *leaf;
6922 struct btrfs_key found_key;
6923 struct extent_map *em = NULL;
6924 struct extent_map_tree *em_tree = &inode->extent_tree;
6925 struct extent_io_tree *io_tree = &inode->io_tree;
6926 struct btrfs_trans_handle *trans = NULL;
6927 const bool new_inline = !page || create;
6930 read_lock(&em_tree->lock);
6931 em = lookup_extent_mapping(em_tree, start, len);
6933 em->bdev = fs_info->fs_devices->latest_bdev;
6934 read_unlock(&em_tree->lock);
6937 if (em->start > start || em->start + em->len <= start)
6938 free_extent_map(em);
6939 else if (em->block_start == EXTENT_MAP_INLINE && page)
6940 free_extent_map(em);
6944 em = alloc_extent_map();
6949 em->bdev = fs_info->fs_devices->latest_bdev;
6950 em->start = EXTENT_MAP_HOLE;
6951 em->orig_start = EXTENT_MAP_HOLE;
6953 em->block_len = (u64)-1;
6956 path = btrfs_alloc_path();
6962 * Chances are we'll be called again, so go ahead and do
6965 path->reada = READA_FORWARD;
6968 ret = btrfs_lookup_file_extent(trans, root, path,
6969 objectid, start, trans != NULL);
6976 if (path->slots[0] == 0)
6981 leaf = path->nodes[0];
6982 item = btrfs_item_ptr(leaf, path->slots[0],
6983 struct btrfs_file_extent_item);
6984 /* are we inside the extent that was found? */
6985 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
6986 found_type = found_key.type;
6987 if (found_key.objectid != objectid ||
6988 found_type != BTRFS_EXTENT_DATA_KEY) {
6990 * If we backup past the first extent we want to move forward
6991 * and see if there is an extent in front of us, otherwise we'll
6992 * say there is a hole for our whole search range which can
6999 found_type = btrfs_file_extent_type(leaf, item);
7000 extent_start = found_key.offset;
7001 if (found_type == BTRFS_FILE_EXTENT_REG ||
7002 found_type == BTRFS_FILE_EXTENT_PREALLOC) {
7003 extent_end = extent_start +
7004 btrfs_file_extent_num_bytes(leaf, item);
7006 trace_btrfs_get_extent_show_fi_regular(inode, leaf, item,
7008 } else if (found_type == BTRFS_FILE_EXTENT_INLINE) {
7010 size = btrfs_file_extent_inline_len(leaf, path->slots[0], item);
7011 extent_end = ALIGN(extent_start + size,
7012 fs_info->sectorsize);
7014 trace_btrfs_get_extent_show_fi_inline(inode, leaf, item,
7019 if (start >= extent_end) {
7021 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
7022 ret = btrfs_next_leaf(root, path);
7029 leaf = path->nodes[0];
7031 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
7032 if (found_key.objectid != objectid ||
7033 found_key.type != BTRFS_EXTENT_DATA_KEY)
7035 if (start + len <= found_key.offset)
7037 if (start > found_key.offset)
7040 em->orig_start = start;
7041 em->len = found_key.offset - start;
7045 btrfs_extent_item_to_extent_map(inode, path, item,
7048 if (found_type == BTRFS_FILE_EXTENT_REG ||
7049 found_type == BTRFS_FILE_EXTENT_PREALLOC) {
7051 } else if (found_type == BTRFS_FILE_EXTENT_INLINE) {
7055 size_t extent_offset;
7061 size = btrfs_file_extent_inline_len(leaf, path->slots[0], item);
7062 extent_offset = page_offset(page) + pg_offset - extent_start;
7063 copy_size = min_t(u64, PAGE_SIZE - pg_offset,
7064 size - extent_offset);
7065 em->start = extent_start + extent_offset;
7066 em->len = ALIGN(copy_size, fs_info->sectorsize);
7067 em->orig_block_len = em->len;
7068 em->orig_start = em->start;
7069 ptr = btrfs_file_extent_inline_start(item) + extent_offset;
7070 if (create == 0 && !PageUptodate(page)) {
7071 if (btrfs_file_extent_compression(leaf, item) !=
7072 BTRFS_COMPRESS_NONE) {
7073 ret = uncompress_inline(path, page, pg_offset,
7074 extent_offset, item);
7081 read_extent_buffer(leaf, map + pg_offset, ptr,
7083 if (pg_offset + copy_size < PAGE_SIZE) {
7084 memset(map + pg_offset + copy_size, 0,
7085 PAGE_SIZE - pg_offset -
7090 flush_dcache_page(page);
7091 } else if (create && PageUptodate(page)) {
7095 free_extent_map(em);
7098 btrfs_release_path(path);
7099 trans = btrfs_join_transaction(root);
7102 return ERR_CAST(trans);
7106 write_extent_buffer(leaf, map + pg_offset, ptr,
7109 btrfs_mark_buffer_dirty(leaf);
7111 set_extent_uptodate(io_tree, em->start,
7112 extent_map_end(em) - 1, NULL, GFP_NOFS);
7117 em->orig_start = start;
7120 em->block_start = EXTENT_MAP_HOLE;
7121 set_bit(EXTENT_FLAG_VACANCY, &em->flags);
7123 btrfs_release_path(path);
7124 if (em->start > start || extent_map_end(em) <= start) {
7126 "bad extent! em: [%llu %llu] passed [%llu %llu]",
7127 em->start, em->len, start, len);
7133 write_lock(&em_tree->lock);
7134 ret = add_extent_mapping(em_tree, em, 0);
7135 /* it is possible that someone inserted the extent into the tree
7136 * while we had the lock dropped. It is also possible that
7137 * an overlapping map exists in the tree
7139 if (ret == -EEXIST) {
7140 struct extent_map *existing;
7144 existing = search_extent_mapping(em_tree, start, len);
7146 * existing will always be non-NULL, since there must be
7147 * extent causing the -EEXIST.
7149 if (existing->start == em->start &&
7150 extent_map_end(existing) >= extent_map_end(em) &&
7151 em->block_start == existing->block_start) {
7153 * The existing extent map already encompasses the
7154 * entire extent map we tried to add.
7156 free_extent_map(em);
7160 } else if (start >= extent_map_end(existing) ||
7161 start <= existing->start) {
7163 * The existing extent map is the one nearest to
7164 * the [start, start + len) range which overlaps
7166 err = merge_extent_mapping(em_tree, existing,
7168 free_extent_map(existing);
7170 free_extent_map(em);
7174 free_extent_map(em);
7179 write_unlock(&em_tree->lock);
7182 trace_btrfs_get_extent(root, inode, em);
7184 btrfs_free_path(path);
7186 ret = btrfs_end_transaction(trans);
7191 free_extent_map(em);
7192 return ERR_PTR(err);
7194 BUG_ON(!em); /* Error is always set */
7198 struct extent_map *btrfs_get_extent_fiemap(struct btrfs_inode *inode,
7200 size_t pg_offset, u64 start, u64 len,
7203 struct extent_map *em;
7204 struct extent_map *hole_em = NULL;
7205 u64 range_start = start;
7211 em = btrfs_get_extent(inode, page, pg_offset, start, len, create);
7215 * If our em maps to:
7217 * - a pre-alloc extent,
7218 * there might actually be delalloc bytes behind it.
7220 if (em->block_start != EXTENT_MAP_HOLE &&
7221 !test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
7226 /* check to see if we've wrapped (len == -1 or similar) */
7235 /* ok, we didn't find anything, lets look for delalloc */
7236 found = count_range_bits(&inode->io_tree, &range_start,
7237 end, len, EXTENT_DELALLOC, 1);
7238 found_end = range_start + found;
7239 if (found_end < range_start)
7240 found_end = (u64)-1;
7243 * we didn't find anything useful, return
7244 * the original results from get_extent()
7246 if (range_start > end || found_end <= start) {
7252 /* adjust the range_start to make sure it doesn't
7253 * go backwards from the start they passed in
7255 range_start = max(start, range_start);
7256 found = found_end - range_start;
7259 u64 hole_start = start;
7262 em = alloc_extent_map();
7268 * when btrfs_get_extent can't find anything it
7269 * returns one huge hole
7271 * make sure what it found really fits our range, and
7272 * adjust to make sure it is based on the start from
7276 u64 calc_end = extent_map_end(hole_em);
7278 if (calc_end <= start || (hole_em->start > end)) {
7279 free_extent_map(hole_em);
7282 hole_start = max(hole_em->start, start);
7283 hole_len = calc_end - hole_start;
7287 if (hole_em && range_start > hole_start) {
7288 /* our hole starts before our delalloc, so we
7289 * have to return just the parts of the hole
7290 * that go until the delalloc starts
7292 em->len = min(hole_len,
7293 range_start - hole_start);
7294 em->start = hole_start;
7295 em->orig_start = hole_start;
7297 * don't adjust block start at all,
7298 * it is fixed at EXTENT_MAP_HOLE
7300 em->block_start = hole_em->block_start;
7301 em->block_len = hole_len;
7302 if (test_bit(EXTENT_FLAG_PREALLOC, &hole_em->flags))
7303 set_bit(EXTENT_FLAG_PREALLOC, &em->flags);
7305 em->start = range_start;
7307 em->orig_start = range_start;
7308 em->block_start = EXTENT_MAP_DELALLOC;
7309 em->block_len = found;
7311 } else if (hole_em) {
7316 free_extent_map(hole_em);
7318 free_extent_map(em);
7319 return ERR_PTR(err);
7324 static struct extent_map *btrfs_create_dio_extent(struct inode *inode,
7327 const u64 orig_start,
7328 const u64 block_start,
7329 const u64 block_len,
7330 const u64 orig_block_len,
7331 const u64 ram_bytes,
7334 struct extent_map *em = NULL;
7337 if (type != BTRFS_ORDERED_NOCOW) {
7338 em = create_io_em(inode, start, len, orig_start,
7339 block_start, block_len, orig_block_len,
7341 BTRFS_COMPRESS_NONE, /* compress_type */
7346 ret = btrfs_add_ordered_extent_dio(inode, start, block_start,
7347 len, block_len, type);
7350 free_extent_map(em);
7351 btrfs_drop_extent_cache(BTRFS_I(inode), start,
7352 start + len - 1, 0);
7361 static struct extent_map *btrfs_new_extent_direct(struct inode *inode,
7364 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7365 struct btrfs_root *root = BTRFS_I(inode)->root;
7366 struct extent_map *em;
7367 struct btrfs_key ins;
7371 alloc_hint = get_extent_allocation_hint(inode, start, len);
7372 ret = btrfs_reserve_extent(root, len, len, fs_info->sectorsize,
7373 0, alloc_hint, &ins, 1, 1);
7375 return ERR_PTR(ret);
7377 em = btrfs_create_dio_extent(inode, start, ins.offset, start,
7378 ins.objectid, ins.offset, ins.offset,
7379 ins.offset, BTRFS_ORDERED_REGULAR);
7380 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
7382 btrfs_free_reserved_extent(fs_info, ins.objectid,
7389 * returns 1 when the nocow is safe, < 1 on error, 0 if the
7390 * block must be cow'd
7392 noinline int can_nocow_extent(struct inode *inode, u64 offset, u64 *len,
7393 u64 *orig_start, u64 *orig_block_len,
7396 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7397 struct btrfs_path *path;
7399 struct extent_buffer *leaf;
7400 struct btrfs_root *root = BTRFS_I(inode)->root;
7401 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
7402 struct btrfs_file_extent_item *fi;
7403 struct btrfs_key key;
7410 bool nocow = (BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW);
7412 path = btrfs_alloc_path();
7416 ret = btrfs_lookup_file_extent(NULL, root, path,
7417 btrfs_ino(BTRFS_I(inode)), offset, 0);
7421 slot = path->slots[0];
7424 /* can't find the item, must cow */
7431 leaf = path->nodes[0];
7432 btrfs_item_key_to_cpu(leaf, &key, slot);
7433 if (key.objectid != btrfs_ino(BTRFS_I(inode)) ||
7434 key.type != BTRFS_EXTENT_DATA_KEY) {
7435 /* not our file or wrong item type, must cow */
7439 if (key.offset > offset) {
7440 /* Wrong offset, must cow */
7444 fi = btrfs_item_ptr(leaf, slot, struct btrfs_file_extent_item);
7445 found_type = btrfs_file_extent_type(leaf, fi);
7446 if (found_type != BTRFS_FILE_EXTENT_REG &&
7447 found_type != BTRFS_FILE_EXTENT_PREALLOC) {
7448 /* not a regular extent, must cow */
7452 if (!nocow && found_type == BTRFS_FILE_EXTENT_REG)
7455 extent_end = key.offset + btrfs_file_extent_num_bytes(leaf, fi);
7456 if (extent_end <= offset)
7459 disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
7460 if (disk_bytenr == 0)
7463 if (btrfs_file_extent_compression(leaf, fi) ||
7464 btrfs_file_extent_encryption(leaf, fi) ||
7465 btrfs_file_extent_other_encoding(leaf, fi))
7468 backref_offset = btrfs_file_extent_offset(leaf, fi);
7471 *orig_start = key.offset - backref_offset;
7472 *orig_block_len = btrfs_file_extent_disk_num_bytes(leaf, fi);
7473 *ram_bytes = btrfs_file_extent_ram_bytes(leaf, fi);
7476 if (btrfs_extent_readonly(fs_info, disk_bytenr))
7479 num_bytes = min(offset + *len, extent_end) - offset;
7480 if (!nocow && found_type == BTRFS_FILE_EXTENT_PREALLOC) {
7483 range_end = round_up(offset + num_bytes,
7484 root->fs_info->sectorsize) - 1;
7485 ret = test_range_bit(io_tree, offset, range_end,
7486 EXTENT_DELALLOC, 0, NULL);
7493 btrfs_release_path(path);
7496 * look for other files referencing this extent, if we
7497 * find any we must cow
7500 ret = btrfs_cross_ref_exist(root, btrfs_ino(BTRFS_I(inode)),
7501 key.offset - backref_offset, disk_bytenr);
7508 * adjust disk_bytenr and num_bytes to cover just the bytes
7509 * in this extent we are about to write. If there
7510 * are any csums in that range we have to cow in order
7511 * to keep the csums correct
7513 disk_bytenr += backref_offset;
7514 disk_bytenr += offset - key.offset;
7515 if (csum_exist_in_range(fs_info, disk_bytenr, num_bytes))
7518 * all of the above have passed, it is safe to overwrite this extent
7524 btrfs_free_path(path);
7528 bool btrfs_page_exists_in_range(struct inode *inode, loff_t start, loff_t end)
7530 struct radix_tree_root *root = &inode->i_mapping->page_tree;
7532 void **pagep = NULL;
7533 struct page *page = NULL;
7534 unsigned long start_idx;
7535 unsigned long end_idx;
7537 start_idx = start >> PAGE_SHIFT;
7540 * end is the last byte in the last page. end == start is legal
7542 end_idx = end >> PAGE_SHIFT;
7546 /* Most of the code in this while loop is lifted from
7547 * find_get_page. It's been modified to begin searching from a
7548 * page and return just the first page found in that range. If the
7549 * found idx is less than or equal to the end idx then we know that
7550 * a page exists. If no pages are found or if those pages are
7551 * outside of the range then we're fine (yay!) */
7552 while (page == NULL &&
7553 radix_tree_gang_lookup_slot(root, &pagep, NULL, start_idx, 1)) {
7554 page = radix_tree_deref_slot(pagep);
7555 if (unlikely(!page))
7558 if (radix_tree_exception(page)) {
7559 if (radix_tree_deref_retry(page)) {
7564 * Otherwise, shmem/tmpfs must be storing a swap entry
7565 * here as an exceptional entry: so return it without
7566 * attempting to raise page count.
7569 break; /* TODO: Is this relevant for this use case? */
7572 if (!page_cache_get_speculative(page)) {
7578 * Has the page moved?
7579 * This is part of the lockless pagecache protocol. See
7580 * include/linux/pagemap.h for details.
7582 if (unlikely(page != *pagep)) {
7589 if (page->index <= end_idx)
7598 static int lock_extent_direct(struct inode *inode, u64 lockstart, u64 lockend,
7599 struct extent_state **cached_state, int writing)
7601 struct btrfs_ordered_extent *ordered;
7605 lock_extent_bits(&BTRFS_I(inode)->io_tree, lockstart, lockend,
7608 * We're concerned with the entire range that we're going to be
7609 * doing DIO to, so we need to make sure there's no ordered
7610 * extents in this range.
7612 ordered = btrfs_lookup_ordered_range(BTRFS_I(inode), lockstart,
7613 lockend - lockstart + 1);
7616 * We need to make sure there are no buffered pages in this
7617 * range either, we could have raced between the invalidate in
7618 * generic_file_direct_write and locking the extent. The
7619 * invalidate needs to happen so that reads after a write do not
7624 !btrfs_page_exists_in_range(inode, lockstart, lockend)))
7627 unlock_extent_cached(&BTRFS_I(inode)->io_tree, lockstart, lockend,
7628 cached_state, GFP_NOFS);
7632 * If we are doing a DIO read and the ordered extent we
7633 * found is for a buffered write, we can not wait for it
7634 * to complete and retry, because if we do so we can
7635 * deadlock with concurrent buffered writes on page
7636 * locks. This happens only if our DIO read covers more
7637 * than one extent map, if at this point has already
7638 * created an ordered extent for a previous extent map
7639 * and locked its range in the inode's io tree, and a
7640 * concurrent write against that previous extent map's
7641 * range and this range started (we unlock the ranges
7642 * in the io tree only when the bios complete and
7643 * buffered writes always lock pages before attempting
7644 * to lock range in the io tree).
7647 test_bit(BTRFS_ORDERED_DIRECT, &ordered->flags))
7648 btrfs_start_ordered_extent(inode, ordered, 1);
7651 btrfs_put_ordered_extent(ordered);
7654 * We could trigger writeback for this range (and wait
7655 * for it to complete) and then invalidate the pages for
7656 * this range (through invalidate_inode_pages2_range()),
7657 * but that can lead us to a deadlock with a concurrent
7658 * call to readpages() (a buffered read or a defrag call
7659 * triggered a readahead) on a page lock due to an
7660 * ordered dio extent we created before but did not have
7661 * yet a corresponding bio submitted (whence it can not
7662 * complete), which makes readpages() wait for that
7663 * ordered extent to complete while holding a lock on
7678 /* The callers of this must take lock_extent() */
7679 static struct extent_map *create_io_em(struct inode *inode, u64 start, u64 len,
7680 u64 orig_start, u64 block_start,
7681 u64 block_len, u64 orig_block_len,
7682 u64 ram_bytes, int compress_type,
7685 struct extent_map_tree *em_tree;
7686 struct extent_map *em;
7687 struct btrfs_root *root = BTRFS_I(inode)->root;
7690 ASSERT(type == BTRFS_ORDERED_PREALLOC ||
7691 type == BTRFS_ORDERED_COMPRESSED ||
7692 type == BTRFS_ORDERED_NOCOW ||
7693 type == BTRFS_ORDERED_REGULAR);
7695 em_tree = &BTRFS_I(inode)->extent_tree;
7696 em = alloc_extent_map();
7698 return ERR_PTR(-ENOMEM);
7701 em->orig_start = orig_start;
7703 em->block_len = block_len;
7704 em->block_start = block_start;
7705 em->bdev = root->fs_info->fs_devices->latest_bdev;
7706 em->orig_block_len = orig_block_len;
7707 em->ram_bytes = ram_bytes;
7708 em->generation = -1;
7709 set_bit(EXTENT_FLAG_PINNED, &em->flags);
7710 if (type == BTRFS_ORDERED_PREALLOC) {
7711 set_bit(EXTENT_FLAG_FILLING, &em->flags);
7712 } else if (type == BTRFS_ORDERED_COMPRESSED) {
7713 set_bit(EXTENT_FLAG_COMPRESSED, &em->flags);
7714 em->compress_type = compress_type;
7718 btrfs_drop_extent_cache(BTRFS_I(inode), em->start,
7719 em->start + em->len - 1, 0);
7720 write_lock(&em_tree->lock);
7721 ret = add_extent_mapping(em_tree, em, 1);
7722 write_unlock(&em_tree->lock);
7724 * The caller has taken lock_extent(), who could race with us
7727 } while (ret == -EEXIST);
7730 free_extent_map(em);
7731 return ERR_PTR(ret);
7734 /* em got 2 refs now, callers needs to do free_extent_map once. */
7738 static int btrfs_get_blocks_direct(struct inode *inode, sector_t iblock,
7739 struct buffer_head *bh_result, int create)
7741 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7742 struct extent_map *em;
7743 struct extent_state *cached_state = NULL;
7744 struct btrfs_dio_data *dio_data = NULL;
7745 u64 start = iblock << inode->i_blkbits;
7746 u64 lockstart, lockend;
7747 u64 len = bh_result->b_size;
7748 int unlock_bits = EXTENT_LOCKED;
7752 unlock_bits |= EXTENT_DIRTY;
7754 len = min_t(u64, len, fs_info->sectorsize);
7757 lockend = start + len - 1;
7759 if (current->journal_info) {
7761 * Need to pull our outstanding extents and set journal_info to NULL so
7762 * that anything that needs to check if there's a transaction doesn't get
7765 dio_data = current->journal_info;
7766 current->journal_info = NULL;
7770 * If this errors out it's because we couldn't invalidate pagecache for
7771 * this range and we need to fallback to buffered.
7773 if (lock_extent_direct(inode, lockstart, lockend, &cached_state,
7779 em = btrfs_get_extent(BTRFS_I(inode), NULL, 0, start, len, 0);
7786 * Ok for INLINE and COMPRESSED extents we need to fallback on buffered
7787 * io. INLINE is special, and we could probably kludge it in here, but
7788 * it's still buffered so for safety lets just fall back to the generic
7791 * For COMPRESSED we _have_ to read the entire extent in so we can
7792 * decompress it, so there will be buffering required no matter what we
7793 * do, so go ahead and fallback to buffered.
7795 * We return -ENOTBLK because that's what makes DIO go ahead and go back
7796 * to buffered IO. Don't blame me, this is the price we pay for using
7799 if (test_bit(EXTENT_FLAG_COMPRESSED, &em->flags) ||
7800 em->block_start == EXTENT_MAP_INLINE) {
7801 free_extent_map(em);
7806 /* Just a good old fashioned hole, return */
7807 if (!create && (em->block_start == EXTENT_MAP_HOLE ||
7808 test_bit(EXTENT_FLAG_PREALLOC, &em->flags))) {
7809 free_extent_map(em);
7814 * We don't allocate a new extent in the following cases
7816 * 1) The inode is marked as NODATACOW. In this case we'll just use the
7818 * 2) The extent is marked as PREALLOC. We're good to go here and can
7819 * just use the extent.
7823 len = min(len, em->len - (start - em->start));
7824 lockstart = start + len;
7828 if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags) ||
7829 ((BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW) &&
7830 em->block_start != EXTENT_MAP_HOLE)) {
7832 u64 block_start, orig_start, orig_block_len, ram_bytes;
7834 if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
7835 type = BTRFS_ORDERED_PREALLOC;
7837 type = BTRFS_ORDERED_NOCOW;
7838 len = min(len, em->len - (start - em->start));
7839 block_start = em->block_start + (start - em->start);
7841 if (can_nocow_extent(inode, start, &len, &orig_start,
7842 &orig_block_len, &ram_bytes) == 1 &&
7843 btrfs_inc_nocow_writers(fs_info, block_start)) {
7844 struct extent_map *em2;
7846 em2 = btrfs_create_dio_extent(inode, start, len,
7847 orig_start, block_start,
7848 len, orig_block_len,
7850 btrfs_dec_nocow_writers(fs_info, block_start);
7851 if (type == BTRFS_ORDERED_PREALLOC) {
7852 free_extent_map(em);
7855 if (em2 && IS_ERR(em2)) {
7860 * For inode marked NODATACOW or extent marked PREALLOC,
7861 * use the existing or preallocated extent, so does not
7862 * need to adjust btrfs_space_info's bytes_may_use.
7864 btrfs_free_reserved_data_space_noquota(inode,
7871 * this will cow the extent, reset the len in case we changed
7874 len = bh_result->b_size;
7875 free_extent_map(em);
7876 em = btrfs_new_extent_direct(inode, start, len);
7881 len = min(len, em->len - (start - em->start));
7883 bh_result->b_blocknr = (em->block_start + (start - em->start)) >>
7885 bh_result->b_size = len;
7886 bh_result->b_bdev = em->bdev;
7887 set_buffer_mapped(bh_result);
7889 if (!test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
7890 set_buffer_new(bh_result);
7893 * Need to update the i_size under the extent lock so buffered
7894 * readers will get the updated i_size when we unlock.
7896 if (!dio_data->overwrite && start + len > i_size_read(inode))
7897 i_size_write(inode, start + len);
7899 WARN_ON(dio_data->reserve < len);
7900 dio_data->reserve -= len;
7901 dio_data->unsubmitted_oe_range_end = start + len;
7902 current->journal_info = dio_data;
7906 * In the case of write we need to clear and unlock the entire range,
7907 * in the case of read we need to unlock only the end area that we
7908 * aren't using if there is any left over space.
7910 if (lockstart < lockend) {
7911 clear_extent_bit(&BTRFS_I(inode)->io_tree, lockstart,
7912 lockend, unlock_bits, 1, 0,
7913 &cached_state, GFP_NOFS);
7915 free_extent_state(cached_state);
7918 free_extent_map(em);
7923 clear_extent_bit(&BTRFS_I(inode)->io_tree, lockstart, lockend,
7924 unlock_bits, 1, 0, &cached_state, GFP_NOFS);
7927 current->journal_info = dio_data;
7931 static inline blk_status_t submit_dio_repair_bio(struct inode *inode,
7935 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7938 BUG_ON(bio_op(bio) == REQ_OP_WRITE);
7942 ret = btrfs_bio_wq_end_io(fs_info, bio, BTRFS_WQ_ENDIO_DIO_REPAIR);
7946 ret = btrfs_map_bio(fs_info, bio, mirror_num, 0);
7952 static int btrfs_check_dio_repairable(struct inode *inode,
7953 struct bio *failed_bio,
7954 struct io_failure_record *failrec,
7957 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7960 num_copies = btrfs_num_copies(fs_info, failrec->logical, failrec->len);
7961 if (num_copies == 1) {
7963 * we only have a single copy of the data, so don't bother with
7964 * all the retry and error correction code that follows. no
7965 * matter what the error is, it is very likely to persist.
7967 btrfs_debug(fs_info,
7968 "Check DIO Repairable: cannot repair, num_copies=%d, next_mirror %d, failed_mirror %d",
7969 num_copies, failrec->this_mirror, failed_mirror);
7973 failrec->failed_mirror = failed_mirror;
7974 failrec->this_mirror++;
7975 if (failrec->this_mirror == failed_mirror)
7976 failrec->this_mirror++;
7978 if (failrec->this_mirror > num_copies) {
7979 btrfs_debug(fs_info,
7980 "Check DIO Repairable: (fail) num_copies=%d, next_mirror %d, failed_mirror %d",
7981 num_copies, failrec->this_mirror, failed_mirror);
7988 static blk_status_t dio_read_error(struct inode *inode, struct bio *failed_bio,
7989 struct page *page, unsigned int pgoff,
7990 u64 start, u64 end, int failed_mirror,
7991 bio_end_io_t *repair_endio, void *repair_arg)
7993 struct io_failure_record *failrec;
7994 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
7995 struct extent_io_tree *failure_tree = &BTRFS_I(inode)->io_failure_tree;
7998 unsigned int read_mode = 0;
8001 blk_status_t status;
8003 BUG_ON(bio_op(failed_bio) == REQ_OP_WRITE);
8005 ret = btrfs_get_io_failure_record(inode, start, end, &failrec);
8007 return errno_to_blk_status(ret);
8009 ret = btrfs_check_dio_repairable(inode, failed_bio, failrec,
8012 free_io_failure(failure_tree, io_tree, failrec);
8013 return BLK_STS_IOERR;
8016 segs = bio_segments(failed_bio);
8018 (failed_bio->bi_io_vec->bv_len > btrfs_inode_sectorsize(inode)))
8019 read_mode |= REQ_FAILFAST_DEV;
8021 isector = start - btrfs_io_bio(failed_bio)->logical;
8022 isector >>= inode->i_sb->s_blocksize_bits;
8023 bio = btrfs_create_repair_bio(inode, failed_bio, failrec, page,
8024 pgoff, isector, repair_endio, repair_arg);
8025 bio_set_op_attrs(bio, REQ_OP_READ, read_mode);
8027 btrfs_debug(BTRFS_I(inode)->root->fs_info,
8028 "repair DIO read error: submitting new dio read[%#x] to this_mirror=%d, in_validation=%d",
8029 read_mode, failrec->this_mirror, failrec->in_validation);
8031 status = submit_dio_repair_bio(inode, bio, failrec->this_mirror);
8033 free_io_failure(failure_tree, io_tree, failrec);
8040 struct btrfs_retry_complete {
8041 struct completion done;
8042 struct inode *inode;
8047 static void btrfs_retry_endio_nocsum(struct bio *bio)
8049 struct btrfs_retry_complete *done = bio->bi_private;
8050 struct inode *inode = done->inode;
8051 struct bio_vec *bvec;
8052 struct extent_io_tree *io_tree, *failure_tree;
8058 ASSERT(bio->bi_vcnt == 1);
8059 io_tree = &BTRFS_I(inode)->io_tree;
8060 failure_tree = &BTRFS_I(inode)->io_failure_tree;
8061 ASSERT(bio->bi_io_vec->bv_len == btrfs_inode_sectorsize(inode));
8064 ASSERT(!bio_flagged(bio, BIO_CLONED));
8065 bio_for_each_segment_all(bvec, bio, i)
8066 clean_io_failure(BTRFS_I(inode)->root->fs_info, failure_tree,
8067 io_tree, done->start, bvec->bv_page,
8068 btrfs_ino(BTRFS_I(inode)), 0);
8070 complete(&done->done);
8074 static blk_status_t __btrfs_correct_data_nocsum(struct inode *inode,
8075 struct btrfs_io_bio *io_bio)
8077 struct btrfs_fs_info *fs_info;
8078 struct bio_vec bvec;
8079 struct bvec_iter iter;
8080 struct btrfs_retry_complete done;
8086 blk_status_t err = BLK_STS_OK;
8088 fs_info = BTRFS_I(inode)->root->fs_info;
8089 sectorsize = fs_info->sectorsize;
8091 start = io_bio->logical;
8093 io_bio->bio.bi_iter = io_bio->iter;
8095 bio_for_each_segment(bvec, &io_bio->bio, iter) {
8096 nr_sectors = BTRFS_BYTES_TO_BLKS(fs_info, bvec.bv_len);
8097 pgoff = bvec.bv_offset;
8099 next_block_or_try_again:
8102 init_completion(&done.done);
8104 ret = dio_read_error(inode, &io_bio->bio, bvec.bv_page,
8105 pgoff, start, start + sectorsize - 1,
8107 btrfs_retry_endio_nocsum, &done);
8113 wait_for_completion_io(&done.done);
8115 if (!done.uptodate) {
8116 /* We might have another mirror, so try again */
8117 goto next_block_or_try_again;
8121 start += sectorsize;
8125 pgoff += sectorsize;
8126 ASSERT(pgoff < PAGE_SIZE);
8127 goto next_block_or_try_again;
8134 static void btrfs_retry_endio(struct bio *bio)
8136 struct btrfs_retry_complete *done = bio->bi_private;
8137 struct btrfs_io_bio *io_bio = btrfs_io_bio(bio);
8138 struct extent_io_tree *io_tree, *failure_tree;
8139 struct inode *inode = done->inode;
8140 struct bio_vec *bvec;
8150 ASSERT(bio->bi_vcnt == 1);
8151 ASSERT(bio->bi_io_vec->bv_len == btrfs_inode_sectorsize(done->inode));
8153 io_tree = &BTRFS_I(inode)->io_tree;
8154 failure_tree = &BTRFS_I(inode)->io_failure_tree;
8156 ASSERT(!bio_flagged(bio, BIO_CLONED));
8157 bio_for_each_segment_all(bvec, bio, i) {
8158 ret = __readpage_endio_check(inode, io_bio, i, bvec->bv_page,
8159 bvec->bv_offset, done->start,
8162 clean_io_failure(BTRFS_I(inode)->root->fs_info,
8163 failure_tree, io_tree, done->start,
8165 btrfs_ino(BTRFS_I(inode)),
8171 done->uptodate = uptodate;
8173 complete(&done->done);
8177 static blk_status_t __btrfs_subio_endio_read(struct inode *inode,
8178 struct btrfs_io_bio *io_bio, blk_status_t err)
8180 struct btrfs_fs_info *fs_info;
8181 struct bio_vec bvec;
8182 struct bvec_iter iter;
8183 struct btrfs_retry_complete done;
8190 bool uptodate = (err == 0);
8192 blk_status_t status;
8194 fs_info = BTRFS_I(inode)->root->fs_info;
8195 sectorsize = fs_info->sectorsize;
8198 start = io_bio->logical;
8200 io_bio->bio.bi_iter = io_bio->iter;
8202 bio_for_each_segment(bvec, &io_bio->bio, iter) {
8203 nr_sectors = BTRFS_BYTES_TO_BLKS(fs_info, bvec.bv_len);
8205 pgoff = bvec.bv_offset;
8208 csum_pos = BTRFS_BYTES_TO_BLKS(fs_info, offset);
8209 ret = __readpage_endio_check(inode, io_bio, csum_pos,
8210 bvec.bv_page, pgoff, start, sectorsize);
8217 init_completion(&done.done);
8219 status = dio_read_error(inode, &io_bio->bio, bvec.bv_page,
8220 pgoff, start, start + sectorsize - 1,
8221 io_bio->mirror_num, btrfs_retry_endio,
8228 wait_for_completion_io(&done.done);
8230 if (!done.uptodate) {
8231 /* We might have another mirror, so try again */
8235 offset += sectorsize;
8236 start += sectorsize;
8242 pgoff += sectorsize;
8243 ASSERT(pgoff < PAGE_SIZE);
8251 static blk_status_t btrfs_subio_endio_read(struct inode *inode,
8252 struct btrfs_io_bio *io_bio, blk_status_t err)
8254 bool skip_csum = BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM;
8258 return __btrfs_correct_data_nocsum(inode, io_bio);
8262 return __btrfs_subio_endio_read(inode, io_bio, err);
8266 static void btrfs_endio_direct_read(struct bio *bio)
8268 struct btrfs_dio_private *dip = bio->bi_private;
8269 struct inode *inode = dip->inode;
8270 struct bio *dio_bio;
8271 struct btrfs_io_bio *io_bio = btrfs_io_bio(bio);
8272 blk_status_t err = bio->bi_status;
8274 if (dip->flags & BTRFS_DIO_ORIG_BIO_SUBMITTED)
8275 err = btrfs_subio_endio_read(inode, io_bio, err);
8277 unlock_extent(&BTRFS_I(inode)->io_tree, dip->logical_offset,
8278 dip->logical_offset + dip->bytes - 1);
8279 dio_bio = dip->dio_bio;
8283 dio_bio->bi_status = err;
8284 dio_end_io(dio_bio);
8287 io_bio->end_io(io_bio, blk_status_to_errno(err));
8291 static void __endio_write_update_ordered(struct inode *inode,
8292 const u64 offset, const u64 bytes,
8293 const bool uptodate)
8295 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
8296 struct btrfs_ordered_extent *ordered = NULL;
8297 struct btrfs_workqueue *wq;
8298 btrfs_work_func_t func;
8299 u64 ordered_offset = offset;
8300 u64 ordered_bytes = bytes;
8304 if (btrfs_is_free_space_inode(BTRFS_I(inode))) {
8305 wq = fs_info->endio_freespace_worker;
8306 func = btrfs_freespace_write_helper;
8308 wq = fs_info->endio_write_workers;
8309 func = btrfs_endio_write_helper;
8313 last_offset = ordered_offset;
8314 ret = btrfs_dec_test_first_ordered_pending(inode, &ordered,
8321 btrfs_init_work(&ordered->work, func, finish_ordered_fn, NULL, NULL);
8322 btrfs_queue_work(wq, &ordered->work);
8325 * If btrfs_dec_test_ordered_pending does not find any ordered extent
8326 * in the range, we can exit.
8328 if (ordered_offset == last_offset)
8331 * our bio might span multiple ordered extents. If we haven't
8332 * completed the accounting for the whole dio, go back and try again
8334 if (ordered_offset < offset + bytes) {
8335 ordered_bytes = offset + bytes - ordered_offset;
8341 static void btrfs_endio_direct_write(struct bio *bio)
8343 struct btrfs_dio_private *dip = bio->bi_private;
8344 struct bio *dio_bio = dip->dio_bio;
8346 __endio_write_update_ordered(dip->inode, dip->logical_offset,
8347 dip->bytes, !bio->bi_status);
8351 dio_bio->bi_status = bio->bi_status;
8352 dio_end_io(dio_bio);
8356 static blk_status_t __btrfs_submit_bio_start_direct_io(void *private_data,
8357 struct bio *bio, int mirror_num,
8358 unsigned long bio_flags, u64 offset)
8360 struct inode *inode = private_data;
8362 ret = btrfs_csum_one_bio(inode, bio, offset, 1);
8363 BUG_ON(ret); /* -ENOMEM */
8367 static void btrfs_end_dio_bio(struct bio *bio)
8369 struct btrfs_dio_private *dip = bio->bi_private;
8370 blk_status_t err = bio->bi_status;
8373 btrfs_warn(BTRFS_I(dip->inode)->root->fs_info,
8374 "direct IO failed ino %llu rw %d,%u sector %#Lx len %u err no %d",
8375 btrfs_ino(BTRFS_I(dip->inode)), bio_op(bio),
8377 (unsigned long long)bio->bi_iter.bi_sector,
8378 bio->bi_iter.bi_size, err);
8380 if (dip->subio_endio)
8381 err = dip->subio_endio(dip->inode, btrfs_io_bio(bio), err);
8387 * before atomic variable goto zero, we must make sure
8388 * dip->errors is perceived to be set.
8390 smp_mb__before_atomic();
8393 /* if there are more bios still pending for this dio, just exit */
8394 if (!atomic_dec_and_test(&dip->pending_bios))
8398 bio_io_error(dip->orig_bio);
8400 dip->dio_bio->bi_status = BLK_STS_OK;
8401 bio_endio(dip->orig_bio);
8407 static inline blk_status_t btrfs_lookup_and_bind_dio_csum(struct inode *inode,
8408 struct btrfs_dio_private *dip,
8412 struct btrfs_io_bio *io_bio = btrfs_io_bio(bio);
8413 struct btrfs_io_bio *orig_io_bio = btrfs_io_bio(dip->orig_bio);
8417 * We load all the csum data we need when we submit
8418 * the first bio to reduce the csum tree search and
8421 if (dip->logical_offset == file_offset) {
8422 ret = btrfs_lookup_bio_sums_dio(inode, dip->orig_bio,
8428 if (bio == dip->orig_bio)
8431 file_offset -= dip->logical_offset;
8432 file_offset >>= inode->i_sb->s_blocksize_bits;
8433 io_bio->csum = (u8 *)(((u32 *)orig_io_bio->csum) + file_offset);
8438 static inline blk_status_t
8439 __btrfs_submit_dio_bio(struct bio *bio, struct inode *inode, u64 file_offset,
8442 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
8443 struct btrfs_dio_private *dip = bio->bi_private;
8444 bool write = bio_op(bio) == REQ_OP_WRITE;
8448 async_submit = !atomic_read(&BTRFS_I(inode)->sync_writers);
8453 ret = btrfs_bio_wq_end_io(fs_info, bio, BTRFS_WQ_ENDIO_DATA);
8458 if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)
8461 if (write && async_submit) {
8462 ret = btrfs_wq_submit_bio(fs_info, bio, 0, 0,
8464 __btrfs_submit_bio_start_direct_io,
8465 __btrfs_submit_bio_done);
8469 * If we aren't doing async submit, calculate the csum of the
8472 ret = btrfs_csum_one_bio(inode, bio, file_offset, 1);
8476 ret = btrfs_lookup_and_bind_dio_csum(inode, dip, bio,
8482 ret = btrfs_map_bio(fs_info, bio, 0, 0);
8488 static int btrfs_submit_direct_hook(struct btrfs_dio_private *dip)
8490 struct inode *inode = dip->inode;
8491 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
8493 struct bio *orig_bio = dip->orig_bio;
8494 u64 start_sector = orig_bio->bi_iter.bi_sector;
8495 u64 file_offset = dip->logical_offset;
8497 int async_submit = 0;
8499 int clone_offset = 0;
8502 blk_status_t status;
8504 map_length = orig_bio->bi_iter.bi_size;
8505 submit_len = map_length;
8506 ret = btrfs_map_block(fs_info, btrfs_op(orig_bio), start_sector << 9,
8507 &map_length, NULL, 0);
8511 if (map_length >= submit_len) {
8513 dip->flags |= BTRFS_DIO_ORIG_BIO_SUBMITTED;
8517 /* async crcs make it difficult to collect full stripe writes. */
8518 if (btrfs_data_alloc_profile(fs_info) & BTRFS_BLOCK_GROUP_RAID56_MASK)
8524 ASSERT(map_length <= INT_MAX);
8525 atomic_inc(&dip->pending_bios);
8527 clone_len = min_t(int, submit_len, map_length);
8530 * This will never fail as it's passing GPF_NOFS and
8531 * the allocation is backed by btrfs_bioset.
8533 bio = btrfs_bio_clone_partial(orig_bio, clone_offset,
8535 bio->bi_private = dip;
8536 bio->bi_end_io = btrfs_end_dio_bio;
8537 btrfs_io_bio(bio)->logical = file_offset;
8539 ASSERT(submit_len >= clone_len);
8540 submit_len -= clone_len;
8541 if (submit_len == 0)
8545 * Increase the count before we submit the bio so we know
8546 * the end IO handler won't happen before we increase the
8547 * count. Otherwise, the dip might get freed before we're
8548 * done setting it up.
8550 atomic_inc(&dip->pending_bios);
8552 status = __btrfs_submit_dio_bio(bio, inode, file_offset,
8556 atomic_dec(&dip->pending_bios);
8560 clone_offset += clone_len;
8561 start_sector += clone_len >> 9;
8562 file_offset += clone_len;
8564 map_length = submit_len;
8565 ret = btrfs_map_block(fs_info, btrfs_op(orig_bio),
8566 start_sector << 9, &map_length, NULL, 0);
8569 } while (submit_len > 0);
8572 status = __btrfs_submit_dio_bio(bio, inode, file_offset, async_submit);
8580 * before atomic variable goto zero, we must
8581 * make sure dip->errors is perceived to be set.
8583 smp_mb__before_atomic();
8584 if (atomic_dec_and_test(&dip->pending_bios))
8585 bio_io_error(dip->orig_bio);
8587 /* bio_end_io() will handle error, so we needn't return it */
8591 static void btrfs_submit_direct(struct bio *dio_bio, struct inode *inode,
8594 struct btrfs_dio_private *dip = NULL;
8595 struct bio *bio = NULL;
8596 struct btrfs_io_bio *io_bio;
8597 bool write = (bio_op(dio_bio) == REQ_OP_WRITE);
8600 bio = btrfs_bio_clone(dio_bio);
8602 dip = kzalloc(sizeof(*dip), GFP_NOFS);
8608 dip->private = dio_bio->bi_private;
8610 dip->logical_offset = file_offset;
8611 dip->bytes = dio_bio->bi_iter.bi_size;
8612 dip->disk_bytenr = (u64)dio_bio->bi_iter.bi_sector << 9;
8613 bio->bi_private = dip;
8614 dip->orig_bio = bio;
8615 dip->dio_bio = dio_bio;
8616 atomic_set(&dip->pending_bios, 0);
8617 io_bio = btrfs_io_bio(bio);
8618 io_bio->logical = file_offset;
8621 bio->bi_end_io = btrfs_endio_direct_write;
8623 bio->bi_end_io = btrfs_endio_direct_read;
8624 dip->subio_endio = btrfs_subio_endio_read;
8628 * Reset the range for unsubmitted ordered extents (to a 0 length range)
8629 * even if we fail to submit a bio, because in such case we do the
8630 * corresponding error handling below and it must not be done a second
8631 * time by btrfs_direct_IO().
8634 struct btrfs_dio_data *dio_data = current->journal_info;
8636 dio_data->unsubmitted_oe_range_end = dip->logical_offset +
8638 dio_data->unsubmitted_oe_range_start =
8639 dio_data->unsubmitted_oe_range_end;
8642 ret = btrfs_submit_direct_hook(dip);
8647 io_bio->end_io(io_bio, ret);
8651 * If we arrived here it means either we failed to submit the dip
8652 * or we either failed to clone the dio_bio or failed to allocate the
8653 * dip. If we cloned the dio_bio and allocated the dip, we can just
8654 * call bio_endio against our io_bio so that we get proper resource
8655 * cleanup if we fail to submit the dip, otherwise, we must do the
8656 * same as btrfs_endio_direct_[write|read] because we can't call these
8657 * callbacks - they require an allocated dip and a clone of dio_bio.
8662 * The end io callbacks free our dip, do the final put on bio
8663 * and all the cleanup and final put for dio_bio (through
8670 __endio_write_update_ordered(inode,
8672 dio_bio->bi_iter.bi_size,
8675 unlock_extent(&BTRFS_I(inode)->io_tree, file_offset,
8676 file_offset + dio_bio->bi_iter.bi_size - 1);
8678 dio_bio->bi_status = BLK_STS_IOERR;
8680 * Releases and cleans up our dio_bio, no need to bio_put()
8681 * nor bio_endio()/bio_io_error() against dio_bio.
8683 dio_end_io(dio_bio);
8690 static ssize_t check_direct_IO(struct btrfs_fs_info *fs_info,
8691 const struct iov_iter *iter, loff_t offset)
8695 unsigned int blocksize_mask = fs_info->sectorsize - 1;
8696 ssize_t retval = -EINVAL;
8698 if (offset & blocksize_mask)
8701 if (iov_iter_alignment(iter) & blocksize_mask)
8704 /* If this is a write we don't need to check anymore */
8705 if (iov_iter_rw(iter) != READ || !iter_is_iovec(iter))
8708 * Check to make sure we don't have duplicate iov_base's in this
8709 * iovec, if so return EINVAL, otherwise we'll get csum errors
8710 * when reading back.
8712 for (seg = 0; seg < iter->nr_segs; seg++) {
8713 for (i = seg + 1; i < iter->nr_segs; i++) {
8714 if (iter->iov[seg].iov_base == iter->iov[i].iov_base)
8723 static ssize_t btrfs_direct_IO(struct kiocb *iocb, struct iov_iter *iter)
8725 struct file *file = iocb->ki_filp;
8726 struct inode *inode = file->f_mapping->host;
8727 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
8728 struct btrfs_dio_data dio_data = { 0 };
8729 struct extent_changeset *data_reserved = NULL;
8730 loff_t offset = iocb->ki_pos;
8734 bool relock = false;
8737 if (check_direct_IO(fs_info, iter, offset))
8740 inode_dio_begin(inode);
8743 * The generic stuff only does filemap_write_and_wait_range, which
8744 * isn't enough if we've written compressed pages to this area, so
8745 * we need to flush the dirty pages again to make absolutely sure
8746 * that any outstanding dirty pages are on disk.
8748 count = iov_iter_count(iter);
8749 if (test_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
8750 &BTRFS_I(inode)->runtime_flags))
8751 filemap_fdatawrite_range(inode->i_mapping, offset,
8752 offset + count - 1);
8754 if (iov_iter_rw(iter) == WRITE) {
8756 * If the write DIO is beyond the EOF, we need update
8757 * the isize, but it is protected by i_mutex. So we can
8758 * not unlock the i_mutex at this case.
8760 if (offset + count <= inode->i_size) {
8761 dio_data.overwrite = 1;
8762 inode_unlock(inode);
8764 } else if (iocb->ki_flags & IOCB_NOWAIT) {
8768 ret = btrfs_delalloc_reserve_space(inode, &data_reserved,
8774 * We need to know how many extents we reserved so that we can
8775 * do the accounting properly if we go over the number we
8776 * originally calculated. Abuse current->journal_info for this.
8778 dio_data.reserve = round_up(count,
8779 fs_info->sectorsize);
8780 dio_data.unsubmitted_oe_range_start = (u64)offset;
8781 dio_data.unsubmitted_oe_range_end = (u64)offset;
8782 current->journal_info = &dio_data;
8783 down_read(&BTRFS_I(inode)->dio_sem);
8784 } else if (test_bit(BTRFS_INODE_READDIO_NEED_LOCK,
8785 &BTRFS_I(inode)->runtime_flags)) {
8786 inode_dio_end(inode);
8787 flags = DIO_LOCKING | DIO_SKIP_HOLES;
8791 ret = __blockdev_direct_IO(iocb, inode,
8792 fs_info->fs_devices->latest_bdev,
8793 iter, btrfs_get_blocks_direct, NULL,
8794 btrfs_submit_direct, flags);
8795 if (iov_iter_rw(iter) == WRITE) {
8796 up_read(&BTRFS_I(inode)->dio_sem);
8797 current->journal_info = NULL;
8798 if (ret < 0 && ret != -EIOCBQUEUED) {
8799 if (dio_data.reserve)
8800 btrfs_delalloc_release_space(inode, data_reserved,
8801 offset, dio_data.reserve);
8803 * On error we might have left some ordered extents
8804 * without submitting corresponding bios for them, so
8805 * cleanup them up to avoid other tasks getting them
8806 * and waiting for them to complete forever.
8808 if (dio_data.unsubmitted_oe_range_start <
8809 dio_data.unsubmitted_oe_range_end)
8810 __endio_write_update_ordered(inode,
8811 dio_data.unsubmitted_oe_range_start,
8812 dio_data.unsubmitted_oe_range_end -
8813 dio_data.unsubmitted_oe_range_start,
8815 } else if (ret >= 0 && (size_t)ret < count)
8816 btrfs_delalloc_release_space(inode, data_reserved,
8817 offset, count - (size_t)ret);
8818 btrfs_delalloc_release_extents(BTRFS_I(inode), count);
8822 inode_dio_end(inode);
8826 extent_changeset_free(data_reserved);
8830 #define BTRFS_FIEMAP_FLAGS (FIEMAP_FLAG_SYNC)
8832 static int btrfs_fiemap(struct inode *inode, struct fiemap_extent_info *fieinfo,
8833 __u64 start, __u64 len)
8837 ret = fiemap_check_flags(fieinfo, BTRFS_FIEMAP_FLAGS);
8841 return extent_fiemap(inode, fieinfo, start, len, btrfs_get_extent_fiemap);
8844 int btrfs_readpage(struct file *file, struct page *page)
8846 struct extent_io_tree *tree;
8847 tree = &BTRFS_I(page->mapping->host)->io_tree;
8848 return extent_read_full_page(tree, page, btrfs_get_extent, 0);
8851 static int btrfs_writepage(struct page *page, struct writeback_control *wbc)
8853 struct extent_io_tree *tree;
8854 struct inode *inode = page->mapping->host;
8857 if (current->flags & PF_MEMALLOC) {
8858 redirty_page_for_writepage(wbc, page);
8864 * If we are under memory pressure we will call this directly from the
8865 * VM, we need to make sure we have the inode referenced for the ordered
8866 * extent. If not just return like we didn't do anything.
8868 if (!igrab(inode)) {
8869 redirty_page_for_writepage(wbc, page);
8870 return AOP_WRITEPAGE_ACTIVATE;
8872 tree = &BTRFS_I(page->mapping->host)->io_tree;
8873 ret = extent_write_full_page(tree, page, btrfs_get_extent, wbc);
8874 btrfs_add_delayed_iput(inode);
8878 static int btrfs_writepages(struct address_space *mapping,
8879 struct writeback_control *wbc)
8881 struct extent_io_tree *tree;
8883 tree = &BTRFS_I(mapping->host)->io_tree;
8884 return extent_writepages(tree, mapping, btrfs_get_extent, wbc);
8888 btrfs_readpages(struct file *file, struct address_space *mapping,
8889 struct list_head *pages, unsigned nr_pages)
8891 struct extent_io_tree *tree;
8892 tree = &BTRFS_I(mapping->host)->io_tree;
8893 return extent_readpages(tree, mapping, pages, nr_pages,
8896 static int __btrfs_releasepage(struct page *page, gfp_t gfp_flags)
8898 struct extent_io_tree *tree;
8899 struct extent_map_tree *map;
8902 tree = &BTRFS_I(page->mapping->host)->io_tree;
8903 map = &BTRFS_I(page->mapping->host)->extent_tree;
8904 ret = try_release_extent_mapping(map, tree, page, gfp_flags);
8906 ClearPagePrivate(page);
8907 set_page_private(page, 0);
8913 static int btrfs_releasepage(struct page *page, gfp_t gfp_flags)
8915 if (PageWriteback(page) || PageDirty(page))
8917 return __btrfs_releasepage(page, gfp_flags);
8920 static void btrfs_invalidatepage(struct page *page, unsigned int offset,
8921 unsigned int length)
8923 struct inode *inode = page->mapping->host;
8924 struct extent_io_tree *tree;
8925 struct btrfs_ordered_extent *ordered;
8926 struct extent_state *cached_state = NULL;
8927 u64 page_start = page_offset(page);
8928 u64 page_end = page_start + PAGE_SIZE - 1;
8931 int inode_evicting = inode->i_state & I_FREEING;
8934 * we have the page locked, so new writeback can't start,
8935 * and the dirty bit won't be cleared while we are here.
8937 * Wait for IO on this page so that we can safely clear
8938 * the PagePrivate2 bit and do ordered accounting
8940 wait_on_page_writeback(page);
8942 tree = &BTRFS_I(inode)->io_tree;
8944 btrfs_releasepage(page, GFP_NOFS);
8948 if (!inode_evicting)
8949 lock_extent_bits(tree, page_start, page_end, &cached_state);
8952 ordered = btrfs_lookup_ordered_range(BTRFS_I(inode), start,
8953 page_end - start + 1);
8955 end = min(page_end, ordered->file_offset + ordered->len - 1);
8957 * IO on this page will never be started, so we need
8958 * to account for any ordered extents now
8960 if (!inode_evicting)
8961 clear_extent_bit(tree, start, end,
8962 EXTENT_DIRTY | EXTENT_DELALLOC |
8963 EXTENT_DELALLOC_NEW |
8964 EXTENT_LOCKED | EXTENT_DO_ACCOUNTING |
8965 EXTENT_DEFRAG, 1, 0, &cached_state,
8968 * whoever cleared the private bit is responsible
8969 * for the finish_ordered_io
8971 if (TestClearPagePrivate2(page)) {
8972 struct btrfs_ordered_inode_tree *tree;
8975 tree = &BTRFS_I(inode)->ordered_tree;
8977 spin_lock_irq(&tree->lock);
8978 set_bit(BTRFS_ORDERED_TRUNCATED, &ordered->flags);
8979 new_len = start - ordered->file_offset;
8980 if (new_len < ordered->truncated_len)
8981 ordered->truncated_len = new_len;
8982 spin_unlock_irq(&tree->lock);
8984 if (btrfs_dec_test_ordered_pending(inode, &ordered,
8986 end - start + 1, 1))
8987 btrfs_finish_ordered_io(ordered);
8989 btrfs_put_ordered_extent(ordered);
8990 if (!inode_evicting) {
8991 cached_state = NULL;
8992 lock_extent_bits(tree, start, end,
8997 if (start < page_end)
9002 * Qgroup reserved space handler
9003 * Page here will be either
9004 * 1) Already written to disk
9005 * In this case, its reserved space is released from data rsv map
9006 * and will be freed by delayed_ref handler finally.
9007 * So even we call qgroup_free_data(), it won't decrease reserved
9009 * 2) Not written to disk
9010 * This means the reserved space should be freed here. However,
9011 * if a truncate invalidates the page (by clearing PageDirty)
9012 * and the page is accounted for while allocating extent
9013 * in btrfs_check_data_free_space() we let delayed_ref to
9014 * free the entire extent.
9016 if (PageDirty(page))
9017 btrfs_qgroup_free_data(inode, NULL, page_start, PAGE_SIZE);
9018 if (!inode_evicting) {
9019 clear_extent_bit(tree, page_start, page_end,
9020 EXTENT_LOCKED | EXTENT_DIRTY |
9021 EXTENT_DELALLOC | EXTENT_DELALLOC_NEW |
9022 EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG, 1, 1,
9023 &cached_state, GFP_NOFS);
9025 __btrfs_releasepage(page, GFP_NOFS);
9028 ClearPageChecked(page);
9029 if (PagePrivate(page)) {
9030 ClearPagePrivate(page);
9031 set_page_private(page, 0);
9037 * btrfs_page_mkwrite() is not allowed to change the file size as it gets
9038 * called from a page fault handler when a page is first dirtied. Hence we must
9039 * be careful to check for EOF conditions here. We set the page up correctly
9040 * for a written page which means we get ENOSPC checking when writing into
9041 * holes and correct delalloc and unwritten extent mapping on filesystems that
9042 * support these features.
9044 * We are not allowed to take the i_mutex here so we have to play games to
9045 * protect against truncate races as the page could now be beyond EOF. Because
9046 * vmtruncate() writes the inode size before removing pages, once we have the
9047 * page lock we can determine safely if the page is beyond EOF. If it is not
9048 * beyond EOF, then the page is guaranteed safe against truncation until we
9051 int btrfs_page_mkwrite(struct vm_fault *vmf)
9053 struct page *page = vmf->page;
9054 struct inode *inode = file_inode(vmf->vma->vm_file);
9055 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
9056 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
9057 struct btrfs_ordered_extent *ordered;
9058 struct extent_state *cached_state = NULL;
9059 struct extent_changeset *data_reserved = NULL;
9061 unsigned long zero_start;
9070 reserved_space = PAGE_SIZE;
9072 sb_start_pagefault(inode->i_sb);
9073 page_start = page_offset(page);
9074 page_end = page_start + PAGE_SIZE - 1;
9078 * Reserving delalloc space after obtaining the page lock can lead to
9079 * deadlock. For example, if a dirty page is locked by this function
9080 * and the call to btrfs_delalloc_reserve_space() ends up triggering
9081 * dirty page write out, then the btrfs_writepage() function could
9082 * end up waiting indefinitely to get a lock on the page currently
9083 * being processed by btrfs_page_mkwrite() function.
9085 ret = btrfs_delalloc_reserve_space(inode, &data_reserved, page_start,
9088 ret = file_update_time(vmf->vma->vm_file);
9094 else /* -ENOSPC, -EIO, etc */
9095 ret = VM_FAULT_SIGBUS;
9101 ret = VM_FAULT_NOPAGE; /* make the VM retry the fault */
9104 size = i_size_read(inode);
9106 if ((page->mapping != inode->i_mapping) ||
9107 (page_start >= size)) {
9108 /* page got truncated out from underneath us */
9111 wait_on_page_writeback(page);
9113 lock_extent_bits(io_tree, page_start, page_end, &cached_state);
9114 set_page_extent_mapped(page);
9117 * we can't set the delalloc bits if there are pending ordered
9118 * extents. Drop our locks and wait for them to finish
9120 ordered = btrfs_lookup_ordered_range(BTRFS_I(inode), page_start,
9123 unlock_extent_cached(io_tree, page_start, page_end,
9124 &cached_state, GFP_NOFS);
9126 btrfs_start_ordered_extent(inode, ordered, 1);
9127 btrfs_put_ordered_extent(ordered);
9131 if (page->index == ((size - 1) >> PAGE_SHIFT)) {
9132 reserved_space = round_up(size - page_start,
9133 fs_info->sectorsize);
9134 if (reserved_space < PAGE_SIZE) {
9135 end = page_start + reserved_space - 1;
9136 btrfs_delalloc_release_space(inode, data_reserved,
9137 page_start, PAGE_SIZE - reserved_space);
9142 * page_mkwrite gets called when the page is firstly dirtied after it's
9143 * faulted in, but write(2) could also dirty a page and set delalloc
9144 * bits, thus in this case for space account reason, we still need to
9145 * clear any delalloc bits within this page range since we have to
9146 * reserve data&meta space before lock_page() (see above comments).
9148 clear_extent_bit(&BTRFS_I(inode)->io_tree, page_start, end,
9149 EXTENT_DIRTY | EXTENT_DELALLOC |
9150 EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG,
9151 0, 0, &cached_state, GFP_NOFS);
9153 ret = btrfs_set_extent_delalloc(inode, page_start, end,
9156 unlock_extent_cached(io_tree, page_start, page_end,
9157 &cached_state, GFP_NOFS);
9158 ret = VM_FAULT_SIGBUS;
9163 /* page is wholly or partially inside EOF */
9164 if (page_start + PAGE_SIZE > size)
9165 zero_start = size & ~PAGE_MASK;
9167 zero_start = PAGE_SIZE;
9169 if (zero_start != PAGE_SIZE) {
9171 memset(kaddr + zero_start, 0, PAGE_SIZE - zero_start);
9172 flush_dcache_page(page);
9175 ClearPageChecked(page);
9176 set_page_dirty(page);
9177 SetPageUptodate(page);
9179 BTRFS_I(inode)->last_trans = fs_info->generation;
9180 BTRFS_I(inode)->last_sub_trans = BTRFS_I(inode)->root->log_transid;
9181 BTRFS_I(inode)->last_log_commit = BTRFS_I(inode)->root->last_log_commit;
9183 unlock_extent_cached(io_tree, page_start, page_end, &cached_state, GFP_NOFS);
9187 btrfs_delalloc_release_extents(BTRFS_I(inode), PAGE_SIZE);
9188 sb_end_pagefault(inode->i_sb);
9189 extent_changeset_free(data_reserved);
9190 return VM_FAULT_LOCKED;
9194 btrfs_delalloc_release_extents(BTRFS_I(inode), PAGE_SIZE);
9195 btrfs_delalloc_release_space(inode, data_reserved, page_start,
9198 sb_end_pagefault(inode->i_sb);
9199 extent_changeset_free(data_reserved);
9203 static int btrfs_truncate(struct inode *inode)
9205 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
9206 struct btrfs_root *root = BTRFS_I(inode)->root;
9207 struct btrfs_block_rsv *rsv;
9210 struct btrfs_trans_handle *trans;
9211 u64 mask = fs_info->sectorsize - 1;
9212 u64 min_size = btrfs_calc_trunc_metadata_size(fs_info, 1);
9214 ret = btrfs_wait_ordered_range(inode, inode->i_size & (~mask),
9220 * Yes ladies and gentlemen, this is indeed ugly. The fact is we have
9221 * 3 things going on here
9223 * 1) We need to reserve space for our orphan item and the space to
9224 * delete our orphan item. Lord knows we don't want to have a dangling
9225 * orphan item because we didn't reserve space to remove it.
9227 * 2) We need to reserve space to update our inode.
9229 * 3) We need to have something to cache all the space that is going to
9230 * be free'd up by the truncate operation, but also have some slack
9231 * space reserved in case it uses space during the truncate (thank you
9232 * very much snapshotting).
9234 * And we need these to all be separate. The fact is we can use a lot of
9235 * space doing the truncate, and we have no earthly idea how much space
9236 * we will use, so we need the truncate reservation to be separate so it
9237 * doesn't end up using space reserved for updating the inode or
9238 * removing the orphan item. We also need to be able to stop the
9239 * transaction and start a new one, which means we need to be able to
9240 * update the inode several times, and we have no idea of knowing how
9241 * many times that will be, so we can't just reserve 1 item for the
9242 * entirety of the operation, so that has to be done separately as well.
9243 * Then there is the orphan item, which does indeed need to be held on
9244 * to for the whole operation, and we need nobody to touch this reserved
9245 * space except the orphan code.
9247 * So that leaves us with
9249 * 1) root->orphan_block_rsv - for the orphan deletion.
9250 * 2) rsv - for the truncate reservation, which we will steal from the
9251 * transaction reservation.
9252 * 3) fs_info->trans_block_rsv - this will have 1 items worth left for
9253 * updating the inode.
9255 rsv = btrfs_alloc_block_rsv(fs_info, BTRFS_BLOCK_RSV_TEMP);
9258 rsv->size = min_size;
9262 * 1 for the truncate slack space
9263 * 1 for updating the inode.
9265 trans = btrfs_start_transaction(root, 2);
9266 if (IS_ERR(trans)) {
9267 err = PTR_ERR(trans);
9271 /* Migrate the slack space for the truncate to our reserve */
9272 ret = btrfs_block_rsv_migrate(&fs_info->trans_block_rsv, rsv,
9277 * So if we truncate and then write and fsync we normally would just
9278 * write the extents that changed, which is a problem if we need to
9279 * first truncate that entire inode. So set this flag so we write out
9280 * all of the extents in the inode to the sync log so we're completely
9283 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &BTRFS_I(inode)->runtime_flags);
9284 trans->block_rsv = rsv;
9287 ret = btrfs_truncate_inode_items(trans, root, inode,
9289 BTRFS_EXTENT_DATA_KEY);
9290 trans->block_rsv = &fs_info->trans_block_rsv;
9291 if (ret != -ENOSPC && ret != -EAGAIN) {
9296 ret = btrfs_update_inode(trans, root, inode);
9302 btrfs_end_transaction(trans);
9303 btrfs_btree_balance_dirty(fs_info);
9305 trans = btrfs_start_transaction(root, 2);
9306 if (IS_ERR(trans)) {
9307 ret = err = PTR_ERR(trans);
9312 btrfs_block_rsv_release(fs_info, rsv, -1);
9313 ret = btrfs_block_rsv_migrate(&fs_info->trans_block_rsv,
9315 BUG_ON(ret); /* shouldn't happen */
9316 trans->block_rsv = rsv;
9320 * We can't call btrfs_truncate_block inside a trans handle as we could
9321 * deadlock with freeze, if we got NEED_TRUNCATE_BLOCK then we know
9322 * we've truncated everything except the last little bit, and can do
9323 * btrfs_truncate_block and then update the disk_i_size.
9325 if (ret == NEED_TRUNCATE_BLOCK) {
9326 btrfs_end_transaction(trans);
9327 btrfs_btree_balance_dirty(fs_info);
9329 ret = btrfs_truncate_block(inode, inode->i_size, 0, 0);
9332 trans = btrfs_start_transaction(root, 1);
9333 if (IS_ERR(trans)) {
9334 ret = PTR_ERR(trans);
9337 btrfs_ordered_update_i_size(inode, inode->i_size, NULL);
9340 if (ret == 0 && inode->i_nlink > 0) {
9341 trans->block_rsv = root->orphan_block_rsv;
9342 ret = btrfs_orphan_del(trans, BTRFS_I(inode));
9348 trans->block_rsv = &fs_info->trans_block_rsv;
9349 ret = btrfs_update_inode(trans, root, inode);
9353 ret = btrfs_end_transaction(trans);
9354 btrfs_btree_balance_dirty(fs_info);
9357 btrfs_free_block_rsv(fs_info, rsv);
9366 * create a new subvolume directory/inode (helper for the ioctl).
9368 int btrfs_create_subvol_root(struct btrfs_trans_handle *trans,
9369 struct btrfs_root *new_root,
9370 struct btrfs_root *parent_root,
9373 struct inode *inode;
9377 inode = btrfs_new_inode(trans, new_root, NULL, "..", 2,
9378 new_dirid, new_dirid,
9379 S_IFDIR | (~current_umask() & S_IRWXUGO),
9382 return PTR_ERR(inode);
9383 inode->i_op = &btrfs_dir_inode_operations;
9384 inode->i_fop = &btrfs_dir_file_operations;
9386 set_nlink(inode, 1);
9387 btrfs_i_size_write(BTRFS_I(inode), 0);
9388 unlock_new_inode(inode);
9390 err = btrfs_subvol_inherit_props(trans, new_root, parent_root);
9392 btrfs_err(new_root->fs_info,
9393 "error inheriting subvolume %llu properties: %d",
9394 new_root->root_key.objectid, err);
9396 err = btrfs_update_inode(trans, new_root, inode);
9402 struct inode *btrfs_alloc_inode(struct super_block *sb)
9404 struct btrfs_fs_info *fs_info = btrfs_sb(sb);
9405 struct btrfs_inode *ei;
9406 struct inode *inode;
9408 ei = kmem_cache_alloc(btrfs_inode_cachep, GFP_NOFS);
9415 ei->last_sub_trans = 0;
9416 ei->logged_trans = 0;
9417 ei->delalloc_bytes = 0;
9418 ei->new_delalloc_bytes = 0;
9419 ei->defrag_bytes = 0;
9420 ei->disk_i_size = 0;
9423 ei->index_cnt = (u64)-1;
9425 ei->last_unlink_trans = 0;
9426 ei->last_log_commit = 0;
9427 ei->delayed_iput_count = 0;
9429 spin_lock_init(&ei->lock);
9430 ei->outstanding_extents = 0;
9431 if (sb->s_magic != BTRFS_TEST_MAGIC)
9432 btrfs_init_metadata_block_rsv(fs_info, &ei->block_rsv,
9433 BTRFS_BLOCK_RSV_DELALLOC);
9434 ei->runtime_flags = 0;
9435 ei->prop_compress = BTRFS_COMPRESS_NONE;
9436 ei->defrag_compress = BTRFS_COMPRESS_NONE;
9438 ei->delayed_node = NULL;
9440 ei->i_otime.tv_sec = 0;
9441 ei->i_otime.tv_nsec = 0;
9443 inode = &ei->vfs_inode;
9444 extent_map_tree_init(&ei->extent_tree);
9445 extent_io_tree_init(&ei->io_tree, inode);
9446 extent_io_tree_init(&ei->io_failure_tree, inode);
9447 ei->io_tree.track_uptodate = 1;
9448 ei->io_failure_tree.track_uptodate = 1;
9449 atomic_set(&ei->sync_writers, 0);
9450 mutex_init(&ei->log_mutex);
9451 mutex_init(&ei->delalloc_mutex);
9452 btrfs_ordered_inode_tree_init(&ei->ordered_tree);
9453 INIT_LIST_HEAD(&ei->delalloc_inodes);
9454 INIT_LIST_HEAD(&ei->delayed_iput);
9455 RB_CLEAR_NODE(&ei->rb_node);
9456 init_rwsem(&ei->dio_sem);
9461 #ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
9462 void btrfs_test_destroy_inode(struct inode *inode)
9464 btrfs_drop_extent_cache(BTRFS_I(inode), 0, (u64)-1, 0);
9465 kmem_cache_free(btrfs_inode_cachep, BTRFS_I(inode));
9469 static void btrfs_i_callback(struct rcu_head *head)
9471 struct inode *inode = container_of(head, struct inode, i_rcu);
9472 kmem_cache_free(btrfs_inode_cachep, BTRFS_I(inode));
9475 void btrfs_destroy_inode(struct inode *inode)
9477 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
9478 struct btrfs_ordered_extent *ordered;
9479 struct btrfs_root *root = BTRFS_I(inode)->root;
9481 WARN_ON(!hlist_empty(&inode->i_dentry));
9482 WARN_ON(inode->i_data.nrpages);
9483 WARN_ON(BTRFS_I(inode)->block_rsv.reserved);
9484 WARN_ON(BTRFS_I(inode)->block_rsv.size);
9485 WARN_ON(BTRFS_I(inode)->outstanding_extents);
9486 WARN_ON(BTRFS_I(inode)->delalloc_bytes);
9487 WARN_ON(BTRFS_I(inode)->new_delalloc_bytes);
9488 WARN_ON(BTRFS_I(inode)->csum_bytes);
9489 WARN_ON(BTRFS_I(inode)->defrag_bytes);
9492 * This can happen where we create an inode, but somebody else also
9493 * created the same inode and we need to destroy the one we already
9499 if (test_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
9500 &BTRFS_I(inode)->runtime_flags)) {
9501 btrfs_info(fs_info, "inode %llu still on the orphan list",
9502 btrfs_ino(BTRFS_I(inode)));
9503 atomic_dec(&root->orphan_inodes);
9507 ordered = btrfs_lookup_first_ordered_extent(inode, (u64)-1);
9512 "found ordered extent %llu %llu on inode cleanup",
9513 ordered->file_offset, ordered->len);
9514 btrfs_remove_ordered_extent(inode, ordered);
9515 btrfs_put_ordered_extent(ordered);
9516 btrfs_put_ordered_extent(ordered);
9519 btrfs_qgroup_check_reserved_leak(inode);
9520 inode_tree_del(inode);
9521 btrfs_drop_extent_cache(BTRFS_I(inode), 0, (u64)-1, 0);
9523 call_rcu(&inode->i_rcu, btrfs_i_callback);
9526 int btrfs_drop_inode(struct inode *inode)
9528 struct btrfs_root *root = BTRFS_I(inode)->root;
9533 /* the snap/subvol tree is on deleting */
9534 if (btrfs_root_refs(&root->root_item) == 0)
9537 return generic_drop_inode(inode);
9540 static void init_once(void *foo)
9542 struct btrfs_inode *ei = (struct btrfs_inode *) foo;
9544 inode_init_once(&ei->vfs_inode);
9547 void btrfs_destroy_cachep(void)
9550 * Make sure all delayed rcu free inodes are flushed before we
9554 kmem_cache_destroy(btrfs_inode_cachep);
9555 kmem_cache_destroy(btrfs_trans_handle_cachep);
9556 kmem_cache_destroy(btrfs_path_cachep);
9557 kmem_cache_destroy(btrfs_free_space_cachep);
9560 int btrfs_init_cachep(void)
9562 btrfs_inode_cachep = kmem_cache_create("btrfs_inode",
9563 sizeof(struct btrfs_inode), 0,
9564 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD | SLAB_ACCOUNT,
9566 if (!btrfs_inode_cachep)
9569 btrfs_trans_handle_cachep = kmem_cache_create("btrfs_trans_handle",
9570 sizeof(struct btrfs_trans_handle), 0,
9571 SLAB_TEMPORARY | SLAB_MEM_SPREAD, NULL);
9572 if (!btrfs_trans_handle_cachep)
9575 btrfs_path_cachep = kmem_cache_create("btrfs_path",
9576 sizeof(struct btrfs_path), 0,
9577 SLAB_MEM_SPREAD, NULL);
9578 if (!btrfs_path_cachep)
9581 btrfs_free_space_cachep = kmem_cache_create("btrfs_free_space",
9582 sizeof(struct btrfs_free_space), 0,
9583 SLAB_MEM_SPREAD, NULL);
9584 if (!btrfs_free_space_cachep)
9589 btrfs_destroy_cachep();
9593 static int btrfs_getattr(const struct path *path, struct kstat *stat,
9594 u32 request_mask, unsigned int flags)
9597 struct inode *inode = d_inode(path->dentry);
9598 u32 blocksize = inode->i_sb->s_blocksize;
9599 u32 bi_flags = BTRFS_I(inode)->flags;
9601 stat->result_mask |= STATX_BTIME;
9602 stat->btime.tv_sec = BTRFS_I(inode)->i_otime.tv_sec;
9603 stat->btime.tv_nsec = BTRFS_I(inode)->i_otime.tv_nsec;
9604 if (bi_flags & BTRFS_INODE_APPEND)
9605 stat->attributes |= STATX_ATTR_APPEND;
9606 if (bi_flags & BTRFS_INODE_COMPRESS)
9607 stat->attributes |= STATX_ATTR_COMPRESSED;
9608 if (bi_flags & BTRFS_INODE_IMMUTABLE)
9609 stat->attributes |= STATX_ATTR_IMMUTABLE;
9610 if (bi_flags & BTRFS_INODE_NODUMP)
9611 stat->attributes |= STATX_ATTR_NODUMP;
9613 stat->attributes_mask |= (STATX_ATTR_APPEND |
9614 STATX_ATTR_COMPRESSED |
9615 STATX_ATTR_IMMUTABLE |
9618 generic_fillattr(inode, stat);
9619 stat->dev = BTRFS_I(inode)->root->anon_dev;
9621 spin_lock(&BTRFS_I(inode)->lock);
9622 delalloc_bytes = BTRFS_I(inode)->new_delalloc_bytes;
9623 spin_unlock(&BTRFS_I(inode)->lock);
9624 stat->blocks = (ALIGN(inode_get_bytes(inode), blocksize) +
9625 ALIGN(delalloc_bytes, blocksize)) >> 9;
9629 static int btrfs_rename_exchange(struct inode *old_dir,
9630 struct dentry *old_dentry,
9631 struct inode *new_dir,
9632 struct dentry *new_dentry)
9634 struct btrfs_fs_info *fs_info = btrfs_sb(old_dir->i_sb);
9635 struct btrfs_trans_handle *trans;
9636 struct btrfs_root *root = BTRFS_I(old_dir)->root;
9637 struct btrfs_root *dest = BTRFS_I(new_dir)->root;
9638 struct inode *new_inode = new_dentry->d_inode;
9639 struct inode *old_inode = old_dentry->d_inode;
9640 struct timespec ctime = current_time(old_inode);
9641 struct dentry *parent;
9642 u64 old_ino = btrfs_ino(BTRFS_I(old_inode));
9643 u64 new_ino = btrfs_ino(BTRFS_I(new_inode));
9648 bool root_log_pinned = false;
9649 bool dest_log_pinned = false;
9651 /* we only allow rename subvolume link between subvolumes */
9652 if (old_ino != BTRFS_FIRST_FREE_OBJECTID && root != dest)
9655 /* close the race window with snapshot create/destroy ioctl */
9656 if (old_ino == BTRFS_FIRST_FREE_OBJECTID)
9657 down_read(&fs_info->subvol_sem);
9658 if (new_ino == BTRFS_FIRST_FREE_OBJECTID)
9659 down_read(&fs_info->subvol_sem);
9662 * We want to reserve the absolute worst case amount of items. So if
9663 * both inodes are subvols and we need to unlink them then that would
9664 * require 4 item modifications, but if they are both normal inodes it
9665 * would require 5 item modifications, so we'll assume their normal
9666 * inodes. So 5 * 2 is 10, plus 2 for the new links, so 12 total items
9667 * should cover the worst case number of items we'll modify.
9669 trans = btrfs_start_transaction(root, 12);
9670 if (IS_ERR(trans)) {
9671 ret = PTR_ERR(trans);
9676 * We need to find a free sequence number both in the source and
9677 * in the destination directory for the exchange.
9679 ret = btrfs_set_inode_index(BTRFS_I(new_dir), &old_idx);
9682 ret = btrfs_set_inode_index(BTRFS_I(old_dir), &new_idx);
9686 BTRFS_I(old_inode)->dir_index = 0ULL;
9687 BTRFS_I(new_inode)->dir_index = 0ULL;
9689 /* Reference for the source. */
9690 if (old_ino == BTRFS_FIRST_FREE_OBJECTID) {
9691 /* force full log commit if subvolume involved. */
9692 btrfs_set_log_full_commit(fs_info, trans);
9694 btrfs_pin_log_trans(root);
9695 root_log_pinned = true;
9696 ret = btrfs_insert_inode_ref(trans, dest,
9697 new_dentry->d_name.name,
9698 new_dentry->d_name.len,
9700 btrfs_ino(BTRFS_I(new_dir)),
9706 /* And now for the dest. */
9707 if (new_ino == BTRFS_FIRST_FREE_OBJECTID) {
9708 /* force full log commit if subvolume involved. */
9709 btrfs_set_log_full_commit(fs_info, trans);
9711 btrfs_pin_log_trans(dest);
9712 dest_log_pinned = true;
9713 ret = btrfs_insert_inode_ref(trans, root,
9714 old_dentry->d_name.name,
9715 old_dentry->d_name.len,
9717 btrfs_ino(BTRFS_I(old_dir)),
9723 /* Update inode version and ctime/mtime. */
9724 inode_inc_iversion(old_dir);
9725 inode_inc_iversion(new_dir);
9726 inode_inc_iversion(old_inode);
9727 inode_inc_iversion(new_inode);
9728 old_dir->i_ctime = old_dir->i_mtime = ctime;
9729 new_dir->i_ctime = new_dir->i_mtime = ctime;
9730 old_inode->i_ctime = ctime;
9731 new_inode->i_ctime = ctime;
9733 if (old_dentry->d_parent != new_dentry->d_parent) {
9734 btrfs_record_unlink_dir(trans, BTRFS_I(old_dir),
9735 BTRFS_I(old_inode), 1);
9736 btrfs_record_unlink_dir(trans, BTRFS_I(new_dir),
9737 BTRFS_I(new_inode), 1);
9740 /* src is a subvolume */
9741 if (old_ino == BTRFS_FIRST_FREE_OBJECTID) {
9742 root_objectid = BTRFS_I(old_inode)->root->root_key.objectid;
9743 ret = btrfs_unlink_subvol(trans, root, old_dir,
9745 old_dentry->d_name.name,
9746 old_dentry->d_name.len);
9747 } else { /* src is an inode */
9748 ret = __btrfs_unlink_inode(trans, root, BTRFS_I(old_dir),
9749 BTRFS_I(old_dentry->d_inode),
9750 old_dentry->d_name.name,
9751 old_dentry->d_name.len);
9753 ret = btrfs_update_inode(trans, root, old_inode);
9756 btrfs_abort_transaction(trans, ret);
9760 /* dest is a subvolume */
9761 if (new_ino == BTRFS_FIRST_FREE_OBJECTID) {
9762 root_objectid = BTRFS_I(new_inode)->root->root_key.objectid;
9763 ret = btrfs_unlink_subvol(trans, dest, new_dir,
9765 new_dentry->d_name.name,
9766 new_dentry->d_name.len);
9767 } else { /* dest is an inode */
9768 ret = __btrfs_unlink_inode(trans, dest, BTRFS_I(new_dir),
9769 BTRFS_I(new_dentry->d_inode),
9770 new_dentry->d_name.name,
9771 new_dentry->d_name.len);
9773 ret = btrfs_update_inode(trans, dest, new_inode);
9776 btrfs_abort_transaction(trans, ret);
9780 ret = btrfs_add_link(trans, BTRFS_I(new_dir), BTRFS_I(old_inode),
9781 new_dentry->d_name.name,
9782 new_dentry->d_name.len, 0, old_idx);
9784 btrfs_abort_transaction(trans, ret);
9788 ret = btrfs_add_link(trans, BTRFS_I(old_dir), BTRFS_I(new_inode),
9789 old_dentry->d_name.name,
9790 old_dentry->d_name.len, 0, new_idx);
9792 btrfs_abort_transaction(trans, ret);
9796 if (old_inode->i_nlink == 1)
9797 BTRFS_I(old_inode)->dir_index = old_idx;
9798 if (new_inode->i_nlink == 1)
9799 BTRFS_I(new_inode)->dir_index = new_idx;
9801 if (root_log_pinned) {
9802 parent = new_dentry->d_parent;
9803 btrfs_log_new_name(trans, BTRFS_I(old_inode), BTRFS_I(old_dir),
9805 btrfs_end_log_trans(root);
9806 root_log_pinned = false;
9808 if (dest_log_pinned) {
9809 parent = old_dentry->d_parent;
9810 btrfs_log_new_name(trans, BTRFS_I(new_inode), BTRFS_I(new_dir),
9812 btrfs_end_log_trans(dest);
9813 dest_log_pinned = false;
9817 * If we have pinned a log and an error happened, we unpin tasks
9818 * trying to sync the log and force them to fallback to a transaction
9819 * commit if the log currently contains any of the inodes involved in
9820 * this rename operation (to ensure we do not persist a log with an
9821 * inconsistent state for any of these inodes or leading to any
9822 * inconsistencies when replayed). If the transaction was aborted, the
9823 * abortion reason is propagated to userspace when attempting to commit
9824 * the transaction. If the log does not contain any of these inodes, we
9825 * allow the tasks to sync it.
9827 if (ret && (root_log_pinned || dest_log_pinned)) {
9828 if (btrfs_inode_in_log(BTRFS_I(old_dir), fs_info->generation) ||
9829 btrfs_inode_in_log(BTRFS_I(new_dir), fs_info->generation) ||
9830 btrfs_inode_in_log(BTRFS_I(old_inode), fs_info->generation) ||
9832 btrfs_inode_in_log(BTRFS_I(new_inode), fs_info->generation)))
9833 btrfs_set_log_full_commit(fs_info, trans);
9835 if (root_log_pinned) {
9836 btrfs_end_log_trans(root);
9837 root_log_pinned = false;
9839 if (dest_log_pinned) {
9840 btrfs_end_log_trans(dest);
9841 dest_log_pinned = false;
9844 ret = btrfs_end_transaction(trans);
9846 if (new_ino == BTRFS_FIRST_FREE_OBJECTID)
9847 up_read(&fs_info->subvol_sem);
9848 if (old_ino == BTRFS_FIRST_FREE_OBJECTID)
9849 up_read(&fs_info->subvol_sem);
9854 static int btrfs_whiteout_for_rename(struct btrfs_trans_handle *trans,
9855 struct btrfs_root *root,
9857 struct dentry *dentry)
9860 struct inode *inode;
9864 ret = btrfs_find_free_ino(root, &objectid);
9868 inode = btrfs_new_inode(trans, root, dir,
9869 dentry->d_name.name,
9871 btrfs_ino(BTRFS_I(dir)),
9873 S_IFCHR | WHITEOUT_MODE,
9876 if (IS_ERR(inode)) {
9877 ret = PTR_ERR(inode);
9881 inode->i_op = &btrfs_special_inode_operations;
9882 init_special_inode(inode, inode->i_mode,
9885 ret = btrfs_init_inode_security(trans, inode, dir,
9890 ret = btrfs_add_nondir(trans, BTRFS_I(dir), dentry,
9891 BTRFS_I(inode), 0, index);
9895 ret = btrfs_update_inode(trans, root, inode);
9897 unlock_new_inode(inode);
9899 inode_dec_link_count(inode);
9905 static int btrfs_rename(struct inode *old_dir, struct dentry *old_dentry,
9906 struct inode *new_dir, struct dentry *new_dentry,
9909 struct btrfs_fs_info *fs_info = btrfs_sb(old_dir->i_sb);
9910 struct btrfs_trans_handle *trans;
9911 unsigned int trans_num_items;
9912 struct btrfs_root *root = BTRFS_I(old_dir)->root;
9913 struct btrfs_root *dest = BTRFS_I(new_dir)->root;
9914 struct inode *new_inode = d_inode(new_dentry);
9915 struct inode *old_inode = d_inode(old_dentry);
9919 u64 old_ino = btrfs_ino(BTRFS_I(old_inode));
9920 bool log_pinned = false;
9922 if (btrfs_ino(BTRFS_I(new_dir)) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)
9925 /* we only allow rename subvolume link between subvolumes */
9926 if (old_ino != BTRFS_FIRST_FREE_OBJECTID && root != dest)
9929 if (old_ino == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID ||
9930 (new_inode && btrfs_ino(BTRFS_I(new_inode)) == BTRFS_FIRST_FREE_OBJECTID))
9933 if (S_ISDIR(old_inode->i_mode) && new_inode &&
9934 new_inode->i_size > BTRFS_EMPTY_DIR_SIZE)
9938 /* check for collisions, even if the name isn't there */
9939 ret = btrfs_check_dir_item_collision(dest, new_dir->i_ino,
9940 new_dentry->d_name.name,
9941 new_dentry->d_name.len);
9944 if (ret == -EEXIST) {
9946 * eexist without a new_inode */
9947 if (WARN_ON(!new_inode)) {
9951 /* maybe -EOVERFLOW */
9958 * we're using rename to replace one file with another. Start IO on it
9959 * now so we don't add too much work to the end of the transaction
9961 if (new_inode && S_ISREG(old_inode->i_mode) && new_inode->i_size)
9962 filemap_flush(old_inode->i_mapping);
9964 /* close the racy window with snapshot create/destroy ioctl */
9965 if (old_ino == BTRFS_FIRST_FREE_OBJECTID)
9966 down_read(&fs_info->subvol_sem);
9968 * We want to reserve the absolute worst case amount of items. So if
9969 * both inodes are subvols and we need to unlink them then that would
9970 * require 4 item modifications, but if they are both normal inodes it
9971 * would require 5 item modifications, so we'll assume they are normal
9972 * inodes. So 5 * 2 is 10, plus 1 for the new link, so 11 total items
9973 * should cover the worst case number of items we'll modify.
9974 * If our rename has the whiteout flag, we need more 5 units for the
9975 * new inode (1 inode item, 1 inode ref, 2 dir items and 1 xattr item
9976 * when selinux is enabled).
9978 trans_num_items = 11;
9979 if (flags & RENAME_WHITEOUT)
9980 trans_num_items += 5;
9981 trans = btrfs_start_transaction(root, trans_num_items);
9982 if (IS_ERR(trans)) {
9983 ret = PTR_ERR(trans);
9988 btrfs_record_root_in_trans(trans, dest);
9990 ret = btrfs_set_inode_index(BTRFS_I(new_dir), &index);
9994 BTRFS_I(old_inode)->dir_index = 0ULL;
9995 if (unlikely(old_ino == BTRFS_FIRST_FREE_OBJECTID)) {
9996 /* force full log commit if subvolume involved. */
9997 btrfs_set_log_full_commit(fs_info, trans);
9999 btrfs_pin_log_trans(root);
10001 ret = btrfs_insert_inode_ref(trans, dest,
10002 new_dentry->d_name.name,
10003 new_dentry->d_name.len,
10005 btrfs_ino(BTRFS_I(new_dir)), index);
10010 inode_inc_iversion(old_dir);
10011 inode_inc_iversion(new_dir);
10012 inode_inc_iversion(old_inode);
10013 old_dir->i_ctime = old_dir->i_mtime =
10014 new_dir->i_ctime = new_dir->i_mtime =
10015 old_inode->i_ctime = current_time(old_dir);
10017 if (old_dentry->d_parent != new_dentry->d_parent)
10018 btrfs_record_unlink_dir(trans, BTRFS_I(old_dir),
10019 BTRFS_I(old_inode), 1);
10021 if (unlikely(old_ino == BTRFS_FIRST_FREE_OBJECTID)) {
10022 root_objectid = BTRFS_I(old_inode)->root->root_key.objectid;
10023 ret = btrfs_unlink_subvol(trans, root, old_dir, root_objectid,
10024 old_dentry->d_name.name,
10025 old_dentry->d_name.len);
10027 ret = __btrfs_unlink_inode(trans, root, BTRFS_I(old_dir),
10028 BTRFS_I(d_inode(old_dentry)),
10029 old_dentry->d_name.name,
10030 old_dentry->d_name.len);
10032 ret = btrfs_update_inode(trans, root, old_inode);
10035 btrfs_abort_transaction(trans, ret);
10040 inode_inc_iversion(new_inode);
10041 new_inode->i_ctime = current_time(new_inode);
10042 if (unlikely(btrfs_ino(BTRFS_I(new_inode)) ==
10043 BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)) {
10044 root_objectid = BTRFS_I(new_inode)->location.objectid;
10045 ret = btrfs_unlink_subvol(trans, dest, new_dir,
10047 new_dentry->d_name.name,
10048 new_dentry->d_name.len);
10049 BUG_ON(new_inode->i_nlink == 0);
10051 ret = btrfs_unlink_inode(trans, dest, BTRFS_I(new_dir),
10052 BTRFS_I(d_inode(new_dentry)),
10053 new_dentry->d_name.name,
10054 new_dentry->d_name.len);
10056 if (!ret && new_inode->i_nlink == 0)
10057 ret = btrfs_orphan_add(trans,
10058 BTRFS_I(d_inode(new_dentry)));
10060 btrfs_abort_transaction(trans, ret);
10065 ret = btrfs_add_link(trans, BTRFS_I(new_dir), BTRFS_I(old_inode),
10066 new_dentry->d_name.name,
10067 new_dentry->d_name.len, 0, index);
10069 btrfs_abort_transaction(trans, ret);
10073 if (old_inode->i_nlink == 1)
10074 BTRFS_I(old_inode)->dir_index = index;
10077 struct dentry *parent = new_dentry->d_parent;
10079 btrfs_log_new_name(trans, BTRFS_I(old_inode), BTRFS_I(old_dir),
10081 btrfs_end_log_trans(root);
10082 log_pinned = false;
10085 if (flags & RENAME_WHITEOUT) {
10086 ret = btrfs_whiteout_for_rename(trans, root, old_dir,
10090 btrfs_abort_transaction(trans, ret);
10096 * If we have pinned the log and an error happened, we unpin tasks
10097 * trying to sync the log and force them to fallback to a transaction
10098 * commit if the log currently contains any of the inodes involved in
10099 * this rename operation (to ensure we do not persist a log with an
10100 * inconsistent state for any of these inodes or leading to any
10101 * inconsistencies when replayed). If the transaction was aborted, the
10102 * abortion reason is propagated to userspace when attempting to commit
10103 * the transaction. If the log does not contain any of these inodes, we
10104 * allow the tasks to sync it.
10106 if (ret && log_pinned) {
10107 if (btrfs_inode_in_log(BTRFS_I(old_dir), fs_info->generation) ||
10108 btrfs_inode_in_log(BTRFS_I(new_dir), fs_info->generation) ||
10109 btrfs_inode_in_log(BTRFS_I(old_inode), fs_info->generation) ||
10111 btrfs_inode_in_log(BTRFS_I(new_inode), fs_info->generation)))
10112 btrfs_set_log_full_commit(fs_info, trans);
10114 btrfs_end_log_trans(root);
10115 log_pinned = false;
10117 btrfs_end_transaction(trans);
10119 if (old_ino == BTRFS_FIRST_FREE_OBJECTID)
10120 up_read(&fs_info->subvol_sem);
10125 static int btrfs_rename2(struct inode *old_dir, struct dentry *old_dentry,
10126 struct inode *new_dir, struct dentry *new_dentry,
10127 unsigned int flags)
10129 if (flags & ~(RENAME_NOREPLACE | RENAME_EXCHANGE | RENAME_WHITEOUT))
10132 if (flags & RENAME_EXCHANGE)
10133 return btrfs_rename_exchange(old_dir, old_dentry, new_dir,
10136 return btrfs_rename(old_dir, old_dentry, new_dir, new_dentry, flags);
10139 static void btrfs_run_delalloc_work(struct btrfs_work *work)
10141 struct btrfs_delalloc_work *delalloc_work;
10142 struct inode *inode;
10144 delalloc_work = container_of(work, struct btrfs_delalloc_work,
10146 inode = delalloc_work->inode;
10147 filemap_flush(inode->i_mapping);
10148 if (test_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
10149 &BTRFS_I(inode)->runtime_flags))
10150 filemap_flush(inode->i_mapping);
10152 if (delalloc_work->delay_iput)
10153 btrfs_add_delayed_iput(inode);
10156 complete(&delalloc_work->completion);
10159 struct btrfs_delalloc_work *btrfs_alloc_delalloc_work(struct inode *inode,
10162 struct btrfs_delalloc_work *work;
10164 work = kmalloc(sizeof(*work), GFP_NOFS);
10168 init_completion(&work->completion);
10169 INIT_LIST_HEAD(&work->list);
10170 work->inode = inode;
10171 work->delay_iput = delay_iput;
10172 WARN_ON_ONCE(!inode);
10173 btrfs_init_work(&work->work, btrfs_flush_delalloc_helper,
10174 btrfs_run_delalloc_work, NULL, NULL);
10179 void btrfs_wait_and_free_delalloc_work(struct btrfs_delalloc_work *work)
10181 wait_for_completion(&work->completion);
10186 * some fairly slow code that needs optimization. This walks the list
10187 * of all the inodes with pending delalloc and forces them to disk.
10189 static int __start_delalloc_inodes(struct btrfs_root *root, int delay_iput,
10192 struct btrfs_inode *binode;
10193 struct inode *inode;
10194 struct btrfs_delalloc_work *work, *next;
10195 struct list_head works;
10196 struct list_head splice;
10199 INIT_LIST_HEAD(&works);
10200 INIT_LIST_HEAD(&splice);
10202 mutex_lock(&root->delalloc_mutex);
10203 spin_lock(&root->delalloc_lock);
10204 list_splice_init(&root->delalloc_inodes, &splice);
10205 while (!list_empty(&splice)) {
10206 binode = list_entry(splice.next, struct btrfs_inode,
10209 list_move_tail(&binode->delalloc_inodes,
10210 &root->delalloc_inodes);
10211 inode = igrab(&binode->vfs_inode);
10213 cond_resched_lock(&root->delalloc_lock);
10216 spin_unlock(&root->delalloc_lock);
10218 work = btrfs_alloc_delalloc_work(inode, delay_iput);
10221 btrfs_add_delayed_iput(inode);
10227 list_add_tail(&work->list, &works);
10228 btrfs_queue_work(root->fs_info->flush_workers,
10231 if (nr != -1 && ret >= nr)
10234 spin_lock(&root->delalloc_lock);
10236 spin_unlock(&root->delalloc_lock);
10239 list_for_each_entry_safe(work, next, &works, list) {
10240 list_del_init(&work->list);
10241 btrfs_wait_and_free_delalloc_work(work);
10244 if (!list_empty_careful(&splice)) {
10245 spin_lock(&root->delalloc_lock);
10246 list_splice_tail(&splice, &root->delalloc_inodes);
10247 spin_unlock(&root->delalloc_lock);
10249 mutex_unlock(&root->delalloc_mutex);
10253 int btrfs_start_delalloc_inodes(struct btrfs_root *root, int delay_iput)
10255 struct btrfs_fs_info *fs_info = root->fs_info;
10258 if (test_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state))
10261 ret = __start_delalloc_inodes(root, delay_iput, -1);
10267 int btrfs_start_delalloc_roots(struct btrfs_fs_info *fs_info, int delay_iput,
10270 struct btrfs_root *root;
10271 struct list_head splice;
10274 if (test_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state))
10277 INIT_LIST_HEAD(&splice);
10279 mutex_lock(&fs_info->delalloc_root_mutex);
10280 spin_lock(&fs_info->delalloc_root_lock);
10281 list_splice_init(&fs_info->delalloc_roots, &splice);
10282 while (!list_empty(&splice) && nr) {
10283 root = list_first_entry(&splice, struct btrfs_root,
10285 root = btrfs_grab_fs_root(root);
10287 list_move_tail(&root->delalloc_root,
10288 &fs_info->delalloc_roots);
10289 spin_unlock(&fs_info->delalloc_root_lock);
10291 ret = __start_delalloc_inodes(root, delay_iput, nr);
10292 btrfs_put_fs_root(root);
10300 spin_lock(&fs_info->delalloc_root_lock);
10302 spin_unlock(&fs_info->delalloc_root_lock);
10306 if (!list_empty_careful(&splice)) {
10307 spin_lock(&fs_info->delalloc_root_lock);
10308 list_splice_tail(&splice, &fs_info->delalloc_roots);
10309 spin_unlock(&fs_info->delalloc_root_lock);
10311 mutex_unlock(&fs_info->delalloc_root_mutex);
10315 static int btrfs_symlink(struct inode *dir, struct dentry *dentry,
10316 const char *symname)
10318 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
10319 struct btrfs_trans_handle *trans;
10320 struct btrfs_root *root = BTRFS_I(dir)->root;
10321 struct btrfs_path *path;
10322 struct btrfs_key key;
10323 struct inode *inode = NULL;
10325 int drop_inode = 0;
10331 struct btrfs_file_extent_item *ei;
10332 struct extent_buffer *leaf;
10334 name_len = strlen(symname);
10335 if (name_len > BTRFS_MAX_INLINE_DATA_SIZE(fs_info))
10336 return -ENAMETOOLONG;
10339 * 2 items for inode item and ref
10340 * 2 items for dir items
10341 * 1 item for updating parent inode item
10342 * 1 item for the inline extent item
10343 * 1 item for xattr if selinux is on
10345 trans = btrfs_start_transaction(root, 7);
10347 return PTR_ERR(trans);
10349 err = btrfs_find_free_ino(root, &objectid);
10353 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
10354 dentry->d_name.len, btrfs_ino(BTRFS_I(dir)),
10355 objectid, S_IFLNK|S_IRWXUGO, &index);
10356 if (IS_ERR(inode)) {
10357 err = PTR_ERR(inode);
10362 * If the active LSM wants to access the inode during
10363 * d_instantiate it needs these. Smack checks to see
10364 * if the filesystem supports xattrs by looking at the
10367 inode->i_fop = &btrfs_file_operations;
10368 inode->i_op = &btrfs_file_inode_operations;
10369 inode->i_mapping->a_ops = &btrfs_aops;
10370 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
10372 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
10374 goto out_unlock_inode;
10376 path = btrfs_alloc_path();
10379 goto out_unlock_inode;
10381 key.objectid = btrfs_ino(BTRFS_I(inode));
10383 key.type = BTRFS_EXTENT_DATA_KEY;
10384 datasize = btrfs_file_extent_calc_inline_size(name_len);
10385 err = btrfs_insert_empty_item(trans, root, path, &key,
10388 btrfs_free_path(path);
10389 goto out_unlock_inode;
10391 leaf = path->nodes[0];
10392 ei = btrfs_item_ptr(leaf, path->slots[0],
10393 struct btrfs_file_extent_item);
10394 btrfs_set_file_extent_generation(leaf, ei, trans->transid);
10395 btrfs_set_file_extent_type(leaf, ei,
10396 BTRFS_FILE_EXTENT_INLINE);
10397 btrfs_set_file_extent_encryption(leaf, ei, 0);
10398 btrfs_set_file_extent_compression(leaf, ei, 0);
10399 btrfs_set_file_extent_other_encoding(leaf, ei, 0);
10400 btrfs_set_file_extent_ram_bytes(leaf, ei, name_len);
10402 ptr = btrfs_file_extent_inline_start(ei);
10403 write_extent_buffer(leaf, symname, ptr, name_len);
10404 btrfs_mark_buffer_dirty(leaf);
10405 btrfs_free_path(path);
10407 inode->i_op = &btrfs_symlink_inode_operations;
10408 inode_nohighmem(inode);
10409 inode->i_mapping->a_ops = &btrfs_symlink_aops;
10410 inode_set_bytes(inode, name_len);
10411 btrfs_i_size_write(BTRFS_I(inode), name_len);
10412 err = btrfs_update_inode(trans, root, inode);
10414 * Last step, add directory indexes for our symlink inode. This is the
10415 * last step to avoid extra cleanup of these indexes if an error happens
10419 err = btrfs_add_nondir(trans, BTRFS_I(dir), dentry,
10420 BTRFS_I(inode), 0, index);
10423 goto out_unlock_inode;
10426 unlock_new_inode(inode);
10427 d_instantiate(dentry, inode);
10430 btrfs_end_transaction(trans);
10432 inode_dec_link_count(inode);
10435 btrfs_btree_balance_dirty(fs_info);
10440 unlock_new_inode(inode);
10444 static int __btrfs_prealloc_file_range(struct inode *inode, int mode,
10445 u64 start, u64 num_bytes, u64 min_size,
10446 loff_t actual_len, u64 *alloc_hint,
10447 struct btrfs_trans_handle *trans)
10449 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
10450 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
10451 struct extent_map *em;
10452 struct btrfs_root *root = BTRFS_I(inode)->root;
10453 struct btrfs_key ins;
10454 u64 cur_offset = start;
10457 u64 last_alloc = (u64)-1;
10459 bool own_trans = true;
10460 u64 end = start + num_bytes - 1;
10464 while (num_bytes > 0) {
10466 trans = btrfs_start_transaction(root, 3);
10467 if (IS_ERR(trans)) {
10468 ret = PTR_ERR(trans);
10473 cur_bytes = min_t(u64, num_bytes, SZ_256M);
10474 cur_bytes = max(cur_bytes, min_size);
10476 * If we are severely fragmented we could end up with really
10477 * small allocations, so if the allocator is returning small
10478 * chunks lets make its job easier by only searching for those
10481 cur_bytes = min(cur_bytes, last_alloc);
10482 ret = btrfs_reserve_extent(root, cur_bytes, cur_bytes,
10483 min_size, 0, *alloc_hint, &ins, 1, 0);
10486 btrfs_end_transaction(trans);
10489 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
10491 last_alloc = ins.offset;
10492 ret = insert_reserved_file_extent(trans, inode,
10493 cur_offset, ins.objectid,
10494 ins.offset, ins.offset,
10495 ins.offset, 0, 0, 0,
10496 BTRFS_FILE_EXTENT_PREALLOC);
10498 btrfs_free_reserved_extent(fs_info, ins.objectid,
10500 btrfs_abort_transaction(trans, ret);
10502 btrfs_end_transaction(trans);
10506 btrfs_drop_extent_cache(BTRFS_I(inode), cur_offset,
10507 cur_offset + ins.offset -1, 0);
10509 em = alloc_extent_map();
10511 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
10512 &BTRFS_I(inode)->runtime_flags);
10516 em->start = cur_offset;
10517 em->orig_start = cur_offset;
10518 em->len = ins.offset;
10519 em->block_start = ins.objectid;
10520 em->block_len = ins.offset;
10521 em->orig_block_len = ins.offset;
10522 em->ram_bytes = ins.offset;
10523 em->bdev = fs_info->fs_devices->latest_bdev;
10524 set_bit(EXTENT_FLAG_PREALLOC, &em->flags);
10525 em->generation = trans->transid;
10528 write_lock(&em_tree->lock);
10529 ret = add_extent_mapping(em_tree, em, 1);
10530 write_unlock(&em_tree->lock);
10531 if (ret != -EEXIST)
10533 btrfs_drop_extent_cache(BTRFS_I(inode), cur_offset,
10534 cur_offset + ins.offset - 1,
10537 free_extent_map(em);
10539 num_bytes -= ins.offset;
10540 cur_offset += ins.offset;
10541 *alloc_hint = ins.objectid + ins.offset;
10543 inode_inc_iversion(inode);
10544 inode->i_ctime = current_time(inode);
10545 BTRFS_I(inode)->flags |= BTRFS_INODE_PREALLOC;
10546 if (!(mode & FALLOC_FL_KEEP_SIZE) &&
10547 (actual_len > inode->i_size) &&
10548 (cur_offset > inode->i_size)) {
10549 if (cur_offset > actual_len)
10550 i_size = actual_len;
10552 i_size = cur_offset;
10553 i_size_write(inode, i_size);
10554 btrfs_ordered_update_i_size(inode, i_size, NULL);
10557 ret = btrfs_update_inode(trans, root, inode);
10560 btrfs_abort_transaction(trans, ret);
10562 btrfs_end_transaction(trans);
10567 btrfs_end_transaction(trans);
10569 if (cur_offset < end)
10570 btrfs_free_reserved_data_space(inode, NULL, cur_offset,
10571 end - cur_offset + 1);
10575 int btrfs_prealloc_file_range(struct inode *inode, int mode,
10576 u64 start, u64 num_bytes, u64 min_size,
10577 loff_t actual_len, u64 *alloc_hint)
10579 return __btrfs_prealloc_file_range(inode, mode, start, num_bytes,
10580 min_size, actual_len, alloc_hint,
10584 int btrfs_prealloc_file_range_trans(struct inode *inode,
10585 struct btrfs_trans_handle *trans, int mode,
10586 u64 start, u64 num_bytes, u64 min_size,
10587 loff_t actual_len, u64 *alloc_hint)
10589 return __btrfs_prealloc_file_range(inode, mode, start, num_bytes,
10590 min_size, actual_len, alloc_hint, trans);
10593 static int btrfs_set_page_dirty(struct page *page)
10595 return __set_page_dirty_nobuffers(page);
10598 static int btrfs_permission(struct inode *inode, int mask)
10600 struct btrfs_root *root = BTRFS_I(inode)->root;
10601 umode_t mode = inode->i_mode;
10603 if (mask & MAY_WRITE &&
10604 (S_ISREG(mode) || S_ISDIR(mode) || S_ISLNK(mode))) {
10605 if (btrfs_root_readonly(root))
10607 if (BTRFS_I(inode)->flags & BTRFS_INODE_READONLY)
10610 return generic_permission(inode, mask);
10613 static int btrfs_tmpfile(struct inode *dir, struct dentry *dentry, umode_t mode)
10615 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
10616 struct btrfs_trans_handle *trans;
10617 struct btrfs_root *root = BTRFS_I(dir)->root;
10618 struct inode *inode = NULL;
10624 * 5 units required for adding orphan entry
10626 trans = btrfs_start_transaction(root, 5);
10628 return PTR_ERR(trans);
10630 ret = btrfs_find_free_ino(root, &objectid);
10634 inode = btrfs_new_inode(trans, root, dir, NULL, 0,
10635 btrfs_ino(BTRFS_I(dir)), objectid, mode, &index);
10636 if (IS_ERR(inode)) {
10637 ret = PTR_ERR(inode);
10642 inode->i_fop = &btrfs_file_operations;
10643 inode->i_op = &btrfs_file_inode_operations;
10645 inode->i_mapping->a_ops = &btrfs_aops;
10646 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
10648 ret = btrfs_init_inode_security(trans, inode, dir, NULL);
10652 ret = btrfs_update_inode(trans, root, inode);
10655 ret = btrfs_orphan_add(trans, BTRFS_I(inode));
10660 * We set number of links to 0 in btrfs_new_inode(), and here we set
10661 * it to 1 because d_tmpfile() will issue a warning if the count is 0,
10664 * d_tmpfile() -> inode_dec_link_count() -> drop_nlink()
10666 set_nlink(inode, 1);
10667 unlock_new_inode(inode);
10668 d_tmpfile(dentry, inode);
10669 mark_inode_dirty(inode);
10672 btrfs_end_transaction(trans);
10675 btrfs_balance_delayed_items(fs_info);
10676 btrfs_btree_balance_dirty(fs_info);
10680 unlock_new_inode(inode);
10685 __attribute__((const))
10686 static int btrfs_readpage_io_failed_hook(struct page *page, int failed_mirror)
10691 static struct btrfs_fs_info *iotree_fs_info(void *private_data)
10693 struct inode *inode = private_data;
10694 return btrfs_sb(inode->i_sb);
10697 static void btrfs_check_extent_io_range(void *private_data, const char *caller,
10698 u64 start, u64 end)
10700 struct inode *inode = private_data;
10703 isize = i_size_read(inode);
10704 if (end >= PAGE_SIZE && (end % 2) == 0 && end != isize - 1) {
10705 btrfs_debug_rl(BTRFS_I(inode)->root->fs_info,
10706 "%s: ino %llu isize %llu odd range [%llu,%llu]",
10707 caller, btrfs_ino(BTRFS_I(inode)), isize, start, end);
10711 void btrfs_set_range_writeback(void *private_data, u64 start, u64 end)
10713 struct inode *inode = private_data;
10714 unsigned long index = start >> PAGE_SHIFT;
10715 unsigned long end_index = end >> PAGE_SHIFT;
10718 while (index <= end_index) {
10719 page = find_get_page(inode->i_mapping, index);
10720 ASSERT(page); /* Pages should be in the extent_io_tree */
10721 set_page_writeback(page);
10727 static const struct inode_operations btrfs_dir_inode_operations = {
10728 .getattr = btrfs_getattr,
10729 .lookup = btrfs_lookup,
10730 .create = btrfs_create,
10731 .unlink = btrfs_unlink,
10732 .link = btrfs_link,
10733 .mkdir = btrfs_mkdir,
10734 .rmdir = btrfs_rmdir,
10735 .rename = btrfs_rename2,
10736 .symlink = btrfs_symlink,
10737 .setattr = btrfs_setattr,
10738 .mknod = btrfs_mknod,
10739 .listxattr = btrfs_listxattr,
10740 .permission = btrfs_permission,
10741 .get_acl = btrfs_get_acl,
10742 .set_acl = btrfs_set_acl,
10743 .update_time = btrfs_update_time,
10744 .tmpfile = btrfs_tmpfile,
10746 static const struct inode_operations btrfs_dir_ro_inode_operations = {
10747 .lookup = btrfs_lookup,
10748 .permission = btrfs_permission,
10749 .update_time = btrfs_update_time,
10752 static const struct file_operations btrfs_dir_file_operations = {
10753 .llseek = generic_file_llseek,
10754 .read = generic_read_dir,
10755 .iterate_shared = btrfs_real_readdir,
10756 .open = btrfs_opendir,
10757 .unlocked_ioctl = btrfs_ioctl,
10758 #ifdef CONFIG_COMPAT
10759 .compat_ioctl = btrfs_compat_ioctl,
10761 .release = btrfs_release_file,
10762 .fsync = btrfs_sync_file,
10765 static const struct extent_io_ops btrfs_extent_io_ops = {
10766 /* mandatory callbacks */
10767 .submit_bio_hook = btrfs_submit_bio_hook,
10768 .readpage_end_io_hook = btrfs_readpage_end_io_hook,
10769 .merge_bio_hook = btrfs_merge_bio_hook,
10770 .readpage_io_failed_hook = btrfs_readpage_io_failed_hook,
10771 .tree_fs_info = iotree_fs_info,
10772 .set_range_writeback = btrfs_set_range_writeback,
10774 /* optional callbacks */
10775 .fill_delalloc = run_delalloc_range,
10776 .writepage_end_io_hook = btrfs_writepage_end_io_hook,
10777 .writepage_start_hook = btrfs_writepage_start_hook,
10778 .set_bit_hook = btrfs_set_bit_hook,
10779 .clear_bit_hook = btrfs_clear_bit_hook,
10780 .merge_extent_hook = btrfs_merge_extent_hook,
10781 .split_extent_hook = btrfs_split_extent_hook,
10782 .check_extent_io_range = btrfs_check_extent_io_range,
10786 * btrfs doesn't support the bmap operation because swapfiles
10787 * use bmap to make a mapping of extents in the file. They assume
10788 * these extents won't change over the life of the file and they
10789 * use the bmap result to do IO directly to the drive.
10791 * the btrfs bmap call would return logical addresses that aren't
10792 * suitable for IO and they also will change frequently as COW
10793 * operations happen. So, swapfile + btrfs == corruption.
10795 * For now we're avoiding this by dropping bmap.
10797 static const struct address_space_operations btrfs_aops = {
10798 .readpage = btrfs_readpage,
10799 .writepage = btrfs_writepage,
10800 .writepages = btrfs_writepages,
10801 .readpages = btrfs_readpages,
10802 .direct_IO = btrfs_direct_IO,
10803 .invalidatepage = btrfs_invalidatepage,
10804 .releasepage = btrfs_releasepage,
10805 .set_page_dirty = btrfs_set_page_dirty,
10806 .error_remove_page = generic_error_remove_page,
10809 static const struct address_space_operations btrfs_symlink_aops = {
10810 .readpage = btrfs_readpage,
10811 .writepage = btrfs_writepage,
10812 .invalidatepage = btrfs_invalidatepage,
10813 .releasepage = btrfs_releasepage,
10816 static const struct inode_operations btrfs_file_inode_operations = {
10817 .getattr = btrfs_getattr,
10818 .setattr = btrfs_setattr,
10819 .listxattr = btrfs_listxattr,
10820 .permission = btrfs_permission,
10821 .fiemap = btrfs_fiemap,
10822 .get_acl = btrfs_get_acl,
10823 .set_acl = btrfs_set_acl,
10824 .update_time = btrfs_update_time,
10826 static const struct inode_operations btrfs_special_inode_operations = {
10827 .getattr = btrfs_getattr,
10828 .setattr = btrfs_setattr,
10829 .permission = btrfs_permission,
10830 .listxattr = btrfs_listxattr,
10831 .get_acl = btrfs_get_acl,
10832 .set_acl = btrfs_set_acl,
10833 .update_time = btrfs_update_time,
10835 static const struct inode_operations btrfs_symlink_inode_operations = {
10836 .get_link = page_get_link,
10837 .getattr = btrfs_getattr,
10838 .setattr = btrfs_setattr,
10839 .permission = btrfs_permission,
10840 .listxattr = btrfs_listxattr,
10841 .update_time = btrfs_update_time,
10844 const struct dentry_operations btrfs_dentry_operations = {
10845 .d_delete = btrfs_dentry_delete,
10846 .d_release = btrfs_dentry_release,