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 <asm/unaligned.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 {
71 u64 outstanding_extents;
73 u64 unsubmitted_oe_range_start;
74 u64 unsubmitted_oe_range_end;
78 static const struct inode_operations btrfs_dir_inode_operations;
79 static const struct inode_operations btrfs_symlink_inode_operations;
80 static const struct inode_operations btrfs_dir_ro_inode_operations;
81 static const struct inode_operations btrfs_special_inode_operations;
82 static const struct inode_operations btrfs_file_inode_operations;
83 static const struct address_space_operations btrfs_aops;
84 static const struct address_space_operations btrfs_symlink_aops;
85 static const struct file_operations btrfs_dir_file_operations;
86 static const struct extent_io_ops btrfs_extent_io_ops;
88 static struct kmem_cache *btrfs_inode_cachep;
89 struct kmem_cache *btrfs_trans_handle_cachep;
90 struct kmem_cache *btrfs_path_cachep;
91 struct kmem_cache *btrfs_free_space_cachep;
94 static const unsigned char btrfs_type_by_mode[S_IFMT >> S_SHIFT] = {
95 [S_IFREG >> S_SHIFT] = BTRFS_FT_REG_FILE,
96 [S_IFDIR >> S_SHIFT] = BTRFS_FT_DIR,
97 [S_IFCHR >> S_SHIFT] = BTRFS_FT_CHRDEV,
98 [S_IFBLK >> S_SHIFT] = BTRFS_FT_BLKDEV,
99 [S_IFIFO >> S_SHIFT] = BTRFS_FT_FIFO,
100 [S_IFSOCK >> S_SHIFT] = BTRFS_FT_SOCK,
101 [S_IFLNK >> S_SHIFT] = BTRFS_FT_SYMLINK,
104 static int btrfs_setsize(struct inode *inode, struct iattr *attr);
105 static int btrfs_truncate(struct inode *inode);
106 static int btrfs_finish_ordered_io(struct btrfs_ordered_extent *ordered_extent);
107 static noinline int cow_file_range(struct inode *inode,
108 struct page *locked_page,
109 u64 start, u64 end, u64 delalloc_end,
110 int *page_started, unsigned long *nr_written,
111 int unlock, struct btrfs_dedupe_hash *hash);
112 static struct extent_map *create_io_em(struct inode *inode, u64 start, u64 len,
113 u64 orig_start, u64 block_start,
114 u64 block_len, u64 orig_block_len,
115 u64 ram_bytes, int compress_type,
118 static void __endio_write_update_ordered(struct inode *inode,
119 const u64 offset, const u64 bytes,
120 const bool uptodate);
123 * Cleanup all submitted ordered extents in specified range to handle errors
124 * from the fill_dellaloc() callback.
126 * NOTE: caller must ensure that when an error happens, it can not call
127 * extent_clear_unlock_delalloc() to clear both the bits EXTENT_DO_ACCOUNTING
128 * and EXTENT_DELALLOC simultaneously, because that causes the reserved metadata
129 * to be released, which we want to happen only when finishing the ordered
130 * extent (btrfs_finish_ordered_io()). Also note that the caller of the
131 * fill_delalloc() callback already does proper cleanup for the first page of
132 * the range, that is, it invokes the callback writepage_end_io_hook() for the
133 * range of the first page.
135 static inline void btrfs_cleanup_ordered_extents(struct inode *inode,
139 unsigned long index = offset >> PAGE_SHIFT;
140 unsigned long end_index = (offset + bytes - 1) >> PAGE_SHIFT;
143 while (index <= end_index) {
144 page = find_get_page(inode->i_mapping, index);
148 ClearPagePrivate2(page);
151 return __endio_write_update_ordered(inode, offset + PAGE_SIZE,
152 bytes - PAGE_SIZE, false);
155 static int btrfs_dirty_inode(struct inode *inode);
157 #ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
158 void btrfs_test_inode_set_ops(struct inode *inode)
160 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
164 static int btrfs_init_inode_security(struct btrfs_trans_handle *trans,
165 struct inode *inode, struct inode *dir,
166 const struct qstr *qstr)
170 err = btrfs_init_acl(trans, inode, dir);
172 err = btrfs_xattr_security_init(trans, inode, dir, qstr);
177 * this does all the hard work for inserting an inline extent into
178 * the btree. The caller should have done a btrfs_drop_extents so that
179 * no overlapping inline items exist in the btree
181 static int insert_inline_extent(struct btrfs_trans_handle *trans,
182 struct btrfs_path *path, int extent_inserted,
183 struct btrfs_root *root, struct inode *inode,
184 u64 start, size_t size, size_t compressed_size,
186 struct page **compressed_pages)
188 struct extent_buffer *leaf;
189 struct page *page = NULL;
192 struct btrfs_file_extent_item *ei;
194 size_t cur_size = size;
195 unsigned long offset;
197 if (compressed_size && compressed_pages)
198 cur_size = compressed_size;
200 inode_add_bytes(inode, size);
202 if (!extent_inserted) {
203 struct btrfs_key key;
206 key.objectid = btrfs_ino(BTRFS_I(inode));
208 key.type = BTRFS_EXTENT_DATA_KEY;
210 datasize = btrfs_file_extent_calc_inline_size(cur_size);
211 path->leave_spinning = 1;
212 ret = btrfs_insert_empty_item(trans, root, path, &key,
217 leaf = path->nodes[0];
218 ei = btrfs_item_ptr(leaf, path->slots[0],
219 struct btrfs_file_extent_item);
220 btrfs_set_file_extent_generation(leaf, ei, trans->transid);
221 btrfs_set_file_extent_type(leaf, ei, BTRFS_FILE_EXTENT_INLINE);
222 btrfs_set_file_extent_encryption(leaf, ei, 0);
223 btrfs_set_file_extent_other_encoding(leaf, ei, 0);
224 btrfs_set_file_extent_ram_bytes(leaf, ei, size);
225 ptr = btrfs_file_extent_inline_start(ei);
227 if (compress_type != BTRFS_COMPRESS_NONE) {
230 while (compressed_size > 0) {
231 cpage = compressed_pages[i];
232 cur_size = min_t(unsigned long, compressed_size,
235 kaddr = kmap_atomic(cpage);
236 write_extent_buffer(leaf, kaddr, ptr, cur_size);
237 kunmap_atomic(kaddr);
241 compressed_size -= cur_size;
243 btrfs_set_file_extent_compression(leaf, ei,
246 page = find_get_page(inode->i_mapping,
247 start >> PAGE_SHIFT);
248 btrfs_set_file_extent_compression(leaf, ei, 0);
249 kaddr = kmap_atomic(page);
250 offset = start & (PAGE_SIZE - 1);
251 write_extent_buffer(leaf, kaddr + offset, ptr, size);
252 kunmap_atomic(kaddr);
255 btrfs_mark_buffer_dirty(leaf);
256 btrfs_release_path(path);
259 * we're an inline extent, so nobody can
260 * extend the file past i_size without locking
261 * a page we already have locked.
263 * We must do any isize and inode updates
264 * before we unlock the pages. Otherwise we
265 * could end up racing with unlink.
267 BTRFS_I(inode)->disk_i_size = inode->i_size;
268 ret = btrfs_update_inode(trans, root, inode);
276 * conditionally insert an inline extent into the file. This
277 * does the checks required to make sure the data is small enough
278 * to fit as an inline extent.
280 static noinline int cow_file_range_inline(struct btrfs_root *root,
281 struct inode *inode, u64 start,
282 u64 end, size_t compressed_size,
284 struct page **compressed_pages)
286 struct btrfs_fs_info *fs_info = root->fs_info;
287 struct btrfs_trans_handle *trans;
288 u64 isize = i_size_read(inode);
289 u64 actual_end = min(end + 1, isize);
290 u64 inline_len = actual_end - start;
291 u64 aligned_end = ALIGN(end, fs_info->sectorsize);
292 u64 data_len = inline_len;
294 struct btrfs_path *path;
295 int extent_inserted = 0;
296 u32 extent_item_size;
299 data_len = compressed_size;
302 actual_end > fs_info->sectorsize ||
303 data_len > BTRFS_MAX_INLINE_DATA_SIZE(fs_info) ||
305 (actual_end & (fs_info->sectorsize - 1)) == 0) ||
307 data_len > fs_info->max_inline) {
311 path = btrfs_alloc_path();
315 trans = btrfs_join_transaction(root);
317 btrfs_free_path(path);
318 return PTR_ERR(trans);
320 trans->block_rsv = &fs_info->delalloc_block_rsv;
322 if (compressed_size && compressed_pages)
323 extent_item_size = btrfs_file_extent_calc_inline_size(
326 extent_item_size = btrfs_file_extent_calc_inline_size(
329 ret = __btrfs_drop_extents(trans, root, inode, path,
330 start, aligned_end, NULL,
331 1, 1, extent_item_size, &extent_inserted);
333 btrfs_abort_transaction(trans, ret);
337 if (isize > actual_end)
338 inline_len = min_t(u64, isize, actual_end);
339 ret = insert_inline_extent(trans, path, extent_inserted,
341 inline_len, compressed_size,
342 compress_type, compressed_pages);
343 if (ret && ret != -ENOSPC) {
344 btrfs_abort_transaction(trans, ret);
346 } else if (ret == -ENOSPC) {
351 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &BTRFS_I(inode)->runtime_flags);
352 btrfs_delalloc_release_metadata(BTRFS_I(inode), end + 1 - start);
353 btrfs_drop_extent_cache(BTRFS_I(inode), start, aligned_end - 1, 0);
356 * Don't forget to free the reserved space, as for inlined extent
357 * it won't count as data extent, free them directly here.
358 * And at reserve time, it's always aligned to page size, so
359 * just free one page here.
361 btrfs_qgroup_free_data(inode, NULL, 0, PAGE_SIZE);
362 btrfs_free_path(path);
363 btrfs_end_transaction(trans);
367 struct async_extent {
372 unsigned long nr_pages;
374 struct list_head list;
379 struct btrfs_root *root;
380 struct page *locked_page;
383 struct list_head extents;
384 struct btrfs_work work;
387 static noinline int add_async_extent(struct async_cow *cow,
388 u64 start, u64 ram_size,
391 unsigned long nr_pages,
394 struct async_extent *async_extent;
396 async_extent = kmalloc(sizeof(*async_extent), GFP_NOFS);
397 BUG_ON(!async_extent); /* -ENOMEM */
398 async_extent->start = start;
399 async_extent->ram_size = ram_size;
400 async_extent->compressed_size = compressed_size;
401 async_extent->pages = pages;
402 async_extent->nr_pages = nr_pages;
403 async_extent->compress_type = compress_type;
404 list_add_tail(&async_extent->list, &cow->extents);
409 * Check if the inode has flags compatible with compression
411 static inline bool inode_can_compress(struct inode *inode)
413 if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW ||
414 BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)
420 * Check if the inode needs to be submitted to compression, based on mount
421 * options, defragmentation, properties or heuristics.
423 static inline int inode_need_compress(struct inode *inode, u64 start, u64 end)
425 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
427 if (!inode_can_compress(inode)) {
428 WARN(IS_ENABLED(CONFIG_BTRFS_DEBUG),
429 KERN_ERR "BTRFS: unexpected compression for ino %llu\n",
430 btrfs_ino(BTRFS_I(inode)));
434 if (btrfs_test_opt(fs_info, FORCE_COMPRESS))
437 if (BTRFS_I(inode)->defrag_compress)
439 /* bad compression ratios */
440 if (BTRFS_I(inode)->flags & BTRFS_INODE_NOCOMPRESS)
442 if (btrfs_test_opt(fs_info, COMPRESS) ||
443 BTRFS_I(inode)->flags & BTRFS_INODE_COMPRESS ||
444 BTRFS_I(inode)->prop_compress)
445 return btrfs_compress_heuristic(inode, start, end);
449 static inline void inode_should_defrag(struct btrfs_inode *inode,
450 u64 start, u64 end, u64 num_bytes, u64 small_write)
452 /* If this is a small write inside eof, kick off a defrag */
453 if (num_bytes < small_write &&
454 (start > 0 || end + 1 < inode->disk_i_size))
455 btrfs_add_inode_defrag(NULL, inode);
459 * we create compressed extents in two phases. The first
460 * phase compresses a range of pages that have already been
461 * locked (both pages and state bits are locked).
463 * This is done inside an ordered work queue, and the compression
464 * is spread across many cpus. The actual IO submission is step
465 * two, and the ordered work queue takes care of making sure that
466 * happens in the same order things were put onto the queue by
467 * writepages and friends.
469 * If this code finds it can't get good compression, it puts an
470 * entry onto the work queue to write the uncompressed bytes. This
471 * makes sure that both compressed inodes and uncompressed inodes
472 * are written in the same order that the flusher thread sent them
475 static noinline void compress_file_range(struct inode *inode,
476 struct page *locked_page,
478 struct async_cow *async_cow,
481 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
482 struct btrfs_root *root = BTRFS_I(inode)->root;
484 u64 blocksize = fs_info->sectorsize;
486 u64 isize = i_size_read(inode);
488 struct page **pages = NULL;
489 unsigned long nr_pages;
490 unsigned long total_compressed = 0;
491 unsigned long total_in = 0;
494 int compress_type = fs_info->compress_type;
497 inode_should_defrag(BTRFS_I(inode), start, end, end - start + 1,
500 actual_end = min_t(u64, isize, end + 1);
503 nr_pages = (end >> PAGE_SHIFT) - (start >> PAGE_SHIFT) + 1;
504 BUILD_BUG_ON((BTRFS_MAX_COMPRESSED % PAGE_SIZE) != 0);
505 nr_pages = min_t(unsigned long, nr_pages,
506 BTRFS_MAX_COMPRESSED / PAGE_SIZE);
509 * we don't want to send crud past the end of i_size through
510 * compression, that's just a waste of CPU time. So, if the
511 * end of the file is before the start of our current
512 * requested range of bytes, we bail out to the uncompressed
513 * cleanup code that can deal with all of this.
515 * It isn't really the fastest way to fix things, but this is a
516 * very uncommon corner.
518 if (actual_end <= start)
519 goto cleanup_and_bail_uncompressed;
521 total_compressed = actual_end - start;
524 * skip compression for a small file range(<=blocksize) that
525 * isn't an inline extent, since it doesn't save disk space at all.
527 if (total_compressed <= blocksize &&
528 (start > 0 || end + 1 < BTRFS_I(inode)->disk_i_size))
529 goto cleanup_and_bail_uncompressed;
531 total_compressed = min_t(unsigned long, total_compressed,
532 BTRFS_MAX_UNCOMPRESSED);
533 num_bytes = ALIGN(end - start + 1, blocksize);
534 num_bytes = max(blocksize, num_bytes);
539 * we do compression for mount -o compress and when the
540 * inode has not been flagged as nocompress. This flag can
541 * change at any time if we discover bad compression ratios.
543 if (inode_need_compress(inode, start, end)) {
545 pages = kcalloc(nr_pages, sizeof(struct page *), GFP_NOFS);
547 /* just bail out to the uncompressed code */
552 if (BTRFS_I(inode)->defrag_compress)
553 compress_type = BTRFS_I(inode)->defrag_compress;
554 else if (BTRFS_I(inode)->prop_compress)
555 compress_type = BTRFS_I(inode)->prop_compress;
558 * we need to call clear_page_dirty_for_io on each
559 * page in the range. Otherwise applications with the file
560 * mmap'd can wander in and change the page contents while
561 * we are compressing them.
563 * If the compression fails for any reason, we set the pages
564 * dirty again later on.
566 extent_range_clear_dirty_for_io(inode, start, end);
568 ret = btrfs_compress_pages(compress_type,
569 inode->i_mapping, start,
576 unsigned long offset = total_compressed &
578 struct page *page = pages[nr_pages - 1];
581 /* zero the tail end of the last page, we might be
582 * sending it down to disk
585 kaddr = kmap_atomic(page);
586 memset(kaddr + offset, 0,
588 kunmap_atomic(kaddr);
595 /* lets try to make an inline extent */
596 if (ret || total_in < (actual_end - start)) {
597 /* we didn't compress the entire range, try
598 * to make an uncompressed inline extent.
600 ret = cow_file_range_inline(root, inode, start, end,
601 0, BTRFS_COMPRESS_NONE, NULL);
603 /* try making a compressed inline extent */
604 ret = cow_file_range_inline(root, inode, start, end,
606 compress_type, pages);
609 unsigned long clear_flags = EXTENT_DELALLOC |
610 EXTENT_DELALLOC_NEW | EXTENT_DEFRAG;
611 unsigned long page_error_op;
613 clear_flags |= (ret < 0) ? EXTENT_DO_ACCOUNTING : 0;
614 page_error_op = ret < 0 ? PAGE_SET_ERROR : 0;
617 * inline extent creation worked or returned error,
618 * we don't need to create any more async work items.
619 * Unlock and free up our temp pages.
621 extent_clear_unlock_delalloc(inode, start, end, end,
629 btrfs_free_reserved_data_space_noquota(inode,
634 * Ensure we only free the compressed pages if we have
635 * them allocated, as we can still reach here with
636 * inode_need_compress() == false.
639 for (i = 0; i < nr_pages; i++) {
640 WARN_ON(pages[i]->mapping);
652 * we aren't doing an inline extent round the compressed size
653 * up to a block size boundary so the allocator does sane
656 total_compressed = ALIGN(total_compressed, blocksize);
659 * one last check to make sure the compression is really a
660 * win, compare the page count read with the blocks on disk,
661 * compression must free at least one sector size
663 total_in = ALIGN(total_in, PAGE_SIZE);
664 if (total_compressed + blocksize <= total_in) {
665 num_bytes = total_in;
669 * The async work queues will take care of doing actual
670 * allocation on disk for these compressed pages, and
671 * will submit them to the elevator.
673 add_async_extent(async_cow, start, num_bytes,
674 total_compressed, pages, nr_pages,
677 if (start + num_bytes < end) {
688 * the compression code ran but failed to make things smaller,
689 * free any pages it allocated and our page pointer array
691 for (i = 0; i < nr_pages; i++) {
692 WARN_ON(pages[i]->mapping);
697 total_compressed = 0;
700 /* flag the file so we don't compress in the future */
701 if (!btrfs_test_opt(fs_info, FORCE_COMPRESS) &&
702 !(BTRFS_I(inode)->prop_compress)) {
703 BTRFS_I(inode)->flags |= BTRFS_INODE_NOCOMPRESS;
706 cleanup_and_bail_uncompressed:
708 * No compression, but we still need to write the pages in the file
709 * we've been given so far. redirty the locked page if it corresponds
710 * to our extent and set things up for the async work queue to run
711 * cow_file_range to do the normal delalloc dance.
713 if (page_offset(locked_page) >= start &&
714 page_offset(locked_page) <= end)
715 __set_page_dirty_nobuffers(locked_page);
716 /* unlocked later on in the async handlers */
719 extent_range_redirty_for_io(inode, start, end);
720 add_async_extent(async_cow, start, end - start + 1, 0, NULL, 0,
721 BTRFS_COMPRESS_NONE);
727 static void free_async_extent_pages(struct async_extent *async_extent)
731 if (!async_extent->pages)
734 for (i = 0; i < async_extent->nr_pages; i++) {
735 WARN_ON(async_extent->pages[i]->mapping);
736 put_page(async_extent->pages[i]);
738 kfree(async_extent->pages);
739 async_extent->nr_pages = 0;
740 async_extent->pages = NULL;
744 * phase two of compressed writeback. This is the ordered portion
745 * of the code, which only gets called in the order the work was
746 * queued. We walk all the async extents created by compress_file_range
747 * and send them down to the disk.
749 static noinline void submit_compressed_extents(struct inode *inode,
750 struct async_cow *async_cow)
752 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
753 struct async_extent *async_extent;
755 struct btrfs_key ins;
756 struct extent_map *em;
757 struct btrfs_root *root = BTRFS_I(inode)->root;
758 struct extent_io_tree *io_tree;
762 while (!list_empty(&async_cow->extents)) {
763 async_extent = list_entry(async_cow->extents.next,
764 struct async_extent, list);
765 list_del(&async_extent->list);
767 io_tree = &BTRFS_I(inode)->io_tree;
770 /* did the compression code fall back to uncompressed IO? */
771 if (!async_extent->pages) {
772 int page_started = 0;
773 unsigned long nr_written = 0;
775 lock_extent(io_tree, async_extent->start,
776 async_extent->start +
777 async_extent->ram_size - 1);
779 /* allocate blocks */
780 ret = cow_file_range(inode, async_cow->locked_page,
782 async_extent->start +
783 async_extent->ram_size - 1,
784 async_extent->start +
785 async_extent->ram_size - 1,
786 &page_started, &nr_written, 0,
792 * if page_started, cow_file_range inserted an
793 * inline extent and took care of all the unlocking
794 * and IO for us. Otherwise, we need to submit
795 * all those pages down to the drive.
797 if (!page_started && !ret)
798 extent_write_locked_range(io_tree,
799 inode, async_extent->start,
800 async_extent->start +
801 async_extent->ram_size - 1,
805 unlock_page(async_cow->locked_page);
811 lock_extent(io_tree, async_extent->start,
812 async_extent->start + async_extent->ram_size - 1);
814 ret = btrfs_reserve_extent(root, async_extent->ram_size,
815 async_extent->compressed_size,
816 async_extent->compressed_size,
817 0, alloc_hint, &ins, 1, 1);
819 free_async_extent_pages(async_extent);
821 if (ret == -ENOSPC) {
822 unlock_extent(io_tree, async_extent->start,
823 async_extent->start +
824 async_extent->ram_size - 1);
827 * we need to redirty the pages if we decide to
828 * fallback to uncompressed IO, otherwise we
829 * will not submit these pages down to lower
832 extent_range_redirty_for_io(inode,
834 async_extent->start +
835 async_extent->ram_size - 1);
842 * here we're doing allocation and writeback of the
845 em = create_io_em(inode, async_extent->start,
846 async_extent->ram_size, /* len */
847 async_extent->start, /* orig_start */
848 ins.objectid, /* block_start */
849 ins.offset, /* block_len */
850 ins.offset, /* orig_block_len */
851 async_extent->ram_size, /* ram_bytes */
852 async_extent->compress_type,
853 BTRFS_ORDERED_COMPRESSED);
855 /* ret value is not necessary due to void function */
856 goto out_free_reserve;
859 ret = btrfs_add_ordered_extent_compress(inode,
862 async_extent->ram_size,
864 BTRFS_ORDERED_COMPRESSED,
865 async_extent->compress_type);
867 btrfs_drop_extent_cache(BTRFS_I(inode),
869 async_extent->start +
870 async_extent->ram_size - 1, 0);
871 goto out_free_reserve;
873 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
876 * clear dirty, set writeback and unlock the pages.
878 extent_clear_unlock_delalloc(inode, async_extent->start,
879 async_extent->start +
880 async_extent->ram_size - 1,
881 async_extent->start +
882 async_extent->ram_size - 1,
883 NULL, EXTENT_LOCKED | EXTENT_DELALLOC,
884 PAGE_UNLOCK | PAGE_CLEAR_DIRTY |
886 if (btrfs_submit_compressed_write(inode,
888 async_extent->ram_size,
890 ins.offset, async_extent->pages,
891 async_extent->nr_pages)) {
892 struct extent_io_tree *tree = &BTRFS_I(inode)->io_tree;
893 struct page *p = async_extent->pages[0];
894 const u64 start = async_extent->start;
895 const u64 end = start + async_extent->ram_size - 1;
897 p->mapping = inode->i_mapping;
898 tree->ops->writepage_end_io_hook(p, start, end,
901 extent_clear_unlock_delalloc(inode, start, end, end,
905 free_async_extent_pages(async_extent);
907 alloc_hint = ins.objectid + ins.offset;
913 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
914 btrfs_free_reserved_extent(fs_info, ins.objectid, ins.offset, 1);
916 extent_clear_unlock_delalloc(inode, async_extent->start,
917 async_extent->start +
918 async_extent->ram_size - 1,
919 async_extent->start +
920 async_extent->ram_size - 1,
921 NULL, EXTENT_LOCKED | EXTENT_DELALLOC |
922 EXTENT_DELALLOC_NEW |
923 EXTENT_DEFRAG | EXTENT_DO_ACCOUNTING,
924 PAGE_UNLOCK | PAGE_CLEAR_DIRTY |
925 PAGE_SET_WRITEBACK | PAGE_END_WRITEBACK |
927 free_async_extent_pages(async_extent);
932 static u64 get_extent_allocation_hint(struct inode *inode, u64 start,
935 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
936 struct extent_map *em;
939 read_lock(&em_tree->lock);
940 em = search_extent_mapping(em_tree, start, num_bytes);
943 * if block start isn't an actual block number then find the
944 * first block in this inode and use that as a hint. If that
945 * block is also bogus then just don't worry about it.
947 if (em->block_start >= EXTENT_MAP_LAST_BYTE) {
949 em = search_extent_mapping(em_tree, 0, 0);
950 if (em && em->block_start < EXTENT_MAP_LAST_BYTE)
951 alloc_hint = em->block_start;
955 alloc_hint = em->block_start;
959 read_unlock(&em_tree->lock);
965 * when extent_io.c finds a delayed allocation range in the file,
966 * the call backs end up in this code. The basic idea is to
967 * allocate extents on disk for the range, and create ordered data structs
968 * in ram to track those extents.
970 * locked_page is the page that writepage had locked already. We use
971 * it to make sure we don't do extra locks or unlocks.
973 * *page_started is set to one if we unlock locked_page and do everything
974 * required to start IO on it. It may be clean and already done with
977 static noinline int cow_file_range(struct inode *inode,
978 struct page *locked_page,
979 u64 start, u64 end, u64 delalloc_end,
980 int *page_started, unsigned long *nr_written,
981 int unlock, struct btrfs_dedupe_hash *hash)
983 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
984 struct btrfs_root *root = BTRFS_I(inode)->root;
987 unsigned long ram_size;
988 u64 cur_alloc_size = 0;
990 u64 blocksize = fs_info->sectorsize;
991 struct btrfs_key ins;
992 struct extent_map *em;
994 unsigned long page_ops;
995 bool extent_reserved = false;
998 if (btrfs_is_free_space_inode(BTRFS_I(inode))) {
1004 num_bytes = ALIGN(end - start + 1, blocksize);
1005 num_bytes = max(blocksize, num_bytes);
1007 inode_should_defrag(BTRFS_I(inode), start, end, num_bytes, SZ_64K);
1010 /* lets try to make an inline extent */
1011 ret = cow_file_range_inline(root, inode, start, end, 0,
1012 BTRFS_COMPRESS_NONE, NULL);
1014 extent_clear_unlock_delalloc(inode, start, end,
1016 EXTENT_LOCKED | EXTENT_DELALLOC |
1017 EXTENT_DELALLOC_NEW |
1018 EXTENT_DEFRAG, PAGE_UNLOCK |
1019 PAGE_CLEAR_DIRTY | PAGE_SET_WRITEBACK |
1020 PAGE_END_WRITEBACK);
1021 btrfs_free_reserved_data_space_noquota(inode, start,
1023 *nr_written = *nr_written +
1024 (end - start + PAGE_SIZE) / PAGE_SIZE;
1027 } else if (ret < 0) {
1032 BUG_ON(num_bytes > btrfs_super_total_bytes(fs_info->super_copy));
1034 alloc_hint = get_extent_allocation_hint(inode, start, num_bytes);
1035 btrfs_drop_extent_cache(BTRFS_I(inode), start,
1036 start + num_bytes - 1, 0);
1039 * Relocation relies on the relocated extents to have exactly the same
1040 * size as the original extents. Normally writeback for relocation data
1041 * extents follows a NOCOW path because relocation preallocates the
1042 * extents. However, due to an operation such as scrub turning a block
1043 * group to RO mode, it may fallback to COW mode, so we must make sure
1044 * an extent allocated during COW has exactly the requested size and can
1045 * not be split into smaller extents, otherwise relocation breaks and
1046 * fails during the stage where it updates the bytenr of file extent
1049 if (root->root_key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID)
1050 min_alloc_size = num_bytes;
1052 min_alloc_size = fs_info->sectorsize;
1054 while (num_bytes > 0) {
1055 cur_alloc_size = num_bytes;
1056 ret = btrfs_reserve_extent(root, cur_alloc_size, cur_alloc_size,
1057 min_alloc_size, 0, alloc_hint,
1061 cur_alloc_size = ins.offset;
1062 extent_reserved = true;
1064 ram_size = ins.offset;
1065 em = create_io_em(inode, start, ins.offset, /* len */
1066 start, /* orig_start */
1067 ins.objectid, /* block_start */
1068 ins.offset, /* block_len */
1069 ins.offset, /* orig_block_len */
1070 ram_size, /* ram_bytes */
1071 BTRFS_COMPRESS_NONE, /* compress_type */
1072 BTRFS_ORDERED_REGULAR /* type */);
1077 free_extent_map(em);
1079 ret = btrfs_add_ordered_extent(inode, start, ins.objectid,
1080 ram_size, cur_alloc_size, 0);
1082 goto out_drop_extent_cache;
1084 if (root->root_key.objectid ==
1085 BTRFS_DATA_RELOC_TREE_OBJECTID) {
1086 ret = btrfs_reloc_clone_csums(inode, start,
1089 * Only drop cache here, and process as normal.
1091 * We must not allow extent_clear_unlock_delalloc()
1092 * at out_unlock label to free meta of this ordered
1093 * extent, as its meta should be freed by
1094 * btrfs_finish_ordered_io().
1096 * So we must continue until @start is increased to
1097 * skip current ordered extent.
1100 btrfs_drop_extent_cache(BTRFS_I(inode), start,
1101 start + ram_size - 1, 0);
1104 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
1106 /* we're not doing compressed IO, don't unlock the first
1107 * page (which the caller expects to stay locked), don't
1108 * clear any dirty bits and don't set any writeback bits
1110 * Do set the Private2 bit so we know this page was properly
1111 * setup for writepage
1113 page_ops = unlock ? PAGE_UNLOCK : 0;
1114 page_ops |= PAGE_SET_PRIVATE2;
1116 extent_clear_unlock_delalloc(inode, start,
1117 start + ram_size - 1,
1118 delalloc_end, locked_page,
1119 EXTENT_LOCKED | EXTENT_DELALLOC,
1121 if (num_bytes < cur_alloc_size)
1124 num_bytes -= cur_alloc_size;
1125 alloc_hint = ins.objectid + ins.offset;
1126 start += cur_alloc_size;
1127 extent_reserved = false;
1130 * btrfs_reloc_clone_csums() error, since start is increased
1131 * extent_clear_unlock_delalloc() at out_unlock label won't
1132 * free metadata of current ordered extent, we're OK to exit.
1140 out_drop_extent_cache:
1141 btrfs_drop_extent_cache(BTRFS_I(inode), start, start + ram_size - 1, 0);
1143 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
1144 btrfs_free_reserved_extent(fs_info, ins.objectid, ins.offset, 1);
1146 clear_bits = EXTENT_LOCKED | EXTENT_DELALLOC | EXTENT_DELALLOC_NEW |
1147 EXTENT_DEFRAG | EXTENT_CLEAR_META_RESV;
1148 page_ops = PAGE_UNLOCK | PAGE_CLEAR_DIRTY | PAGE_SET_WRITEBACK |
1151 * If we reserved an extent for our delalloc range (or a subrange) and
1152 * failed to create the respective ordered extent, then it means that
1153 * when we reserved the extent we decremented the extent's size from
1154 * the data space_info's bytes_may_use counter and incremented the
1155 * space_info's bytes_reserved counter by the same amount. We must make
1156 * sure extent_clear_unlock_delalloc() does not try to decrement again
1157 * the data space_info's bytes_may_use counter, therefore we do not pass
1158 * it the flag EXTENT_CLEAR_DATA_RESV.
1160 if (extent_reserved) {
1161 extent_clear_unlock_delalloc(inode, start,
1162 start + cur_alloc_size - 1,
1163 start + cur_alloc_size - 1,
1167 start += cur_alloc_size;
1171 extent_clear_unlock_delalloc(inode, start, end, delalloc_end,
1173 clear_bits | EXTENT_CLEAR_DATA_RESV,
1179 * work queue call back to started compression on a file and pages
1181 static noinline void async_cow_start(struct btrfs_work *work)
1183 struct async_cow *async_cow;
1185 async_cow = container_of(work, struct async_cow, work);
1187 compress_file_range(async_cow->inode, async_cow->locked_page,
1188 async_cow->start, async_cow->end, async_cow,
1190 if (num_added == 0) {
1191 btrfs_add_delayed_iput(async_cow->inode);
1192 async_cow->inode = NULL;
1197 * work queue call back to submit previously compressed pages
1199 static noinline void async_cow_submit(struct btrfs_work *work)
1201 struct btrfs_fs_info *fs_info;
1202 struct async_cow *async_cow;
1203 struct btrfs_root *root;
1204 unsigned long nr_pages;
1206 async_cow = container_of(work, struct async_cow, work);
1208 root = async_cow->root;
1209 fs_info = root->fs_info;
1210 nr_pages = (async_cow->end - async_cow->start + PAGE_SIZE) >>
1214 * atomic_sub_return implies a barrier for waitqueue_active
1216 if (atomic_sub_return(nr_pages, &fs_info->async_delalloc_pages) <
1218 waitqueue_active(&fs_info->async_submit_wait))
1219 wake_up(&fs_info->async_submit_wait);
1221 if (async_cow->inode)
1222 submit_compressed_extents(async_cow->inode, async_cow);
1225 static noinline void async_cow_free(struct btrfs_work *work)
1227 struct async_cow *async_cow;
1228 async_cow = container_of(work, struct async_cow, work);
1229 if (async_cow->inode)
1230 btrfs_add_delayed_iput(async_cow->inode);
1234 static int cow_file_range_async(struct inode *inode, struct page *locked_page,
1235 u64 start, u64 end, int *page_started,
1236 unsigned long *nr_written)
1238 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1239 struct async_cow *async_cow;
1240 struct btrfs_root *root = BTRFS_I(inode)->root;
1241 unsigned long nr_pages;
1244 clear_extent_bit(&BTRFS_I(inode)->io_tree, start, end, EXTENT_LOCKED,
1245 1, 0, NULL, GFP_NOFS);
1246 while (start < end) {
1247 async_cow = kmalloc(sizeof(*async_cow), GFP_NOFS);
1248 BUG_ON(!async_cow); /* -ENOMEM */
1249 async_cow->inode = igrab(inode);
1250 async_cow->root = root;
1251 async_cow->locked_page = locked_page;
1252 async_cow->start = start;
1254 if (BTRFS_I(inode)->flags & BTRFS_INODE_NOCOMPRESS &&
1255 !btrfs_test_opt(fs_info, FORCE_COMPRESS))
1258 cur_end = min(end, start + SZ_512K - 1);
1260 async_cow->end = cur_end;
1261 INIT_LIST_HEAD(&async_cow->extents);
1263 btrfs_init_work(&async_cow->work,
1264 btrfs_delalloc_helper,
1265 async_cow_start, async_cow_submit,
1268 nr_pages = (cur_end - start + PAGE_SIZE) >>
1270 atomic_add(nr_pages, &fs_info->async_delalloc_pages);
1272 btrfs_queue_work(fs_info->delalloc_workers, &async_cow->work);
1274 while (atomic_read(&fs_info->async_submit_draining) &&
1275 atomic_read(&fs_info->async_delalloc_pages)) {
1276 wait_event(fs_info->async_submit_wait,
1277 (atomic_read(&fs_info->async_delalloc_pages) ==
1281 *nr_written += nr_pages;
1282 start = cur_end + 1;
1288 static noinline int csum_exist_in_range(struct btrfs_fs_info *fs_info,
1289 u64 bytenr, u64 num_bytes)
1292 struct btrfs_ordered_sum *sums;
1295 ret = btrfs_lookup_csums_range(fs_info->csum_root, bytenr,
1296 bytenr + num_bytes - 1, &list, 0);
1297 if (ret == 0 && list_empty(&list))
1300 while (!list_empty(&list)) {
1301 sums = list_entry(list.next, struct btrfs_ordered_sum, list);
1302 list_del(&sums->list);
1311 * when nowcow writeback call back. This checks for snapshots or COW copies
1312 * of the extents that exist in the file, and COWs the file as required.
1314 * If no cow copies or snapshots exist, we write directly to the existing
1317 static noinline int run_delalloc_nocow(struct inode *inode,
1318 struct page *locked_page,
1319 u64 start, u64 end, int *page_started, int force,
1320 unsigned long *nr_written)
1322 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1323 struct btrfs_root *root = BTRFS_I(inode)->root;
1324 struct extent_buffer *leaf;
1325 struct btrfs_path *path;
1326 struct btrfs_file_extent_item *fi;
1327 struct btrfs_key found_key;
1328 struct extent_map *em;
1343 u64 ino = btrfs_ino(BTRFS_I(inode));
1345 path = btrfs_alloc_path();
1347 extent_clear_unlock_delalloc(inode, start, end, end,
1349 EXTENT_LOCKED | EXTENT_DELALLOC |
1350 EXTENT_DO_ACCOUNTING |
1351 EXTENT_DEFRAG, PAGE_UNLOCK |
1353 PAGE_SET_WRITEBACK |
1354 PAGE_END_WRITEBACK);
1358 nolock = btrfs_is_free_space_inode(BTRFS_I(inode));
1360 cow_start = (u64)-1;
1363 ret = btrfs_lookup_file_extent(NULL, root, path, ino,
1367 if (ret > 0 && path->slots[0] > 0 && check_prev) {
1368 leaf = path->nodes[0];
1369 btrfs_item_key_to_cpu(leaf, &found_key,
1370 path->slots[0] - 1);
1371 if (found_key.objectid == ino &&
1372 found_key.type == BTRFS_EXTENT_DATA_KEY)
1377 leaf = path->nodes[0];
1378 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
1379 ret = btrfs_next_leaf(root, path);
1381 if (cow_start != (u64)-1)
1382 cur_offset = cow_start;
1387 leaf = path->nodes[0];
1393 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
1395 if (found_key.objectid > ino)
1397 if (WARN_ON_ONCE(found_key.objectid < ino) ||
1398 found_key.type < BTRFS_EXTENT_DATA_KEY) {
1402 if (found_key.type > BTRFS_EXTENT_DATA_KEY ||
1403 found_key.offset > end)
1406 if (found_key.offset > cur_offset) {
1407 extent_end = found_key.offset;
1412 fi = btrfs_item_ptr(leaf, path->slots[0],
1413 struct btrfs_file_extent_item);
1414 extent_type = btrfs_file_extent_type(leaf, fi);
1416 ram_bytes = btrfs_file_extent_ram_bytes(leaf, fi);
1417 if (extent_type == BTRFS_FILE_EXTENT_REG ||
1418 extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
1419 disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
1420 extent_offset = btrfs_file_extent_offset(leaf, fi);
1421 extent_end = found_key.offset +
1422 btrfs_file_extent_num_bytes(leaf, fi);
1424 btrfs_file_extent_disk_num_bytes(leaf, fi);
1425 if (extent_end <= start) {
1429 if (disk_bytenr == 0)
1431 if (btrfs_file_extent_compression(leaf, fi) ||
1432 btrfs_file_extent_encryption(leaf, fi) ||
1433 btrfs_file_extent_other_encoding(leaf, fi))
1435 if (extent_type == BTRFS_FILE_EXTENT_REG && !force)
1437 if (btrfs_extent_readonly(fs_info, disk_bytenr))
1439 ret = btrfs_cross_ref_exist(root, ino,
1441 extent_offset, disk_bytenr);
1444 * ret could be -EIO if the above fails to read
1448 if (cow_start != (u64)-1)
1449 cur_offset = cow_start;
1453 WARN_ON_ONCE(nolock);
1456 disk_bytenr += extent_offset;
1457 disk_bytenr += cur_offset - found_key.offset;
1458 num_bytes = min(end + 1, extent_end) - cur_offset;
1460 * if there are pending snapshots for this root,
1461 * we fall into common COW way.
1463 if (!nolock && atomic_read(&root->snapshot_force_cow))
1466 * force cow if csum exists in the range.
1467 * this ensure that csum for a given extent are
1468 * either valid or do not exist.
1470 ret = csum_exist_in_range(fs_info, disk_bytenr,
1474 * ret could be -EIO if the above fails to read
1478 if (cow_start != (u64)-1)
1479 cur_offset = cow_start;
1482 WARN_ON_ONCE(nolock);
1485 if (!btrfs_inc_nocow_writers(fs_info, disk_bytenr))
1488 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
1489 extent_end = found_key.offset +
1490 btrfs_file_extent_ram_bytes(leaf, fi);
1491 extent_end = ALIGN(extent_end,
1492 fs_info->sectorsize);
1497 if (extent_end <= start) {
1500 btrfs_dec_nocow_writers(fs_info, disk_bytenr);
1504 if (cow_start == (u64)-1)
1505 cow_start = cur_offset;
1506 cur_offset = extent_end;
1507 if (cur_offset > end)
1513 btrfs_release_path(path);
1514 if (cow_start != (u64)-1) {
1515 ret = cow_file_range(inode, locked_page,
1516 cow_start, found_key.offset - 1,
1517 end, page_started, nr_written, 1,
1521 btrfs_dec_nocow_writers(fs_info,
1525 cow_start = (u64)-1;
1528 if (extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
1529 u64 orig_start = found_key.offset - extent_offset;
1531 em = create_io_em(inode, cur_offset, num_bytes,
1533 disk_bytenr, /* block_start */
1534 num_bytes, /* block_len */
1535 disk_num_bytes, /* orig_block_len */
1536 ram_bytes, BTRFS_COMPRESS_NONE,
1537 BTRFS_ORDERED_PREALLOC);
1540 btrfs_dec_nocow_writers(fs_info,
1545 free_extent_map(em);
1548 if (extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
1549 type = BTRFS_ORDERED_PREALLOC;
1551 type = BTRFS_ORDERED_NOCOW;
1554 ret = btrfs_add_ordered_extent(inode, cur_offset, disk_bytenr,
1555 num_bytes, num_bytes, type);
1557 btrfs_dec_nocow_writers(fs_info, disk_bytenr);
1558 BUG_ON(ret); /* -ENOMEM */
1560 if (root->root_key.objectid ==
1561 BTRFS_DATA_RELOC_TREE_OBJECTID)
1563 * Error handled later, as we must prevent
1564 * extent_clear_unlock_delalloc() in error handler
1565 * from freeing metadata of created ordered extent.
1567 ret = btrfs_reloc_clone_csums(inode, cur_offset,
1570 extent_clear_unlock_delalloc(inode, cur_offset,
1571 cur_offset + num_bytes - 1, end,
1572 locked_page, EXTENT_LOCKED |
1574 EXTENT_CLEAR_DATA_RESV,
1575 PAGE_UNLOCK | PAGE_SET_PRIVATE2);
1577 cur_offset = extent_end;
1580 * btrfs_reloc_clone_csums() error, now we're OK to call error
1581 * handler, as metadata for created ordered extent will only
1582 * be freed by btrfs_finish_ordered_io().
1586 if (cur_offset > end)
1589 btrfs_release_path(path);
1591 if (cur_offset <= end && cow_start == (u64)-1)
1592 cow_start = cur_offset;
1594 if (cow_start != (u64)-1) {
1596 ret = cow_file_range(inode, locked_page, cow_start, end, end,
1597 page_started, nr_written, 1, NULL);
1603 if (ret && cur_offset < end)
1604 extent_clear_unlock_delalloc(inode, cur_offset, end, end,
1605 locked_page, EXTENT_LOCKED |
1606 EXTENT_DELALLOC | EXTENT_DEFRAG |
1607 EXTENT_DO_ACCOUNTING, PAGE_UNLOCK |
1609 PAGE_SET_WRITEBACK |
1610 PAGE_END_WRITEBACK);
1611 btrfs_free_path(path);
1615 static inline int need_force_cow(struct inode *inode, u64 start, u64 end)
1618 if (!(BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW) &&
1619 !(BTRFS_I(inode)->flags & BTRFS_INODE_PREALLOC))
1623 * @defrag_bytes is a hint value, no spinlock held here,
1624 * if is not zero, it means the file is defragging.
1625 * Force cow if given extent needs to be defragged.
1627 if (BTRFS_I(inode)->defrag_bytes &&
1628 test_range_bit(&BTRFS_I(inode)->io_tree, start, end,
1629 EXTENT_DEFRAG, 0, NULL))
1636 * extent_io.c call back to do delayed allocation processing
1638 static int run_delalloc_range(void *private_data, struct page *locked_page,
1639 u64 start, u64 end, int *page_started,
1640 unsigned long *nr_written)
1642 struct inode *inode = private_data;
1644 int force_cow = need_force_cow(inode, start, end);
1646 if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW && !force_cow) {
1647 ret = run_delalloc_nocow(inode, locked_page, start, end,
1648 page_started, 1, nr_written);
1649 } else if (BTRFS_I(inode)->flags & BTRFS_INODE_PREALLOC && !force_cow) {
1650 ret = run_delalloc_nocow(inode, locked_page, start, end,
1651 page_started, 0, nr_written);
1652 } else if (!inode_can_compress(inode) ||
1653 !inode_need_compress(inode, start, end)) {
1654 ret = cow_file_range(inode, locked_page, start, end, end,
1655 page_started, nr_written, 1, NULL);
1657 set_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
1658 &BTRFS_I(inode)->runtime_flags);
1659 ret = cow_file_range_async(inode, locked_page, start, end,
1660 page_started, nr_written);
1663 btrfs_cleanup_ordered_extents(inode, start, end - start + 1);
1667 static void btrfs_split_extent_hook(void *private_data,
1668 struct extent_state *orig, u64 split)
1670 struct inode *inode = private_data;
1673 /* not delalloc, ignore it */
1674 if (!(orig->state & EXTENT_DELALLOC))
1677 size = orig->end - orig->start + 1;
1678 if (size > BTRFS_MAX_EXTENT_SIZE) {
1683 * See the explanation in btrfs_merge_extent_hook, the same
1684 * applies here, just in reverse.
1686 new_size = orig->end - split + 1;
1687 num_extents = count_max_extents(new_size);
1688 new_size = split - orig->start;
1689 num_extents += count_max_extents(new_size);
1690 if (count_max_extents(size) >= num_extents)
1694 spin_lock(&BTRFS_I(inode)->lock);
1695 BTRFS_I(inode)->outstanding_extents++;
1696 spin_unlock(&BTRFS_I(inode)->lock);
1700 * extent_io.c merge_extent_hook, used to track merged delayed allocation
1701 * extents so we can keep track of new extents that are just merged onto old
1702 * extents, such as when we are doing sequential writes, so we can properly
1703 * account for the metadata space we'll need.
1705 static void btrfs_merge_extent_hook(void *private_data,
1706 struct extent_state *new,
1707 struct extent_state *other)
1709 struct inode *inode = private_data;
1710 u64 new_size, old_size;
1713 /* not delalloc, ignore it */
1714 if (!(other->state & EXTENT_DELALLOC))
1717 if (new->start > other->start)
1718 new_size = new->end - other->start + 1;
1720 new_size = other->end - new->start + 1;
1722 /* we're not bigger than the max, unreserve the space and go */
1723 if (new_size <= BTRFS_MAX_EXTENT_SIZE) {
1724 spin_lock(&BTRFS_I(inode)->lock);
1725 BTRFS_I(inode)->outstanding_extents--;
1726 spin_unlock(&BTRFS_I(inode)->lock);
1731 * We have to add up either side to figure out how many extents were
1732 * accounted for before we merged into one big extent. If the number of
1733 * extents we accounted for is <= the amount we need for the new range
1734 * then we can return, otherwise drop. Think of it like this
1738 * So we've grown the extent by a MAX_SIZE extent, this would mean we
1739 * need 2 outstanding extents, on one side we have 1 and the other side
1740 * we have 1 so they are == and we can return. But in this case
1742 * [MAX_SIZE+4k][MAX_SIZE+4k]
1744 * Each range on their own accounts for 2 extents, but merged together
1745 * they are only 3 extents worth of accounting, so we need to drop in
1748 old_size = other->end - other->start + 1;
1749 num_extents = count_max_extents(old_size);
1750 old_size = new->end - new->start + 1;
1751 num_extents += count_max_extents(old_size);
1752 if (count_max_extents(new_size) >= num_extents)
1755 spin_lock(&BTRFS_I(inode)->lock);
1756 BTRFS_I(inode)->outstanding_extents--;
1757 spin_unlock(&BTRFS_I(inode)->lock);
1760 static void btrfs_add_delalloc_inodes(struct btrfs_root *root,
1761 struct inode *inode)
1763 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1765 spin_lock(&root->delalloc_lock);
1766 if (list_empty(&BTRFS_I(inode)->delalloc_inodes)) {
1767 list_add_tail(&BTRFS_I(inode)->delalloc_inodes,
1768 &root->delalloc_inodes);
1769 set_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1770 &BTRFS_I(inode)->runtime_flags);
1771 root->nr_delalloc_inodes++;
1772 if (root->nr_delalloc_inodes == 1) {
1773 spin_lock(&fs_info->delalloc_root_lock);
1774 BUG_ON(!list_empty(&root->delalloc_root));
1775 list_add_tail(&root->delalloc_root,
1776 &fs_info->delalloc_roots);
1777 spin_unlock(&fs_info->delalloc_root_lock);
1780 spin_unlock(&root->delalloc_lock);
1784 void __btrfs_del_delalloc_inode(struct btrfs_root *root,
1785 struct btrfs_inode *inode)
1787 struct btrfs_fs_info *fs_info = btrfs_sb(inode->vfs_inode.i_sb);
1789 if (!list_empty(&inode->delalloc_inodes)) {
1790 list_del_init(&inode->delalloc_inodes);
1791 clear_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1792 &inode->runtime_flags);
1793 root->nr_delalloc_inodes--;
1794 if (!root->nr_delalloc_inodes) {
1795 spin_lock(&fs_info->delalloc_root_lock);
1796 BUG_ON(list_empty(&root->delalloc_root));
1797 list_del_init(&root->delalloc_root);
1798 spin_unlock(&fs_info->delalloc_root_lock);
1803 static void btrfs_del_delalloc_inode(struct btrfs_root *root,
1804 struct btrfs_inode *inode)
1806 spin_lock(&root->delalloc_lock);
1807 __btrfs_del_delalloc_inode(root, inode);
1808 spin_unlock(&root->delalloc_lock);
1812 * extent_io.c set_bit_hook, used to track delayed allocation
1813 * bytes in this file, and to maintain the list of inodes that
1814 * have pending delalloc work to be done.
1816 static void btrfs_set_bit_hook(void *private_data,
1817 struct extent_state *state, unsigned *bits)
1819 struct inode *inode = private_data;
1821 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1823 if ((*bits & EXTENT_DEFRAG) && !(*bits & EXTENT_DELALLOC))
1826 * set_bit and clear bit hooks normally require _irqsave/restore
1827 * but in this case, we are only testing for the DELALLOC
1828 * bit, which is only set or cleared with irqs on
1830 if (!(state->state & EXTENT_DELALLOC) && (*bits & EXTENT_DELALLOC)) {
1831 struct btrfs_root *root = BTRFS_I(inode)->root;
1832 u64 len = state->end + 1 - state->start;
1833 bool do_list = !btrfs_is_free_space_inode(BTRFS_I(inode));
1835 if (*bits & EXTENT_FIRST_DELALLOC) {
1836 *bits &= ~EXTENT_FIRST_DELALLOC;
1838 spin_lock(&BTRFS_I(inode)->lock);
1839 BTRFS_I(inode)->outstanding_extents++;
1840 spin_unlock(&BTRFS_I(inode)->lock);
1843 /* For sanity tests */
1844 if (btrfs_is_testing(fs_info))
1847 percpu_counter_add_batch(&fs_info->delalloc_bytes, len,
1848 fs_info->delalloc_batch);
1849 spin_lock(&BTRFS_I(inode)->lock);
1850 BTRFS_I(inode)->delalloc_bytes += len;
1851 if (*bits & EXTENT_DEFRAG)
1852 BTRFS_I(inode)->defrag_bytes += len;
1853 if (do_list && !test_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1854 &BTRFS_I(inode)->runtime_flags))
1855 btrfs_add_delalloc_inodes(root, inode);
1856 spin_unlock(&BTRFS_I(inode)->lock);
1859 if (!(state->state & EXTENT_DELALLOC_NEW) &&
1860 (*bits & EXTENT_DELALLOC_NEW)) {
1861 spin_lock(&BTRFS_I(inode)->lock);
1862 BTRFS_I(inode)->new_delalloc_bytes += state->end + 1 -
1864 spin_unlock(&BTRFS_I(inode)->lock);
1869 * extent_io.c clear_bit_hook, see set_bit_hook for why
1871 static void btrfs_clear_bit_hook(void *private_data,
1872 struct extent_state *state,
1875 struct btrfs_inode *inode = BTRFS_I((struct inode *)private_data);
1876 struct btrfs_fs_info *fs_info = btrfs_sb(inode->vfs_inode.i_sb);
1877 u64 len = state->end + 1 - state->start;
1878 u32 num_extents = count_max_extents(len);
1880 if ((state->state & EXTENT_DEFRAG) && (*bits & EXTENT_DEFRAG)) {
1881 spin_lock(&inode->lock);
1882 inode->defrag_bytes -= len;
1883 spin_unlock(&inode->lock);
1887 * set_bit and clear bit hooks normally require _irqsave/restore
1888 * but in this case, we are only testing for the DELALLOC
1889 * bit, which is only set or cleared with irqs on
1891 if ((state->state & EXTENT_DELALLOC) && (*bits & EXTENT_DELALLOC)) {
1892 struct btrfs_root *root = inode->root;
1893 bool do_list = !btrfs_is_free_space_inode(inode);
1895 if (*bits & EXTENT_FIRST_DELALLOC) {
1896 *bits &= ~EXTENT_FIRST_DELALLOC;
1897 } else if (!(*bits & EXTENT_CLEAR_META_RESV)) {
1898 spin_lock(&inode->lock);
1899 inode->outstanding_extents -= num_extents;
1900 spin_unlock(&inode->lock);
1904 * We don't reserve metadata space for space cache inodes so we
1905 * don't need to call dellalloc_release_metadata if there is an
1908 if (*bits & EXTENT_CLEAR_META_RESV &&
1909 root != fs_info->tree_root)
1910 btrfs_delalloc_release_metadata(inode, len);
1912 /* For sanity tests. */
1913 if (btrfs_is_testing(fs_info))
1916 if (root->root_key.objectid != BTRFS_DATA_RELOC_TREE_OBJECTID &&
1917 do_list && !(state->state & EXTENT_NORESERVE) &&
1918 (*bits & EXTENT_CLEAR_DATA_RESV))
1919 btrfs_free_reserved_data_space_noquota(
1923 percpu_counter_add_batch(&fs_info->delalloc_bytes, -len,
1924 fs_info->delalloc_batch);
1925 spin_lock(&inode->lock);
1926 inode->delalloc_bytes -= len;
1927 if (do_list && inode->delalloc_bytes == 0 &&
1928 test_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1929 &inode->runtime_flags))
1930 btrfs_del_delalloc_inode(root, inode);
1931 spin_unlock(&inode->lock);
1934 if ((state->state & EXTENT_DELALLOC_NEW) &&
1935 (*bits & EXTENT_DELALLOC_NEW)) {
1936 spin_lock(&inode->lock);
1937 ASSERT(inode->new_delalloc_bytes >= len);
1938 inode->new_delalloc_bytes -= len;
1939 spin_unlock(&inode->lock);
1944 * extent_io.c merge_bio_hook, this must check the chunk tree to make sure
1945 * we don't create bios that span stripes or chunks
1947 * return 1 if page cannot be merged to bio
1948 * return 0 if page can be merged to bio
1949 * return error otherwise
1951 int btrfs_merge_bio_hook(struct page *page, unsigned long offset,
1952 size_t size, struct bio *bio,
1953 unsigned long bio_flags)
1955 struct inode *inode = page->mapping->host;
1956 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1957 u64 logical = (u64)bio->bi_iter.bi_sector << 9;
1962 if (bio_flags & EXTENT_BIO_COMPRESSED)
1965 length = bio->bi_iter.bi_size;
1966 map_length = length;
1967 ret = btrfs_map_block(fs_info, btrfs_op(bio), logical, &map_length,
1971 if (map_length < length + size)
1977 * in order to insert checksums into the metadata in large chunks,
1978 * we wait until bio submission time. All the pages in the bio are
1979 * checksummed and sums are attached onto the ordered extent record.
1981 * At IO completion time the cums attached on the ordered extent record
1982 * are inserted into the btree
1984 static blk_status_t __btrfs_submit_bio_start(void *private_data, struct bio *bio,
1985 int mirror_num, unsigned long bio_flags,
1988 struct inode *inode = private_data;
1989 blk_status_t ret = 0;
1991 ret = btrfs_csum_one_bio(inode, bio, 0, 0);
1992 BUG_ON(ret); /* -ENOMEM */
1997 * in order to insert checksums into the metadata in large chunks,
1998 * we wait until bio submission time. All the pages in the bio are
1999 * checksummed and sums are attached onto the ordered extent record.
2001 * At IO completion time the cums attached on the ordered extent record
2002 * are inserted into the btree
2004 static blk_status_t __btrfs_submit_bio_done(void *private_data, struct bio *bio,
2005 int mirror_num, unsigned long bio_flags,
2008 struct inode *inode = private_data;
2009 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2012 ret = btrfs_map_bio(fs_info, bio, mirror_num, 1);
2014 bio->bi_status = ret;
2021 * extent_io.c submission hook. This does the right thing for csum calculation
2022 * on write, or reading the csums from the tree before a read
2024 static blk_status_t btrfs_submit_bio_hook(void *private_data, struct bio *bio,
2025 int mirror_num, unsigned long bio_flags,
2028 struct inode *inode = private_data;
2029 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2030 struct btrfs_root *root = BTRFS_I(inode)->root;
2031 enum btrfs_wq_endio_type metadata = BTRFS_WQ_ENDIO_DATA;
2032 blk_status_t ret = 0;
2034 int async = !atomic_read(&BTRFS_I(inode)->sync_writers);
2036 skip_sum = BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM;
2038 if (btrfs_is_free_space_inode(BTRFS_I(inode)))
2039 metadata = BTRFS_WQ_ENDIO_FREE_SPACE;
2041 if (bio_op(bio) != REQ_OP_WRITE) {
2042 ret = btrfs_bio_wq_end_io(fs_info, bio, metadata);
2046 if (bio_flags & EXTENT_BIO_COMPRESSED) {
2047 ret = btrfs_submit_compressed_read(inode, bio,
2051 } else if (!skip_sum) {
2052 ret = btrfs_lookup_bio_sums(inode, bio, NULL);
2057 } else if (async && !skip_sum) {
2058 /* csum items have already been cloned */
2059 if (root->root_key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID)
2061 /* we're doing a write, do the async checksumming */
2062 ret = btrfs_wq_submit_bio(fs_info, bio, mirror_num, bio_flags,
2064 __btrfs_submit_bio_start,
2065 __btrfs_submit_bio_done);
2067 } else if (!skip_sum) {
2068 ret = btrfs_csum_one_bio(inode, bio, 0, 0);
2074 ret = btrfs_map_bio(fs_info, bio, mirror_num, 0);
2078 bio->bi_status = ret;
2085 * given a list of ordered sums record them in the inode. This happens
2086 * at IO completion time based on sums calculated at bio submission time.
2088 static noinline int add_pending_csums(struct btrfs_trans_handle *trans,
2089 struct inode *inode, struct list_head *list)
2091 struct btrfs_ordered_sum *sum;
2093 list_for_each_entry(sum, list, list) {
2094 trans->adding_csums = 1;
2095 btrfs_csum_file_blocks(trans,
2096 BTRFS_I(inode)->root->fs_info->csum_root, sum);
2097 trans->adding_csums = 0;
2102 int btrfs_set_extent_delalloc(struct inode *inode, u64 start, u64 end,
2103 struct extent_state **cached_state, int dedupe)
2105 WARN_ON((end & (PAGE_SIZE - 1)) == 0);
2106 return set_extent_delalloc(&BTRFS_I(inode)->io_tree, start, end,
2110 /* see btrfs_writepage_start_hook for details on why this is required */
2111 struct btrfs_writepage_fixup {
2113 struct btrfs_work work;
2116 static void btrfs_writepage_fixup_worker(struct btrfs_work *work)
2118 struct btrfs_writepage_fixup *fixup;
2119 struct btrfs_ordered_extent *ordered;
2120 struct extent_state *cached_state = NULL;
2121 struct extent_changeset *data_reserved = NULL;
2123 struct inode *inode;
2128 fixup = container_of(work, struct btrfs_writepage_fixup, work);
2132 if (!page->mapping || !PageDirty(page) || !PageChecked(page)) {
2133 ClearPageChecked(page);
2137 inode = page->mapping->host;
2138 page_start = page_offset(page);
2139 page_end = page_offset(page) + PAGE_SIZE - 1;
2141 lock_extent_bits(&BTRFS_I(inode)->io_tree, page_start, page_end,
2144 /* already ordered? We're done */
2145 if (PagePrivate2(page))
2148 ordered = btrfs_lookup_ordered_range(BTRFS_I(inode), page_start,
2151 unlock_extent_cached(&BTRFS_I(inode)->io_tree, page_start,
2152 page_end, &cached_state, GFP_NOFS);
2154 btrfs_start_ordered_extent(inode, ordered, 1);
2155 btrfs_put_ordered_extent(ordered);
2159 ret = btrfs_delalloc_reserve_space(inode, &data_reserved, page_start,
2162 mapping_set_error(page->mapping, ret);
2163 end_extent_writepage(page, ret, page_start, page_end);
2164 ClearPageChecked(page);
2168 ret = btrfs_set_extent_delalloc(inode, page_start, page_end,
2171 mapping_set_error(page->mapping, ret);
2172 end_extent_writepage(page, ret, page_start, page_end);
2173 ClearPageChecked(page);
2177 ClearPageChecked(page);
2178 set_page_dirty(page);
2180 unlock_extent_cached(&BTRFS_I(inode)->io_tree, page_start, page_end,
2181 &cached_state, GFP_NOFS);
2186 extent_changeset_free(data_reserved);
2190 * There are a few paths in the higher layers of the kernel that directly
2191 * set the page dirty bit without asking the filesystem if it is a
2192 * good idea. This causes problems because we want to make sure COW
2193 * properly happens and the data=ordered rules are followed.
2195 * In our case any range that doesn't have the ORDERED bit set
2196 * hasn't been properly setup for IO. We kick off an async process
2197 * to fix it up. The async helper will wait for ordered extents, set
2198 * the delalloc bit and make it safe to write the page.
2200 static int btrfs_writepage_start_hook(struct page *page, u64 start, u64 end)
2202 struct inode *inode = page->mapping->host;
2203 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2204 struct btrfs_writepage_fixup *fixup;
2206 /* this page is properly in the ordered list */
2207 if (TestClearPagePrivate2(page))
2210 if (PageChecked(page))
2213 fixup = kzalloc(sizeof(*fixup), GFP_NOFS);
2217 SetPageChecked(page);
2219 btrfs_init_work(&fixup->work, btrfs_fixup_helper,
2220 btrfs_writepage_fixup_worker, NULL, NULL);
2222 btrfs_queue_work(fs_info->fixup_workers, &fixup->work);
2226 static int insert_reserved_file_extent(struct btrfs_trans_handle *trans,
2227 struct inode *inode, u64 file_pos,
2228 u64 disk_bytenr, u64 disk_num_bytes,
2229 u64 num_bytes, u64 ram_bytes,
2230 u8 compression, u8 encryption,
2231 u16 other_encoding, int extent_type)
2233 struct btrfs_root *root = BTRFS_I(inode)->root;
2234 struct btrfs_file_extent_item *fi;
2235 struct btrfs_path *path;
2236 struct extent_buffer *leaf;
2237 struct btrfs_key ins;
2239 int extent_inserted = 0;
2242 path = btrfs_alloc_path();
2247 * we may be replacing one extent in the tree with another.
2248 * The new extent is pinned in the extent map, and we don't want
2249 * to drop it from the cache until it is completely in the btree.
2251 * So, tell btrfs_drop_extents to leave this extent in the cache.
2252 * the caller is expected to unpin it and allow it to be merged
2255 ret = __btrfs_drop_extents(trans, root, inode, path, file_pos,
2256 file_pos + num_bytes, NULL, 0,
2257 1, sizeof(*fi), &extent_inserted);
2261 if (!extent_inserted) {
2262 ins.objectid = btrfs_ino(BTRFS_I(inode));
2263 ins.offset = file_pos;
2264 ins.type = BTRFS_EXTENT_DATA_KEY;
2266 path->leave_spinning = 1;
2267 ret = btrfs_insert_empty_item(trans, root, path, &ins,
2272 leaf = path->nodes[0];
2273 fi = btrfs_item_ptr(leaf, path->slots[0],
2274 struct btrfs_file_extent_item);
2275 btrfs_set_file_extent_generation(leaf, fi, trans->transid);
2276 btrfs_set_file_extent_type(leaf, fi, extent_type);
2277 btrfs_set_file_extent_disk_bytenr(leaf, fi, disk_bytenr);
2278 btrfs_set_file_extent_disk_num_bytes(leaf, fi, disk_num_bytes);
2279 btrfs_set_file_extent_offset(leaf, fi, 0);
2280 btrfs_set_file_extent_num_bytes(leaf, fi, num_bytes);
2281 btrfs_set_file_extent_ram_bytes(leaf, fi, ram_bytes);
2282 btrfs_set_file_extent_compression(leaf, fi, compression);
2283 btrfs_set_file_extent_encryption(leaf, fi, encryption);
2284 btrfs_set_file_extent_other_encoding(leaf, fi, other_encoding);
2286 btrfs_mark_buffer_dirty(leaf);
2287 btrfs_release_path(path);
2289 inode_add_bytes(inode, num_bytes);
2291 ins.objectid = disk_bytenr;
2292 ins.offset = disk_num_bytes;
2293 ins.type = BTRFS_EXTENT_ITEM_KEY;
2296 * Release the reserved range from inode dirty range map, as it is
2297 * already moved into delayed_ref_head
2299 ret = btrfs_qgroup_release_data(inode, file_pos, ram_bytes);
2303 ret = btrfs_alloc_reserved_file_extent(trans, root->root_key.objectid,
2304 btrfs_ino(BTRFS_I(inode)), file_pos, qg_released, &ins);
2306 btrfs_free_path(path);
2311 /* snapshot-aware defrag */
2312 struct sa_defrag_extent_backref {
2313 struct rb_node node;
2314 struct old_sa_defrag_extent *old;
2323 struct old_sa_defrag_extent {
2324 struct list_head list;
2325 struct new_sa_defrag_extent *new;
2334 struct new_sa_defrag_extent {
2335 struct rb_root root;
2336 struct list_head head;
2337 struct btrfs_path *path;
2338 struct inode *inode;
2346 static int backref_comp(struct sa_defrag_extent_backref *b1,
2347 struct sa_defrag_extent_backref *b2)
2349 if (b1->root_id < b2->root_id)
2351 else if (b1->root_id > b2->root_id)
2354 if (b1->inum < b2->inum)
2356 else if (b1->inum > b2->inum)
2359 if (b1->file_pos < b2->file_pos)
2361 else if (b1->file_pos > b2->file_pos)
2365 * [------------------------------] ===> (a range of space)
2366 * |<--->| |<---->| =============> (fs/file tree A)
2367 * |<---------------------------->| ===> (fs/file tree B)
2369 * A range of space can refer to two file extents in one tree while
2370 * refer to only one file extent in another tree.
2372 * So we may process a disk offset more than one time(two extents in A)
2373 * and locate at the same extent(one extent in B), then insert two same
2374 * backrefs(both refer to the extent in B).
2379 static void backref_insert(struct rb_root *root,
2380 struct sa_defrag_extent_backref *backref)
2382 struct rb_node **p = &root->rb_node;
2383 struct rb_node *parent = NULL;
2384 struct sa_defrag_extent_backref *entry;
2389 entry = rb_entry(parent, struct sa_defrag_extent_backref, node);
2391 ret = backref_comp(backref, entry);
2395 p = &(*p)->rb_right;
2398 rb_link_node(&backref->node, parent, p);
2399 rb_insert_color(&backref->node, root);
2403 * Note the backref might has changed, and in this case we just return 0.
2405 static noinline int record_one_backref(u64 inum, u64 offset, u64 root_id,
2408 struct btrfs_file_extent_item *extent;
2409 struct old_sa_defrag_extent *old = ctx;
2410 struct new_sa_defrag_extent *new = old->new;
2411 struct btrfs_path *path = new->path;
2412 struct btrfs_key key;
2413 struct btrfs_root *root;
2414 struct sa_defrag_extent_backref *backref;
2415 struct extent_buffer *leaf;
2416 struct inode *inode = new->inode;
2417 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2423 if (BTRFS_I(inode)->root->root_key.objectid == root_id &&
2424 inum == btrfs_ino(BTRFS_I(inode)))
2427 key.objectid = root_id;
2428 key.type = BTRFS_ROOT_ITEM_KEY;
2429 key.offset = (u64)-1;
2431 root = btrfs_read_fs_root_no_name(fs_info, &key);
2433 if (PTR_ERR(root) == -ENOENT)
2436 btrfs_debug(fs_info, "inum=%llu, offset=%llu, root_id=%llu",
2437 inum, offset, root_id);
2438 return PTR_ERR(root);
2441 key.objectid = inum;
2442 key.type = BTRFS_EXTENT_DATA_KEY;
2443 if (offset > (u64)-1 << 32)
2446 key.offset = offset;
2448 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2449 if (WARN_ON(ret < 0))
2456 leaf = path->nodes[0];
2457 slot = path->slots[0];
2459 if (slot >= btrfs_header_nritems(leaf)) {
2460 ret = btrfs_next_leaf(root, path);
2463 } else if (ret > 0) {
2472 btrfs_item_key_to_cpu(leaf, &key, slot);
2474 if (key.objectid > inum)
2477 if (key.objectid < inum || key.type != BTRFS_EXTENT_DATA_KEY)
2480 extent = btrfs_item_ptr(leaf, slot,
2481 struct btrfs_file_extent_item);
2483 if (btrfs_file_extent_disk_bytenr(leaf, extent) != old->bytenr)
2487 * 'offset' refers to the exact key.offset,
2488 * NOT the 'offset' field in btrfs_extent_data_ref, ie.
2489 * (key.offset - extent_offset).
2491 if (key.offset != offset)
2494 extent_offset = btrfs_file_extent_offset(leaf, extent);
2495 num_bytes = btrfs_file_extent_num_bytes(leaf, extent);
2497 if (extent_offset >= old->extent_offset + old->offset +
2498 old->len || extent_offset + num_bytes <=
2499 old->extent_offset + old->offset)
2504 backref = kmalloc(sizeof(*backref), GFP_NOFS);
2510 backref->root_id = root_id;
2511 backref->inum = inum;
2512 backref->file_pos = offset;
2513 backref->num_bytes = num_bytes;
2514 backref->extent_offset = extent_offset;
2515 backref->generation = btrfs_file_extent_generation(leaf, extent);
2517 backref_insert(&new->root, backref);
2520 btrfs_release_path(path);
2525 static noinline bool record_extent_backrefs(struct btrfs_path *path,
2526 struct new_sa_defrag_extent *new)
2528 struct btrfs_fs_info *fs_info = btrfs_sb(new->inode->i_sb);
2529 struct old_sa_defrag_extent *old, *tmp;
2534 list_for_each_entry_safe(old, tmp, &new->head, list) {
2535 ret = iterate_inodes_from_logical(old->bytenr +
2536 old->extent_offset, fs_info,
2537 path, record_one_backref,
2539 if (ret < 0 && ret != -ENOENT)
2542 /* no backref to be processed for this extent */
2544 list_del(&old->list);
2549 if (list_empty(&new->head))
2555 static int relink_is_mergable(struct extent_buffer *leaf,
2556 struct btrfs_file_extent_item *fi,
2557 struct new_sa_defrag_extent *new)
2559 if (btrfs_file_extent_disk_bytenr(leaf, fi) != new->bytenr)
2562 if (btrfs_file_extent_type(leaf, fi) != BTRFS_FILE_EXTENT_REG)
2565 if (btrfs_file_extent_compression(leaf, fi) != new->compress_type)
2568 if (btrfs_file_extent_encryption(leaf, fi) ||
2569 btrfs_file_extent_other_encoding(leaf, fi))
2576 * Note the backref might has changed, and in this case we just return 0.
2578 static noinline int relink_extent_backref(struct btrfs_path *path,
2579 struct sa_defrag_extent_backref *prev,
2580 struct sa_defrag_extent_backref *backref)
2582 struct btrfs_file_extent_item *extent;
2583 struct btrfs_file_extent_item *item;
2584 struct btrfs_ordered_extent *ordered;
2585 struct btrfs_trans_handle *trans;
2586 struct btrfs_root *root;
2587 struct btrfs_key key;
2588 struct extent_buffer *leaf;
2589 struct old_sa_defrag_extent *old = backref->old;
2590 struct new_sa_defrag_extent *new = old->new;
2591 struct btrfs_fs_info *fs_info = btrfs_sb(new->inode->i_sb);
2592 struct inode *inode;
2593 struct extent_state *cached = NULL;
2602 if (prev && prev->root_id == backref->root_id &&
2603 prev->inum == backref->inum &&
2604 prev->file_pos + prev->num_bytes == backref->file_pos)
2607 /* step 1: get root */
2608 key.objectid = backref->root_id;
2609 key.type = BTRFS_ROOT_ITEM_KEY;
2610 key.offset = (u64)-1;
2612 index = srcu_read_lock(&fs_info->subvol_srcu);
2614 root = btrfs_read_fs_root_no_name(fs_info, &key);
2616 srcu_read_unlock(&fs_info->subvol_srcu, index);
2617 if (PTR_ERR(root) == -ENOENT)
2619 return PTR_ERR(root);
2622 if (btrfs_root_readonly(root)) {
2623 srcu_read_unlock(&fs_info->subvol_srcu, index);
2627 /* step 2: get inode */
2628 key.objectid = backref->inum;
2629 key.type = BTRFS_INODE_ITEM_KEY;
2632 inode = btrfs_iget(fs_info->sb, &key, root, NULL);
2633 if (IS_ERR(inode)) {
2634 srcu_read_unlock(&fs_info->subvol_srcu, index);
2638 srcu_read_unlock(&fs_info->subvol_srcu, index);
2640 /* step 3: relink backref */
2641 lock_start = backref->file_pos;
2642 lock_end = backref->file_pos + backref->num_bytes - 1;
2643 lock_extent_bits(&BTRFS_I(inode)->io_tree, lock_start, lock_end,
2646 ordered = btrfs_lookup_first_ordered_extent(inode, lock_end);
2648 btrfs_put_ordered_extent(ordered);
2652 trans = btrfs_join_transaction(root);
2653 if (IS_ERR(trans)) {
2654 ret = PTR_ERR(trans);
2658 key.objectid = backref->inum;
2659 key.type = BTRFS_EXTENT_DATA_KEY;
2660 key.offset = backref->file_pos;
2662 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2665 } else if (ret > 0) {
2670 extent = btrfs_item_ptr(path->nodes[0], path->slots[0],
2671 struct btrfs_file_extent_item);
2673 if (btrfs_file_extent_generation(path->nodes[0], extent) !=
2674 backref->generation)
2677 btrfs_release_path(path);
2679 start = backref->file_pos;
2680 if (backref->extent_offset < old->extent_offset + old->offset)
2681 start += old->extent_offset + old->offset -
2682 backref->extent_offset;
2684 len = min(backref->extent_offset + backref->num_bytes,
2685 old->extent_offset + old->offset + old->len);
2686 len -= max(backref->extent_offset, old->extent_offset + old->offset);
2688 ret = btrfs_drop_extents(trans, root, inode, start,
2693 key.objectid = btrfs_ino(BTRFS_I(inode));
2694 key.type = BTRFS_EXTENT_DATA_KEY;
2697 path->leave_spinning = 1;
2699 struct btrfs_file_extent_item *fi;
2701 struct btrfs_key found_key;
2703 ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
2708 leaf = path->nodes[0];
2709 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
2711 fi = btrfs_item_ptr(leaf, path->slots[0],
2712 struct btrfs_file_extent_item);
2713 extent_len = btrfs_file_extent_num_bytes(leaf, fi);
2715 if (extent_len + found_key.offset == start &&
2716 relink_is_mergable(leaf, fi, new)) {
2717 btrfs_set_file_extent_num_bytes(leaf, fi,
2719 btrfs_mark_buffer_dirty(leaf);
2720 inode_add_bytes(inode, len);
2726 btrfs_release_path(path);
2731 ret = btrfs_insert_empty_item(trans, root, path, &key,
2734 btrfs_abort_transaction(trans, ret);
2738 leaf = path->nodes[0];
2739 item = btrfs_item_ptr(leaf, path->slots[0],
2740 struct btrfs_file_extent_item);
2741 btrfs_set_file_extent_disk_bytenr(leaf, item, new->bytenr);
2742 btrfs_set_file_extent_disk_num_bytes(leaf, item, new->disk_len);
2743 btrfs_set_file_extent_offset(leaf, item, start - new->file_pos);
2744 btrfs_set_file_extent_num_bytes(leaf, item, len);
2745 btrfs_set_file_extent_ram_bytes(leaf, item, new->len);
2746 btrfs_set_file_extent_generation(leaf, item, trans->transid);
2747 btrfs_set_file_extent_type(leaf, item, BTRFS_FILE_EXTENT_REG);
2748 btrfs_set_file_extent_compression(leaf, item, new->compress_type);
2749 btrfs_set_file_extent_encryption(leaf, item, 0);
2750 btrfs_set_file_extent_other_encoding(leaf, item, 0);
2752 btrfs_mark_buffer_dirty(leaf);
2753 inode_add_bytes(inode, len);
2754 btrfs_release_path(path);
2756 ret = btrfs_inc_extent_ref(trans, fs_info, new->bytenr,
2758 backref->root_id, backref->inum,
2759 new->file_pos); /* start - extent_offset */
2761 btrfs_abort_transaction(trans, ret);
2767 btrfs_release_path(path);
2768 path->leave_spinning = 0;
2769 btrfs_end_transaction(trans);
2771 unlock_extent_cached(&BTRFS_I(inode)->io_tree, lock_start, lock_end,
2777 static void free_sa_defrag_extent(struct new_sa_defrag_extent *new)
2779 struct old_sa_defrag_extent *old, *tmp;
2784 list_for_each_entry_safe(old, tmp, &new->head, list) {
2790 static void relink_file_extents(struct new_sa_defrag_extent *new)
2792 struct btrfs_fs_info *fs_info = btrfs_sb(new->inode->i_sb);
2793 struct btrfs_path *path;
2794 struct sa_defrag_extent_backref *backref;
2795 struct sa_defrag_extent_backref *prev = NULL;
2796 struct inode *inode;
2797 struct btrfs_root *root;
2798 struct rb_node *node;
2802 root = BTRFS_I(inode)->root;
2804 path = btrfs_alloc_path();
2808 if (!record_extent_backrefs(path, new)) {
2809 btrfs_free_path(path);
2812 btrfs_release_path(path);
2815 node = rb_first(&new->root);
2818 rb_erase(node, &new->root);
2820 backref = rb_entry(node, struct sa_defrag_extent_backref, node);
2822 ret = relink_extent_backref(path, prev, backref);
2835 btrfs_free_path(path);
2837 free_sa_defrag_extent(new);
2839 atomic_dec(&fs_info->defrag_running);
2840 wake_up(&fs_info->transaction_wait);
2843 static struct new_sa_defrag_extent *
2844 record_old_file_extents(struct inode *inode,
2845 struct btrfs_ordered_extent *ordered)
2847 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2848 struct btrfs_root *root = BTRFS_I(inode)->root;
2849 struct btrfs_path *path;
2850 struct btrfs_key key;
2851 struct old_sa_defrag_extent *old;
2852 struct new_sa_defrag_extent *new;
2855 new = kmalloc(sizeof(*new), GFP_NOFS);
2860 new->file_pos = ordered->file_offset;
2861 new->len = ordered->len;
2862 new->bytenr = ordered->start;
2863 new->disk_len = ordered->disk_len;
2864 new->compress_type = ordered->compress_type;
2865 new->root = RB_ROOT;
2866 INIT_LIST_HEAD(&new->head);
2868 path = btrfs_alloc_path();
2872 key.objectid = btrfs_ino(BTRFS_I(inode));
2873 key.type = BTRFS_EXTENT_DATA_KEY;
2874 key.offset = new->file_pos;
2876 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2879 if (ret > 0 && path->slots[0] > 0)
2882 /* find out all the old extents for the file range */
2884 struct btrfs_file_extent_item *extent;
2885 struct extent_buffer *l;
2894 slot = path->slots[0];
2896 if (slot >= btrfs_header_nritems(l)) {
2897 ret = btrfs_next_leaf(root, path);
2905 btrfs_item_key_to_cpu(l, &key, slot);
2907 if (key.objectid != btrfs_ino(BTRFS_I(inode)))
2909 if (key.type != BTRFS_EXTENT_DATA_KEY)
2911 if (key.offset >= new->file_pos + new->len)
2914 extent = btrfs_item_ptr(l, slot, struct btrfs_file_extent_item);
2916 num_bytes = btrfs_file_extent_num_bytes(l, extent);
2917 if (key.offset + num_bytes < new->file_pos)
2920 disk_bytenr = btrfs_file_extent_disk_bytenr(l, extent);
2924 extent_offset = btrfs_file_extent_offset(l, extent);
2926 old = kmalloc(sizeof(*old), GFP_NOFS);
2930 offset = max(new->file_pos, key.offset);
2931 end = min(new->file_pos + new->len, key.offset + num_bytes);
2933 old->bytenr = disk_bytenr;
2934 old->extent_offset = extent_offset;
2935 old->offset = offset - key.offset;
2936 old->len = end - offset;
2939 list_add_tail(&old->list, &new->head);
2945 btrfs_free_path(path);
2946 atomic_inc(&fs_info->defrag_running);
2951 btrfs_free_path(path);
2953 free_sa_defrag_extent(new);
2957 static void btrfs_release_delalloc_bytes(struct btrfs_fs_info *fs_info,
2960 struct btrfs_block_group_cache *cache;
2962 cache = btrfs_lookup_block_group(fs_info, start);
2965 spin_lock(&cache->lock);
2966 cache->delalloc_bytes -= len;
2967 spin_unlock(&cache->lock);
2969 btrfs_put_block_group(cache);
2972 /* as ordered data IO finishes, this gets called so we can finish
2973 * an ordered extent if the range of bytes in the file it covers are
2976 static int btrfs_finish_ordered_io(struct btrfs_ordered_extent *ordered_extent)
2978 struct inode *inode = ordered_extent->inode;
2979 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2980 struct btrfs_root *root = BTRFS_I(inode)->root;
2981 struct btrfs_trans_handle *trans = NULL;
2982 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
2983 struct extent_state *cached_state = NULL;
2984 struct new_sa_defrag_extent *new = NULL;
2985 int compress_type = 0;
2987 u64 logical_len = ordered_extent->len;
2989 bool truncated = false;
2990 bool range_locked = false;
2991 bool clear_new_delalloc_bytes = false;
2992 bool clear_reserved_extent = true;
2994 if (!test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags) &&
2995 !test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags) &&
2996 !test_bit(BTRFS_ORDERED_DIRECT, &ordered_extent->flags))
2997 clear_new_delalloc_bytes = true;
2999 nolock = btrfs_is_free_space_inode(BTRFS_I(inode));
3001 if (test_bit(BTRFS_ORDERED_IOERR, &ordered_extent->flags)) {
3006 btrfs_free_io_failure_record(BTRFS_I(inode),
3007 ordered_extent->file_offset,
3008 ordered_extent->file_offset +
3009 ordered_extent->len - 1);
3011 if (test_bit(BTRFS_ORDERED_TRUNCATED, &ordered_extent->flags)) {
3013 logical_len = ordered_extent->truncated_len;
3014 /* Truncated the entire extent, don't bother adding */
3019 if (test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags)) {
3020 BUG_ON(!list_empty(&ordered_extent->list)); /* Logic error */
3023 * For mwrite(mmap + memset to write) case, we still reserve
3024 * space for NOCOW range.
3025 * As NOCOW won't cause a new delayed ref, just free the space
3027 btrfs_qgroup_free_data(inode, NULL, ordered_extent->file_offset,
3028 ordered_extent->len);
3029 btrfs_ordered_update_i_size(inode, 0, ordered_extent);
3031 trans = btrfs_join_transaction_nolock(root);
3033 trans = btrfs_join_transaction(root);
3034 if (IS_ERR(trans)) {
3035 ret = PTR_ERR(trans);
3039 trans->block_rsv = &fs_info->delalloc_block_rsv;
3040 ret = btrfs_update_inode_fallback(trans, root, inode);
3041 if (ret) /* -ENOMEM or corruption */
3042 btrfs_abort_transaction(trans, ret);
3046 range_locked = true;
3047 lock_extent_bits(io_tree, ordered_extent->file_offset,
3048 ordered_extent->file_offset + ordered_extent->len - 1,
3051 ret = test_range_bit(io_tree, ordered_extent->file_offset,
3052 ordered_extent->file_offset + ordered_extent->len - 1,
3053 EXTENT_DEFRAG, 0, cached_state);
3055 u64 last_snapshot = btrfs_root_last_snapshot(&root->root_item);
3056 if (0 && last_snapshot >= BTRFS_I(inode)->generation)
3057 /* the inode is shared */
3058 new = record_old_file_extents(inode, ordered_extent);
3060 clear_extent_bit(io_tree, ordered_extent->file_offset,
3061 ordered_extent->file_offset + ordered_extent->len - 1,
3062 EXTENT_DEFRAG, 0, 0, &cached_state, GFP_NOFS);
3066 trans = btrfs_join_transaction_nolock(root);
3068 trans = btrfs_join_transaction(root);
3069 if (IS_ERR(trans)) {
3070 ret = PTR_ERR(trans);
3075 trans->block_rsv = &fs_info->delalloc_block_rsv;
3077 if (test_bit(BTRFS_ORDERED_COMPRESSED, &ordered_extent->flags))
3078 compress_type = ordered_extent->compress_type;
3079 if (test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags)) {
3080 BUG_ON(compress_type);
3081 btrfs_qgroup_free_data(inode, NULL, ordered_extent->file_offset,
3082 ordered_extent->len);
3083 ret = btrfs_mark_extent_written(trans, BTRFS_I(inode),
3084 ordered_extent->file_offset,
3085 ordered_extent->file_offset +
3088 BUG_ON(root == fs_info->tree_root);
3089 ret = insert_reserved_file_extent(trans, inode,
3090 ordered_extent->file_offset,
3091 ordered_extent->start,
3092 ordered_extent->disk_len,
3093 logical_len, logical_len,
3094 compress_type, 0, 0,
3095 BTRFS_FILE_EXTENT_REG);
3097 clear_reserved_extent = false;
3098 btrfs_release_delalloc_bytes(fs_info,
3099 ordered_extent->start,
3100 ordered_extent->disk_len);
3103 unpin_extent_cache(&BTRFS_I(inode)->extent_tree,
3104 ordered_extent->file_offset, ordered_extent->len,
3107 btrfs_abort_transaction(trans, ret);
3111 add_pending_csums(trans, inode, &ordered_extent->list);
3113 btrfs_ordered_update_i_size(inode, 0, ordered_extent);
3114 ret = btrfs_update_inode_fallback(trans, root, inode);
3115 if (ret) { /* -ENOMEM or corruption */
3116 btrfs_abort_transaction(trans, ret);
3121 if (range_locked || clear_new_delalloc_bytes) {
3122 unsigned int clear_bits = 0;
3125 clear_bits |= EXTENT_LOCKED;
3126 if (clear_new_delalloc_bytes)
3127 clear_bits |= EXTENT_DELALLOC_NEW;
3128 clear_extent_bit(&BTRFS_I(inode)->io_tree,
3129 ordered_extent->file_offset,
3130 ordered_extent->file_offset +
3131 ordered_extent->len - 1,
3133 (clear_bits & EXTENT_LOCKED) ? 1 : 0,
3134 0, &cached_state, GFP_NOFS);
3137 if (root != fs_info->tree_root)
3138 btrfs_delalloc_release_metadata(BTRFS_I(inode),
3139 ordered_extent->len);
3141 btrfs_end_transaction(trans);
3143 if (ret || truncated) {
3147 start = ordered_extent->file_offset + logical_len;
3149 start = ordered_extent->file_offset;
3150 end = ordered_extent->file_offset + ordered_extent->len - 1;
3151 clear_extent_uptodate(io_tree, start, end, NULL, GFP_NOFS);
3153 /* Drop the cache for the part of the extent we didn't write. */
3154 btrfs_drop_extent_cache(BTRFS_I(inode), start, end, 0);
3157 * If the ordered extent had an IOERR or something else went
3158 * wrong we need to return the space for this ordered extent
3159 * back to the allocator. We only free the extent in the
3160 * truncated case if we didn't write out the extent at all.
3162 * If we made it past insert_reserved_file_extent before we
3163 * errored out then we don't need to do this as the accounting
3164 * has already been done.
3166 if ((ret || !logical_len) &&
3167 clear_reserved_extent &&
3168 !test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags) &&
3169 !test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags))
3170 btrfs_free_reserved_extent(fs_info,
3171 ordered_extent->start,
3172 ordered_extent->disk_len, 1);
3177 * This needs to be done to make sure anybody waiting knows we are done
3178 * updating everything for this ordered extent.
3180 btrfs_remove_ordered_extent(inode, ordered_extent);
3182 /* for snapshot-aware defrag */
3185 free_sa_defrag_extent(new);
3186 atomic_dec(&fs_info->defrag_running);
3188 relink_file_extents(new);
3193 btrfs_put_ordered_extent(ordered_extent);
3194 /* once for the tree */
3195 btrfs_put_ordered_extent(ordered_extent);
3200 static void finish_ordered_fn(struct btrfs_work *work)
3202 struct btrfs_ordered_extent *ordered_extent;
3203 ordered_extent = container_of(work, struct btrfs_ordered_extent, work);
3204 btrfs_finish_ordered_io(ordered_extent);
3207 static void btrfs_writepage_end_io_hook(struct page *page, u64 start, u64 end,
3208 struct extent_state *state, int uptodate)
3210 struct inode *inode = page->mapping->host;
3211 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
3212 struct btrfs_ordered_extent *ordered_extent = NULL;
3213 struct btrfs_workqueue *wq;
3214 btrfs_work_func_t func;
3216 trace_btrfs_writepage_end_io_hook(page, start, end, uptodate);
3218 ClearPagePrivate2(page);
3219 if (!btrfs_dec_test_ordered_pending(inode, &ordered_extent, start,
3220 end - start + 1, uptodate))
3223 if (btrfs_is_free_space_inode(BTRFS_I(inode))) {
3224 wq = fs_info->endio_freespace_worker;
3225 func = btrfs_freespace_write_helper;
3227 wq = fs_info->endio_write_workers;
3228 func = btrfs_endio_write_helper;
3231 btrfs_init_work(&ordered_extent->work, func, finish_ordered_fn, NULL,
3233 btrfs_queue_work(wq, &ordered_extent->work);
3236 static int __readpage_endio_check(struct inode *inode,
3237 struct btrfs_io_bio *io_bio,
3238 int icsum, struct page *page,
3239 int pgoff, u64 start, size_t len)
3245 csum_expected = *(((u32 *)io_bio->csum) + icsum);
3247 kaddr = kmap_atomic(page);
3248 csum = btrfs_csum_data(kaddr + pgoff, csum, len);
3249 btrfs_csum_final(csum, (u8 *)&csum);
3250 if (csum != csum_expected)
3253 kunmap_atomic(kaddr);
3256 btrfs_print_data_csum_error(BTRFS_I(inode), start, csum, csum_expected,
3257 io_bio->mirror_num);
3258 memset(kaddr + pgoff, 1, len);
3259 flush_dcache_page(page);
3260 kunmap_atomic(kaddr);
3265 * when reads are done, we need to check csums to verify the data is correct
3266 * if there's a match, we allow the bio to finish. If not, the code in
3267 * extent_io.c will try to find good copies for us.
3269 static int btrfs_readpage_end_io_hook(struct btrfs_io_bio *io_bio,
3270 u64 phy_offset, struct page *page,
3271 u64 start, u64 end, int mirror)
3273 size_t offset = start - page_offset(page);
3274 struct inode *inode = page->mapping->host;
3275 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
3276 struct btrfs_root *root = BTRFS_I(inode)->root;
3278 if (PageChecked(page)) {
3279 ClearPageChecked(page);
3283 if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)
3286 if (root->root_key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID &&
3287 test_range_bit(io_tree, start, end, EXTENT_NODATASUM, 1, NULL)) {
3288 clear_extent_bits(io_tree, start, end, EXTENT_NODATASUM);
3292 phy_offset >>= inode->i_sb->s_blocksize_bits;
3293 return __readpage_endio_check(inode, io_bio, phy_offset, page, offset,
3294 start, (size_t)(end - start + 1));
3297 void btrfs_add_delayed_iput(struct inode *inode)
3299 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
3300 struct btrfs_inode *binode = BTRFS_I(inode);
3302 if (atomic_add_unless(&inode->i_count, -1, 1))
3305 spin_lock(&fs_info->delayed_iput_lock);
3306 if (binode->delayed_iput_count == 0) {
3307 ASSERT(list_empty(&binode->delayed_iput));
3308 list_add_tail(&binode->delayed_iput, &fs_info->delayed_iputs);
3310 binode->delayed_iput_count++;
3312 spin_unlock(&fs_info->delayed_iput_lock);
3315 void btrfs_run_delayed_iputs(struct btrfs_fs_info *fs_info)
3318 spin_lock(&fs_info->delayed_iput_lock);
3319 while (!list_empty(&fs_info->delayed_iputs)) {
3320 struct btrfs_inode *inode;
3322 inode = list_first_entry(&fs_info->delayed_iputs,
3323 struct btrfs_inode, delayed_iput);
3324 if (inode->delayed_iput_count) {
3325 inode->delayed_iput_count--;
3326 list_move_tail(&inode->delayed_iput,
3327 &fs_info->delayed_iputs);
3329 list_del_init(&inode->delayed_iput);
3331 spin_unlock(&fs_info->delayed_iput_lock);
3332 iput(&inode->vfs_inode);
3333 spin_lock(&fs_info->delayed_iput_lock);
3335 spin_unlock(&fs_info->delayed_iput_lock);
3339 * This is called in transaction commit time. If there are no orphan
3340 * files in the subvolume, it removes orphan item and frees block_rsv
3343 void btrfs_orphan_commit_root(struct btrfs_trans_handle *trans,
3344 struct btrfs_root *root)
3346 struct btrfs_fs_info *fs_info = root->fs_info;
3347 struct btrfs_block_rsv *block_rsv;
3350 if (atomic_read(&root->orphan_inodes) ||
3351 root->orphan_cleanup_state != ORPHAN_CLEANUP_DONE)
3354 spin_lock(&root->orphan_lock);
3355 if (atomic_read(&root->orphan_inodes)) {
3356 spin_unlock(&root->orphan_lock);
3360 if (root->orphan_cleanup_state != ORPHAN_CLEANUP_DONE) {
3361 spin_unlock(&root->orphan_lock);
3365 block_rsv = root->orphan_block_rsv;
3366 root->orphan_block_rsv = NULL;
3367 spin_unlock(&root->orphan_lock);
3369 if (test_bit(BTRFS_ROOT_ORPHAN_ITEM_INSERTED, &root->state) &&
3370 btrfs_root_refs(&root->root_item) > 0) {
3371 ret = btrfs_del_orphan_item(trans, fs_info->tree_root,
3372 root->root_key.objectid);
3374 btrfs_abort_transaction(trans, ret);
3376 clear_bit(BTRFS_ROOT_ORPHAN_ITEM_INSERTED,
3381 WARN_ON(block_rsv->size > 0);
3382 btrfs_free_block_rsv(fs_info, block_rsv);
3387 * This creates an orphan entry for the given inode in case something goes
3388 * wrong in the middle of an unlink/truncate.
3390 * NOTE: caller of this function should reserve 5 units of metadata for
3393 int btrfs_orphan_add(struct btrfs_trans_handle *trans,
3394 struct btrfs_inode *inode)
3396 struct btrfs_fs_info *fs_info = btrfs_sb(inode->vfs_inode.i_sb);
3397 struct btrfs_root *root = inode->root;
3398 struct btrfs_block_rsv *block_rsv = NULL;
3403 if (!root->orphan_block_rsv) {
3404 block_rsv = btrfs_alloc_block_rsv(fs_info,
3405 BTRFS_BLOCK_RSV_TEMP);
3410 spin_lock(&root->orphan_lock);
3411 if (!root->orphan_block_rsv) {
3412 root->orphan_block_rsv = block_rsv;
3413 } else if (block_rsv) {
3414 btrfs_free_block_rsv(fs_info, block_rsv);
3418 if (!test_and_set_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
3419 &inode->runtime_flags)) {
3422 * For proper ENOSPC handling, we should do orphan
3423 * cleanup when mounting. But this introduces backward
3424 * compatibility issue.
3426 if (!xchg(&root->orphan_item_inserted, 1))
3432 atomic_inc(&root->orphan_inodes);
3435 if (!test_and_set_bit(BTRFS_INODE_ORPHAN_META_RESERVED,
3436 &inode->runtime_flags))
3438 spin_unlock(&root->orphan_lock);
3440 /* grab metadata reservation from transaction handle */
3442 ret = btrfs_orphan_reserve_metadata(trans, inode);
3446 * dec doesn't need spin_lock as ->orphan_block_rsv
3447 * would be released only if ->orphan_inodes is
3450 atomic_dec(&root->orphan_inodes);
3451 clear_bit(BTRFS_INODE_ORPHAN_META_RESERVED,
3452 &inode->runtime_flags);
3454 clear_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
3455 &inode->runtime_flags);
3460 /* insert an orphan item to track this unlinked/truncated file */
3462 ret = btrfs_insert_orphan_item(trans, root, btrfs_ino(inode));
3465 clear_bit(BTRFS_INODE_ORPHAN_META_RESERVED,
3466 &inode->runtime_flags);
3467 btrfs_orphan_release_metadata(inode);
3470 * btrfs_orphan_commit_root may race with us and set
3471 * ->orphan_block_rsv to zero, in order to avoid that,
3472 * decrease ->orphan_inodes after everything is done.
3474 atomic_dec(&root->orphan_inodes);
3475 if (ret != -EEXIST) {
3476 clear_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
3477 &inode->runtime_flags);
3478 btrfs_abort_transaction(trans, ret);
3485 /* insert an orphan item to track subvolume contains orphan files */
3487 ret = btrfs_insert_orphan_item(trans, fs_info->tree_root,
3488 root->root_key.objectid);
3489 if (ret && ret != -EEXIST) {
3490 btrfs_abort_transaction(trans, ret);
3498 * We have done the truncate/delete so we can go ahead and remove the orphan
3499 * item for this particular inode.
3501 static int btrfs_orphan_del(struct btrfs_trans_handle *trans,
3502 struct btrfs_inode *inode)
3504 struct btrfs_root *root = inode->root;
3505 int delete_item = 0;
3508 if (test_and_clear_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
3509 &inode->runtime_flags))
3512 if (delete_item && trans)
3513 ret = btrfs_del_orphan_item(trans, root, btrfs_ino(inode));
3515 if (test_and_clear_bit(BTRFS_INODE_ORPHAN_META_RESERVED,
3516 &inode->runtime_flags))
3517 btrfs_orphan_release_metadata(inode);
3520 * btrfs_orphan_commit_root may race with us and set ->orphan_block_rsv
3521 * to zero, in order to avoid that, decrease ->orphan_inodes after
3522 * everything is done.
3525 atomic_dec(&root->orphan_inodes);
3531 * this cleans up any orphans that may be left on the list from the last use
3534 int btrfs_orphan_cleanup(struct btrfs_root *root)
3536 struct btrfs_fs_info *fs_info = root->fs_info;
3537 struct btrfs_path *path;
3538 struct extent_buffer *leaf;
3539 struct btrfs_key key, found_key;
3540 struct btrfs_trans_handle *trans;
3541 struct inode *inode;
3542 u64 last_objectid = 0;
3543 int ret = 0, nr_unlink = 0, nr_truncate = 0;
3545 if (cmpxchg(&root->orphan_cleanup_state, 0, ORPHAN_CLEANUP_STARTED))
3548 path = btrfs_alloc_path();
3553 path->reada = READA_BACK;
3555 key.objectid = BTRFS_ORPHAN_OBJECTID;
3556 key.type = BTRFS_ORPHAN_ITEM_KEY;
3557 key.offset = (u64)-1;
3560 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
3565 * if ret == 0 means we found what we were searching for, which
3566 * is weird, but possible, so only screw with path if we didn't
3567 * find the key and see if we have stuff that matches
3571 if (path->slots[0] == 0)
3576 /* pull out the item */
3577 leaf = path->nodes[0];
3578 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
3580 /* make sure the item matches what we want */
3581 if (found_key.objectid != BTRFS_ORPHAN_OBJECTID)
3583 if (found_key.type != BTRFS_ORPHAN_ITEM_KEY)
3586 /* release the path since we're done with it */
3587 btrfs_release_path(path);
3590 * this is where we are basically btrfs_lookup, without the
3591 * crossing root thing. we store the inode number in the
3592 * offset of the orphan item.
3595 if (found_key.offset == last_objectid) {
3597 "Error removing orphan entry, stopping orphan cleanup");
3602 last_objectid = found_key.offset;
3604 found_key.objectid = found_key.offset;
3605 found_key.type = BTRFS_INODE_ITEM_KEY;
3606 found_key.offset = 0;
3607 inode = btrfs_iget(fs_info->sb, &found_key, root, NULL);
3608 ret = PTR_ERR_OR_ZERO(inode);
3609 if (ret && ret != -ENOENT)
3612 if (ret == -ENOENT && root == fs_info->tree_root) {
3613 struct btrfs_root *dead_root;
3614 struct btrfs_fs_info *fs_info = root->fs_info;
3615 int is_dead_root = 0;
3618 * this is an orphan in the tree root. Currently these
3619 * could come from 2 sources:
3620 * a) a snapshot deletion in progress
3621 * b) a free space cache inode
3622 * We need to distinguish those two, as the snapshot
3623 * orphan must not get deleted.
3624 * find_dead_roots already ran before us, so if this
3625 * is a snapshot deletion, we should find the root
3626 * in the dead_roots list
3628 spin_lock(&fs_info->trans_lock);
3629 list_for_each_entry(dead_root, &fs_info->dead_roots,
3631 if (dead_root->root_key.objectid ==
3632 found_key.objectid) {
3637 spin_unlock(&fs_info->trans_lock);
3639 /* prevent this orphan from being found again */
3640 key.offset = found_key.objectid - 1;
3645 * Inode is already gone but the orphan item is still there,
3646 * kill the orphan item.
3648 if (ret == -ENOENT) {
3649 trans = btrfs_start_transaction(root, 1);
3650 if (IS_ERR(trans)) {
3651 ret = PTR_ERR(trans);
3654 btrfs_debug(fs_info, "auto deleting %Lu",
3655 found_key.objectid);
3656 ret = btrfs_del_orphan_item(trans, root,
3657 found_key.objectid);
3658 btrfs_end_transaction(trans);
3665 * add this inode to the orphan list so btrfs_orphan_del does
3666 * the proper thing when we hit it
3668 set_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
3669 &BTRFS_I(inode)->runtime_flags);
3670 atomic_inc(&root->orphan_inodes);
3672 /* if we have links, this was a truncate, lets do that */
3673 if (inode->i_nlink) {
3674 if (WARN_ON(!S_ISREG(inode->i_mode))) {
3680 /* 1 for the orphan item deletion. */
3681 trans = btrfs_start_transaction(root, 1);
3682 if (IS_ERR(trans)) {
3684 ret = PTR_ERR(trans);
3687 ret = btrfs_orphan_add(trans, BTRFS_I(inode));
3688 btrfs_end_transaction(trans);
3694 ret = btrfs_truncate(inode);
3696 btrfs_orphan_del(NULL, BTRFS_I(inode));
3701 /* this will do delete_inode and everything for us */
3706 /* release the path since we're done with it */
3707 btrfs_release_path(path);
3709 root->orphan_cleanup_state = ORPHAN_CLEANUP_DONE;
3711 if (root->orphan_block_rsv)
3712 btrfs_block_rsv_release(fs_info, root->orphan_block_rsv,
3715 if (root->orphan_block_rsv ||
3716 test_bit(BTRFS_ROOT_ORPHAN_ITEM_INSERTED, &root->state)) {
3717 trans = btrfs_join_transaction(root);
3719 btrfs_end_transaction(trans);
3723 btrfs_debug(fs_info, "unlinked %d orphans", nr_unlink);
3725 btrfs_debug(fs_info, "truncated %d orphans", nr_truncate);
3729 btrfs_err(fs_info, "could not do orphan cleanup %d", ret);
3730 btrfs_free_path(path);
3735 * very simple check to peek ahead in the leaf looking for xattrs. If we
3736 * don't find any xattrs, we know there can't be any acls.
3738 * slot is the slot the inode is in, objectid is the objectid of the inode
3740 static noinline int acls_after_inode_item(struct extent_buffer *leaf,
3741 int slot, u64 objectid,
3742 int *first_xattr_slot)
3744 u32 nritems = btrfs_header_nritems(leaf);
3745 struct btrfs_key found_key;
3746 static u64 xattr_access = 0;
3747 static u64 xattr_default = 0;
3750 if (!xattr_access) {
3751 xattr_access = btrfs_name_hash(XATTR_NAME_POSIX_ACL_ACCESS,
3752 strlen(XATTR_NAME_POSIX_ACL_ACCESS));
3753 xattr_default = btrfs_name_hash(XATTR_NAME_POSIX_ACL_DEFAULT,
3754 strlen(XATTR_NAME_POSIX_ACL_DEFAULT));
3758 *first_xattr_slot = -1;
3759 while (slot < nritems) {
3760 btrfs_item_key_to_cpu(leaf, &found_key, slot);
3762 /* we found a different objectid, there must not be acls */
3763 if (found_key.objectid != objectid)
3766 /* we found an xattr, assume we've got an acl */
3767 if (found_key.type == BTRFS_XATTR_ITEM_KEY) {
3768 if (*first_xattr_slot == -1)
3769 *first_xattr_slot = slot;
3770 if (found_key.offset == xattr_access ||
3771 found_key.offset == xattr_default)
3776 * we found a key greater than an xattr key, there can't
3777 * be any acls later on
3779 if (found_key.type > BTRFS_XATTR_ITEM_KEY)
3786 * it goes inode, inode backrefs, xattrs, extents,
3787 * so if there are a ton of hard links to an inode there can
3788 * be a lot of backrefs. Don't waste time searching too hard,
3789 * this is just an optimization
3794 /* we hit the end of the leaf before we found an xattr or
3795 * something larger than an xattr. We have to assume the inode
3798 if (*first_xattr_slot == -1)
3799 *first_xattr_slot = slot;
3804 * read an inode from the btree into the in-memory inode
3806 static int btrfs_read_locked_inode(struct inode *inode)
3808 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
3809 struct btrfs_path *path;
3810 struct extent_buffer *leaf;
3811 struct btrfs_inode_item *inode_item;
3812 struct btrfs_root *root = BTRFS_I(inode)->root;
3813 struct btrfs_key location;
3818 bool filled = false;
3819 int first_xattr_slot;
3821 ret = btrfs_fill_inode(inode, &rdev);
3825 path = btrfs_alloc_path();
3831 memcpy(&location, &BTRFS_I(inode)->location, sizeof(location));
3833 ret = btrfs_lookup_inode(NULL, root, path, &location, 0);
3840 leaf = path->nodes[0];
3845 inode_item = btrfs_item_ptr(leaf, path->slots[0],
3846 struct btrfs_inode_item);
3847 inode->i_mode = btrfs_inode_mode(leaf, inode_item);
3848 set_nlink(inode, btrfs_inode_nlink(leaf, inode_item));
3849 i_uid_write(inode, btrfs_inode_uid(leaf, inode_item));
3850 i_gid_write(inode, btrfs_inode_gid(leaf, inode_item));
3851 btrfs_i_size_write(BTRFS_I(inode), btrfs_inode_size(leaf, inode_item));
3853 inode->i_atime.tv_sec = btrfs_timespec_sec(leaf, &inode_item->atime);
3854 inode->i_atime.tv_nsec = btrfs_timespec_nsec(leaf, &inode_item->atime);
3856 inode->i_mtime.tv_sec = btrfs_timespec_sec(leaf, &inode_item->mtime);
3857 inode->i_mtime.tv_nsec = btrfs_timespec_nsec(leaf, &inode_item->mtime);
3859 inode->i_ctime.tv_sec = btrfs_timespec_sec(leaf, &inode_item->ctime);
3860 inode->i_ctime.tv_nsec = btrfs_timespec_nsec(leaf, &inode_item->ctime);
3862 BTRFS_I(inode)->i_otime.tv_sec =
3863 btrfs_timespec_sec(leaf, &inode_item->otime);
3864 BTRFS_I(inode)->i_otime.tv_nsec =
3865 btrfs_timespec_nsec(leaf, &inode_item->otime);
3867 inode_set_bytes(inode, btrfs_inode_nbytes(leaf, inode_item));
3868 BTRFS_I(inode)->generation = btrfs_inode_generation(leaf, inode_item);
3869 BTRFS_I(inode)->last_trans = btrfs_inode_transid(leaf, inode_item);
3871 inode->i_version = btrfs_inode_sequence(leaf, inode_item);
3872 inode->i_generation = BTRFS_I(inode)->generation;
3874 rdev = btrfs_inode_rdev(leaf, inode_item);
3876 BTRFS_I(inode)->index_cnt = (u64)-1;
3877 BTRFS_I(inode)->flags = btrfs_inode_flags(leaf, inode_item);
3881 * If we were modified in the current generation and evicted from memory
3882 * and then re-read we need to do a full sync since we don't have any
3883 * idea about which extents were modified before we were evicted from
3886 * This is required for both inode re-read from disk and delayed inode
3887 * in delayed_nodes_tree.
3889 if (BTRFS_I(inode)->last_trans == fs_info->generation)
3890 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
3891 &BTRFS_I(inode)->runtime_flags);
3894 * We don't persist the id of the transaction where an unlink operation
3895 * against the inode was last made. So here we assume the inode might
3896 * have been evicted, and therefore the exact value of last_unlink_trans
3897 * lost, and set it to last_trans to avoid metadata inconsistencies
3898 * between the inode and its parent if the inode is fsync'ed and the log
3899 * replayed. For example, in the scenario:
3902 * ln mydir/foo mydir/bar
3905 * echo 2 > /proc/sys/vm/drop_caches # evicts inode
3906 * xfs_io -c fsync mydir/foo
3908 * mount fs, triggers fsync log replay
3910 * We must make sure that when we fsync our inode foo we also log its
3911 * parent inode, otherwise after log replay the parent still has the
3912 * dentry with the "bar" name but our inode foo has a link count of 1
3913 * and doesn't have an inode ref with the name "bar" anymore.
3915 * Setting last_unlink_trans to last_trans is a pessimistic approach,
3916 * but it guarantees correctness at the expense of occasional full
3917 * transaction commits on fsync if our inode is a directory, or if our
3918 * inode is not a directory, logging its parent unnecessarily.
3920 BTRFS_I(inode)->last_unlink_trans = BTRFS_I(inode)->last_trans;
3922 * Similar reasoning for last_link_trans, needs to be set otherwise
3923 * for a case like the following:
3928 * echo 2 > /proc/sys/vm/drop_caches
3932 * Would result in link bar and directory A not existing after the power
3935 BTRFS_I(inode)->last_link_trans = BTRFS_I(inode)->last_trans;
3938 if (inode->i_nlink != 1 ||
3939 path->slots[0] >= btrfs_header_nritems(leaf))
3942 btrfs_item_key_to_cpu(leaf, &location, path->slots[0]);
3943 if (location.objectid != btrfs_ino(BTRFS_I(inode)))
3946 ptr = btrfs_item_ptr_offset(leaf, path->slots[0]);
3947 if (location.type == BTRFS_INODE_REF_KEY) {
3948 struct btrfs_inode_ref *ref;
3950 ref = (struct btrfs_inode_ref *)ptr;
3951 BTRFS_I(inode)->dir_index = btrfs_inode_ref_index(leaf, ref);
3952 } else if (location.type == BTRFS_INODE_EXTREF_KEY) {
3953 struct btrfs_inode_extref *extref;
3955 extref = (struct btrfs_inode_extref *)ptr;
3956 BTRFS_I(inode)->dir_index = btrfs_inode_extref_index(leaf,
3961 * try to precache a NULL acl entry for files that don't have
3962 * any xattrs or acls
3964 maybe_acls = acls_after_inode_item(leaf, path->slots[0],
3965 btrfs_ino(BTRFS_I(inode)), &first_xattr_slot);
3966 if (first_xattr_slot != -1) {
3967 path->slots[0] = first_xattr_slot;
3968 ret = btrfs_load_inode_props(inode, path);
3971 "error loading props for ino %llu (root %llu): %d",
3972 btrfs_ino(BTRFS_I(inode)),
3973 root->root_key.objectid, ret);
3975 btrfs_free_path(path);
3978 cache_no_acl(inode);
3980 switch (inode->i_mode & S_IFMT) {
3982 inode->i_mapping->a_ops = &btrfs_aops;
3983 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
3984 inode->i_fop = &btrfs_file_operations;
3985 inode->i_op = &btrfs_file_inode_operations;
3988 inode->i_fop = &btrfs_dir_file_operations;
3989 inode->i_op = &btrfs_dir_inode_operations;
3992 inode->i_op = &btrfs_symlink_inode_operations;
3993 inode_nohighmem(inode);
3994 inode->i_mapping->a_ops = &btrfs_symlink_aops;
3997 inode->i_op = &btrfs_special_inode_operations;
3998 init_special_inode(inode, inode->i_mode, rdev);
4002 btrfs_update_iflags(inode);
4006 btrfs_free_path(path);
4007 make_bad_inode(inode);
4012 * given a leaf and an inode, copy the inode fields into the leaf
4014 static void fill_inode_item(struct btrfs_trans_handle *trans,
4015 struct extent_buffer *leaf,
4016 struct btrfs_inode_item *item,
4017 struct inode *inode)
4019 struct btrfs_map_token token;
4021 btrfs_init_map_token(&token);
4023 btrfs_set_token_inode_uid(leaf, item, i_uid_read(inode), &token);
4024 btrfs_set_token_inode_gid(leaf, item, i_gid_read(inode), &token);
4025 btrfs_set_token_inode_size(leaf, item, BTRFS_I(inode)->disk_i_size,
4027 btrfs_set_token_inode_mode(leaf, item, inode->i_mode, &token);
4028 btrfs_set_token_inode_nlink(leaf, item, inode->i_nlink, &token);
4030 btrfs_set_token_timespec_sec(leaf, &item->atime,
4031 inode->i_atime.tv_sec, &token);
4032 btrfs_set_token_timespec_nsec(leaf, &item->atime,
4033 inode->i_atime.tv_nsec, &token);
4035 btrfs_set_token_timespec_sec(leaf, &item->mtime,
4036 inode->i_mtime.tv_sec, &token);
4037 btrfs_set_token_timespec_nsec(leaf, &item->mtime,
4038 inode->i_mtime.tv_nsec, &token);
4040 btrfs_set_token_timespec_sec(leaf, &item->ctime,
4041 inode->i_ctime.tv_sec, &token);
4042 btrfs_set_token_timespec_nsec(leaf, &item->ctime,
4043 inode->i_ctime.tv_nsec, &token);
4045 btrfs_set_token_timespec_sec(leaf, &item->otime,
4046 BTRFS_I(inode)->i_otime.tv_sec, &token);
4047 btrfs_set_token_timespec_nsec(leaf, &item->otime,
4048 BTRFS_I(inode)->i_otime.tv_nsec, &token);
4050 btrfs_set_token_inode_nbytes(leaf, item, inode_get_bytes(inode),
4052 btrfs_set_token_inode_generation(leaf, item, BTRFS_I(inode)->generation,
4054 btrfs_set_token_inode_sequence(leaf, item, inode->i_version, &token);
4055 btrfs_set_token_inode_transid(leaf, item, trans->transid, &token);
4056 btrfs_set_token_inode_rdev(leaf, item, inode->i_rdev, &token);
4057 btrfs_set_token_inode_flags(leaf, item, BTRFS_I(inode)->flags, &token);
4058 btrfs_set_token_inode_block_group(leaf, item, 0, &token);
4062 * copy everything in the in-memory inode into the btree.
4064 static noinline int btrfs_update_inode_item(struct btrfs_trans_handle *trans,
4065 struct btrfs_root *root, struct inode *inode)
4067 struct btrfs_inode_item *inode_item;
4068 struct btrfs_path *path;
4069 struct extent_buffer *leaf;
4072 path = btrfs_alloc_path();
4076 path->leave_spinning = 1;
4077 ret = btrfs_lookup_inode(trans, root, path, &BTRFS_I(inode)->location,
4085 leaf = path->nodes[0];
4086 inode_item = btrfs_item_ptr(leaf, path->slots[0],
4087 struct btrfs_inode_item);
4089 fill_inode_item(trans, leaf, inode_item, inode);
4090 btrfs_mark_buffer_dirty(leaf);
4091 btrfs_set_inode_last_trans(trans, inode);
4094 btrfs_free_path(path);
4099 * copy everything in the in-memory inode into the btree.
4101 noinline int btrfs_update_inode(struct btrfs_trans_handle *trans,
4102 struct btrfs_root *root, struct inode *inode)
4104 struct btrfs_fs_info *fs_info = root->fs_info;
4108 * If the inode is a free space inode, we can deadlock during commit
4109 * if we put it into the delayed code.
4111 * The data relocation inode should also be directly updated
4114 if (!btrfs_is_free_space_inode(BTRFS_I(inode))
4115 && root->root_key.objectid != BTRFS_DATA_RELOC_TREE_OBJECTID
4116 && !test_bit(BTRFS_FS_LOG_RECOVERING, &fs_info->flags)) {
4117 btrfs_update_root_times(trans, root);
4119 ret = btrfs_delayed_update_inode(trans, root, inode);
4121 btrfs_set_inode_last_trans(trans, inode);
4125 return btrfs_update_inode_item(trans, root, inode);
4128 noinline int btrfs_update_inode_fallback(struct btrfs_trans_handle *trans,
4129 struct btrfs_root *root,
4130 struct inode *inode)
4134 ret = btrfs_update_inode(trans, root, inode);
4136 return btrfs_update_inode_item(trans, root, inode);
4141 * unlink helper that gets used here in inode.c and in the tree logging
4142 * recovery code. It remove a link in a directory with a given name, and
4143 * also drops the back refs in the inode to the directory
4145 static int __btrfs_unlink_inode(struct btrfs_trans_handle *trans,
4146 struct btrfs_root *root,
4147 struct btrfs_inode *dir,
4148 struct btrfs_inode *inode,
4149 const char *name, int name_len)
4151 struct btrfs_fs_info *fs_info = root->fs_info;
4152 struct btrfs_path *path;
4154 struct extent_buffer *leaf;
4155 struct btrfs_dir_item *di;
4156 struct btrfs_key key;
4158 u64 ino = btrfs_ino(inode);
4159 u64 dir_ino = btrfs_ino(dir);
4161 path = btrfs_alloc_path();
4167 path->leave_spinning = 1;
4168 di = btrfs_lookup_dir_item(trans, root, path, dir_ino,
4169 name, name_len, -1);
4178 leaf = path->nodes[0];
4179 btrfs_dir_item_key_to_cpu(leaf, di, &key);
4180 ret = btrfs_delete_one_dir_name(trans, root, path, di);
4183 btrfs_release_path(path);
4186 * If we don't have dir index, we have to get it by looking up
4187 * the inode ref, since we get the inode ref, remove it directly,
4188 * it is unnecessary to do delayed deletion.
4190 * But if we have dir index, needn't search inode ref to get it.
4191 * Since the inode ref is close to the inode item, it is better
4192 * that we delay to delete it, and just do this deletion when
4193 * we update the inode item.
4195 if (inode->dir_index) {
4196 ret = btrfs_delayed_delete_inode_ref(inode);
4198 index = inode->dir_index;
4203 ret = btrfs_del_inode_ref(trans, root, name, name_len, ino,
4207 "failed to delete reference to %.*s, inode %llu parent %llu",
4208 name_len, name, ino, dir_ino);
4209 btrfs_abort_transaction(trans, ret);
4213 ret = btrfs_delete_delayed_dir_index(trans, fs_info, dir, index);
4215 btrfs_abort_transaction(trans, ret);
4219 ret = btrfs_del_inode_ref_in_log(trans, root, name, name_len, inode,
4221 if (ret != 0 && ret != -ENOENT) {
4222 btrfs_abort_transaction(trans, ret);
4226 ret = btrfs_del_dir_entries_in_log(trans, root, name, name_len, dir,
4231 btrfs_abort_transaction(trans, ret);
4233 btrfs_free_path(path);
4237 btrfs_i_size_write(dir, dir->vfs_inode.i_size - name_len * 2);
4238 inode_inc_iversion(&inode->vfs_inode);
4239 inode_inc_iversion(&dir->vfs_inode);
4240 inode->vfs_inode.i_ctime = dir->vfs_inode.i_mtime =
4241 dir->vfs_inode.i_ctime = current_time(&inode->vfs_inode);
4242 ret = btrfs_update_inode(trans, root, &dir->vfs_inode);
4247 int btrfs_unlink_inode(struct btrfs_trans_handle *trans,
4248 struct btrfs_root *root,
4249 struct btrfs_inode *dir, struct btrfs_inode *inode,
4250 const char *name, int name_len)
4253 ret = __btrfs_unlink_inode(trans, root, dir, inode, name, name_len);
4255 drop_nlink(&inode->vfs_inode);
4256 ret = btrfs_update_inode(trans, root, &inode->vfs_inode);
4262 * helper to start transaction for unlink and rmdir.
4264 * unlink and rmdir are special in btrfs, they do not always free space, so
4265 * if we cannot make our reservations the normal way try and see if there is
4266 * plenty of slack room in the global reserve to migrate, otherwise we cannot
4267 * allow the unlink to occur.
4269 static struct btrfs_trans_handle *__unlink_start_trans(struct inode *dir)
4271 struct btrfs_root *root = BTRFS_I(dir)->root;
4274 * 1 for the possible orphan item
4275 * 1 for the dir item
4276 * 1 for the dir index
4277 * 1 for the inode ref
4280 return btrfs_start_transaction_fallback_global_rsv(root, 5, 5);
4283 static int btrfs_unlink(struct inode *dir, struct dentry *dentry)
4285 struct btrfs_root *root = BTRFS_I(dir)->root;
4286 struct btrfs_trans_handle *trans;
4287 struct inode *inode = d_inode(dentry);
4290 trans = __unlink_start_trans(dir);
4292 return PTR_ERR(trans);
4294 btrfs_record_unlink_dir(trans, BTRFS_I(dir), BTRFS_I(d_inode(dentry)),
4297 ret = btrfs_unlink_inode(trans, root, BTRFS_I(dir),
4298 BTRFS_I(d_inode(dentry)), dentry->d_name.name,
4299 dentry->d_name.len);
4303 if (inode->i_nlink == 0) {
4304 ret = btrfs_orphan_add(trans, BTRFS_I(inode));
4310 btrfs_end_transaction(trans);
4311 btrfs_btree_balance_dirty(root->fs_info);
4315 int btrfs_unlink_subvol(struct btrfs_trans_handle *trans,
4316 struct btrfs_root *root,
4317 struct inode *dir, u64 objectid,
4318 const char *name, int name_len)
4320 struct btrfs_fs_info *fs_info = root->fs_info;
4321 struct btrfs_path *path;
4322 struct extent_buffer *leaf;
4323 struct btrfs_dir_item *di;
4324 struct btrfs_key key;
4327 u64 dir_ino = btrfs_ino(BTRFS_I(dir));
4329 path = btrfs_alloc_path();
4333 di = btrfs_lookup_dir_item(trans, root, path, dir_ino,
4334 name, name_len, -1);
4335 if (IS_ERR_OR_NULL(di)) {
4343 leaf = path->nodes[0];
4344 btrfs_dir_item_key_to_cpu(leaf, di, &key);
4345 WARN_ON(key.type != BTRFS_ROOT_ITEM_KEY || key.objectid != objectid);
4346 ret = btrfs_delete_one_dir_name(trans, root, path, di);
4348 btrfs_abort_transaction(trans, ret);
4351 btrfs_release_path(path);
4353 ret = btrfs_del_root_ref(trans, fs_info, objectid,
4354 root->root_key.objectid, dir_ino,
4355 &index, name, name_len);
4357 if (ret != -ENOENT) {
4358 btrfs_abort_transaction(trans, ret);
4361 di = btrfs_search_dir_index_item(root, path, dir_ino,
4363 if (IS_ERR_OR_NULL(di)) {
4368 btrfs_abort_transaction(trans, ret);
4372 leaf = path->nodes[0];
4373 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
4374 btrfs_release_path(path);
4377 btrfs_release_path(path);
4379 ret = btrfs_delete_delayed_dir_index(trans, fs_info, BTRFS_I(dir), index);
4381 btrfs_abort_transaction(trans, ret);
4385 btrfs_i_size_write(BTRFS_I(dir), dir->i_size - name_len * 2);
4386 inode_inc_iversion(dir);
4387 dir->i_mtime = dir->i_ctime = current_time(dir);
4388 ret = btrfs_update_inode_fallback(trans, root, dir);
4390 btrfs_abort_transaction(trans, ret);
4392 btrfs_free_path(path);
4396 static int btrfs_rmdir(struct inode *dir, struct dentry *dentry)
4398 struct inode *inode = d_inode(dentry);
4400 struct btrfs_root *root = BTRFS_I(dir)->root;
4401 struct btrfs_trans_handle *trans;
4402 u64 last_unlink_trans;
4404 if (inode->i_size > BTRFS_EMPTY_DIR_SIZE)
4406 if (btrfs_ino(BTRFS_I(inode)) == BTRFS_FIRST_FREE_OBJECTID)
4409 trans = __unlink_start_trans(dir);
4411 return PTR_ERR(trans);
4413 if (unlikely(btrfs_ino(BTRFS_I(inode)) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)) {
4414 err = btrfs_unlink_subvol(trans, root, dir,
4415 BTRFS_I(inode)->location.objectid,
4416 dentry->d_name.name,
4417 dentry->d_name.len);
4421 err = btrfs_orphan_add(trans, BTRFS_I(inode));
4425 last_unlink_trans = BTRFS_I(inode)->last_unlink_trans;
4427 /* now the directory is empty */
4428 err = btrfs_unlink_inode(trans, root, BTRFS_I(dir),
4429 BTRFS_I(d_inode(dentry)), dentry->d_name.name,
4430 dentry->d_name.len);
4432 btrfs_i_size_write(BTRFS_I(inode), 0);
4434 * Propagate the last_unlink_trans value of the deleted dir to
4435 * its parent directory. This is to prevent an unrecoverable
4436 * log tree in the case we do something like this:
4438 * 2) create snapshot under dir foo
4439 * 3) delete the snapshot
4442 * 6) fsync foo or some file inside foo
4444 if (last_unlink_trans >= trans->transid)
4445 BTRFS_I(dir)->last_unlink_trans = last_unlink_trans;
4448 btrfs_end_transaction(trans);
4449 btrfs_btree_balance_dirty(root->fs_info);
4454 static int truncate_space_check(struct btrfs_trans_handle *trans,
4455 struct btrfs_root *root,
4458 struct btrfs_fs_info *fs_info = root->fs_info;
4462 * This is only used to apply pressure to the enospc system, we don't
4463 * intend to use this reservation at all.
4465 bytes_deleted = btrfs_csum_bytes_to_leaves(fs_info, bytes_deleted);
4466 bytes_deleted *= fs_info->nodesize;
4467 ret = btrfs_block_rsv_add(root, &fs_info->trans_block_rsv,
4468 bytes_deleted, BTRFS_RESERVE_NO_FLUSH);
4470 trace_btrfs_space_reservation(fs_info, "transaction",
4473 trans->bytes_reserved += bytes_deleted;
4479 static int truncate_inline_extent(struct inode *inode,
4480 struct btrfs_path *path,
4481 struct btrfs_key *found_key,
4485 struct extent_buffer *leaf = path->nodes[0];
4486 int slot = path->slots[0];
4487 struct btrfs_file_extent_item *fi;
4488 u32 size = (u32)(new_size - found_key->offset);
4489 struct btrfs_root *root = BTRFS_I(inode)->root;
4491 fi = btrfs_item_ptr(leaf, slot, struct btrfs_file_extent_item);
4493 if (btrfs_file_extent_compression(leaf, fi) != BTRFS_COMPRESS_NONE) {
4494 loff_t offset = new_size;
4495 loff_t page_end = ALIGN(offset, PAGE_SIZE);
4498 * Zero out the remaining of the last page of our inline extent,
4499 * instead of directly truncating our inline extent here - that
4500 * would be much more complex (decompressing all the data, then
4501 * compressing the truncated data, which might be bigger than
4502 * the size of the inline extent, resize the extent, etc).
4503 * We release the path because to get the page we might need to
4504 * read the extent item from disk (data not in the page cache).
4506 btrfs_release_path(path);
4507 return btrfs_truncate_block(inode, offset, page_end - offset,
4511 btrfs_set_file_extent_ram_bytes(leaf, fi, size);
4512 size = btrfs_file_extent_calc_inline_size(size);
4513 btrfs_truncate_item(root->fs_info, path, size, 1);
4515 if (test_bit(BTRFS_ROOT_REF_COWS, &root->state))
4516 inode_sub_bytes(inode, item_end + 1 - new_size);
4522 * this can truncate away extent items, csum items and directory items.
4523 * It starts at a high offset and removes keys until it can't find
4524 * any higher than new_size
4526 * csum items that cross the new i_size are truncated to the new size
4529 * min_type is the minimum key type to truncate down to. If set to 0, this
4530 * will kill all the items on this inode, including the INODE_ITEM_KEY.
4532 int btrfs_truncate_inode_items(struct btrfs_trans_handle *trans,
4533 struct btrfs_root *root,
4534 struct inode *inode,
4535 u64 new_size, u32 min_type)
4537 struct btrfs_fs_info *fs_info = root->fs_info;
4538 struct btrfs_path *path;
4539 struct extent_buffer *leaf;
4540 struct btrfs_file_extent_item *fi;
4541 struct btrfs_key key;
4542 struct btrfs_key found_key;
4543 u64 extent_start = 0;
4544 u64 extent_num_bytes = 0;
4545 u64 extent_offset = 0;
4547 u64 last_size = new_size;
4548 u32 found_type = (u8)-1;
4551 int pending_del_nr = 0;
4552 int pending_del_slot = 0;
4553 int extent_type = -1;
4556 u64 ino = btrfs_ino(BTRFS_I(inode));
4557 u64 bytes_deleted = 0;
4559 bool should_throttle = 0;
4560 bool should_end = 0;
4562 BUG_ON(new_size > 0 && min_type != BTRFS_EXTENT_DATA_KEY);
4565 * for non-free space inodes and ref cows, we want to back off from
4568 if (!btrfs_is_free_space_inode(BTRFS_I(inode)) &&
4569 test_bit(BTRFS_ROOT_REF_COWS, &root->state))
4572 path = btrfs_alloc_path();
4575 path->reada = READA_BACK;
4578 * We want to drop from the next block forward in case this new size is
4579 * not block aligned since we will be keeping the last block of the
4580 * extent just the way it is.
4582 if (test_bit(BTRFS_ROOT_REF_COWS, &root->state) ||
4583 root == fs_info->tree_root)
4584 btrfs_drop_extent_cache(BTRFS_I(inode), ALIGN(new_size,
4585 fs_info->sectorsize),
4589 * This function is also used to drop the items in the log tree before
4590 * we relog the inode, so if root != BTRFS_I(inode)->root, it means
4591 * it is used to drop the loged items. So we shouldn't kill the delayed
4594 if (min_type == 0 && root == BTRFS_I(inode)->root)
4595 btrfs_kill_delayed_inode_items(BTRFS_I(inode));
4598 key.offset = (u64)-1;
4603 * with a 16K leaf size and 128MB extents, you can actually queue
4604 * up a huge file in a single leaf. Most of the time that
4605 * bytes_deleted is > 0, it will be huge by the time we get here
4607 if (be_nice && bytes_deleted > SZ_32M) {
4608 if (btrfs_should_end_transaction(trans)) {
4615 path->leave_spinning = 1;
4616 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
4623 /* there are no items in the tree for us to truncate, we're
4626 if (path->slots[0] == 0)
4633 leaf = path->nodes[0];
4634 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
4635 found_type = found_key.type;
4637 if (found_key.objectid != ino)
4640 if (found_type < min_type)
4643 item_end = found_key.offset;
4644 if (found_type == BTRFS_EXTENT_DATA_KEY) {
4645 fi = btrfs_item_ptr(leaf, path->slots[0],
4646 struct btrfs_file_extent_item);
4647 extent_type = btrfs_file_extent_type(leaf, fi);
4648 if (extent_type != BTRFS_FILE_EXTENT_INLINE) {
4650 btrfs_file_extent_num_bytes(leaf, fi);
4652 trace_btrfs_truncate_show_fi_regular(
4653 BTRFS_I(inode), leaf, fi,
4655 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
4656 item_end += btrfs_file_extent_ram_bytes(leaf,
4659 trace_btrfs_truncate_show_fi_inline(
4660 BTRFS_I(inode), leaf, fi, path->slots[0],
4665 if (found_type > min_type) {
4668 if (item_end < new_size)
4670 if (found_key.offset >= new_size)
4676 /* FIXME, shrink the extent if the ref count is only 1 */
4677 if (found_type != BTRFS_EXTENT_DATA_KEY)
4681 last_size = found_key.offset;
4683 last_size = new_size;
4685 if (extent_type != BTRFS_FILE_EXTENT_INLINE) {
4687 extent_start = btrfs_file_extent_disk_bytenr(leaf, fi);
4689 u64 orig_num_bytes =
4690 btrfs_file_extent_num_bytes(leaf, fi);
4691 extent_num_bytes = ALIGN(new_size -
4693 fs_info->sectorsize);
4694 btrfs_set_file_extent_num_bytes(leaf, fi,
4696 num_dec = (orig_num_bytes -
4698 if (test_bit(BTRFS_ROOT_REF_COWS,
4701 inode_sub_bytes(inode, num_dec);
4702 btrfs_mark_buffer_dirty(leaf);
4705 btrfs_file_extent_disk_num_bytes(leaf,
4707 extent_offset = found_key.offset -
4708 btrfs_file_extent_offset(leaf, fi);
4710 /* FIXME blocksize != 4096 */
4711 num_dec = btrfs_file_extent_num_bytes(leaf, fi);
4712 if (extent_start != 0) {
4714 if (test_bit(BTRFS_ROOT_REF_COWS,
4716 inode_sub_bytes(inode, num_dec);
4719 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
4721 * we can't truncate inline items that have had
4725 btrfs_file_extent_encryption(leaf, fi) == 0 &&
4726 btrfs_file_extent_other_encoding(leaf, fi) == 0) {
4729 * Need to release path in order to truncate a
4730 * compressed extent. So delete any accumulated
4731 * extent items so far.
4733 if (btrfs_file_extent_compression(leaf, fi) !=
4734 BTRFS_COMPRESS_NONE && pending_del_nr) {
4735 err = btrfs_del_items(trans, root, path,
4739 btrfs_abort_transaction(trans,
4746 err = truncate_inline_extent(inode, path,
4751 btrfs_abort_transaction(trans, err);
4754 } else if (test_bit(BTRFS_ROOT_REF_COWS,
4756 inode_sub_bytes(inode, item_end + 1 - new_size);
4761 if (!pending_del_nr) {
4762 /* no pending yet, add ourselves */
4763 pending_del_slot = path->slots[0];
4765 } else if (pending_del_nr &&
4766 path->slots[0] + 1 == pending_del_slot) {
4767 /* hop on the pending chunk */
4769 pending_del_slot = path->slots[0];
4776 should_throttle = 0;
4779 (test_bit(BTRFS_ROOT_REF_COWS, &root->state) ||
4780 root == fs_info->tree_root)) {
4781 btrfs_set_path_blocking(path);
4782 bytes_deleted += extent_num_bytes;
4783 ret = btrfs_free_extent(trans, fs_info, extent_start,
4784 extent_num_bytes, 0,
4785 btrfs_header_owner(leaf),
4786 ino, extent_offset);
4788 btrfs_abort_transaction(trans, ret);
4791 if (btrfs_should_throttle_delayed_refs(trans, fs_info))
4792 btrfs_async_run_delayed_refs(fs_info,
4793 trans->delayed_ref_updates * 2,
4796 if (truncate_space_check(trans, root,
4797 extent_num_bytes)) {
4800 if (btrfs_should_throttle_delayed_refs(trans,
4802 should_throttle = 1;
4806 if (found_type == BTRFS_INODE_ITEM_KEY)
4809 if (path->slots[0] == 0 ||
4810 path->slots[0] != pending_del_slot ||
4811 should_throttle || should_end) {
4812 if (pending_del_nr) {
4813 ret = btrfs_del_items(trans, root, path,
4817 btrfs_abort_transaction(trans, ret);
4822 btrfs_release_path(path);
4823 if (should_throttle) {
4824 unsigned long updates = trans->delayed_ref_updates;
4826 trans->delayed_ref_updates = 0;
4827 ret = btrfs_run_delayed_refs(trans,
4835 * if we failed to refill our space rsv, bail out
4836 * and let the transaction restart
4848 if (pending_del_nr) {
4849 ret = btrfs_del_items(trans, root, path, pending_del_slot,
4852 btrfs_abort_transaction(trans, ret);
4855 if (root->root_key.objectid != BTRFS_TREE_LOG_OBJECTID) {
4856 ASSERT(last_size >= new_size);
4857 if (!err && last_size > new_size)
4858 last_size = new_size;
4859 btrfs_ordered_update_i_size(inode, last_size, NULL);
4862 btrfs_free_path(path);
4864 if (be_nice && bytes_deleted > SZ_32M) {
4865 unsigned long updates = trans->delayed_ref_updates;
4867 trans->delayed_ref_updates = 0;
4868 ret = btrfs_run_delayed_refs(trans, fs_info,
4878 * btrfs_truncate_block - read, zero a chunk and write a block
4879 * @inode - inode that we're zeroing
4880 * @from - the offset to start zeroing
4881 * @len - the length to zero, 0 to zero the entire range respective to the
4883 * @front - zero up to the offset instead of from the offset on
4885 * This will find the block for the "from" offset and cow the block and zero the
4886 * part we want to zero. This is used with truncate and hole punching.
4888 int btrfs_truncate_block(struct inode *inode, loff_t from, loff_t len,
4891 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
4892 struct address_space *mapping = inode->i_mapping;
4893 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
4894 struct btrfs_ordered_extent *ordered;
4895 struct extent_state *cached_state = NULL;
4896 struct extent_changeset *data_reserved = NULL;
4898 u32 blocksize = fs_info->sectorsize;
4899 pgoff_t index = from >> PAGE_SHIFT;
4900 unsigned offset = from & (blocksize - 1);
4902 gfp_t mask = btrfs_alloc_write_mask(mapping);
4907 if ((offset & (blocksize - 1)) == 0 &&
4908 (!len || ((len & (blocksize - 1)) == 0)))
4911 ret = btrfs_delalloc_reserve_space(inode, &data_reserved,
4912 round_down(from, blocksize), blocksize);
4917 page = find_or_create_page(mapping, index, mask);
4919 btrfs_delalloc_release_space(inode, data_reserved,
4920 round_down(from, blocksize),
4926 block_start = round_down(from, blocksize);
4927 block_end = block_start + blocksize - 1;
4929 if (!PageUptodate(page)) {
4930 ret = btrfs_readpage(NULL, page);
4932 if (page->mapping != mapping) {
4937 if (!PageUptodate(page)) {
4942 wait_on_page_writeback(page);
4944 lock_extent_bits(io_tree, block_start, block_end, &cached_state);
4945 set_page_extent_mapped(page);
4947 ordered = btrfs_lookup_ordered_extent(inode, block_start);
4949 unlock_extent_cached(io_tree, block_start, block_end,
4950 &cached_state, GFP_NOFS);
4953 btrfs_start_ordered_extent(inode, ordered, 1);
4954 btrfs_put_ordered_extent(ordered);
4958 clear_extent_bit(&BTRFS_I(inode)->io_tree, block_start, block_end,
4959 EXTENT_DIRTY | EXTENT_DELALLOC |
4960 EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG,
4961 0, 0, &cached_state, GFP_NOFS);
4963 ret = btrfs_set_extent_delalloc(inode, block_start, block_end,
4966 unlock_extent_cached(io_tree, block_start, block_end,
4967 &cached_state, GFP_NOFS);
4971 if (offset != blocksize) {
4973 len = blocksize - offset;
4976 memset(kaddr + (block_start - page_offset(page)),
4979 memset(kaddr + (block_start - page_offset(page)) + offset,
4981 flush_dcache_page(page);
4984 ClearPageChecked(page);
4985 set_page_dirty(page);
4986 unlock_extent_cached(io_tree, block_start, block_end, &cached_state,
4991 btrfs_delalloc_release_space(inode, data_reserved, block_start,
4996 extent_changeset_free(data_reserved);
5000 static int maybe_insert_hole(struct btrfs_root *root, struct inode *inode,
5001 u64 offset, u64 len)
5003 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
5004 struct btrfs_trans_handle *trans;
5008 * Still need to make sure the inode looks like it's been updated so
5009 * that any holes get logged if we fsync.
5011 if (btrfs_fs_incompat(fs_info, NO_HOLES)) {
5012 BTRFS_I(inode)->last_trans = fs_info->generation;
5013 BTRFS_I(inode)->last_sub_trans = root->log_transid;
5014 BTRFS_I(inode)->last_log_commit = root->last_log_commit;
5019 * 1 - for the one we're dropping
5020 * 1 - for the one we're adding
5021 * 1 - for updating the inode.
5023 trans = btrfs_start_transaction(root, 3);
5025 return PTR_ERR(trans);
5027 ret = btrfs_drop_extents(trans, root, inode, offset, offset + len, 1);
5029 btrfs_abort_transaction(trans, ret);
5030 btrfs_end_transaction(trans);
5034 ret = btrfs_insert_file_extent(trans, root, btrfs_ino(BTRFS_I(inode)),
5035 offset, 0, 0, len, 0, len, 0, 0, 0);
5037 btrfs_abort_transaction(trans, ret);
5039 btrfs_update_inode(trans, root, inode);
5040 btrfs_end_transaction(trans);
5045 * This function puts in dummy file extents for the area we're creating a hole
5046 * for. So if we are truncating this file to a larger size we need to insert
5047 * these file extents so that btrfs_get_extent will return a EXTENT_MAP_HOLE for
5048 * the range between oldsize and size
5050 int btrfs_cont_expand(struct inode *inode, loff_t oldsize, loff_t size)
5052 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
5053 struct btrfs_root *root = BTRFS_I(inode)->root;
5054 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
5055 struct extent_map *em = NULL;
5056 struct extent_state *cached_state = NULL;
5057 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
5058 u64 hole_start = ALIGN(oldsize, fs_info->sectorsize);
5059 u64 block_end = ALIGN(size, fs_info->sectorsize);
5066 * If our size started in the middle of a block we need to zero out the
5067 * rest of the block before we expand the i_size, otherwise we could
5068 * expose stale data.
5070 err = btrfs_truncate_block(inode, oldsize, 0, 0);
5074 if (size <= hole_start)
5078 struct btrfs_ordered_extent *ordered;
5080 lock_extent_bits(io_tree, hole_start, block_end - 1,
5082 ordered = btrfs_lookup_ordered_range(BTRFS_I(inode), hole_start,
5083 block_end - hole_start);
5086 unlock_extent_cached(io_tree, hole_start, block_end - 1,
5087 &cached_state, GFP_NOFS);
5088 btrfs_start_ordered_extent(inode, ordered, 1);
5089 btrfs_put_ordered_extent(ordered);
5092 cur_offset = hole_start;
5094 em = btrfs_get_extent(BTRFS_I(inode), NULL, 0, cur_offset,
5095 block_end - cur_offset, 0);
5101 last_byte = min(extent_map_end(em), block_end);
5102 last_byte = ALIGN(last_byte, fs_info->sectorsize);
5103 if (!test_bit(EXTENT_FLAG_PREALLOC, &em->flags)) {
5104 struct extent_map *hole_em;
5105 hole_size = last_byte - cur_offset;
5107 err = maybe_insert_hole(root, inode, cur_offset,
5111 btrfs_drop_extent_cache(BTRFS_I(inode), cur_offset,
5112 cur_offset + hole_size - 1, 0);
5113 hole_em = alloc_extent_map();
5115 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
5116 &BTRFS_I(inode)->runtime_flags);
5119 hole_em->start = cur_offset;
5120 hole_em->len = hole_size;
5121 hole_em->orig_start = cur_offset;
5123 hole_em->block_start = EXTENT_MAP_HOLE;
5124 hole_em->block_len = 0;
5125 hole_em->orig_block_len = 0;
5126 hole_em->ram_bytes = hole_size;
5127 hole_em->bdev = fs_info->fs_devices->latest_bdev;
5128 hole_em->compress_type = BTRFS_COMPRESS_NONE;
5129 hole_em->generation = fs_info->generation;
5132 write_lock(&em_tree->lock);
5133 err = add_extent_mapping(em_tree, hole_em, 1);
5134 write_unlock(&em_tree->lock);
5137 btrfs_drop_extent_cache(BTRFS_I(inode),
5142 free_extent_map(hole_em);
5145 free_extent_map(em);
5147 cur_offset = last_byte;
5148 if (cur_offset >= block_end)
5151 free_extent_map(em);
5152 unlock_extent_cached(io_tree, hole_start, block_end - 1, &cached_state,
5157 static int btrfs_setsize(struct inode *inode, struct iattr *attr)
5159 struct btrfs_root *root = BTRFS_I(inode)->root;
5160 struct btrfs_trans_handle *trans;
5161 loff_t oldsize = i_size_read(inode);
5162 loff_t newsize = attr->ia_size;
5163 int mask = attr->ia_valid;
5167 * The regular truncate() case without ATTR_CTIME and ATTR_MTIME is a
5168 * special case where we need to update the times despite not having
5169 * these flags set. For all other operations the VFS set these flags
5170 * explicitly if it wants a timestamp update.
5172 if (newsize != oldsize) {
5173 inode_inc_iversion(inode);
5174 if (!(mask & (ATTR_CTIME | ATTR_MTIME)))
5175 inode->i_ctime = inode->i_mtime =
5176 current_time(inode);
5179 if (newsize > oldsize) {
5181 * Don't do an expanding truncate while snapshotting is ongoing.
5182 * This is to ensure the snapshot captures a fully consistent
5183 * state of this file - if the snapshot captures this expanding
5184 * truncation, it must capture all writes that happened before
5187 btrfs_wait_for_snapshot_creation(root);
5188 ret = btrfs_cont_expand(inode, oldsize, newsize);
5190 btrfs_end_write_no_snapshotting(root);
5194 trans = btrfs_start_transaction(root, 1);
5195 if (IS_ERR(trans)) {
5196 btrfs_end_write_no_snapshotting(root);
5197 return PTR_ERR(trans);
5200 i_size_write(inode, newsize);
5201 btrfs_ordered_update_i_size(inode, i_size_read(inode), NULL);
5202 pagecache_isize_extended(inode, oldsize, newsize);
5203 ret = btrfs_update_inode(trans, root, inode);
5204 btrfs_end_write_no_snapshotting(root);
5205 btrfs_end_transaction(trans);
5209 * We're truncating a file that used to have good data down to
5210 * zero. Make sure it gets into the ordered flush list so that
5211 * any new writes get down to disk quickly.
5214 set_bit(BTRFS_INODE_ORDERED_DATA_CLOSE,
5215 &BTRFS_I(inode)->runtime_flags);
5218 * 1 for the orphan item we're going to add
5219 * 1 for the orphan item deletion.
5221 trans = btrfs_start_transaction(root, 2);
5223 return PTR_ERR(trans);
5226 * We need to do this in case we fail at _any_ point during the
5227 * actual truncate. Once we do the truncate_setsize we could
5228 * invalidate pages which forces any outstanding ordered io to
5229 * be instantly completed which will give us extents that need
5230 * to be truncated. If we fail to get an orphan inode down we
5231 * could have left over extents that were never meant to live,
5232 * so we need to guarantee from this point on that everything
5233 * will be consistent.
5235 ret = btrfs_orphan_add(trans, BTRFS_I(inode));
5236 btrfs_end_transaction(trans);
5240 /* we don't support swapfiles, so vmtruncate shouldn't fail */
5241 truncate_setsize(inode, newsize);
5243 /* Disable nonlocked read DIO to avoid the end less truncate */
5244 btrfs_inode_block_unlocked_dio(BTRFS_I(inode));
5245 inode_dio_wait(inode);
5246 btrfs_inode_resume_unlocked_dio(BTRFS_I(inode));
5248 ret = btrfs_truncate(inode);
5249 if (ret && inode->i_nlink) {
5252 /* To get a stable disk_i_size */
5253 err = btrfs_wait_ordered_range(inode, 0, (u64)-1);
5255 btrfs_orphan_del(NULL, BTRFS_I(inode));
5260 * failed to truncate, disk_i_size is only adjusted down
5261 * as we remove extents, so it should represent the true
5262 * size of the inode, so reset the in memory size and
5263 * delete our orphan entry.
5265 trans = btrfs_join_transaction(root);
5266 if (IS_ERR(trans)) {
5267 btrfs_orphan_del(NULL, BTRFS_I(inode));
5270 i_size_write(inode, BTRFS_I(inode)->disk_i_size);
5271 err = btrfs_orphan_del(trans, BTRFS_I(inode));
5273 btrfs_abort_transaction(trans, err);
5274 btrfs_end_transaction(trans);
5281 static int btrfs_setattr(struct dentry *dentry, struct iattr *attr)
5283 struct inode *inode = d_inode(dentry);
5284 struct btrfs_root *root = BTRFS_I(inode)->root;
5287 if (btrfs_root_readonly(root))
5290 err = setattr_prepare(dentry, attr);
5294 if (S_ISREG(inode->i_mode) && (attr->ia_valid & ATTR_SIZE)) {
5295 err = btrfs_setsize(inode, attr);
5300 if (attr->ia_valid) {
5301 setattr_copy(inode, attr);
5302 inode_inc_iversion(inode);
5303 err = btrfs_dirty_inode(inode);
5305 if (!err && attr->ia_valid & ATTR_MODE)
5306 err = posix_acl_chmod(inode, inode->i_mode);
5313 * While truncating the inode pages during eviction, we get the VFS calling
5314 * btrfs_invalidatepage() against each page of the inode. This is slow because
5315 * the calls to btrfs_invalidatepage() result in a huge amount of calls to
5316 * lock_extent_bits() and clear_extent_bit(), which keep merging and splitting
5317 * extent_state structures over and over, wasting lots of time.
5319 * Therefore if the inode is being evicted, let btrfs_invalidatepage() skip all
5320 * those expensive operations on a per page basis and do only the ordered io
5321 * finishing, while we release here the extent_map and extent_state structures,
5322 * without the excessive merging and splitting.
5324 static void evict_inode_truncate_pages(struct inode *inode)
5326 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
5327 struct extent_map_tree *map_tree = &BTRFS_I(inode)->extent_tree;
5328 struct rb_node *node;
5330 ASSERT(inode->i_state & I_FREEING);
5331 truncate_inode_pages_final(&inode->i_data);
5333 write_lock(&map_tree->lock);
5334 while (!RB_EMPTY_ROOT(&map_tree->map)) {
5335 struct extent_map *em;
5337 node = rb_first(&map_tree->map);
5338 em = rb_entry(node, struct extent_map, rb_node);
5339 clear_bit(EXTENT_FLAG_PINNED, &em->flags);
5340 clear_bit(EXTENT_FLAG_LOGGING, &em->flags);
5341 remove_extent_mapping(map_tree, em);
5342 free_extent_map(em);
5343 if (need_resched()) {
5344 write_unlock(&map_tree->lock);
5346 write_lock(&map_tree->lock);
5349 write_unlock(&map_tree->lock);
5352 * Keep looping until we have no more ranges in the io tree.
5353 * We can have ongoing bios started by readpages (called from readahead)
5354 * that have their endio callback (extent_io.c:end_bio_extent_readpage)
5355 * still in progress (unlocked the pages in the bio but did not yet
5356 * unlocked the ranges in the io tree). Therefore this means some
5357 * ranges can still be locked and eviction started because before
5358 * submitting those bios, which are executed by a separate task (work
5359 * queue kthread), inode references (inode->i_count) were not taken
5360 * (which would be dropped in the end io callback of each bio).
5361 * Therefore here we effectively end up waiting for those bios and
5362 * anyone else holding locked ranges without having bumped the inode's
5363 * reference count - if we don't do it, when they access the inode's
5364 * io_tree to unlock a range it may be too late, leading to an
5365 * use-after-free issue.
5367 spin_lock(&io_tree->lock);
5368 while (!RB_EMPTY_ROOT(&io_tree->state)) {
5369 struct extent_state *state;
5370 struct extent_state *cached_state = NULL;
5373 unsigned state_flags;
5375 node = rb_first(&io_tree->state);
5376 state = rb_entry(node, struct extent_state, rb_node);
5377 start = state->start;
5379 state_flags = state->state;
5380 spin_unlock(&io_tree->lock);
5382 lock_extent_bits(io_tree, start, end, &cached_state);
5385 * If still has DELALLOC flag, the extent didn't reach disk,
5386 * and its reserved space won't be freed by delayed_ref.
5387 * So we need to free its reserved space here.
5388 * (Refer to comment in btrfs_invalidatepage, case 2)
5390 * Note, end is the bytenr of last byte, so we need + 1 here.
5392 if (state_flags & EXTENT_DELALLOC)
5393 btrfs_qgroup_free_data(inode, NULL, start, end - start + 1);
5395 clear_extent_bit(io_tree, start, end,
5396 EXTENT_LOCKED | EXTENT_DIRTY |
5397 EXTENT_DELALLOC | EXTENT_DO_ACCOUNTING |
5398 EXTENT_DEFRAG, 1, 1,
5399 &cached_state, GFP_NOFS);
5402 spin_lock(&io_tree->lock);
5404 spin_unlock(&io_tree->lock);
5407 void btrfs_evict_inode(struct inode *inode)
5409 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
5410 struct btrfs_trans_handle *trans;
5411 struct btrfs_root *root = BTRFS_I(inode)->root;
5412 struct btrfs_block_rsv *rsv, *global_rsv;
5413 int steal_from_global = 0;
5417 trace_btrfs_inode_evict(inode);
5424 min_size = btrfs_calc_trunc_metadata_size(fs_info, 1);
5426 evict_inode_truncate_pages(inode);
5428 if (inode->i_nlink &&
5429 ((btrfs_root_refs(&root->root_item) != 0 &&
5430 root->root_key.objectid != BTRFS_ROOT_TREE_OBJECTID) ||
5431 btrfs_is_free_space_inode(BTRFS_I(inode))))
5434 if (is_bad_inode(inode)) {
5435 btrfs_orphan_del(NULL, BTRFS_I(inode));
5438 /* do we really want it for ->i_nlink > 0 and zero btrfs_root_refs? */
5439 if (!special_file(inode->i_mode))
5440 btrfs_wait_ordered_range(inode, 0, (u64)-1);
5442 btrfs_free_io_failure_record(BTRFS_I(inode), 0, (u64)-1);
5444 if (test_bit(BTRFS_FS_LOG_RECOVERING, &fs_info->flags)) {
5445 BUG_ON(test_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
5446 &BTRFS_I(inode)->runtime_flags));
5450 if (inode->i_nlink > 0) {
5451 BUG_ON(btrfs_root_refs(&root->root_item) != 0 &&
5452 root->root_key.objectid != BTRFS_ROOT_TREE_OBJECTID);
5456 ret = btrfs_commit_inode_delayed_inode(BTRFS_I(inode));
5458 btrfs_orphan_del(NULL, BTRFS_I(inode));
5462 rsv = btrfs_alloc_block_rsv(fs_info, BTRFS_BLOCK_RSV_TEMP);
5464 btrfs_orphan_del(NULL, BTRFS_I(inode));
5467 rsv->size = min_size;
5469 global_rsv = &fs_info->global_block_rsv;
5471 btrfs_i_size_write(BTRFS_I(inode), 0);
5474 * This is a bit simpler than btrfs_truncate since we've already
5475 * reserved our space for our orphan item in the unlink, so we just
5476 * need to reserve some slack space in case we add bytes and update
5477 * inode item when doing the truncate.
5480 ret = btrfs_block_rsv_refill(root, rsv, min_size,
5481 BTRFS_RESERVE_FLUSH_LIMIT);
5484 * Try and steal from the global reserve since we will
5485 * likely not use this space anyway, we want to try as
5486 * hard as possible to get this to work.
5489 steal_from_global++;
5491 steal_from_global = 0;
5495 * steal_from_global == 0: we reserved stuff, hooray!
5496 * steal_from_global == 1: we didn't reserve stuff, boo!
5497 * steal_from_global == 2: we've committed, still not a lot of
5498 * room but maybe we'll have room in the global reserve this
5500 * steal_from_global == 3: abandon all hope!
5502 if (steal_from_global > 2) {
5504 "Could not get space for a delete, will truncate on mount %d",
5506 btrfs_orphan_del(NULL, BTRFS_I(inode));
5507 btrfs_free_block_rsv(fs_info, rsv);
5511 trans = btrfs_join_transaction(root);
5512 if (IS_ERR(trans)) {
5513 btrfs_orphan_del(NULL, BTRFS_I(inode));
5514 btrfs_free_block_rsv(fs_info, rsv);
5519 * We can't just steal from the global reserve, we need to make
5520 * sure there is room to do it, if not we need to commit and try
5523 if (steal_from_global) {
5524 if (!btrfs_check_space_for_delayed_refs(trans, fs_info))
5525 ret = btrfs_block_rsv_migrate(global_rsv, rsv,
5532 * Couldn't steal from the global reserve, we have too much
5533 * pending stuff built up, commit the transaction and try it
5537 ret = btrfs_commit_transaction(trans);
5539 btrfs_orphan_del(NULL, BTRFS_I(inode));
5540 btrfs_free_block_rsv(fs_info, rsv);
5545 steal_from_global = 0;
5548 trans->block_rsv = rsv;
5550 ret = btrfs_truncate_inode_items(trans, root, inode, 0, 0);
5552 trans->block_rsv = &fs_info->trans_block_rsv;
5553 btrfs_end_transaction(trans);
5554 btrfs_btree_balance_dirty(fs_info);
5555 if (ret != -ENOSPC && ret != -EAGAIN) {
5556 btrfs_orphan_del(NULL, BTRFS_I(inode));
5557 btrfs_free_block_rsv(fs_info, rsv);
5565 btrfs_free_block_rsv(fs_info, rsv);
5568 * Errors here aren't a big deal, it just means we leave orphan items
5569 * in the tree. They will be cleaned up on the next mount.
5571 trans->block_rsv = root->orphan_block_rsv;
5572 btrfs_orphan_del(trans, BTRFS_I(inode));
5574 trans->block_rsv = &fs_info->trans_block_rsv;
5575 if (!(root == fs_info->tree_root ||
5576 root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID))
5577 btrfs_return_ino(root, btrfs_ino(BTRFS_I(inode)));
5579 btrfs_end_transaction(trans);
5580 btrfs_btree_balance_dirty(fs_info);
5582 btrfs_remove_delayed_node(BTRFS_I(inode));
5587 * Return the key found in the dir entry in the location pointer, fill @type
5588 * with BTRFS_FT_*, and return 0.
5590 * If no dir entries were found, returns -ENOENT.
5591 * If found a corrupted location in dir entry, returns -EUCLEAN.
5593 static int btrfs_inode_by_name(struct inode *dir, struct dentry *dentry,
5594 struct btrfs_key *location, u8 *type)
5596 const char *name = dentry->d_name.name;
5597 int namelen = dentry->d_name.len;
5598 struct btrfs_dir_item *di;
5599 struct btrfs_path *path;
5600 struct btrfs_root *root = BTRFS_I(dir)->root;
5603 path = btrfs_alloc_path();
5607 di = btrfs_lookup_dir_item(NULL, root, path, btrfs_ino(BTRFS_I(dir)),
5618 btrfs_dir_item_key_to_cpu(path->nodes[0], di, location);
5619 if (location->type != BTRFS_INODE_ITEM_KEY &&
5620 location->type != BTRFS_ROOT_ITEM_KEY) {
5622 btrfs_warn(root->fs_info,
5623 "%s gets something invalid in DIR_ITEM (name %s, directory ino %llu, location(%llu %u %llu))",
5624 __func__, name, btrfs_ino(BTRFS_I(dir)),
5625 location->objectid, location->type, location->offset);
5628 *type = btrfs_dir_type(path->nodes[0], di);
5630 btrfs_free_path(path);
5635 * when we hit a tree root in a directory, the btrfs part of the inode
5636 * needs to be changed to reflect the root directory of the tree root. This
5637 * is kind of like crossing a mount point.
5639 static int fixup_tree_root_location(struct btrfs_fs_info *fs_info,
5641 struct dentry *dentry,
5642 struct btrfs_key *location,
5643 struct btrfs_root **sub_root)
5645 struct btrfs_path *path;
5646 struct btrfs_root *new_root;
5647 struct btrfs_root_ref *ref;
5648 struct extent_buffer *leaf;
5649 struct btrfs_key key;
5653 path = btrfs_alloc_path();
5660 key.objectid = BTRFS_I(dir)->root->root_key.objectid;
5661 key.type = BTRFS_ROOT_REF_KEY;
5662 key.offset = location->objectid;
5664 ret = btrfs_search_slot(NULL, fs_info->tree_root, &key, path, 0, 0);
5671 leaf = path->nodes[0];
5672 ref = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_root_ref);
5673 if (btrfs_root_ref_dirid(leaf, ref) != btrfs_ino(BTRFS_I(dir)) ||
5674 btrfs_root_ref_name_len(leaf, ref) != dentry->d_name.len)
5677 ret = memcmp_extent_buffer(leaf, dentry->d_name.name,
5678 (unsigned long)(ref + 1),
5679 dentry->d_name.len);
5683 btrfs_release_path(path);
5685 new_root = btrfs_read_fs_root_no_name(fs_info, location);
5686 if (IS_ERR(new_root)) {
5687 err = PTR_ERR(new_root);
5691 *sub_root = new_root;
5692 location->objectid = btrfs_root_dirid(&new_root->root_item);
5693 location->type = BTRFS_INODE_ITEM_KEY;
5694 location->offset = 0;
5697 btrfs_free_path(path);
5701 static void inode_tree_add(struct inode *inode)
5703 struct btrfs_root *root = BTRFS_I(inode)->root;
5704 struct btrfs_inode *entry;
5706 struct rb_node *parent;
5707 struct rb_node *new = &BTRFS_I(inode)->rb_node;
5708 u64 ino = btrfs_ino(BTRFS_I(inode));
5710 if (inode_unhashed(inode))
5713 spin_lock(&root->inode_lock);
5714 p = &root->inode_tree.rb_node;
5717 entry = rb_entry(parent, struct btrfs_inode, rb_node);
5719 if (ino < btrfs_ino(BTRFS_I(&entry->vfs_inode)))
5720 p = &parent->rb_left;
5721 else if (ino > btrfs_ino(BTRFS_I(&entry->vfs_inode)))
5722 p = &parent->rb_right;
5724 WARN_ON(!(entry->vfs_inode.i_state &
5725 (I_WILL_FREE | I_FREEING)));
5726 rb_replace_node(parent, new, &root->inode_tree);
5727 RB_CLEAR_NODE(parent);
5728 spin_unlock(&root->inode_lock);
5732 rb_link_node(new, parent, p);
5733 rb_insert_color(new, &root->inode_tree);
5734 spin_unlock(&root->inode_lock);
5737 static void inode_tree_del(struct inode *inode)
5739 struct btrfs_root *root = BTRFS_I(inode)->root;
5742 spin_lock(&root->inode_lock);
5743 if (!RB_EMPTY_NODE(&BTRFS_I(inode)->rb_node)) {
5744 rb_erase(&BTRFS_I(inode)->rb_node, &root->inode_tree);
5745 RB_CLEAR_NODE(&BTRFS_I(inode)->rb_node);
5746 empty = RB_EMPTY_ROOT(&root->inode_tree);
5748 spin_unlock(&root->inode_lock);
5750 if (empty && btrfs_root_refs(&root->root_item) == 0) {
5751 spin_lock(&root->inode_lock);
5752 empty = RB_EMPTY_ROOT(&root->inode_tree);
5753 spin_unlock(&root->inode_lock);
5755 btrfs_add_dead_root(root);
5759 void btrfs_invalidate_inodes(struct btrfs_root *root)
5761 struct btrfs_fs_info *fs_info = root->fs_info;
5762 struct rb_node *node;
5763 struct rb_node *prev;
5764 struct btrfs_inode *entry;
5765 struct inode *inode;
5768 if (!test_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state))
5769 WARN_ON(btrfs_root_refs(&root->root_item) != 0);
5771 spin_lock(&root->inode_lock);
5773 node = root->inode_tree.rb_node;
5777 entry = rb_entry(node, struct btrfs_inode, rb_node);
5779 if (objectid < btrfs_ino(BTRFS_I(&entry->vfs_inode)))
5780 node = node->rb_left;
5781 else if (objectid > btrfs_ino(BTRFS_I(&entry->vfs_inode)))
5782 node = node->rb_right;
5788 entry = rb_entry(prev, struct btrfs_inode, rb_node);
5789 if (objectid <= btrfs_ino(BTRFS_I(&entry->vfs_inode))) {
5793 prev = rb_next(prev);
5797 entry = rb_entry(node, struct btrfs_inode, rb_node);
5798 objectid = btrfs_ino(BTRFS_I(&entry->vfs_inode)) + 1;
5799 inode = igrab(&entry->vfs_inode);
5801 spin_unlock(&root->inode_lock);
5802 if (atomic_read(&inode->i_count) > 1)
5803 d_prune_aliases(inode);
5805 * btrfs_drop_inode will have it removed from
5806 * the inode cache when its usage count
5811 spin_lock(&root->inode_lock);
5815 if (cond_resched_lock(&root->inode_lock))
5818 node = rb_next(node);
5820 spin_unlock(&root->inode_lock);
5823 static int btrfs_init_locked_inode(struct inode *inode, void *p)
5825 struct btrfs_iget_args *args = p;
5826 inode->i_ino = args->location->objectid;
5827 memcpy(&BTRFS_I(inode)->location, args->location,
5828 sizeof(*args->location));
5829 BTRFS_I(inode)->root = args->root;
5833 static int btrfs_find_actor(struct inode *inode, void *opaque)
5835 struct btrfs_iget_args *args = opaque;
5836 return args->location->objectid == BTRFS_I(inode)->location.objectid &&
5837 args->root == BTRFS_I(inode)->root;
5840 static struct inode *btrfs_iget_locked(struct super_block *s,
5841 struct btrfs_key *location,
5842 struct btrfs_root *root)
5844 struct inode *inode;
5845 struct btrfs_iget_args args;
5846 unsigned long hashval = btrfs_inode_hash(location->objectid, root);
5848 args.location = location;
5851 inode = iget5_locked(s, hashval, btrfs_find_actor,
5852 btrfs_init_locked_inode,
5857 /* Get an inode object given its location and corresponding root.
5858 * Returns in *is_new if the inode was read from disk
5860 struct inode *btrfs_iget(struct super_block *s, struct btrfs_key *location,
5861 struct btrfs_root *root, int *new)
5863 struct inode *inode;
5865 inode = btrfs_iget_locked(s, location, root);
5867 return ERR_PTR(-ENOMEM);
5869 if (inode->i_state & I_NEW) {
5872 ret = btrfs_read_locked_inode(inode);
5873 if (!is_bad_inode(inode)) {
5874 inode_tree_add(inode);
5875 unlock_new_inode(inode);
5879 unlock_new_inode(inode);
5882 inode = ERR_PTR(ret < 0 ? ret : -ESTALE);
5889 static struct inode *new_simple_dir(struct super_block *s,
5890 struct btrfs_key *key,
5891 struct btrfs_root *root)
5893 struct inode *inode = new_inode(s);
5896 return ERR_PTR(-ENOMEM);
5898 BTRFS_I(inode)->root = root;
5899 memcpy(&BTRFS_I(inode)->location, key, sizeof(*key));
5900 set_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags);
5902 inode->i_ino = BTRFS_EMPTY_SUBVOL_DIR_OBJECTID;
5903 inode->i_op = &btrfs_dir_ro_inode_operations;
5904 inode->i_opflags &= ~IOP_XATTR;
5905 inode->i_fop = &simple_dir_operations;
5906 inode->i_mode = S_IFDIR | S_IRUGO | S_IWUSR | S_IXUGO;
5907 inode->i_mtime = current_time(inode);
5908 inode->i_atime = inode->i_mtime;
5909 inode->i_ctime = inode->i_mtime;
5910 BTRFS_I(inode)->i_otime = inode->i_mtime;
5915 static inline u8 btrfs_inode_type(struct inode *inode)
5917 return btrfs_type_by_mode[(inode->i_mode & S_IFMT) >> S_SHIFT];
5920 struct inode *btrfs_lookup_dentry(struct inode *dir, struct dentry *dentry)
5922 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
5923 struct inode *inode;
5924 struct btrfs_root *root = BTRFS_I(dir)->root;
5925 struct btrfs_root *sub_root = root;
5926 struct btrfs_key location;
5931 if (dentry->d_name.len > BTRFS_NAME_LEN)
5932 return ERR_PTR(-ENAMETOOLONG);
5934 ret = btrfs_inode_by_name(dir, dentry, &location, &di_type);
5936 return ERR_PTR(ret);
5938 if (location.type == BTRFS_INODE_ITEM_KEY) {
5939 inode = btrfs_iget(dir->i_sb, &location, root, NULL);
5943 /* Do extra check against inode mode with di_type */
5944 if (btrfs_inode_type(inode) != di_type) {
5946 "inode mode mismatch with dir: inode mode=0%o btrfs type=%u dir type=%u",
5947 inode->i_mode, btrfs_inode_type(inode),
5950 return ERR_PTR(-EUCLEAN);
5955 index = srcu_read_lock(&fs_info->subvol_srcu);
5956 ret = fixup_tree_root_location(fs_info, dir, dentry,
5957 &location, &sub_root);
5960 inode = ERR_PTR(ret);
5962 inode = new_simple_dir(dir->i_sb, &location, sub_root);
5964 inode = btrfs_iget(dir->i_sb, &location, sub_root, NULL);
5966 srcu_read_unlock(&fs_info->subvol_srcu, index);
5968 if (!IS_ERR(inode) && root != sub_root) {
5969 down_read(&fs_info->cleanup_work_sem);
5970 if (!sb_rdonly(inode->i_sb))
5971 ret = btrfs_orphan_cleanup(sub_root);
5972 up_read(&fs_info->cleanup_work_sem);
5975 inode = ERR_PTR(ret);
5982 static int btrfs_dentry_delete(const struct dentry *dentry)
5984 struct btrfs_root *root;
5985 struct inode *inode = d_inode(dentry);
5987 if (!inode && !IS_ROOT(dentry))
5988 inode = d_inode(dentry->d_parent);
5991 root = BTRFS_I(inode)->root;
5992 if (btrfs_root_refs(&root->root_item) == 0)
5995 if (btrfs_ino(BTRFS_I(inode)) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)
6001 static void btrfs_dentry_release(struct dentry *dentry)
6003 kfree(dentry->d_fsdata);
6006 static struct dentry *btrfs_lookup(struct inode *dir, struct dentry *dentry,
6009 struct inode *inode;
6011 inode = btrfs_lookup_dentry(dir, dentry);
6012 if (IS_ERR(inode)) {
6013 if (PTR_ERR(inode) == -ENOENT)
6016 return ERR_CAST(inode);
6019 return d_splice_alias(inode, dentry);
6022 unsigned char btrfs_filetype_table[] = {
6023 DT_UNKNOWN, DT_REG, DT_DIR, DT_CHR, DT_BLK, DT_FIFO, DT_SOCK, DT_LNK
6027 * All this infrastructure exists because dir_emit can fault, and we are holding
6028 * the tree lock when doing readdir. For now just allocate a buffer and copy
6029 * our information into that, and then dir_emit from the buffer. This is
6030 * similar to what NFS does, only we don't keep the buffer around in pagecache
6031 * because I'm afraid I'll mess that up. Long term we need to make filldir do
6032 * copy_to_user_inatomic so we don't have to worry about page faulting under the
6035 static int btrfs_opendir(struct inode *inode, struct file *file)
6037 struct btrfs_file_private *private;
6039 private = kzalloc(sizeof(struct btrfs_file_private), GFP_KERNEL);
6042 private->filldir_buf = kzalloc(PAGE_SIZE, GFP_KERNEL);
6043 if (!private->filldir_buf) {
6047 file->private_data = private;
6058 static int btrfs_filldir(void *addr, int entries, struct dir_context *ctx)
6061 struct dir_entry *entry = addr;
6062 char *name = (char *)(entry + 1);
6064 ctx->pos = get_unaligned(&entry->offset);
6065 if (!dir_emit(ctx, name, get_unaligned(&entry->name_len),
6066 get_unaligned(&entry->ino),
6067 get_unaligned(&entry->type)))
6069 addr += sizeof(struct dir_entry) +
6070 get_unaligned(&entry->name_len);
6076 static int btrfs_real_readdir(struct file *file, struct dir_context *ctx)
6078 struct inode *inode = file_inode(file);
6079 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
6080 struct btrfs_root *root = BTRFS_I(inode)->root;
6081 struct btrfs_file_private *private = file->private_data;
6082 struct btrfs_dir_item *di;
6083 struct btrfs_key key;
6084 struct btrfs_key found_key;
6085 struct btrfs_path *path;
6087 struct list_head ins_list;
6088 struct list_head del_list;
6090 struct extent_buffer *leaf;
6097 struct btrfs_key location;
6099 if (!dir_emit_dots(file, ctx))
6102 path = btrfs_alloc_path();
6106 addr = private->filldir_buf;
6107 path->reada = READA_FORWARD;
6109 INIT_LIST_HEAD(&ins_list);
6110 INIT_LIST_HEAD(&del_list);
6111 put = btrfs_readdir_get_delayed_items(inode, &ins_list, &del_list);
6114 key.type = BTRFS_DIR_INDEX_KEY;
6115 key.offset = ctx->pos;
6116 key.objectid = btrfs_ino(BTRFS_I(inode));
6118 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
6123 struct dir_entry *entry;
6125 leaf = path->nodes[0];
6126 slot = path->slots[0];
6127 if (slot >= btrfs_header_nritems(leaf)) {
6128 ret = btrfs_next_leaf(root, path);
6136 btrfs_item_key_to_cpu(leaf, &found_key, slot);
6138 if (found_key.objectid != key.objectid)
6140 if (found_key.type != BTRFS_DIR_INDEX_KEY)
6142 if (found_key.offset < ctx->pos)
6144 if (btrfs_should_delete_dir_index(&del_list, found_key.offset))
6146 di = btrfs_item_ptr(leaf, slot, struct btrfs_dir_item);
6147 if (verify_dir_item(fs_info, leaf, slot, di))
6150 name_len = btrfs_dir_name_len(leaf, di);
6151 if ((total_len + sizeof(struct dir_entry) + name_len) >=
6153 btrfs_release_path(path);
6154 ret = btrfs_filldir(private->filldir_buf, entries, ctx);
6157 addr = private->filldir_buf;
6164 put_unaligned(name_len, &entry->name_len);
6165 name_ptr = (char *)(entry + 1);
6166 read_extent_buffer(leaf, name_ptr, (unsigned long)(di + 1),
6168 put_unaligned(btrfs_filetype_table[btrfs_dir_type(leaf, di)],
6170 btrfs_dir_item_key_to_cpu(leaf, di, &location);
6171 put_unaligned(location.objectid, &entry->ino);
6172 put_unaligned(found_key.offset, &entry->offset);
6174 addr += sizeof(struct dir_entry) + name_len;
6175 total_len += sizeof(struct dir_entry) + name_len;
6179 btrfs_release_path(path);
6181 ret = btrfs_filldir(private->filldir_buf, entries, ctx);
6185 ret = btrfs_readdir_delayed_dir_index(ctx, &ins_list);
6190 * Stop new entries from being returned after we return the last
6193 * New directory entries are assigned a strictly increasing
6194 * offset. This means that new entries created during readdir
6195 * are *guaranteed* to be seen in the future by that readdir.
6196 * This has broken buggy programs which operate on names as
6197 * they're returned by readdir. Until we re-use freed offsets
6198 * we have this hack to stop new entries from being returned
6199 * under the assumption that they'll never reach this huge
6202 * This is being careful not to overflow 32bit loff_t unless the
6203 * last entry requires it because doing so has broken 32bit apps
6206 if (ctx->pos >= INT_MAX)
6207 ctx->pos = LLONG_MAX;
6214 btrfs_readdir_put_delayed_items(inode, &ins_list, &del_list);
6215 btrfs_free_path(path);
6220 * This is somewhat expensive, updating the tree every time the
6221 * inode changes. But, it is most likely to find the inode in cache.
6222 * FIXME, needs more benchmarking...there are no reasons other than performance
6223 * to keep or drop this code.
6225 static int btrfs_dirty_inode(struct inode *inode)
6227 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
6228 struct btrfs_root *root = BTRFS_I(inode)->root;
6229 struct btrfs_trans_handle *trans;
6232 if (test_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags))
6235 trans = btrfs_join_transaction(root);
6237 return PTR_ERR(trans);
6239 ret = btrfs_update_inode(trans, root, inode);
6240 if (ret && ret == -ENOSPC) {
6241 /* whoops, lets try again with the full transaction */
6242 btrfs_end_transaction(trans);
6243 trans = btrfs_start_transaction(root, 1);
6245 return PTR_ERR(trans);
6247 ret = btrfs_update_inode(trans, root, inode);
6249 btrfs_end_transaction(trans);
6250 if (BTRFS_I(inode)->delayed_node)
6251 btrfs_balance_delayed_items(fs_info);
6257 * This is a copy of file_update_time. We need this so we can return error on
6258 * ENOSPC for updating the inode in the case of file write and mmap writes.
6260 static int btrfs_update_time(struct inode *inode, struct timespec *now,
6263 struct btrfs_root *root = BTRFS_I(inode)->root;
6265 if (btrfs_root_readonly(root))
6268 if (flags & S_VERSION)
6269 inode_inc_iversion(inode);
6270 if (flags & S_CTIME)
6271 inode->i_ctime = *now;
6272 if (flags & S_MTIME)
6273 inode->i_mtime = *now;
6274 if (flags & S_ATIME)
6275 inode->i_atime = *now;
6276 return btrfs_dirty_inode(inode);
6280 * find the highest existing sequence number in a directory
6281 * and then set the in-memory index_cnt variable to reflect
6282 * free sequence numbers
6284 static int btrfs_set_inode_index_count(struct btrfs_inode *inode)
6286 struct btrfs_root *root = inode->root;
6287 struct btrfs_key key, found_key;
6288 struct btrfs_path *path;
6289 struct extent_buffer *leaf;
6292 key.objectid = btrfs_ino(inode);
6293 key.type = BTRFS_DIR_INDEX_KEY;
6294 key.offset = (u64)-1;
6296 path = btrfs_alloc_path();
6300 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
6303 /* FIXME: we should be able to handle this */
6309 * MAGIC NUMBER EXPLANATION:
6310 * since we search a directory based on f_pos we have to start at 2
6311 * since '.' and '..' have f_pos of 0 and 1 respectively, so everybody
6312 * else has to start at 2
6314 if (path->slots[0] == 0) {
6315 inode->index_cnt = 2;
6321 leaf = path->nodes[0];
6322 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
6324 if (found_key.objectid != btrfs_ino(inode) ||
6325 found_key.type != BTRFS_DIR_INDEX_KEY) {
6326 inode->index_cnt = 2;
6330 inode->index_cnt = found_key.offset + 1;
6332 btrfs_free_path(path);
6337 * helper to find a free sequence number in a given directory. This current
6338 * code is very simple, later versions will do smarter things in the btree
6340 int btrfs_set_inode_index(struct btrfs_inode *dir, u64 *index)
6344 if (dir->index_cnt == (u64)-1) {
6345 ret = btrfs_inode_delayed_dir_index_count(dir);
6347 ret = btrfs_set_inode_index_count(dir);
6353 *index = dir->index_cnt;
6359 static int btrfs_insert_inode_locked(struct inode *inode)
6361 struct btrfs_iget_args args;
6362 args.location = &BTRFS_I(inode)->location;
6363 args.root = BTRFS_I(inode)->root;
6365 return insert_inode_locked4(inode,
6366 btrfs_inode_hash(inode->i_ino, BTRFS_I(inode)->root),
6367 btrfs_find_actor, &args);
6371 * Inherit flags from the parent inode.
6373 * Currently only the compression flags and the cow flags are inherited.
6375 static void btrfs_inherit_iflags(struct inode *inode, struct inode *dir)
6382 flags = BTRFS_I(dir)->flags;
6384 if (flags & BTRFS_INODE_NOCOMPRESS) {
6385 BTRFS_I(inode)->flags &= ~BTRFS_INODE_COMPRESS;
6386 BTRFS_I(inode)->flags |= BTRFS_INODE_NOCOMPRESS;
6387 } else if (flags & BTRFS_INODE_COMPRESS) {
6388 BTRFS_I(inode)->flags &= ~BTRFS_INODE_NOCOMPRESS;
6389 BTRFS_I(inode)->flags |= BTRFS_INODE_COMPRESS;
6392 if (flags & BTRFS_INODE_NODATACOW) {
6393 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATACOW;
6394 if (S_ISREG(inode->i_mode))
6395 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATASUM;
6398 btrfs_update_iflags(inode);
6401 static struct inode *btrfs_new_inode(struct btrfs_trans_handle *trans,
6402 struct btrfs_root *root,
6404 const char *name, int name_len,
6405 u64 ref_objectid, u64 objectid,
6406 umode_t mode, u64 *index)
6408 struct btrfs_fs_info *fs_info = root->fs_info;
6409 struct inode *inode;
6410 struct btrfs_inode_item *inode_item;
6411 struct btrfs_key *location;
6412 struct btrfs_path *path;
6413 struct btrfs_inode_ref *ref;
6414 struct btrfs_key key[2];
6416 int nitems = name ? 2 : 1;
6420 path = btrfs_alloc_path();
6422 return ERR_PTR(-ENOMEM);
6424 inode = new_inode(fs_info->sb);
6426 btrfs_free_path(path);
6427 return ERR_PTR(-ENOMEM);
6431 * O_TMPFILE, set link count to 0, so that after this point,
6432 * we fill in an inode item with the correct link count.
6435 set_nlink(inode, 0);
6438 * we have to initialize this early, so we can reclaim the inode
6439 * number if we fail afterwards in this function.
6441 inode->i_ino = objectid;
6444 trace_btrfs_inode_request(dir);
6446 ret = btrfs_set_inode_index(BTRFS_I(dir), index);
6448 btrfs_free_path(path);
6450 return ERR_PTR(ret);
6456 * index_cnt is ignored for everything but a dir,
6457 * btrfs_get_inode_index_count has an explanation for the magic
6460 BTRFS_I(inode)->index_cnt = 2;
6461 BTRFS_I(inode)->dir_index = *index;
6462 BTRFS_I(inode)->root = root;
6463 BTRFS_I(inode)->generation = trans->transid;
6464 inode->i_generation = BTRFS_I(inode)->generation;
6467 * We could have gotten an inode number from somebody who was fsynced
6468 * and then removed in this same transaction, so let's just set full
6469 * sync since it will be a full sync anyway and this will blow away the
6470 * old info in the log.
6472 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &BTRFS_I(inode)->runtime_flags);
6474 key[0].objectid = objectid;
6475 key[0].type = BTRFS_INODE_ITEM_KEY;
6478 sizes[0] = sizeof(struct btrfs_inode_item);
6482 * Start new inodes with an inode_ref. This is slightly more
6483 * efficient for small numbers of hard links since they will
6484 * be packed into one item. Extended refs will kick in if we
6485 * add more hard links than can fit in the ref item.
6487 key[1].objectid = objectid;
6488 key[1].type = BTRFS_INODE_REF_KEY;
6489 key[1].offset = ref_objectid;
6491 sizes[1] = name_len + sizeof(*ref);
6494 location = &BTRFS_I(inode)->location;
6495 location->objectid = objectid;
6496 location->offset = 0;
6497 location->type = BTRFS_INODE_ITEM_KEY;
6499 ret = btrfs_insert_inode_locked(inode);
6503 path->leave_spinning = 1;
6504 ret = btrfs_insert_empty_items(trans, root, path, key, sizes, nitems);
6508 inode_init_owner(inode, dir, mode);
6509 inode_set_bytes(inode, 0);
6511 inode->i_mtime = current_time(inode);
6512 inode->i_atime = inode->i_mtime;
6513 inode->i_ctime = inode->i_mtime;
6514 BTRFS_I(inode)->i_otime = inode->i_mtime;
6516 inode_item = btrfs_item_ptr(path->nodes[0], path->slots[0],
6517 struct btrfs_inode_item);
6518 memzero_extent_buffer(path->nodes[0], (unsigned long)inode_item,
6519 sizeof(*inode_item));
6520 fill_inode_item(trans, path->nodes[0], inode_item, inode);
6523 ref = btrfs_item_ptr(path->nodes[0], path->slots[0] + 1,
6524 struct btrfs_inode_ref);
6525 btrfs_set_inode_ref_name_len(path->nodes[0], ref, name_len);
6526 btrfs_set_inode_ref_index(path->nodes[0], ref, *index);
6527 ptr = (unsigned long)(ref + 1);
6528 write_extent_buffer(path->nodes[0], name, ptr, name_len);
6531 btrfs_mark_buffer_dirty(path->nodes[0]);
6532 btrfs_free_path(path);
6534 btrfs_inherit_iflags(inode, dir);
6536 if (S_ISREG(mode)) {
6537 if (btrfs_test_opt(fs_info, NODATASUM))
6538 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATASUM;
6539 if (btrfs_test_opt(fs_info, NODATACOW))
6540 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATACOW |
6541 BTRFS_INODE_NODATASUM;
6544 inode_tree_add(inode);
6546 trace_btrfs_inode_new(inode);
6547 btrfs_set_inode_last_trans(trans, inode);
6549 btrfs_update_root_times(trans, root);
6551 ret = btrfs_inode_inherit_props(trans, inode, dir);
6554 "error inheriting props for ino %llu (root %llu): %d",
6555 btrfs_ino(BTRFS_I(inode)), root->root_key.objectid, ret);
6560 unlock_new_inode(inode);
6563 BTRFS_I(dir)->index_cnt--;
6564 btrfs_free_path(path);
6566 return ERR_PTR(ret);
6570 * utility function to add 'inode' into 'parent_inode' with
6571 * a give name and a given sequence number.
6572 * if 'add_backref' is true, also insert a backref from the
6573 * inode to the parent directory.
6575 int btrfs_add_link(struct btrfs_trans_handle *trans,
6576 struct btrfs_inode *parent_inode, struct btrfs_inode *inode,
6577 const char *name, int name_len, int add_backref, u64 index)
6579 struct btrfs_fs_info *fs_info = btrfs_sb(inode->vfs_inode.i_sb);
6581 struct btrfs_key key;
6582 struct btrfs_root *root = parent_inode->root;
6583 u64 ino = btrfs_ino(inode);
6584 u64 parent_ino = btrfs_ino(parent_inode);
6586 if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
6587 memcpy(&key, &inode->root->root_key, sizeof(key));
6590 key.type = BTRFS_INODE_ITEM_KEY;
6594 if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
6595 ret = btrfs_add_root_ref(trans, fs_info, key.objectid,
6596 root->root_key.objectid, parent_ino,
6597 index, name, name_len);
6598 } else if (add_backref) {
6599 ret = btrfs_insert_inode_ref(trans, root, name, name_len, ino,
6603 /* Nothing to clean up yet */
6607 ret = btrfs_insert_dir_item(trans, root, name, name_len,
6609 btrfs_inode_type(&inode->vfs_inode), index);
6610 if (ret == -EEXIST || ret == -EOVERFLOW)
6613 btrfs_abort_transaction(trans, ret);
6617 btrfs_i_size_write(parent_inode, parent_inode->vfs_inode.i_size +
6619 inode_inc_iversion(&parent_inode->vfs_inode);
6621 * If we are replaying a log tree, we do not want to update the mtime
6622 * and ctime of the parent directory with the current time, since the
6623 * log replay procedure is responsible for setting them to their correct
6624 * values (the ones it had when the fsync was done).
6626 if (!test_bit(BTRFS_FS_LOG_RECOVERING, &root->fs_info->flags)) {
6627 struct timespec now = current_time(&parent_inode->vfs_inode);
6629 parent_inode->vfs_inode.i_mtime = now;
6630 parent_inode->vfs_inode.i_ctime = now;
6632 ret = btrfs_update_inode(trans, root, &parent_inode->vfs_inode);
6634 btrfs_abort_transaction(trans, ret);
6638 if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
6641 err = btrfs_del_root_ref(trans, fs_info, key.objectid,
6642 root->root_key.objectid, parent_ino,
6643 &local_index, name, name_len);
6645 btrfs_abort_transaction(trans, err);
6646 } else if (add_backref) {
6650 err = btrfs_del_inode_ref(trans, root, name, name_len,
6651 ino, parent_ino, &local_index);
6653 btrfs_abort_transaction(trans, err);
6656 /* Return the original error code */
6660 static int btrfs_add_nondir(struct btrfs_trans_handle *trans,
6661 struct btrfs_inode *dir, struct dentry *dentry,
6662 struct btrfs_inode *inode, int backref, u64 index)
6664 int err = btrfs_add_link(trans, dir, inode,
6665 dentry->d_name.name, dentry->d_name.len,
6672 static int btrfs_mknod(struct inode *dir, struct dentry *dentry,
6673 umode_t mode, dev_t rdev)
6675 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
6676 struct btrfs_trans_handle *trans;
6677 struct btrfs_root *root = BTRFS_I(dir)->root;
6678 struct inode *inode = NULL;
6685 * 2 for inode item and ref
6687 * 1 for xattr if selinux is on
6689 trans = btrfs_start_transaction(root, 5);
6691 return PTR_ERR(trans);
6693 err = btrfs_find_free_ino(root, &objectid);
6697 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
6698 dentry->d_name.len, btrfs_ino(BTRFS_I(dir)), objectid,
6700 if (IS_ERR(inode)) {
6701 err = PTR_ERR(inode);
6706 * If the active LSM wants to access the inode during
6707 * d_instantiate it needs these. Smack checks to see
6708 * if the filesystem supports xattrs by looking at the
6711 inode->i_op = &btrfs_special_inode_operations;
6712 init_special_inode(inode, inode->i_mode, rdev);
6714 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
6716 goto out_unlock_inode;
6718 err = btrfs_add_nondir(trans, BTRFS_I(dir), dentry, BTRFS_I(inode),
6721 goto out_unlock_inode;
6723 btrfs_update_inode(trans, root, inode);
6724 d_instantiate_new(dentry, inode);
6728 btrfs_end_transaction(trans);
6729 btrfs_balance_delayed_items(fs_info);
6730 btrfs_btree_balance_dirty(fs_info);
6732 inode_dec_link_count(inode);
6739 unlock_new_inode(inode);
6744 static int btrfs_create(struct inode *dir, struct dentry *dentry,
6745 umode_t mode, bool excl)
6747 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
6748 struct btrfs_trans_handle *trans;
6749 struct btrfs_root *root = BTRFS_I(dir)->root;
6750 struct inode *inode = NULL;
6751 int drop_inode_on_err = 0;
6757 * 2 for inode item and ref
6759 * 1 for xattr if selinux is on
6761 trans = btrfs_start_transaction(root, 5);
6763 return PTR_ERR(trans);
6765 err = btrfs_find_free_ino(root, &objectid);
6769 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
6770 dentry->d_name.len, btrfs_ino(BTRFS_I(dir)), objectid,
6772 if (IS_ERR(inode)) {
6773 err = PTR_ERR(inode);
6776 drop_inode_on_err = 1;
6778 * If the active LSM wants to access the inode during
6779 * d_instantiate it needs these. Smack checks to see
6780 * if the filesystem supports xattrs by looking at the
6783 inode->i_fop = &btrfs_file_operations;
6784 inode->i_op = &btrfs_file_inode_operations;
6785 inode->i_mapping->a_ops = &btrfs_aops;
6787 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
6789 goto out_unlock_inode;
6791 err = btrfs_update_inode(trans, root, inode);
6793 goto out_unlock_inode;
6795 err = btrfs_add_nondir(trans, BTRFS_I(dir), dentry, BTRFS_I(inode),
6798 goto out_unlock_inode;
6800 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
6801 d_instantiate_new(dentry, inode);
6804 btrfs_end_transaction(trans);
6805 if (err && drop_inode_on_err) {
6806 inode_dec_link_count(inode);
6809 btrfs_balance_delayed_items(fs_info);
6810 btrfs_btree_balance_dirty(fs_info);
6814 unlock_new_inode(inode);
6819 static int btrfs_link(struct dentry *old_dentry, struct inode *dir,
6820 struct dentry *dentry)
6822 struct btrfs_trans_handle *trans = NULL;
6823 struct btrfs_root *root = BTRFS_I(dir)->root;
6824 struct inode *inode = d_inode(old_dentry);
6825 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
6830 /* do not allow sys_link's with other subvols of the same device */
6831 if (root->objectid != BTRFS_I(inode)->root->objectid)
6834 if (inode->i_nlink >= BTRFS_LINK_MAX)
6837 err = btrfs_set_inode_index(BTRFS_I(dir), &index);
6842 * 2 items for inode and inode ref
6843 * 2 items for dir items
6844 * 1 item for parent inode
6846 trans = btrfs_start_transaction(root, 5);
6847 if (IS_ERR(trans)) {
6848 err = PTR_ERR(trans);
6853 /* There are several dir indexes for this inode, clear the cache. */
6854 BTRFS_I(inode)->dir_index = 0ULL;
6856 inode_inc_iversion(inode);
6857 inode->i_ctime = current_time(inode);
6859 set_bit(BTRFS_INODE_COPY_EVERYTHING, &BTRFS_I(inode)->runtime_flags);
6861 err = btrfs_add_nondir(trans, BTRFS_I(dir), dentry, BTRFS_I(inode),
6867 struct dentry *parent = dentry->d_parent;
6868 err = btrfs_update_inode(trans, root, inode);
6871 if (inode->i_nlink == 1) {
6873 * If new hard link count is 1, it's a file created
6874 * with open(2) O_TMPFILE flag.
6876 err = btrfs_orphan_del(trans, BTRFS_I(inode));
6880 BTRFS_I(inode)->last_link_trans = trans->transid;
6881 d_instantiate(dentry, inode);
6882 btrfs_log_new_name(trans, BTRFS_I(inode), NULL, parent);
6885 btrfs_balance_delayed_items(fs_info);
6888 btrfs_end_transaction(trans);
6890 inode_dec_link_count(inode);
6893 btrfs_btree_balance_dirty(fs_info);
6897 static int btrfs_mkdir(struct inode *dir, struct dentry *dentry, umode_t mode)
6899 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
6900 struct inode *inode = NULL;
6901 struct btrfs_trans_handle *trans;
6902 struct btrfs_root *root = BTRFS_I(dir)->root;
6904 int drop_on_err = 0;
6909 * 2 items for inode and ref
6910 * 2 items for dir items
6911 * 1 for xattr if selinux is on
6913 trans = btrfs_start_transaction(root, 5);
6915 return PTR_ERR(trans);
6917 err = btrfs_find_free_ino(root, &objectid);
6921 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
6922 dentry->d_name.len, btrfs_ino(BTRFS_I(dir)), objectid,
6923 S_IFDIR | mode, &index);
6924 if (IS_ERR(inode)) {
6925 err = PTR_ERR(inode);
6930 /* these must be set before we unlock the inode */
6931 inode->i_op = &btrfs_dir_inode_operations;
6932 inode->i_fop = &btrfs_dir_file_operations;
6934 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
6936 goto out_fail_inode;
6938 btrfs_i_size_write(BTRFS_I(inode), 0);
6939 err = btrfs_update_inode(trans, root, inode);
6941 goto out_fail_inode;
6943 err = btrfs_add_link(trans, BTRFS_I(dir), BTRFS_I(inode),
6944 dentry->d_name.name,
6945 dentry->d_name.len, 0, index);
6947 goto out_fail_inode;
6949 d_instantiate_new(dentry, inode);
6953 btrfs_end_transaction(trans);
6955 inode_dec_link_count(inode);
6958 btrfs_balance_delayed_items(fs_info);
6959 btrfs_btree_balance_dirty(fs_info);
6963 unlock_new_inode(inode);
6967 /* Find next extent map of a given extent map, caller needs to ensure locks */
6968 static struct extent_map *next_extent_map(struct extent_map *em)
6970 struct rb_node *next;
6972 next = rb_next(&em->rb_node);
6975 return container_of(next, struct extent_map, rb_node);
6978 static struct extent_map *prev_extent_map(struct extent_map *em)
6980 struct rb_node *prev;
6982 prev = rb_prev(&em->rb_node);
6985 return container_of(prev, struct extent_map, rb_node);
6988 /* helper for btfs_get_extent. Given an existing extent in the tree,
6989 * the existing extent is the nearest extent to map_start,
6990 * and an extent that you want to insert, deal with overlap and insert
6991 * the best fitted new extent into the tree.
6993 static int merge_extent_mapping(struct extent_map_tree *em_tree,
6994 struct extent_map *existing,
6995 struct extent_map *em,
6998 struct extent_map *prev;
6999 struct extent_map *next;
7004 BUG_ON(map_start < em->start || map_start >= extent_map_end(em));
7006 if (existing->start > map_start) {
7008 prev = prev_extent_map(next);
7011 next = next_extent_map(prev);
7014 start = prev ? extent_map_end(prev) : em->start;
7015 start = max_t(u64, start, em->start);
7016 end = next ? next->start : extent_map_end(em);
7017 end = min_t(u64, end, extent_map_end(em));
7018 start_diff = start - em->start;
7020 em->len = end - start;
7021 if (em->block_start < EXTENT_MAP_LAST_BYTE &&
7022 !test_bit(EXTENT_FLAG_COMPRESSED, &em->flags)) {
7023 em->block_start += start_diff;
7024 em->block_len -= start_diff;
7026 return add_extent_mapping(em_tree, em, 0);
7029 static noinline int uncompress_inline(struct btrfs_path *path,
7031 size_t pg_offset, u64 extent_offset,
7032 struct btrfs_file_extent_item *item)
7035 struct extent_buffer *leaf = path->nodes[0];
7038 unsigned long inline_size;
7042 WARN_ON(pg_offset != 0);
7043 compress_type = btrfs_file_extent_compression(leaf, item);
7044 max_size = btrfs_file_extent_ram_bytes(leaf, item);
7045 inline_size = btrfs_file_extent_inline_item_len(leaf,
7046 btrfs_item_nr(path->slots[0]));
7047 tmp = kmalloc(inline_size, GFP_NOFS);
7050 ptr = btrfs_file_extent_inline_start(item);
7052 read_extent_buffer(leaf, tmp, ptr, inline_size);
7054 max_size = min_t(unsigned long, PAGE_SIZE, max_size);
7055 ret = btrfs_decompress(compress_type, tmp, page,
7056 extent_offset, inline_size, max_size);
7059 * decompression code contains a memset to fill in any space between the end
7060 * of the uncompressed data and the end of max_size in case the decompressed
7061 * data ends up shorter than ram_bytes. That doesn't cover the hole between
7062 * the end of an inline extent and the beginning of the next block, so we
7063 * cover that region here.
7066 if (max_size + pg_offset < PAGE_SIZE) {
7067 char *map = kmap(page);
7068 memset(map + pg_offset + max_size, 0, PAGE_SIZE - max_size - pg_offset);
7076 * a bit scary, this does extent mapping from logical file offset to the disk.
7077 * the ugly parts come from merging extents from the disk with the in-ram
7078 * representation. This gets more complex because of the data=ordered code,
7079 * where the in-ram extents might be locked pending data=ordered completion.
7081 * This also copies inline extents directly into the page.
7083 struct extent_map *btrfs_get_extent(struct btrfs_inode *inode,
7085 size_t pg_offset, u64 start, u64 len,
7088 struct btrfs_fs_info *fs_info = btrfs_sb(inode->vfs_inode.i_sb);
7091 u64 extent_start = 0;
7093 u64 objectid = btrfs_ino(inode);
7095 struct btrfs_path *path = NULL;
7096 struct btrfs_root *root = inode->root;
7097 struct btrfs_file_extent_item *item;
7098 struct extent_buffer *leaf;
7099 struct btrfs_key found_key;
7100 struct extent_map *em = NULL;
7101 struct extent_map_tree *em_tree = &inode->extent_tree;
7102 struct extent_io_tree *io_tree = &inode->io_tree;
7103 struct btrfs_trans_handle *trans = NULL;
7104 const bool new_inline = !page || create;
7107 read_lock(&em_tree->lock);
7108 em = lookup_extent_mapping(em_tree, start, len);
7110 em->bdev = fs_info->fs_devices->latest_bdev;
7111 read_unlock(&em_tree->lock);
7114 if (em->start > start || em->start + em->len <= start)
7115 free_extent_map(em);
7116 else if (em->block_start == EXTENT_MAP_INLINE && page)
7117 free_extent_map(em);
7121 em = alloc_extent_map();
7126 em->bdev = fs_info->fs_devices->latest_bdev;
7127 em->start = EXTENT_MAP_HOLE;
7128 em->orig_start = EXTENT_MAP_HOLE;
7130 em->block_len = (u64)-1;
7133 path = btrfs_alloc_path();
7139 * Chances are we'll be called again, so go ahead and do
7142 path->reada = READA_FORWARD;
7145 ret = btrfs_lookup_file_extent(trans, root, path,
7146 objectid, start, trans != NULL);
7153 if (path->slots[0] == 0)
7158 leaf = path->nodes[0];
7159 item = btrfs_item_ptr(leaf, path->slots[0],
7160 struct btrfs_file_extent_item);
7161 /* are we inside the extent that was found? */
7162 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
7163 found_type = found_key.type;
7164 if (found_key.objectid != objectid ||
7165 found_type != BTRFS_EXTENT_DATA_KEY) {
7167 * If we backup past the first extent we want to move forward
7168 * and see if there is an extent in front of us, otherwise we'll
7169 * say there is a hole for our whole search range which can
7176 found_type = btrfs_file_extent_type(leaf, item);
7177 extent_start = found_key.offset;
7178 if (found_type == BTRFS_FILE_EXTENT_REG ||
7179 found_type == BTRFS_FILE_EXTENT_PREALLOC) {
7180 /* Only regular file could have regular/prealloc extent */
7181 if (!S_ISREG(inode->vfs_inode.i_mode)) {
7184 "regular/prealloc extent found for non-regular inode %llu",
7188 extent_end = extent_start +
7189 btrfs_file_extent_num_bytes(leaf, item);
7191 trace_btrfs_get_extent_show_fi_regular(inode, leaf, item,
7193 } else if (found_type == BTRFS_FILE_EXTENT_INLINE) {
7196 size = btrfs_file_extent_ram_bytes(leaf, item);
7197 extent_end = ALIGN(extent_start + size,
7198 fs_info->sectorsize);
7200 trace_btrfs_get_extent_show_fi_inline(inode, leaf, item,
7205 if (start >= extent_end) {
7207 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
7208 ret = btrfs_next_leaf(root, path);
7215 leaf = path->nodes[0];
7217 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
7218 if (found_key.objectid != objectid ||
7219 found_key.type != BTRFS_EXTENT_DATA_KEY)
7221 if (start + len <= found_key.offset)
7223 if (start > found_key.offset)
7226 em->orig_start = start;
7227 em->len = found_key.offset - start;
7231 btrfs_extent_item_to_extent_map(inode, path, item,
7234 if (found_type == BTRFS_FILE_EXTENT_REG ||
7235 found_type == BTRFS_FILE_EXTENT_PREALLOC) {
7237 } else if (found_type == BTRFS_FILE_EXTENT_INLINE) {
7241 size_t extent_offset;
7247 size = btrfs_file_extent_ram_bytes(leaf, item);
7248 extent_offset = page_offset(page) + pg_offset - extent_start;
7249 copy_size = min_t(u64, PAGE_SIZE - pg_offset,
7250 size - extent_offset);
7251 em->start = extent_start + extent_offset;
7252 em->len = ALIGN(copy_size, fs_info->sectorsize);
7253 em->orig_block_len = em->len;
7254 em->orig_start = em->start;
7255 ptr = btrfs_file_extent_inline_start(item) + extent_offset;
7256 if (create == 0 && !PageUptodate(page)) {
7257 if (btrfs_file_extent_compression(leaf, item) !=
7258 BTRFS_COMPRESS_NONE) {
7259 ret = uncompress_inline(path, page, pg_offset,
7260 extent_offset, item);
7267 read_extent_buffer(leaf, map + pg_offset, ptr,
7269 if (pg_offset + copy_size < PAGE_SIZE) {
7270 memset(map + pg_offset + copy_size, 0,
7271 PAGE_SIZE - pg_offset -
7276 flush_dcache_page(page);
7277 } else if (create && PageUptodate(page)) {
7281 free_extent_map(em);
7284 btrfs_release_path(path);
7285 trans = btrfs_join_transaction(root);
7288 return ERR_CAST(trans);
7292 write_extent_buffer(leaf, map + pg_offset, ptr,
7295 btrfs_mark_buffer_dirty(leaf);
7297 set_extent_uptodate(io_tree, em->start,
7298 extent_map_end(em) - 1, NULL, GFP_NOFS);
7303 em->orig_start = start;
7306 em->block_start = EXTENT_MAP_HOLE;
7307 set_bit(EXTENT_FLAG_VACANCY, &em->flags);
7309 btrfs_release_path(path);
7310 if (em->start > start || extent_map_end(em) <= start) {
7312 "bad extent! em: [%llu %llu] passed [%llu %llu]",
7313 em->start, em->len, start, len);
7319 write_lock(&em_tree->lock);
7320 ret = add_extent_mapping(em_tree, em, 0);
7321 /* it is possible that someone inserted the extent into the tree
7322 * while we had the lock dropped. It is also possible that
7323 * an overlapping map exists in the tree
7325 if (ret == -EEXIST) {
7326 struct extent_map *existing;
7330 existing = search_extent_mapping(em_tree, start, len);
7332 * existing will always be non-NULL, since there must be
7333 * extent causing the -EEXIST.
7335 if (start >= existing->start &&
7336 start < extent_map_end(existing)) {
7337 free_extent_map(em);
7342 * The existing extent map is the one nearest to
7343 * the [start, start + len) range which overlaps
7345 err = merge_extent_mapping(em_tree, existing,
7347 free_extent_map(existing);
7349 free_extent_map(em);
7354 write_unlock(&em_tree->lock);
7357 trace_btrfs_get_extent(root, inode, em);
7359 btrfs_free_path(path);
7361 ret = btrfs_end_transaction(trans);
7366 free_extent_map(em);
7367 return ERR_PTR(err);
7369 BUG_ON(!em); /* Error is always set */
7373 struct extent_map *btrfs_get_extent_fiemap(struct btrfs_inode *inode,
7375 size_t pg_offset, u64 start, u64 len,
7378 struct extent_map *em;
7379 struct extent_map *hole_em = NULL;
7380 u64 range_start = start;
7386 em = btrfs_get_extent(inode, page, pg_offset, start, len, create);
7390 * If our em maps to:
7392 * - a pre-alloc extent,
7393 * there might actually be delalloc bytes behind it.
7395 if (em->block_start != EXTENT_MAP_HOLE &&
7396 !test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
7401 /* check to see if we've wrapped (len == -1 or similar) */
7410 /* ok, we didn't find anything, lets look for delalloc */
7411 found = count_range_bits(&inode->io_tree, &range_start,
7412 end, len, EXTENT_DELALLOC, 1);
7413 found_end = range_start + found;
7414 if (found_end < range_start)
7415 found_end = (u64)-1;
7418 * we didn't find anything useful, return
7419 * the original results from get_extent()
7421 if (range_start > end || found_end <= start) {
7427 /* adjust the range_start to make sure it doesn't
7428 * go backwards from the start they passed in
7430 range_start = max(start, range_start);
7431 found = found_end - range_start;
7434 u64 hole_start = start;
7437 em = alloc_extent_map();
7443 * when btrfs_get_extent can't find anything it
7444 * returns one huge hole
7446 * make sure what it found really fits our range, and
7447 * adjust to make sure it is based on the start from
7451 u64 calc_end = extent_map_end(hole_em);
7453 if (calc_end <= start || (hole_em->start > end)) {
7454 free_extent_map(hole_em);
7457 hole_start = max(hole_em->start, start);
7458 hole_len = calc_end - hole_start;
7462 if (hole_em && range_start > hole_start) {
7463 /* our hole starts before our delalloc, so we
7464 * have to return just the parts of the hole
7465 * that go until the delalloc starts
7467 em->len = min(hole_len,
7468 range_start - hole_start);
7469 em->start = hole_start;
7470 em->orig_start = hole_start;
7472 * don't adjust block start at all,
7473 * it is fixed at EXTENT_MAP_HOLE
7475 em->block_start = hole_em->block_start;
7476 em->block_len = hole_len;
7477 if (test_bit(EXTENT_FLAG_PREALLOC, &hole_em->flags))
7478 set_bit(EXTENT_FLAG_PREALLOC, &em->flags);
7480 em->start = range_start;
7482 em->orig_start = range_start;
7483 em->block_start = EXTENT_MAP_DELALLOC;
7484 em->block_len = found;
7486 } else if (hole_em) {
7491 free_extent_map(hole_em);
7493 free_extent_map(em);
7494 return ERR_PTR(err);
7499 static struct extent_map *btrfs_create_dio_extent(struct inode *inode,
7502 const u64 orig_start,
7503 const u64 block_start,
7504 const u64 block_len,
7505 const u64 orig_block_len,
7506 const u64 ram_bytes,
7509 struct extent_map *em = NULL;
7512 if (type != BTRFS_ORDERED_NOCOW) {
7513 em = create_io_em(inode, start, len, orig_start,
7514 block_start, block_len, orig_block_len,
7516 BTRFS_COMPRESS_NONE, /* compress_type */
7521 ret = btrfs_add_ordered_extent_dio(inode, start, block_start,
7522 len, block_len, type);
7525 free_extent_map(em);
7526 btrfs_drop_extent_cache(BTRFS_I(inode), start,
7527 start + len - 1, 0);
7536 static struct extent_map *btrfs_new_extent_direct(struct inode *inode,
7539 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7540 struct btrfs_root *root = BTRFS_I(inode)->root;
7541 struct extent_map *em;
7542 struct btrfs_key ins;
7546 alloc_hint = get_extent_allocation_hint(inode, start, len);
7547 ret = btrfs_reserve_extent(root, len, len, fs_info->sectorsize,
7548 0, alloc_hint, &ins, 1, 1);
7550 return ERR_PTR(ret);
7552 em = btrfs_create_dio_extent(inode, start, ins.offset, start,
7553 ins.objectid, ins.offset, ins.offset,
7554 ins.offset, BTRFS_ORDERED_REGULAR);
7555 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
7557 btrfs_free_reserved_extent(fs_info, ins.objectid,
7564 * returns 1 when the nocow is safe, < 1 on error, 0 if the
7565 * block must be cow'd
7567 noinline int can_nocow_extent(struct inode *inode, u64 offset, u64 *len,
7568 u64 *orig_start, u64 *orig_block_len,
7571 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7572 struct btrfs_path *path;
7574 struct extent_buffer *leaf;
7575 struct btrfs_root *root = BTRFS_I(inode)->root;
7576 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
7577 struct btrfs_file_extent_item *fi;
7578 struct btrfs_key key;
7585 bool nocow = (BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW);
7587 path = btrfs_alloc_path();
7591 ret = btrfs_lookup_file_extent(NULL, root, path,
7592 btrfs_ino(BTRFS_I(inode)), offset, 0);
7596 slot = path->slots[0];
7599 /* can't find the item, must cow */
7606 leaf = path->nodes[0];
7607 btrfs_item_key_to_cpu(leaf, &key, slot);
7608 if (key.objectid != btrfs_ino(BTRFS_I(inode)) ||
7609 key.type != BTRFS_EXTENT_DATA_KEY) {
7610 /* not our file or wrong item type, must cow */
7614 if (key.offset > offset) {
7615 /* Wrong offset, must cow */
7619 fi = btrfs_item_ptr(leaf, slot, struct btrfs_file_extent_item);
7620 found_type = btrfs_file_extent_type(leaf, fi);
7621 if (found_type != BTRFS_FILE_EXTENT_REG &&
7622 found_type != BTRFS_FILE_EXTENT_PREALLOC) {
7623 /* not a regular extent, must cow */
7627 if (!nocow && found_type == BTRFS_FILE_EXTENT_REG)
7630 extent_end = key.offset + btrfs_file_extent_num_bytes(leaf, fi);
7631 if (extent_end <= offset)
7634 disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
7635 if (disk_bytenr == 0)
7638 if (btrfs_file_extent_compression(leaf, fi) ||
7639 btrfs_file_extent_encryption(leaf, fi) ||
7640 btrfs_file_extent_other_encoding(leaf, fi))
7643 backref_offset = btrfs_file_extent_offset(leaf, fi);
7646 *orig_start = key.offset - backref_offset;
7647 *orig_block_len = btrfs_file_extent_disk_num_bytes(leaf, fi);
7648 *ram_bytes = btrfs_file_extent_ram_bytes(leaf, fi);
7651 if (btrfs_extent_readonly(fs_info, disk_bytenr))
7654 num_bytes = min(offset + *len, extent_end) - offset;
7655 if (!nocow && found_type == BTRFS_FILE_EXTENT_PREALLOC) {
7658 range_end = round_up(offset + num_bytes,
7659 root->fs_info->sectorsize) - 1;
7660 ret = test_range_bit(io_tree, offset, range_end,
7661 EXTENT_DELALLOC, 0, NULL);
7668 btrfs_release_path(path);
7671 * look for other files referencing this extent, if we
7672 * find any we must cow
7675 ret = btrfs_cross_ref_exist(root, btrfs_ino(BTRFS_I(inode)),
7676 key.offset - backref_offset, disk_bytenr);
7683 * adjust disk_bytenr and num_bytes to cover just the bytes
7684 * in this extent we are about to write. If there
7685 * are any csums in that range we have to cow in order
7686 * to keep the csums correct
7688 disk_bytenr += backref_offset;
7689 disk_bytenr += offset - key.offset;
7690 if (csum_exist_in_range(fs_info, disk_bytenr, num_bytes))
7693 * all of the above have passed, it is safe to overwrite this extent
7699 btrfs_free_path(path);
7703 bool btrfs_page_exists_in_range(struct inode *inode, loff_t start, loff_t end)
7705 struct radix_tree_root *root = &inode->i_mapping->page_tree;
7707 void **pagep = NULL;
7708 struct page *page = NULL;
7709 unsigned long start_idx;
7710 unsigned long end_idx;
7712 start_idx = start >> PAGE_SHIFT;
7715 * end is the last byte in the last page. end == start is legal
7717 end_idx = end >> PAGE_SHIFT;
7721 /* Most of the code in this while loop is lifted from
7722 * find_get_page. It's been modified to begin searching from a
7723 * page and return just the first page found in that range. If the
7724 * found idx is less than or equal to the end idx then we know that
7725 * a page exists. If no pages are found or if those pages are
7726 * outside of the range then we're fine (yay!) */
7727 while (page == NULL &&
7728 radix_tree_gang_lookup_slot(root, &pagep, NULL, start_idx, 1)) {
7729 page = radix_tree_deref_slot(pagep);
7730 if (unlikely(!page))
7733 if (radix_tree_exception(page)) {
7734 if (radix_tree_deref_retry(page)) {
7739 * Otherwise, shmem/tmpfs must be storing a swap entry
7740 * here as an exceptional entry: so return it without
7741 * attempting to raise page count.
7744 break; /* TODO: Is this relevant for this use case? */
7747 if (!page_cache_get_speculative(page)) {
7753 * Has the page moved?
7754 * This is part of the lockless pagecache protocol. See
7755 * include/linux/pagemap.h for details.
7757 if (unlikely(page != *pagep)) {
7764 if (page->index <= end_idx)
7773 static int lock_extent_direct(struct inode *inode, u64 lockstart, u64 lockend,
7774 struct extent_state **cached_state, int writing)
7776 struct btrfs_ordered_extent *ordered;
7780 lock_extent_bits(&BTRFS_I(inode)->io_tree, lockstart, lockend,
7783 * We're concerned with the entire range that we're going to be
7784 * doing DIO to, so we need to make sure there's no ordered
7785 * extents in this range.
7787 ordered = btrfs_lookup_ordered_range(BTRFS_I(inode), lockstart,
7788 lockend - lockstart + 1);
7791 * We need to make sure there are no buffered pages in this
7792 * range either, we could have raced between the invalidate in
7793 * generic_file_direct_write and locking the extent. The
7794 * invalidate needs to happen so that reads after a write do not
7799 !btrfs_page_exists_in_range(inode, lockstart, lockend)))
7802 unlock_extent_cached(&BTRFS_I(inode)->io_tree, lockstart, lockend,
7803 cached_state, GFP_NOFS);
7807 * If we are doing a DIO read and the ordered extent we
7808 * found is for a buffered write, we can not wait for it
7809 * to complete and retry, because if we do so we can
7810 * deadlock with concurrent buffered writes on page
7811 * locks. This happens only if our DIO read covers more
7812 * than one extent map, if at this point has already
7813 * created an ordered extent for a previous extent map
7814 * and locked its range in the inode's io tree, and a
7815 * concurrent write against that previous extent map's
7816 * range and this range started (we unlock the ranges
7817 * in the io tree only when the bios complete and
7818 * buffered writes always lock pages before attempting
7819 * to lock range in the io tree).
7822 test_bit(BTRFS_ORDERED_DIRECT, &ordered->flags))
7823 btrfs_start_ordered_extent(inode, ordered, 1);
7826 btrfs_put_ordered_extent(ordered);
7829 * We could trigger writeback for this range (and wait
7830 * for it to complete) and then invalidate the pages for
7831 * this range (through invalidate_inode_pages2_range()),
7832 * but that can lead us to a deadlock with a concurrent
7833 * call to readpages() (a buffered read or a defrag call
7834 * triggered a readahead) on a page lock due to an
7835 * ordered dio extent we created before but did not have
7836 * yet a corresponding bio submitted (whence it can not
7837 * complete), which makes readpages() wait for that
7838 * ordered extent to complete while holding a lock on
7853 /* The callers of this must take lock_extent() */
7854 static struct extent_map *create_io_em(struct inode *inode, u64 start, u64 len,
7855 u64 orig_start, u64 block_start,
7856 u64 block_len, u64 orig_block_len,
7857 u64 ram_bytes, int compress_type,
7860 struct extent_map_tree *em_tree;
7861 struct extent_map *em;
7862 struct btrfs_root *root = BTRFS_I(inode)->root;
7865 ASSERT(type == BTRFS_ORDERED_PREALLOC ||
7866 type == BTRFS_ORDERED_COMPRESSED ||
7867 type == BTRFS_ORDERED_NOCOW ||
7868 type == BTRFS_ORDERED_REGULAR);
7870 em_tree = &BTRFS_I(inode)->extent_tree;
7871 em = alloc_extent_map();
7873 return ERR_PTR(-ENOMEM);
7876 em->orig_start = orig_start;
7878 em->block_len = block_len;
7879 em->block_start = block_start;
7880 em->bdev = root->fs_info->fs_devices->latest_bdev;
7881 em->orig_block_len = orig_block_len;
7882 em->ram_bytes = ram_bytes;
7883 em->generation = -1;
7884 set_bit(EXTENT_FLAG_PINNED, &em->flags);
7885 if (type == BTRFS_ORDERED_PREALLOC) {
7886 set_bit(EXTENT_FLAG_FILLING, &em->flags);
7887 } else if (type == BTRFS_ORDERED_COMPRESSED) {
7888 set_bit(EXTENT_FLAG_COMPRESSED, &em->flags);
7889 em->compress_type = compress_type;
7893 btrfs_drop_extent_cache(BTRFS_I(inode), em->start,
7894 em->start + em->len - 1, 0);
7895 write_lock(&em_tree->lock);
7896 ret = add_extent_mapping(em_tree, em, 1);
7897 write_unlock(&em_tree->lock);
7899 * The caller has taken lock_extent(), who could race with us
7902 } while (ret == -EEXIST);
7905 free_extent_map(em);
7906 return ERR_PTR(ret);
7909 /* em got 2 refs now, callers needs to do free_extent_map once. */
7913 static void adjust_dio_outstanding_extents(struct inode *inode,
7914 struct btrfs_dio_data *dio_data,
7917 unsigned num_extents = count_max_extents(len);
7920 * If we have an outstanding_extents count still set then we're
7921 * within our reservation, otherwise we need to adjust our inode
7922 * counter appropriately.
7924 if (dio_data->outstanding_extents >= num_extents) {
7925 dio_data->outstanding_extents -= num_extents;
7928 * If dio write length has been split due to no large enough
7929 * contiguous space, we need to compensate our inode counter
7932 u64 num_needed = num_extents - dio_data->outstanding_extents;
7934 spin_lock(&BTRFS_I(inode)->lock);
7935 BTRFS_I(inode)->outstanding_extents += num_needed;
7936 spin_unlock(&BTRFS_I(inode)->lock);
7940 static int btrfs_get_blocks_direct(struct inode *inode, sector_t iblock,
7941 struct buffer_head *bh_result, int create)
7943 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7944 struct extent_map *em;
7945 struct extent_state *cached_state = NULL;
7946 struct btrfs_dio_data *dio_data = NULL;
7947 u64 start = iblock << inode->i_blkbits;
7948 u64 lockstart, lockend;
7949 u64 len = bh_result->b_size;
7950 int unlock_bits = EXTENT_LOCKED;
7954 unlock_bits |= EXTENT_DIRTY;
7956 len = min_t(u64, len, fs_info->sectorsize);
7959 lockend = start + len - 1;
7961 if (current->journal_info) {
7963 * Need to pull our outstanding extents and set journal_info to NULL so
7964 * that anything that needs to check if there's a transaction doesn't get
7967 dio_data = current->journal_info;
7968 current->journal_info = NULL;
7972 * If this errors out it's because we couldn't invalidate pagecache for
7973 * this range and we need to fallback to buffered.
7975 if (lock_extent_direct(inode, lockstart, lockend, &cached_state,
7981 em = btrfs_get_extent(BTRFS_I(inode), NULL, 0, start, len, 0);
7988 * Ok for INLINE and COMPRESSED extents we need to fallback on buffered
7989 * io. INLINE is special, and we could probably kludge it in here, but
7990 * it's still buffered so for safety lets just fall back to the generic
7993 * For COMPRESSED we _have_ to read the entire extent in so we can
7994 * decompress it, so there will be buffering required no matter what we
7995 * do, so go ahead and fallback to buffered.
7997 * We return -ENOTBLK because that's what makes DIO go ahead and go back
7998 * to buffered IO. Don't blame me, this is the price we pay for using
8001 if (test_bit(EXTENT_FLAG_COMPRESSED, &em->flags) ||
8002 em->block_start == EXTENT_MAP_INLINE) {
8003 free_extent_map(em);
8008 /* Just a good old fashioned hole, return */
8009 if (!create && (em->block_start == EXTENT_MAP_HOLE ||
8010 test_bit(EXTENT_FLAG_PREALLOC, &em->flags))) {
8011 free_extent_map(em);
8016 * We don't allocate a new extent in the following cases
8018 * 1) The inode is marked as NODATACOW. In this case we'll just use the
8020 * 2) The extent is marked as PREALLOC. We're good to go here and can
8021 * just use the extent.
8025 len = min(len, em->len - (start - em->start));
8026 lockstart = start + len;
8030 if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags) ||
8031 ((BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW) &&
8032 em->block_start != EXTENT_MAP_HOLE)) {
8034 u64 block_start, orig_start, orig_block_len, ram_bytes;
8036 if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
8037 type = BTRFS_ORDERED_PREALLOC;
8039 type = BTRFS_ORDERED_NOCOW;
8040 len = min(len, em->len - (start - em->start));
8041 block_start = em->block_start + (start - em->start);
8043 if (can_nocow_extent(inode, start, &len, &orig_start,
8044 &orig_block_len, &ram_bytes) == 1 &&
8045 btrfs_inc_nocow_writers(fs_info, block_start)) {
8046 struct extent_map *em2;
8048 em2 = btrfs_create_dio_extent(inode, start, len,
8049 orig_start, block_start,
8050 len, orig_block_len,
8052 btrfs_dec_nocow_writers(fs_info, block_start);
8053 if (type == BTRFS_ORDERED_PREALLOC) {
8054 free_extent_map(em);
8057 if (em2 && IS_ERR(em2)) {
8062 * For inode marked NODATACOW or extent marked PREALLOC,
8063 * use the existing or preallocated extent, so does not
8064 * need to adjust btrfs_space_info's bytes_may_use.
8066 btrfs_free_reserved_data_space_noquota(inode,
8073 * this will cow the extent, reset the len in case we changed
8076 len = bh_result->b_size;
8077 free_extent_map(em);
8078 em = btrfs_new_extent_direct(inode, start, len);
8083 len = min(len, em->len - (start - em->start));
8085 bh_result->b_blocknr = (em->block_start + (start - em->start)) >>
8087 bh_result->b_size = len;
8088 bh_result->b_bdev = em->bdev;
8089 set_buffer_mapped(bh_result);
8091 if (!test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
8092 set_buffer_new(bh_result);
8095 * Need to update the i_size under the extent lock so buffered
8096 * readers will get the updated i_size when we unlock.
8098 if (!dio_data->overwrite && start + len > i_size_read(inode))
8099 i_size_write(inode, start + len);
8101 adjust_dio_outstanding_extents(inode, dio_data, len);
8102 WARN_ON(dio_data->reserve < len);
8103 dio_data->reserve -= len;
8104 dio_data->unsubmitted_oe_range_end = start + len;
8105 current->journal_info = dio_data;
8109 * In the case of write we need to clear and unlock the entire range,
8110 * in the case of read we need to unlock only the end area that we
8111 * aren't using if there is any left over space.
8113 if (lockstart < lockend) {
8114 clear_extent_bit(&BTRFS_I(inode)->io_tree, lockstart,
8115 lockend, unlock_bits, 1, 0,
8116 &cached_state, GFP_NOFS);
8118 free_extent_state(cached_state);
8121 free_extent_map(em);
8126 clear_extent_bit(&BTRFS_I(inode)->io_tree, lockstart, lockend,
8127 unlock_bits, 1, 0, &cached_state, GFP_NOFS);
8130 current->journal_info = dio_data;
8132 * Compensate the delalloc release we do in btrfs_direct_IO() when we
8133 * write less data then expected, so that we don't underflow our inode's
8134 * outstanding extents counter.
8136 if (create && dio_data)
8137 adjust_dio_outstanding_extents(inode, dio_data, len);
8142 static inline blk_status_t submit_dio_repair_bio(struct inode *inode,
8146 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
8149 BUG_ON(bio_op(bio) == REQ_OP_WRITE);
8153 ret = btrfs_bio_wq_end_io(fs_info, bio, BTRFS_WQ_ENDIO_DIO_REPAIR);
8157 ret = btrfs_map_bio(fs_info, bio, mirror_num, 0);
8163 static int btrfs_check_dio_repairable(struct inode *inode,
8164 struct bio *failed_bio,
8165 struct io_failure_record *failrec,
8168 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
8171 num_copies = btrfs_num_copies(fs_info, failrec->logical, failrec->len);
8172 if (num_copies == 1) {
8174 * we only have a single copy of the data, so don't bother with
8175 * all the retry and error correction code that follows. no
8176 * matter what the error is, it is very likely to persist.
8178 btrfs_debug(fs_info,
8179 "Check DIO Repairable: cannot repair, num_copies=%d, next_mirror %d, failed_mirror %d",
8180 num_copies, failrec->this_mirror, failed_mirror);
8184 failrec->failed_mirror = failed_mirror;
8185 failrec->this_mirror++;
8186 if (failrec->this_mirror == failed_mirror)
8187 failrec->this_mirror++;
8189 if (failrec->this_mirror > num_copies) {
8190 btrfs_debug(fs_info,
8191 "Check DIO Repairable: (fail) num_copies=%d, next_mirror %d, failed_mirror %d",
8192 num_copies, failrec->this_mirror, failed_mirror);
8199 static blk_status_t dio_read_error(struct inode *inode, struct bio *failed_bio,
8200 struct page *page, unsigned int pgoff,
8201 u64 start, u64 end, int failed_mirror,
8202 bio_end_io_t *repair_endio, void *repair_arg)
8204 struct io_failure_record *failrec;
8205 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
8206 struct extent_io_tree *failure_tree = &BTRFS_I(inode)->io_failure_tree;
8209 unsigned int read_mode = 0;
8212 blk_status_t status;
8214 BUG_ON(bio_op(failed_bio) == REQ_OP_WRITE);
8216 ret = btrfs_get_io_failure_record(inode, start, end, &failrec);
8218 return errno_to_blk_status(ret);
8220 ret = btrfs_check_dio_repairable(inode, failed_bio, failrec,
8223 free_io_failure(failure_tree, io_tree, failrec);
8224 return BLK_STS_IOERR;
8227 segs = bio_segments(failed_bio);
8229 (failed_bio->bi_io_vec->bv_len > btrfs_inode_sectorsize(inode)))
8230 read_mode |= REQ_FAILFAST_DEV;
8232 isector = start - btrfs_io_bio(failed_bio)->logical;
8233 isector >>= inode->i_sb->s_blocksize_bits;
8234 bio = btrfs_create_repair_bio(inode, failed_bio, failrec, page,
8235 pgoff, isector, repair_endio, repair_arg);
8236 bio_set_op_attrs(bio, REQ_OP_READ, read_mode);
8238 btrfs_debug(BTRFS_I(inode)->root->fs_info,
8239 "repair DIO read error: submitting new dio read[%#x] to this_mirror=%d, in_validation=%d",
8240 read_mode, failrec->this_mirror, failrec->in_validation);
8242 status = submit_dio_repair_bio(inode, bio, failrec->this_mirror);
8244 free_io_failure(failure_tree, io_tree, failrec);
8251 struct btrfs_retry_complete {
8252 struct completion done;
8253 struct inode *inode;
8258 static void btrfs_retry_endio_nocsum(struct bio *bio)
8260 struct btrfs_retry_complete *done = bio->bi_private;
8261 struct inode *inode = done->inode;
8262 struct bio_vec *bvec;
8263 struct extent_io_tree *io_tree, *failure_tree;
8269 ASSERT(bio->bi_vcnt == 1);
8270 io_tree = &BTRFS_I(inode)->io_tree;
8271 failure_tree = &BTRFS_I(inode)->io_failure_tree;
8272 ASSERT(bio->bi_io_vec->bv_len == btrfs_inode_sectorsize(inode));
8275 ASSERT(!bio_flagged(bio, BIO_CLONED));
8276 bio_for_each_segment_all(bvec, bio, i)
8277 clean_io_failure(BTRFS_I(inode)->root->fs_info, failure_tree,
8278 io_tree, done->start, bvec->bv_page,
8279 btrfs_ino(BTRFS_I(inode)), 0);
8281 complete(&done->done);
8285 static blk_status_t __btrfs_correct_data_nocsum(struct inode *inode,
8286 struct btrfs_io_bio *io_bio)
8288 struct btrfs_fs_info *fs_info;
8289 struct bio_vec bvec;
8290 struct bvec_iter iter;
8291 struct btrfs_retry_complete done;
8297 blk_status_t err = BLK_STS_OK;
8299 fs_info = BTRFS_I(inode)->root->fs_info;
8300 sectorsize = fs_info->sectorsize;
8302 start = io_bio->logical;
8304 io_bio->bio.bi_iter = io_bio->iter;
8306 bio_for_each_segment(bvec, &io_bio->bio, iter) {
8307 nr_sectors = BTRFS_BYTES_TO_BLKS(fs_info, bvec.bv_len);
8308 pgoff = bvec.bv_offset;
8310 next_block_or_try_again:
8313 init_completion(&done.done);
8315 ret = dio_read_error(inode, &io_bio->bio, bvec.bv_page,
8316 pgoff, start, start + sectorsize - 1,
8318 btrfs_retry_endio_nocsum, &done);
8324 wait_for_completion_io(&done.done);
8326 if (!done.uptodate) {
8327 /* We might have another mirror, so try again */
8328 goto next_block_or_try_again;
8332 start += sectorsize;
8336 pgoff += sectorsize;
8337 ASSERT(pgoff < PAGE_SIZE);
8338 goto next_block_or_try_again;
8345 static void btrfs_retry_endio(struct bio *bio)
8347 struct btrfs_retry_complete *done = bio->bi_private;
8348 struct btrfs_io_bio *io_bio = btrfs_io_bio(bio);
8349 struct extent_io_tree *io_tree, *failure_tree;
8350 struct inode *inode = done->inode;
8351 struct bio_vec *bvec;
8361 ASSERT(bio->bi_vcnt == 1);
8362 ASSERT(bio->bi_io_vec->bv_len == btrfs_inode_sectorsize(done->inode));
8364 io_tree = &BTRFS_I(inode)->io_tree;
8365 failure_tree = &BTRFS_I(inode)->io_failure_tree;
8367 ASSERT(!bio_flagged(bio, BIO_CLONED));
8368 bio_for_each_segment_all(bvec, bio, i) {
8369 ret = __readpage_endio_check(inode, io_bio, i, bvec->bv_page,
8370 bvec->bv_offset, done->start,
8373 clean_io_failure(BTRFS_I(inode)->root->fs_info,
8374 failure_tree, io_tree, done->start,
8376 btrfs_ino(BTRFS_I(inode)),
8382 done->uptodate = uptodate;
8384 complete(&done->done);
8388 static blk_status_t __btrfs_subio_endio_read(struct inode *inode,
8389 struct btrfs_io_bio *io_bio, blk_status_t err)
8391 struct btrfs_fs_info *fs_info;
8392 struct bio_vec bvec;
8393 struct bvec_iter iter;
8394 struct btrfs_retry_complete done;
8401 bool uptodate = (err == 0);
8403 blk_status_t status;
8405 fs_info = BTRFS_I(inode)->root->fs_info;
8406 sectorsize = fs_info->sectorsize;
8409 start = io_bio->logical;
8411 io_bio->bio.bi_iter = io_bio->iter;
8413 bio_for_each_segment(bvec, &io_bio->bio, iter) {
8414 nr_sectors = BTRFS_BYTES_TO_BLKS(fs_info, bvec.bv_len);
8416 pgoff = bvec.bv_offset;
8419 csum_pos = BTRFS_BYTES_TO_BLKS(fs_info, offset);
8420 ret = __readpage_endio_check(inode, io_bio, csum_pos,
8421 bvec.bv_page, pgoff, start, sectorsize);
8428 init_completion(&done.done);
8430 status = dio_read_error(inode, &io_bio->bio, bvec.bv_page,
8431 pgoff, start, start + sectorsize - 1,
8432 io_bio->mirror_num, btrfs_retry_endio,
8439 wait_for_completion_io(&done.done);
8441 if (!done.uptodate) {
8442 /* We might have another mirror, so try again */
8446 offset += sectorsize;
8447 start += sectorsize;
8453 pgoff += sectorsize;
8454 ASSERT(pgoff < PAGE_SIZE);
8462 static blk_status_t btrfs_subio_endio_read(struct inode *inode,
8463 struct btrfs_io_bio *io_bio, blk_status_t err)
8465 bool skip_csum = BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM;
8469 return __btrfs_correct_data_nocsum(inode, io_bio);
8473 return __btrfs_subio_endio_read(inode, io_bio, err);
8477 static void btrfs_endio_direct_read(struct bio *bio)
8479 struct btrfs_dio_private *dip = bio->bi_private;
8480 struct inode *inode = dip->inode;
8481 struct bio *dio_bio;
8482 struct btrfs_io_bio *io_bio = btrfs_io_bio(bio);
8483 blk_status_t err = bio->bi_status;
8485 if (dip->flags & BTRFS_DIO_ORIG_BIO_SUBMITTED)
8486 err = btrfs_subio_endio_read(inode, io_bio, err);
8488 unlock_extent(&BTRFS_I(inode)->io_tree, dip->logical_offset,
8489 dip->logical_offset + dip->bytes - 1);
8490 dio_bio = dip->dio_bio;
8494 dio_bio->bi_status = err;
8495 dio_end_io(dio_bio);
8498 io_bio->end_io(io_bio, blk_status_to_errno(err));
8502 static void __endio_write_update_ordered(struct inode *inode,
8503 const u64 offset, const u64 bytes,
8504 const bool uptodate)
8506 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
8507 struct btrfs_ordered_extent *ordered = NULL;
8508 struct btrfs_workqueue *wq;
8509 btrfs_work_func_t func;
8510 u64 ordered_offset = offset;
8511 u64 ordered_bytes = bytes;
8515 if (btrfs_is_free_space_inode(BTRFS_I(inode))) {
8516 wq = fs_info->endio_freespace_worker;
8517 func = btrfs_freespace_write_helper;
8519 wq = fs_info->endio_write_workers;
8520 func = btrfs_endio_write_helper;
8524 last_offset = ordered_offset;
8525 ret = btrfs_dec_test_first_ordered_pending(inode, &ordered,
8532 btrfs_init_work(&ordered->work, func, finish_ordered_fn, NULL, NULL);
8533 btrfs_queue_work(wq, &ordered->work);
8536 * If btrfs_dec_test_ordered_pending does not find any ordered extent
8537 * in the range, we can exit.
8539 if (ordered_offset == last_offset)
8542 * our bio might span multiple ordered extents. If we haven't
8543 * completed the accounting for the whole dio, go back and try again
8545 if (ordered_offset < offset + bytes) {
8546 ordered_bytes = offset + bytes - ordered_offset;
8552 static void btrfs_endio_direct_write(struct bio *bio)
8554 struct btrfs_dio_private *dip = bio->bi_private;
8555 struct bio *dio_bio = dip->dio_bio;
8557 __endio_write_update_ordered(dip->inode, dip->logical_offset,
8558 dip->bytes, !bio->bi_status);
8562 dio_bio->bi_status = bio->bi_status;
8563 dio_end_io(dio_bio);
8567 static blk_status_t __btrfs_submit_bio_start_direct_io(void *private_data,
8568 struct bio *bio, int mirror_num,
8569 unsigned long bio_flags, u64 offset)
8571 struct inode *inode = private_data;
8573 ret = btrfs_csum_one_bio(inode, bio, offset, 1);
8574 BUG_ON(ret); /* -ENOMEM */
8578 static void btrfs_end_dio_bio(struct bio *bio)
8580 struct btrfs_dio_private *dip = bio->bi_private;
8581 blk_status_t err = bio->bi_status;
8584 btrfs_warn(BTRFS_I(dip->inode)->root->fs_info,
8585 "direct IO failed ino %llu rw %d,%u sector %#Lx len %u err no %d",
8586 btrfs_ino(BTRFS_I(dip->inode)), bio_op(bio),
8588 (unsigned long long)bio->bi_iter.bi_sector,
8589 bio->bi_iter.bi_size, err);
8591 if (dip->subio_endio)
8592 err = dip->subio_endio(dip->inode, btrfs_io_bio(bio), err);
8598 * before atomic variable goto zero, we must make sure
8599 * dip->errors is perceived to be set.
8601 smp_mb__before_atomic();
8604 /* if there are more bios still pending for this dio, just exit */
8605 if (!atomic_dec_and_test(&dip->pending_bios))
8609 bio_io_error(dip->orig_bio);
8611 dip->dio_bio->bi_status = 0;
8612 bio_endio(dip->orig_bio);
8618 static inline blk_status_t btrfs_lookup_and_bind_dio_csum(struct inode *inode,
8619 struct btrfs_dio_private *dip,
8623 struct btrfs_io_bio *io_bio = btrfs_io_bio(bio);
8624 struct btrfs_io_bio *orig_io_bio = btrfs_io_bio(dip->orig_bio);
8628 * We load all the csum data we need when we submit
8629 * the first bio to reduce the csum tree search and
8632 if (dip->logical_offset == file_offset) {
8633 ret = btrfs_lookup_bio_sums_dio(inode, dip->orig_bio,
8639 if (bio == dip->orig_bio)
8642 file_offset -= dip->logical_offset;
8643 file_offset >>= inode->i_sb->s_blocksize_bits;
8644 io_bio->csum = (u8 *)(((u32 *)orig_io_bio->csum) + file_offset);
8649 static inline blk_status_t
8650 __btrfs_submit_dio_bio(struct bio *bio, struct inode *inode, u64 file_offset,
8653 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
8654 struct btrfs_dio_private *dip = bio->bi_private;
8655 bool write = bio_op(bio) == REQ_OP_WRITE;
8659 async_submit = !atomic_read(&BTRFS_I(inode)->sync_writers);
8664 ret = btrfs_bio_wq_end_io(fs_info, bio, BTRFS_WQ_ENDIO_DATA);
8669 if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)
8672 if (write && async_submit) {
8673 ret = btrfs_wq_submit_bio(fs_info, bio, 0, 0,
8675 __btrfs_submit_bio_start_direct_io,
8676 __btrfs_submit_bio_done);
8680 * If we aren't doing async submit, calculate the csum of the
8683 ret = btrfs_csum_one_bio(inode, bio, file_offset, 1);
8687 ret = btrfs_lookup_and_bind_dio_csum(inode, dip, bio,
8693 ret = btrfs_map_bio(fs_info, bio, 0, async_submit);
8699 static int btrfs_submit_direct_hook(struct btrfs_dio_private *dip)
8701 struct inode *inode = dip->inode;
8702 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
8704 struct bio *orig_bio = dip->orig_bio;
8705 u64 start_sector = orig_bio->bi_iter.bi_sector;
8706 u64 file_offset = dip->logical_offset;
8708 int async_submit = 0;
8710 int clone_offset = 0;
8713 blk_status_t status;
8715 map_length = orig_bio->bi_iter.bi_size;
8716 submit_len = map_length;
8717 ret = btrfs_map_block(fs_info, btrfs_op(orig_bio), start_sector << 9,
8718 &map_length, NULL, 0);
8722 if (map_length >= submit_len) {
8724 dip->flags |= BTRFS_DIO_ORIG_BIO_SUBMITTED;
8728 /* async crcs make it difficult to collect full stripe writes. */
8729 if (btrfs_data_alloc_profile(fs_info) & BTRFS_BLOCK_GROUP_RAID56_MASK)
8735 ASSERT(map_length <= INT_MAX);
8737 clone_len = min_t(int, submit_len, map_length);
8740 * This will never fail as it's passing GPF_NOFS and
8741 * the allocation is backed by btrfs_bioset.
8743 bio = btrfs_bio_clone_partial(orig_bio, clone_offset,
8745 bio->bi_private = dip;
8746 bio->bi_end_io = btrfs_end_dio_bio;
8747 btrfs_io_bio(bio)->logical = file_offset;
8749 ASSERT(submit_len >= clone_len);
8750 submit_len -= clone_len;
8751 if (submit_len == 0)
8755 * Increase the count before we submit the bio so we know
8756 * the end IO handler won't happen before we increase the
8757 * count. Otherwise, the dip might get freed before we're
8758 * done setting it up.
8760 atomic_inc(&dip->pending_bios);
8762 status = __btrfs_submit_dio_bio(bio, inode, file_offset,
8766 atomic_dec(&dip->pending_bios);
8770 clone_offset += clone_len;
8771 start_sector += clone_len >> 9;
8772 file_offset += clone_len;
8774 map_length = submit_len;
8775 ret = btrfs_map_block(fs_info, btrfs_op(orig_bio),
8776 start_sector << 9, &map_length, NULL, 0);
8779 } while (submit_len > 0);
8782 status = __btrfs_submit_dio_bio(bio, inode, file_offset, async_submit);
8786 if (bio != orig_bio)
8791 * before atomic variable goto zero, we must
8792 * make sure dip->errors is perceived to be set.
8794 smp_mb__before_atomic();
8795 if (atomic_dec_and_test(&dip->pending_bios))
8796 bio_io_error(dip->orig_bio);
8798 /* bio_end_io() will handle error, so we needn't return it */
8802 static void btrfs_submit_direct(struct bio *dio_bio, struct inode *inode,
8805 struct btrfs_dio_private *dip = NULL;
8806 struct bio *bio = NULL;
8807 struct btrfs_io_bio *io_bio;
8808 bool write = (bio_op(dio_bio) == REQ_OP_WRITE);
8811 bio = btrfs_bio_clone(dio_bio);
8813 dip = kzalloc(sizeof(*dip), GFP_NOFS);
8819 dip->private = dio_bio->bi_private;
8821 dip->logical_offset = file_offset;
8822 dip->bytes = dio_bio->bi_iter.bi_size;
8823 dip->disk_bytenr = (u64)dio_bio->bi_iter.bi_sector << 9;
8824 bio->bi_private = dip;
8825 dip->orig_bio = bio;
8826 dip->dio_bio = dio_bio;
8827 atomic_set(&dip->pending_bios, 1);
8828 io_bio = btrfs_io_bio(bio);
8829 io_bio->logical = file_offset;
8832 bio->bi_end_io = btrfs_endio_direct_write;
8834 bio->bi_end_io = btrfs_endio_direct_read;
8835 dip->subio_endio = btrfs_subio_endio_read;
8839 * Reset the range for unsubmitted ordered extents (to a 0 length range)
8840 * even if we fail to submit a bio, because in such case we do the
8841 * corresponding error handling below and it must not be done a second
8842 * time by btrfs_direct_IO().
8845 struct btrfs_dio_data *dio_data = current->journal_info;
8847 dio_data->unsubmitted_oe_range_end = dip->logical_offset +
8849 dio_data->unsubmitted_oe_range_start =
8850 dio_data->unsubmitted_oe_range_end;
8853 ret = btrfs_submit_direct_hook(dip);
8858 io_bio->end_io(io_bio, ret);
8862 * If we arrived here it means either we failed to submit the dip
8863 * or we either failed to clone the dio_bio or failed to allocate the
8864 * dip. If we cloned the dio_bio and allocated the dip, we can just
8865 * call bio_endio against our io_bio so that we get proper resource
8866 * cleanup if we fail to submit the dip, otherwise, we must do the
8867 * same as btrfs_endio_direct_[write|read] because we can't call these
8868 * callbacks - they require an allocated dip and a clone of dio_bio.
8873 * The end io callbacks free our dip, do the final put on bio
8874 * and all the cleanup and final put for dio_bio (through
8881 __endio_write_update_ordered(inode,
8883 dio_bio->bi_iter.bi_size,
8886 unlock_extent(&BTRFS_I(inode)->io_tree, file_offset,
8887 file_offset + dio_bio->bi_iter.bi_size - 1);
8889 dio_bio->bi_status = BLK_STS_IOERR;
8891 * Releases and cleans up our dio_bio, no need to bio_put()
8892 * nor bio_endio()/bio_io_error() against dio_bio.
8894 dio_end_io(dio_bio);
8901 static ssize_t check_direct_IO(struct btrfs_fs_info *fs_info,
8903 const struct iov_iter *iter, loff_t offset)
8907 unsigned int blocksize_mask = fs_info->sectorsize - 1;
8908 ssize_t retval = -EINVAL;
8910 if (offset & blocksize_mask)
8913 if (iov_iter_alignment(iter) & blocksize_mask)
8916 /* If this is a write we don't need to check anymore */
8917 if (iov_iter_rw(iter) != READ || !iter_is_iovec(iter))
8920 * Check to make sure we don't have duplicate iov_base's in this
8921 * iovec, if so return EINVAL, otherwise we'll get csum errors
8922 * when reading back.
8924 for (seg = 0; seg < iter->nr_segs; seg++) {
8925 for (i = seg + 1; i < iter->nr_segs; i++) {
8926 if (iter->iov[seg].iov_base == iter->iov[i].iov_base)
8935 static ssize_t btrfs_direct_IO(struct kiocb *iocb, struct iov_iter *iter)
8937 struct file *file = iocb->ki_filp;
8938 struct inode *inode = file->f_mapping->host;
8939 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
8940 struct btrfs_dio_data dio_data = { 0 };
8941 struct extent_changeset *data_reserved = NULL;
8942 loff_t offset = iocb->ki_pos;
8946 bool relock = false;
8949 if (check_direct_IO(fs_info, iocb, iter, offset))
8952 inode_dio_begin(inode);
8955 * The generic stuff only does filemap_write_and_wait_range, which
8956 * isn't enough if we've written compressed pages to this area, so
8957 * we need to flush the dirty pages again to make absolutely sure
8958 * that any outstanding dirty pages are on disk.
8960 count = iov_iter_count(iter);
8961 if (test_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
8962 &BTRFS_I(inode)->runtime_flags))
8963 filemap_fdatawrite_range(inode->i_mapping, offset,
8964 offset + count - 1);
8966 if (iov_iter_rw(iter) == WRITE) {
8968 * If the write DIO is beyond the EOF, we need update
8969 * the isize, but it is protected by i_mutex. So we can
8970 * not unlock the i_mutex at this case.
8972 if (offset + count <= inode->i_size) {
8973 dio_data.overwrite = 1;
8974 inode_unlock(inode);
8977 ret = btrfs_delalloc_reserve_space(inode, &data_reserved,
8981 dio_data.outstanding_extents = count_max_extents(count);
8984 * We need to know how many extents we reserved so that we can
8985 * do the accounting properly if we go over the number we
8986 * originally calculated. Abuse current->journal_info for this.
8988 dio_data.reserve = round_up(count,
8989 fs_info->sectorsize);
8990 dio_data.unsubmitted_oe_range_start = (u64)offset;
8991 dio_data.unsubmitted_oe_range_end = (u64)offset;
8992 current->journal_info = &dio_data;
8993 down_read(&BTRFS_I(inode)->dio_sem);
8994 } else if (test_bit(BTRFS_INODE_READDIO_NEED_LOCK,
8995 &BTRFS_I(inode)->runtime_flags)) {
8996 inode_dio_end(inode);
8997 flags = DIO_LOCKING | DIO_SKIP_HOLES;
9001 ret = __blockdev_direct_IO(iocb, inode,
9002 fs_info->fs_devices->latest_bdev,
9003 iter, btrfs_get_blocks_direct, NULL,
9004 btrfs_submit_direct, flags);
9005 if (iov_iter_rw(iter) == WRITE) {
9006 up_read(&BTRFS_I(inode)->dio_sem);
9007 current->journal_info = NULL;
9008 if (ret < 0 && ret != -EIOCBQUEUED) {
9009 if (dio_data.reserve)
9010 btrfs_delalloc_release_space(inode, data_reserved,
9011 offset, dio_data.reserve);
9013 * On error we might have left some ordered extents
9014 * without submitting corresponding bios for them, so
9015 * cleanup them up to avoid other tasks getting them
9016 * and waiting for them to complete forever.
9018 if (dio_data.unsubmitted_oe_range_start <
9019 dio_data.unsubmitted_oe_range_end)
9020 __endio_write_update_ordered(inode,
9021 dio_data.unsubmitted_oe_range_start,
9022 dio_data.unsubmitted_oe_range_end -
9023 dio_data.unsubmitted_oe_range_start,
9025 } else if (ret >= 0 && (size_t)ret < count)
9026 btrfs_delalloc_release_space(inode, data_reserved,
9027 offset, count - (size_t)ret);
9031 inode_dio_end(inode);
9035 extent_changeset_free(data_reserved);
9039 #define BTRFS_FIEMAP_FLAGS (FIEMAP_FLAG_SYNC)
9041 static int btrfs_fiemap(struct inode *inode, struct fiemap_extent_info *fieinfo,
9042 __u64 start, __u64 len)
9046 ret = fiemap_check_flags(fieinfo, BTRFS_FIEMAP_FLAGS);
9050 return extent_fiemap(inode, fieinfo, start, len, btrfs_get_extent_fiemap);
9053 int btrfs_readpage(struct file *file, struct page *page)
9055 struct extent_io_tree *tree;
9056 tree = &BTRFS_I(page->mapping->host)->io_tree;
9057 return extent_read_full_page(tree, page, btrfs_get_extent, 0);
9060 static int btrfs_writepage(struct page *page, struct writeback_control *wbc)
9062 struct extent_io_tree *tree;
9063 struct inode *inode = page->mapping->host;
9066 if (current->flags & PF_MEMALLOC) {
9067 redirty_page_for_writepage(wbc, page);
9073 * If we are under memory pressure we will call this directly from the
9074 * VM, we need to make sure we have the inode referenced for the ordered
9075 * extent. If not just return like we didn't do anything.
9077 if (!igrab(inode)) {
9078 redirty_page_for_writepage(wbc, page);
9079 return AOP_WRITEPAGE_ACTIVATE;
9081 tree = &BTRFS_I(page->mapping->host)->io_tree;
9082 ret = extent_write_full_page(tree, page, btrfs_get_extent, wbc);
9083 btrfs_add_delayed_iput(inode);
9087 static int btrfs_writepages(struct address_space *mapping,
9088 struct writeback_control *wbc)
9090 struct extent_io_tree *tree;
9092 tree = &BTRFS_I(mapping->host)->io_tree;
9093 return extent_writepages(tree, mapping, btrfs_get_extent, wbc);
9097 btrfs_readpages(struct file *file, struct address_space *mapping,
9098 struct list_head *pages, unsigned nr_pages)
9100 struct extent_io_tree *tree;
9101 tree = &BTRFS_I(mapping->host)->io_tree;
9102 return extent_readpages(tree, mapping, pages, nr_pages,
9105 static int __btrfs_releasepage(struct page *page, gfp_t gfp_flags)
9107 struct extent_io_tree *tree;
9108 struct extent_map_tree *map;
9111 tree = &BTRFS_I(page->mapping->host)->io_tree;
9112 map = &BTRFS_I(page->mapping->host)->extent_tree;
9113 ret = try_release_extent_mapping(map, tree, page, gfp_flags);
9115 ClearPagePrivate(page);
9116 set_page_private(page, 0);
9122 static int btrfs_releasepage(struct page *page, gfp_t gfp_flags)
9124 if (PageWriteback(page) || PageDirty(page))
9126 return __btrfs_releasepage(page, gfp_flags);
9129 static void btrfs_invalidatepage(struct page *page, unsigned int offset,
9130 unsigned int length)
9132 struct inode *inode = page->mapping->host;
9133 struct extent_io_tree *tree;
9134 struct btrfs_ordered_extent *ordered;
9135 struct extent_state *cached_state = NULL;
9136 u64 page_start = page_offset(page);
9137 u64 page_end = page_start + PAGE_SIZE - 1;
9140 int inode_evicting = inode->i_state & I_FREEING;
9143 * we have the page locked, so new writeback can't start,
9144 * and the dirty bit won't be cleared while we are here.
9146 * Wait for IO on this page so that we can safely clear
9147 * the PagePrivate2 bit and do ordered accounting
9149 wait_on_page_writeback(page);
9151 tree = &BTRFS_I(inode)->io_tree;
9153 btrfs_releasepage(page, GFP_NOFS);
9157 if (!inode_evicting)
9158 lock_extent_bits(tree, page_start, page_end, &cached_state);
9161 ordered = btrfs_lookup_ordered_range(BTRFS_I(inode), start,
9162 page_end - start + 1);
9164 end = min(page_end, ordered->file_offset + ordered->len - 1);
9166 * IO on this page will never be started, so we need
9167 * to account for any ordered extents now
9169 if (!inode_evicting)
9170 clear_extent_bit(tree, start, end,
9171 EXTENT_DIRTY | EXTENT_DELALLOC |
9172 EXTENT_DELALLOC_NEW |
9173 EXTENT_LOCKED | EXTENT_DO_ACCOUNTING |
9174 EXTENT_DEFRAG, 1, 0, &cached_state,
9177 * whoever cleared the private bit is responsible
9178 * for the finish_ordered_io
9180 if (TestClearPagePrivate2(page)) {
9181 struct btrfs_ordered_inode_tree *tree;
9184 tree = &BTRFS_I(inode)->ordered_tree;
9186 spin_lock_irq(&tree->lock);
9187 set_bit(BTRFS_ORDERED_TRUNCATED, &ordered->flags);
9188 new_len = start - ordered->file_offset;
9189 if (new_len < ordered->truncated_len)
9190 ordered->truncated_len = new_len;
9191 spin_unlock_irq(&tree->lock);
9193 if (btrfs_dec_test_ordered_pending(inode, &ordered,
9195 end - start + 1, 1))
9196 btrfs_finish_ordered_io(ordered);
9198 btrfs_put_ordered_extent(ordered);
9199 if (!inode_evicting) {
9200 cached_state = NULL;
9201 lock_extent_bits(tree, start, end,
9206 if (start < page_end)
9211 * Qgroup reserved space handler
9212 * Page here will be either
9213 * 1) Already written to disk or ordered extent already submitted
9214 * Then its QGROUP_RESERVED bit in io_tree is already cleaned.
9215 * Qgroup will be handled by its qgroup_record then.
9216 * btrfs_qgroup_free_data() call will do nothing here.
9218 * 2) Not written to disk yet
9219 * Then btrfs_qgroup_free_data() call will clear the QGROUP_RESERVED
9220 * bit of its io_tree, and free the qgroup reserved data space.
9221 * Since the IO will never happen for this page.
9223 btrfs_qgroup_free_data(inode, NULL, page_start, PAGE_SIZE);
9224 if (!inode_evicting) {
9225 clear_extent_bit(tree, page_start, page_end,
9226 EXTENT_LOCKED | EXTENT_DIRTY |
9227 EXTENT_DELALLOC | EXTENT_DELALLOC_NEW |
9228 EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG, 1, 1,
9229 &cached_state, GFP_NOFS);
9231 __btrfs_releasepage(page, GFP_NOFS);
9234 ClearPageChecked(page);
9235 if (PagePrivate(page)) {
9236 ClearPagePrivate(page);
9237 set_page_private(page, 0);
9243 * btrfs_page_mkwrite() is not allowed to change the file size as it gets
9244 * called from a page fault handler when a page is first dirtied. Hence we must
9245 * be careful to check for EOF conditions here. We set the page up correctly
9246 * for a written page which means we get ENOSPC checking when writing into
9247 * holes and correct delalloc and unwritten extent mapping on filesystems that
9248 * support these features.
9250 * We are not allowed to take the i_mutex here so we have to play games to
9251 * protect against truncate races as the page could now be beyond EOF. Because
9252 * vmtruncate() writes the inode size before removing pages, once we have the
9253 * page lock we can determine safely if the page is beyond EOF. If it is not
9254 * beyond EOF, then the page is guaranteed safe against truncation until we
9257 int btrfs_page_mkwrite(struct vm_fault *vmf)
9259 struct page *page = vmf->page;
9260 struct inode *inode = file_inode(vmf->vma->vm_file);
9261 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
9262 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
9263 struct btrfs_ordered_extent *ordered;
9264 struct extent_state *cached_state = NULL;
9265 struct extent_changeset *data_reserved = NULL;
9267 unsigned long zero_start;
9276 reserved_space = PAGE_SIZE;
9278 sb_start_pagefault(inode->i_sb);
9279 page_start = page_offset(page);
9280 page_end = page_start + PAGE_SIZE - 1;
9284 * Reserving delalloc space after obtaining the page lock can lead to
9285 * deadlock. For example, if a dirty page is locked by this function
9286 * and the call to btrfs_delalloc_reserve_space() ends up triggering
9287 * dirty page write out, then the btrfs_writepage() function could
9288 * end up waiting indefinitely to get a lock on the page currently
9289 * being processed by btrfs_page_mkwrite() function.
9291 ret = btrfs_delalloc_reserve_space(inode, &data_reserved, page_start,
9294 ret = file_update_time(vmf->vma->vm_file);
9300 else /* -ENOSPC, -EIO, etc */
9301 ret = VM_FAULT_SIGBUS;
9307 ret = VM_FAULT_NOPAGE; /* make the VM retry the fault */
9310 size = i_size_read(inode);
9312 if ((page->mapping != inode->i_mapping) ||
9313 (page_start >= size)) {
9314 /* page got truncated out from underneath us */
9317 wait_on_page_writeback(page);
9319 lock_extent_bits(io_tree, page_start, page_end, &cached_state);
9320 set_page_extent_mapped(page);
9323 * we can't set the delalloc bits if there are pending ordered
9324 * extents. Drop our locks and wait for them to finish
9326 ordered = btrfs_lookup_ordered_range(BTRFS_I(inode), page_start,
9329 unlock_extent_cached(io_tree, page_start, page_end,
9330 &cached_state, GFP_NOFS);
9332 btrfs_start_ordered_extent(inode, ordered, 1);
9333 btrfs_put_ordered_extent(ordered);
9337 if (page->index == ((size - 1) >> PAGE_SHIFT)) {
9338 reserved_space = round_up(size - page_start,
9339 fs_info->sectorsize);
9340 if (reserved_space < PAGE_SIZE) {
9341 end = page_start + reserved_space - 1;
9342 spin_lock(&BTRFS_I(inode)->lock);
9343 BTRFS_I(inode)->outstanding_extents++;
9344 spin_unlock(&BTRFS_I(inode)->lock);
9345 btrfs_delalloc_release_space(inode, data_reserved,
9346 page_start, PAGE_SIZE - reserved_space);
9351 * page_mkwrite gets called when the page is firstly dirtied after it's
9352 * faulted in, but write(2) could also dirty a page and set delalloc
9353 * bits, thus in this case for space account reason, we still need to
9354 * clear any delalloc bits within this page range since we have to
9355 * reserve data&meta space before lock_page() (see above comments).
9357 clear_extent_bit(&BTRFS_I(inode)->io_tree, page_start, end,
9358 EXTENT_DIRTY | EXTENT_DELALLOC |
9359 EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG,
9360 0, 0, &cached_state, GFP_NOFS);
9362 ret = btrfs_set_extent_delalloc(inode, page_start, end,
9365 unlock_extent_cached(io_tree, page_start, page_end,
9366 &cached_state, GFP_NOFS);
9367 ret = VM_FAULT_SIGBUS;
9372 /* page is wholly or partially inside EOF */
9373 if (page_start + PAGE_SIZE > size)
9374 zero_start = size & ~PAGE_MASK;
9376 zero_start = PAGE_SIZE;
9378 if (zero_start != PAGE_SIZE) {
9380 memset(kaddr + zero_start, 0, PAGE_SIZE - zero_start);
9381 flush_dcache_page(page);
9384 ClearPageChecked(page);
9385 set_page_dirty(page);
9386 SetPageUptodate(page);
9388 BTRFS_I(inode)->last_trans = fs_info->generation;
9389 BTRFS_I(inode)->last_sub_trans = BTRFS_I(inode)->root->log_transid;
9390 BTRFS_I(inode)->last_log_commit = BTRFS_I(inode)->root->last_log_commit;
9392 unlock_extent_cached(io_tree, page_start, page_end, &cached_state, GFP_NOFS);
9396 sb_end_pagefault(inode->i_sb);
9397 extent_changeset_free(data_reserved);
9398 return VM_FAULT_LOCKED;
9402 btrfs_delalloc_release_space(inode, data_reserved, page_start,
9405 sb_end_pagefault(inode->i_sb);
9406 extent_changeset_free(data_reserved);
9410 static int btrfs_truncate(struct inode *inode)
9412 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
9413 struct btrfs_root *root = BTRFS_I(inode)->root;
9414 struct btrfs_block_rsv *rsv;
9417 struct btrfs_trans_handle *trans;
9418 u64 mask = fs_info->sectorsize - 1;
9419 u64 min_size = btrfs_calc_trunc_metadata_size(fs_info, 1);
9421 ret = btrfs_wait_ordered_range(inode, inode->i_size & (~mask),
9427 * Yes ladies and gentlemen, this is indeed ugly. The fact is we have
9428 * 3 things going on here
9430 * 1) We need to reserve space for our orphan item and the space to
9431 * delete our orphan item. Lord knows we don't want to have a dangling
9432 * orphan item because we didn't reserve space to remove it.
9434 * 2) We need to reserve space to update our inode.
9436 * 3) We need to have something to cache all the space that is going to
9437 * be free'd up by the truncate operation, but also have some slack
9438 * space reserved in case it uses space during the truncate (thank you
9439 * very much snapshotting).
9441 * And we need these to all be separate. The fact is we can use a lot of
9442 * space doing the truncate, and we have no earthly idea how much space
9443 * we will use, so we need the truncate reservation to be separate so it
9444 * doesn't end up using space reserved for updating the inode or
9445 * removing the orphan item. We also need to be able to stop the
9446 * transaction and start a new one, which means we need to be able to
9447 * update the inode several times, and we have no idea of knowing how
9448 * many times that will be, so we can't just reserve 1 item for the
9449 * entirety of the operation, so that has to be done separately as well.
9450 * Then there is the orphan item, which does indeed need to be held on
9451 * to for the whole operation, and we need nobody to touch this reserved
9452 * space except the orphan code.
9454 * So that leaves us with
9456 * 1) root->orphan_block_rsv - for the orphan deletion.
9457 * 2) rsv - for the truncate reservation, which we will steal from the
9458 * transaction reservation.
9459 * 3) fs_info->trans_block_rsv - this will have 1 items worth left for
9460 * updating the inode.
9462 rsv = btrfs_alloc_block_rsv(fs_info, BTRFS_BLOCK_RSV_TEMP);
9465 rsv->size = min_size;
9469 * 1 for the truncate slack space
9470 * 1 for updating the inode.
9472 trans = btrfs_start_transaction(root, 2);
9473 if (IS_ERR(trans)) {
9474 err = PTR_ERR(trans);
9478 /* Migrate the slack space for the truncate to our reserve */
9479 ret = btrfs_block_rsv_migrate(&fs_info->trans_block_rsv, rsv,
9484 * So if we truncate and then write and fsync we normally would just
9485 * write the extents that changed, which is a problem if we need to
9486 * first truncate that entire inode. So set this flag so we write out
9487 * all of the extents in the inode to the sync log so we're completely
9490 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &BTRFS_I(inode)->runtime_flags);
9491 trans->block_rsv = rsv;
9494 ret = btrfs_truncate_inode_items(trans, root, inode,
9496 BTRFS_EXTENT_DATA_KEY);
9497 if (ret != -ENOSPC && ret != -EAGAIN) {
9502 trans->block_rsv = &fs_info->trans_block_rsv;
9503 ret = btrfs_update_inode(trans, root, inode);
9509 btrfs_end_transaction(trans);
9510 btrfs_btree_balance_dirty(fs_info);
9512 trans = btrfs_start_transaction(root, 2);
9513 if (IS_ERR(trans)) {
9514 ret = err = PTR_ERR(trans);
9519 btrfs_block_rsv_release(fs_info, rsv, -1);
9520 ret = btrfs_block_rsv_migrate(&fs_info->trans_block_rsv,
9522 BUG_ON(ret); /* shouldn't happen */
9523 trans->block_rsv = rsv;
9526 if (ret == 0 && inode->i_nlink > 0) {
9527 trans->block_rsv = root->orphan_block_rsv;
9528 ret = btrfs_orphan_del(trans, BTRFS_I(inode));
9534 trans->block_rsv = &fs_info->trans_block_rsv;
9535 ret = btrfs_update_inode(trans, root, inode);
9539 ret = btrfs_end_transaction(trans);
9540 btrfs_btree_balance_dirty(fs_info);
9543 btrfs_free_block_rsv(fs_info, rsv);
9552 * create a new subvolume directory/inode (helper for the ioctl).
9554 int btrfs_create_subvol_root(struct btrfs_trans_handle *trans,
9555 struct btrfs_root *new_root,
9556 struct btrfs_root *parent_root,
9559 struct inode *inode;
9563 inode = btrfs_new_inode(trans, new_root, NULL, "..", 2,
9564 new_dirid, new_dirid,
9565 S_IFDIR | (~current_umask() & S_IRWXUGO),
9568 return PTR_ERR(inode);
9569 inode->i_op = &btrfs_dir_inode_operations;
9570 inode->i_fop = &btrfs_dir_file_operations;
9572 set_nlink(inode, 1);
9573 btrfs_i_size_write(BTRFS_I(inode), 0);
9574 unlock_new_inode(inode);
9576 err = btrfs_subvol_inherit_props(trans, new_root, parent_root);
9578 btrfs_err(new_root->fs_info,
9579 "error inheriting subvolume %llu properties: %d",
9580 new_root->root_key.objectid, err);
9582 err = btrfs_update_inode(trans, new_root, inode);
9588 struct inode *btrfs_alloc_inode(struct super_block *sb)
9590 struct btrfs_inode *ei;
9591 struct inode *inode;
9593 ei = kmem_cache_alloc(btrfs_inode_cachep, GFP_NOFS);
9600 ei->last_sub_trans = 0;
9601 ei->logged_trans = 0;
9602 ei->delalloc_bytes = 0;
9603 ei->new_delalloc_bytes = 0;
9604 ei->defrag_bytes = 0;
9605 ei->disk_i_size = 0;
9608 ei->index_cnt = (u64)-1;
9610 ei->last_unlink_trans = 0;
9611 ei->last_link_trans = 0;
9612 ei->last_log_commit = 0;
9613 ei->delayed_iput_count = 0;
9615 spin_lock_init(&ei->lock);
9616 ei->outstanding_extents = 0;
9617 ei->reserved_extents = 0;
9619 ei->runtime_flags = 0;
9620 ei->prop_compress = BTRFS_COMPRESS_NONE;
9621 ei->defrag_compress = BTRFS_COMPRESS_NONE;
9623 ei->delayed_node = NULL;
9625 ei->i_otime.tv_sec = 0;
9626 ei->i_otime.tv_nsec = 0;
9628 inode = &ei->vfs_inode;
9629 extent_map_tree_init(&ei->extent_tree);
9630 extent_io_tree_init(&ei->io_tree, inode);
9631 extent_io_tree_init(&ei->io_failure_tree, inode);
9632 ei->io_tree.track_uptodate = 1;
9633 ei->io_failure_tree.track_uptodate = 1;
9634 atomic_set(&ei->sync_writers, 0);
9635 mutex_init(&ei->log_mutex);
9636 mutex_init(&ei->delalloc_mutex);
9637 btrfs_ordered_inode_tree_init(&ei->ordered_tree);
9638 INIT_LIST_HEAD(&ei->delalloc_inodes);
9639 INIT_LIST_HEAD(&ei->delayed_iput);
9640 RB_CLEAR_NODE(&ei->rb_node);
9641 init_rwsem(&ei->dio_sem);
9646 #ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
9647 void btrfs_test_destroy_inode(struct inode *inode)
9649 btrfs_drop_extent_cache(BTRFS_I(inode), 0, (u64)-1, 0);
9650 kmem_cache_free(btrfs_inode_cachep, BTRFS_I(inode));
9654 static void btrfs_i_callback(struct rcu_head *head)
9656 struct inode *inode = container_of(head, struct inode, i_rcu);
9657 kmem_cache_free(btrfs_inode_cachep, BTRFS_I(inode));
9660 void btrfs_destroy_inode(struct inode *inode)
9662 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
9663 struct btrfs_ordered_extent *ordered;
9664 struct btrfs_root *root = BTRFS_I(inode)->root;
9666 WARN_ON(!hlist_empty(&inode->i_dentry));
9667 WARN_ON(inode->i_data.nrpages);
9668 WARN_ON(BTRFS_I(inode)->outstanding_extents);
9669 WARN_ON(BTRFS_I(inode)->reserved_extents);
9670 WARN_ON(BTRFS_I(inode)->delalloc_bytes);
9671 WARN_ON(BTRFS_I(inode)->new_delalloc_bytes);
9672 WARN_ON(BTRFS_I(inode)->csum_bytes);
9673 WARN_ON(BTRFS_I(inode)->defrag_bytes);
9676 * This can happen where we create an inode, but somebody else also
9677 * created the same inode and we need to destroy the one we already
9683 if (test_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
9684 &BTRFS_I(inode)->runtime_flags)) {
9685 btrfs_info(fs_info, "inode %llu still on the orphan list",
9686 btrfs_ino(BTRFS_I(inode)));
9687 atomic_dec(&root->orphan_inodes);
9691 ordered = btrfs_lookup_first_ordered_extent(inode, (u64)-1);
9696 "found ordered extent %llu %llu on inode cleanup",
9697 ordered->file_offset, ordered->len);
9698 btrfs_remove_ordered_extent(inode, ordered);
9699 btrfs_put_ordered_extent(ordered);
9700 btrfs_put_ordered_extent(ordered);
9703 btrfs_qgroup_check_reserved_leak(inode);
9704 inode_tree_del(inode);
9705 btrfs_drop_extent_cache(BTRFS_I(inode), 0, (u64)-1, 0);
9707 call_rcu(&inode->i_rcu, btrfs_i_callback);
9710 int btrfs_drop_inode(struct inode *inode)
9712 struct btrfs_root *root = BTRFS_I(inode)->root;
9717 /* the snap/subvol tree is on deleting */
9718 if (btrfs_root_refs(&root->root_item) == 0)
9721 return generic_drop_inode(inode);
9724 static void init_once(void *foo)
9726 struct btrfs_inode *ei = (struct btrfs_inode *) foo;
9728 inode_init_once(&ei->vfs_inode);
9731 void btrfs_destroy_cachep(void)
9734 * Make sure all delayed rcu free inodes are flushed before we
9738 kmem_cache_destroy(btrfs_inode_cachep);
9739 kmem_cache_destroy(btrfs_trans_handle_cachep);
9740 kmem_cache_destroy(btrfs_path_cachep);
9741 kmem_cache_destroy(btrfs_free_space_cachep);
9744 int btrfs_init_cachep(void)
9746 btrfs_inode_cachep = kmem_cache_create("btrfs_inode",
9747 sizeof(struct btrfs_inode), 0,
9748 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD | SLAB_ACCOUNT,
9750 if (!btrfs_inode_cachep)
9753 btrfs_trans_handle_cachep = kmem_cache_create("btrfs_trans_handle",
9754 sizeof(struct btrfs_trans_handle), 0,
9755 SLAB_TEMPORARY | SLAB_MEM_SPREAD, NULL);
9756 if (!btrfs_trans_handle_cachep)
9759 btrfs_path_cachep = kmem_cache_create("btrfs_path",
9760 sizeof(struct btrfs_path), 0,
9761 SLAB_MEM_SPREAD, NULL);
9762 if (!btrfs_path_cachep)
9765 btrfs_free_space_cachep = kmem_cache_create("btrfs_free_space",
9766 sizeof(struct btrfs_free_space), 0,
9767 SLAB_MEM_SPREAD, NULL);
9768 if (!btrfs_free_space_cachep)
9773 btrfs_destroy_cachep();
9777 static int btrfs_getattr(const struct path *path, struct kstat *stat,
9778 u32 request_mask, unsigned int flags)
9781 struct inode *inode = d_inode(path->dentry);
9782 u32 blocksize = inode->i_sb->s_blocksize;
9783 u32 bi_flags = BTRFS_I(inode)->flags;
9785 stat->result_mask |= STATX_BTIME;
9786 stat->btime.tv_sec = BTRFS_I(inode)->i_otime.tv_sec;
9787 stat->btime.tv_nsec = BTRFS_I(inode)->i_otime.tv_nsec;
9788 if (bi_flags & BTRFS_INODE_APPEND)
9789 stat->attributes |= STATX_ATTR_APPEND;
9790 if (bi_flags & BTRFS_INODE_COMPRESS)
9791 stat->attributes |= STATX_ATTR_COMPRESSED;
9792 if (bi_flags & BTRFS_INODE_IMMUTABLE)
9793 stat->attributes |= STATX_ATTR_IMMUTABLE;
9794 if (bi_flags & BTRFS_INODE_NODUMP)
9795 stat->attributes |= STATX_ATTR_NODUMP;
9797 stat->attributes_mask |= (STATX_ATTR_APPEND |
9798 STATX_ATTR_COMPRESSED |
9799 STATX_ATTR_IMMUTABLE |
9802 generic_fillattr(inode, stat);
9803 stat->dev = BTRFS_I(inode)->root->anon_dev;
9805 spin_lock(&BTRFS_I(inode)->lock);
9806 delalloc_bytes = BTRFS_I(inode)->new_delalloc_bytes;
9807 spin_unlock(&BTRFS_I(inode)->lock);
9808 stat->blocks = (ALIGN(inode_get_bytes(inode), blocksize) +
9809 ALIGN(delalloc_bytes, blocksize)) >> 9;
9813 static int btrfs_rename_exchange(struct inode *old_dir,
9814 struct dentry *old_dentry,
9815 struct inode *new_dir,
9816 struct dentry *new_dentry)
9818 struct btrfs_fs_info *fs_info = btrfs_sb(old_dir->i_sb);
9819 struct btrfs_trans_handle *trans;
9820 struct btrfs_root *root = BTRFS_I(old_dir)->root;
9821 struct btrfs_root *dest = BTRFS_I(new_dir)->root;
9822 struct inode *new_inode = new_dentry->d_inode;
9823 struct inode *old_inode = old_dentry->d_inode;
9824 struct timespec ctime = current_time(old_inode);
9825 struct dentry *parent;
9826 u64 old_ino = btrfs_ino(BTRFS_I(old_inode));
9827 u64 new_ino = btrfs_ino(BTRFS_I(new_inode));
9833 bool root_log_pinned = false;
9834 bool dest_log_pinned = false;
9837 * For non-subvolumes allow exchange only within one subvolume, in the
9838 * same inode namespace. Two subvolumes (represented as directory) can
9839 * be exchanged as they're a logical link and have a fixed inode number.
9842 (old_ino != BTRFS_FIRST_FREE_OBJECTID ||
9843 new_ino != BTRFS_FIRST_FREE_OBJECTID))
9846 /* close the race window with snapshot create/destroy ioctl */
9847 if (old_ino == BTRFS_FIRST_FREE_OBJECTID ||
9848 new_ino == BTRFS_FIRST_FREE_OBJECTID)
9849 down_read(&fs_info->subvol_sem);
9852 * We want to reserve the absolute worst case amount of items. So if
9853 * both inodes are subvols and we need to unlink them then that would
9854 * require 4 item modifications, but if they are both normal inodes it
9855 * would require 5 item modifications, so we'll assume their normal
9856 * inodes. So 5 * 2 is 10, plus 2 for the new links, so 12 total items
9857 * should cover the worst case number of items we'll modify.
9859 trans = btrfs_start_transaction(root, 12);
9860 if (IS_ERR(trans)) {
9861 ret = PTR_ERR(trans);
9866 btrfs_record_root_in_trans(trans, dest);
9869 * We need to find a free sequence number both in the source and
9870 * in the destination directory for the exchange.
9872 ret = btrfs_set_inode_index(BTRFS_I(new_dir), &old_idx);
9875 ret = btrfs_set_inode_index(BTRFS_I(old_dir), &new_idx);
9879 BTRFS_I(old_inode)->dir_index = 0ULL;
9880 BTRFS_I(new_inode)->dir_index = 0ULL;
9882 /* Reference for the source. */
9883 if (old_ino == BTRFS_FIRST_FREE_OBJECTID) {
9884 /* force full log commit if subvolume involved. */
9885 btrfs_set_log_full_commit(fs_info, trans);
9887 btrfs_pin_log_trans(root);
9888 root_log_pinned = true;
9889 ret = btrfs_insert_inode_ref(trans, dest,
9890 new_dentry->d_name.name,
9891 new_dentry->d_name.len,
9893 btrfs_ino(BTRFS_I(new_dir)),
9899 /* And now for the dest. */
9900 if (new_ino == BTRFS_FIRST_FREE_OBJECTID) {
9901 /* force full log commit if subvolume involved. */
9902 btrfs_set_log_full_commit(fs_info, trans);
9904 btrfs_pin_log_trans(dest);
9905 dest_log_pinned = true;
9906 ret = btrfs_insert_inode_ref(trans, root,
9907 old_dentry->d_name.name,
9908 old_dentry->d_name.len,
9910 btrfs_ino(BTRFS_I(old_dir)),
9916 /* Update inode version and ctime/mtime. */
9917 inode_inc_iversion(old_dir);
9918 inode_inc_iversion(new_dir);
9919 inode_inc_iversion(old_inode);
9920 inode_inc_iversion(new_inode);
9921 old_dir->i_ctime = old_dir->i_mtime = ctime;
9922 new_dir->i_ctime = new_dir->i_mtime = ctime;
9923 old_inode->i_ctime = ctime;
9924 new_inode->i_ctime = ctime;
9926 if (old_dentry->d_parent != new_dentry->d_parent) {
9927 btrfs_record_unlink_dir(trans, BTRFS_I(old_dir),
9928 BTRFS_I(old_inode), 1);
9929 btrfs_record_unlink_dir(trans, BTRFS_I(new_dir),
9930 BTRFS_I(new_inode), 1);
9933 /* src is a subvolume */
9934 if (old_ino == BTRFS_FIRST_FREE_OBJECTID) {
9935 root_objectid = BTRFS_I(old_inode)->root->root_key.objectid;
9936 ret = btrfs_unlink_subvol(trans, root, old_dir,
9938 old_dentry->d_name.name,
9939 old_dentry->d_name.len);
9940 } else { /* src is an inode */
9941 ret = __btrfs_unlink_inode(trans, root, BTRFS_I(old_dir),
9942 BTRFS_I(old_dentry->d_inode),
9943 old_dentry->d_name.name,
9944 old_dentry->d_name.len);
9946 ret = btrfs_update_inode(trans, root, old_inode);
9949 btrfs_abort_transaction(trans, ret);
9953 /* dest is a subvolume */
9954 if (new_ino == BTRFS_FIRST_FREE_OBJECTID) {
9955 root_objectid = BTRFS_I(new_inode)->root->root_key.objectid;
9956 ret = btrfs_unlink_subvol(trans, dest, new_dir,
9958 new_dentry->d_name.name,
9959 new_dentry->d_name.len);
9960 } else { /* dest is an inode */
9961 ret = __btrfs_unlink_inode(trans, dest, BTRFS_I(new_dir),
9962 BTRFS_I(new_dentry->d_inode),
9963 new_dentry->d_name.name,
9964 new_dentry->d_name.len);
9966 ret = btrfs_update_inode(trans, dest, new_inode);
9969 btrfs_abort_transaction(trans, ret);
9973 ret = btrfs_add_link(trans, BTRFS_I(new_dir), BTRFS_I(old_inode),
9974 new_dentry->d_name.name,
9975 new_dentry->d_name.len, 0, old_idx);
9977 btrfs_abort_transaction(trans, ret);
9981 ret = btrfs_add_link(trans, BTRFS_I(old_dir), BTRFS_I(new_inode),
9982 old_dentry->d_name.name,
9983 old_dentry->d_name.len, 0, new_idx);
9985 btrfs_abort_transaction(trans, ret);
9989 if (old_inode->i_nlink == 1)
9990 BTRFS_I(old_inode)->dir_index = old_idx;
9991 if (new_inode->i_nlink == 1)
9992 BTRFS_I(new_inode)->dir_index = new_idx;
9994 if (root_log_pinned) {
9995 parent = new_dentry->d_parent;
9996 btrfs_log_new_name(trans, BTRFS_I(old_inode), BTRFS_I(old_dir),
9998 btrfs_end_log_trans(root);
9999 root_log_pinned = false;
10001 if (dest_log_pinned) {
10002 parent = old_dentry->d_parent;
10003 btrfs_log_new_name(trans, BTRFS_I(new_inode), BTRFS_I(new_dir),
10005 btrfs_end_log_trans(dest);
10006 dest_log_pinned = false;
10010 * If we have pinned a log and an error happened, we unpin tasks
10011 * trying to sync the log and force them to fallback to a transaction
10012 * commit if the log currently contains any of the inodes involved in
10013 * this rename operation (to ensure we do not persist a log with an
10014 * inconsistent state for any of these inodes or leading to any
10015 * inconsistencies when replayed). If the transaction was aborted, the
10016 * abortion reason is propagated to userspace when attempting to commit
10017 * the transaction. If the log does not contain any of these inodes, we
10018 * allow the tasks to sync it.
10020 if (ret && (root_log_pinned || dest_log_pinned)) {
10021 if (btrfs_inode_in_log(BTRFS_I(old_dir), fs_info->generation) ||
10022 btrfs_inode_in_log(BTRFS_I(new_dir), fs_info->generation) ||
10023 btrfs_inode_in_log(BTRFS_I(old_inode), fs_info->generation) ||
10025 btrfs_inode_in_log(BTRFS_I(new_inode), fs_info->generation)))
10026 btrfs_set_log_full_commit(fs_info, trans);
10028 if (root_log_pinned) {
10029 btrfs_end_log_trans(root);
10030 root_log_pinned = false;
10032 if (dest_log_pinned) {
10033 btrfs_end_log_trans(dest);
10034 dest_log_pinned = false;
10037 ret2 = btrfs_end_transaction(trans);
10038 ret = ret ? ret : ret2;
10040 if (new_ino == BTRFS_FIRST_FREE_OBJECTID ||
10041 old_ino == BTRFS_FIRST_FREE_OBJECTID)
10042 up_read(&fs_info->subvol_sem);
10047 static int btrfs_whiteout_for_rename(struct btrfs_trans_handle *trans,
10048 struct btrfs_root *root,
10050 struct dentry *dentry)
10053 struct inode *inode;
10057 ret = btrfs_find_free_ino(root, &objectid);
10061 inode = btrfs_new_inode(trans, root, dir,
10062 dentry->d_name.name,
10063 dentry->d_name.len,
10064 btrfs_ino(BTRFS_I(dir)),
10066 S_IFCHR | WHITEOUT_MODE,
10069 if (IS_ERR(inode)) {
10070 ret = PTR_ERR(inode);
10074 inode->i_op = &btrfs_special_inode_operations;
10075 init_special_inode(inode, inode->i_mode,
10078 ret = btrfs_init_inode_security(trans, inode, dir,
10083 ret = btrfs_add_nondir(trans, BTRFS_I(dir), dentry,
10084 BTRFS_I(inode), 0, index);
10088 ret = btrfs_update_inode(trans, root, inode);
10090 unlock_new_inode(inode);
10092 inode_dec_link_count(inode);
10098 static int btrfs_rename(struct inode *old_dir, struct dentry *old_dentry,
10099 struct inode *new_dir, struct dentry *new_dentry,
10100 unsigned int flags)
10102 struct btrfs_fs_info *fs_info = btrfs_sb(old_dir->i_sb);
10103 struct btrfs_trans_handle *trans;
10104 unsigned int trans_num_items;
10105 struct btrfs_root *root = BTRFS_I(old_dir)->root;
10106 struct btrfs_root *dest = BTRFS_I(new_dir)->root;
10107 struct inode *new_inode = d_inode(new_dentry);
10108 struct inode *old_inode = d_inode(old_dentry);
10112 u64 old_ino = btrfs_ino(BTRFS_I(old_inode));
10113 bool log_pinned = false;
10115 if (btrfs_ino(BTRFS_I(new_dir)) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)
10118 /* we only allow rename subvolume link between subvolumes */
10119 if (old_ino != BTRFS_FIRST_FREE_OBJECTID && root != dest)
10122 if (old_ino == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID ||
10123 (new_inode && btrfs_ino(BTRFS_I(new_inode)) == BTRFS_FIRST_FREE_OBJECTID))
10126 if (S_ISDIR(old_inode->i_mode) && new_inode &&
10127 new_inode->i_size > BTRFS_EMPTY_DIR_SIZE)
10131 /* check for collisions, even if the name isn't there */
10132 ret = btrfs_check_dir_item_collision(dest, new_dir->i_ino,
10133 new_dentry->d_name.name,
10134 new_dentry->d_name.len);
10137 if (ret == -EEXIST) {
10138 /* we shouldn't get
10139 * eexist without a new_inode */
10140 if (WARN_ON(!new_inode)) {
10144 /* maybe -EOVERFLOW */
10151 * we're using rename to replace one file with another. Start IO on it
10152 * now so we don't add too much work to the end of the transaction
10154 if (new_inode && S_ISREG(old_inode->i_mode) && new_inode->i_size)
10155 filemap_flush(old_inode->i_mapping);
10157 /* close the racy window with snapshot create/destroy ioctl */
10158 if (old_ino == BTRFS_FIRST_FREE_OBJECTID)
10159 down_read(&fs_info->subvol_sem);
10161 * We want to reserve the absolute worst case amount of items. So if
10162 * both inodes are subvols and we need to unlink them then that would
10163 * require 4 item modifications, but if they are both normal inodes it
10164 * would require 5 item modifications, so we'll assume they are normal
10165 * inodes. So 5 * 2 is 10, plus 1 for the new link, so 11 total items
10166 * should cover the worst case number of items we'll modify.
10167 * If our rename has the whiteout flag, we need more 5 units for the
10168 * new inode (1 inode item, 1 inode ref, 2 dir items and 1 xattr item
10169 * when selinux is enabled).
10171 trans_num_items = 11;
10172 if (flags & RENAME_WHITEOUT)
10173 trans_num_items += 5;
10174 trans = btrfs_start_transaction(root, trans_num_items);
10175 if (IS_ERR(trans)) {
10176 ret = PTR_ERR(trans);
10181 btrfs_record_root_in_trans(trans, dest);
10183 ret = btrfs_set_inode_index(BTRFS_I(new_dir), &index);
10187 BTRFS_I(old_inode)->dir_index = 0ULL;
10188 if (unlikely(old_ino == BTRFS_FIRST_FREE_OBJECTID)) {
10189 /* force full log commit if subvolume involved. */
10190 btrfs_set_log_full_commit(fs_info, trans);
10192 btrfs_pin_log_trans(root);
10194 ret = btrfs_insert_inode_ref(trans, dest,
10195 new_dentry->d_name.name,
10196 new_dentry->d_name.len,
10198 btrfs_ino(BTRFS_I(new_dir)), index);
10203 inode_inc_iversion(old_dir);
10204 inode_inc_iversion(new_dir);
10205 inode_inc_iversion(old_inode);
10206 old_dir->i_ctime = old_dir->i_mtime =
10207 new_dir->i_ctime = new_dir->i_mtime =
10208 old_inode->i_ctime = current_time(old_dir);
10210 if (old_dentry->d_parent != new_dentry->d_parent)
10211 btrfs_record_unlink_dir(trans, BTRFS_I(old_dir),
10212 BTRFS_I(old_inode), 1);
10214 if (unlikely(old_ino == BTRFS_FIRST_FREE_OBJECTID)) {
10215 root_objectid = BTRFS_I(old_inode)->root->root_key.objectid;
10216 ret = btrfs_unlink_subvol(trans, root, old_dir, root_objectid,
10217 old_dentry->d_name.name,
10218 old_dentry->d_name.len);
10220 ret = __btrfs_unlink_inode(trans, root, BTRFS_I(old_dir),
10221 BTRFS_I(d_inode(old_dentry)),
10222 old_dentry->d_name.name,
10223 old_dentry->d_name.len);
10225 ret = btrfs_update_inode(trans, root, old_inode);
10228 btrfs_abort_transaction(trans, ret);
10233 inode_inc_iversion(new_inode);
10234 new_inode->i_ctime = current_time(new_inode);
10235 if (unlikely(btrfs_ino(BTRFS_I(new_inode)) ==
10236 BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)) {
10237 root_objectid = BTRFS_I(new_inode)->location.objectid;
10238 ret = btrfs_unlink_subvol(trans, dest, new_dir,
10240 new_dentry->d_name.name,
10241 new_dentry->d_name.len);
10242 BUG_ON(new_inode->i_nlink == 0);
10244 ret = btrfs_unlink_inode(trans, dest, BTRFS_I(new_dir),
10245 BTRFS_I(d_inode(new_dentry)),
10246 new_dentry->d_name.name,
10247 new_dentry->d_name.len);
10249 if (!ret && new_inode->i_nlink == 0)
10250 ret = btrfs_orphan_add(trans,
10251 BTRFS_I(d_inode(new_dentry)));
10253 btrfs_abort_transaction(trans, ret);
10258 ret = btrfs_add_link(trans, BTRFS_I(new_dir), BTRFS_I(old_inode),
10259 new_dentry->d_name.name,
10260 new_dentry->d_name.len, 0, index);
10262 btrfs_abort_transaction(trans, ret);
10266 if (old_inode->i_nlink == 1)
10267 BTRFS_I(old_inode)->dir_index = index;
10270 struct dentry *parent = new_dentry->d_parent;
10272 btrfs_log_new_name(trans, BTRFS_I(old_inode), BTRFS_I(old_dir),
10274 btrfs_end_log_trans(root);
10275 log_pinned = false;
10278 if (flags & RENAME_WHITEOUT) {
10279 ret = btrfs_whiteout_for_rename(trans, root, old_dir,
10283 btrfs_abort_transaction(trans, ret);
10289 * If we have pinned the log and an error happened, we unpin tasks
10290 * trying to sync the log and force them to fallback to a transaction
10291 * commit if the log currently contains any of the inodes involved in
10292 * this rename operation (to ensure we do not persist a log with an
10293 * inconsistent state for any of these inodes or leading to any
10294 * inconsistencies when replayed). If the transaction was aborted, the
10295 * abortion reason is propagated to userspace when attempting to commit
10296 * the transaction. If the log does not contain any of these inodes, we
10297 * allow the tasks to sync it.
10299 if (ret && log_pinned) {
10300 if (btrfs_inode_in_log(BTRFS_I(old_dir), fs_info->generation) ||
10301 btrfs_inode_in_log(BTRFS_I(new_dir), fs_info->generation) ||
10302 btrfs_inode_in_log(BTRFS_I(old_inode), fs_info->generation) ||
10304 btrfs_inode_in_log(BTRFS_I(new_inode), fs_info->generation)))
10305 btrfs_set_log_full_commit(fs_info, trans);
10307 btrfs_end_log_trans(root);
10308 log_pinned = false;
10310 btrfs_end_transaction(trans);
10312 if (old_ino == BTRFS_FIRST_FREE_OBJECTID)
10313 up_read(&fs_info->subvol_sem);
10318 static int btrfs_rename2(struct inode *old_dir, struct dentry *old_dentry,
10319 struct inode *new_dir, struct dentry *new_dentry,
10320 unsigned int flags)
10322 if (flags & ~(RENAME_NOREPLACE | RENAME_EXCHANGE | RENAME_WHITEOUT))
10325 if (flags & RENAME_EXCHANGE)
10326 return btrfs_rename_exchange(old_dir, old_dentry, new_dir,
10329 return btrfs_rename(old_dir, old_dentry, new_dir, new_dentry, flags);
10332 static void btrfs_run_delalloc_work(struct btrfs_work *work)
10334 struct btrfs_delalloc_work *delalloc_work;
10335 struct inode *inode;
10337 delalloc_work = container_of(work, struct btrfs_delalloc_work,
10339 inode = delalloc_work->inode;
10340 filemap_flush(inode->i_mapping);
10341 if (test_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
10342 &BTRFS_I(inode)->runtime_flags))
10343 filemap_flush(inode->i_mapping);
10345 if (delalloc_work->delay_iput)
10346 btrfs_add_delayed_iput(inode);
10349 complete(&delalloc_work->completion);
10352 struct btrfs_delalloc_work *btrfs_alloc_delalloc_work(struct inode *inode,
10355 struct btrfs_delalloc_work *work;
10357 work = kmalloc(sizeof(*work), GFP_NOFS);
10361 init_completion(&work->completion);
10362 INIT_LIST_HEAD(&work->list);
10363 work->inode = inode;
10364 work->delay_iput = delay_iput;
10365 WARN_ON_ONCE(!inode);
10366 btrfs_init_work(&work->work, btrfs_flush_delalloc_helper,
10367 btrfs_run_delalloc_work, NULL, NULL);
10372 void btrfs_wait_and_free_delalloc_work(struct btrfs_delalloc_work *work)
10374 wait_for_completion(&work->completion);
10379 * some fairly slow code that needs optimization. This walks the list
10380 * of all the inodes with pending delalloc and forces them to disk.
10382 static int __start_delalloc_inodes(struct btrfs_root *root, int delay_iput,
10385 struct btrfs_inode *binode;
10386 struct inode *inode;
10387 struct btrfs_delalloc_work *work, *next;
10388 struct list_head works;
10389 struct list_head splice;
10392 INIT_LIST_HEAD(&works);
10393 INIT_LIST_HEAD(&splice);
10395 mutex_lock(&root->delalloc_mutex);
10396 spin_lock(&root->delalloc_lock);
10397 list_splice_init(&root->delalloc_inodes, &splice);
10398 while (!list_empty(&splice)) {
10399 binode = list_entry(splice.next, struct btrfs_inode,
10402 list_move_tail(&binode->delalloc_inodes,
10403 &root->delalloc_inodes);
10404 inode = igrab(&binode->vfs_inode);
10406 cond_resched_lock(&root->delalloc_lock);
10409 spin_unlock(&root->delalloc_lock);
10411 work = btrfs_alloc_delalloc_work(inode, delay_iput);
10414 btrfs_add_delayed_iput(inode);
10420 list_add_tail(&work->list, &works);
10421 btrfs_queue_work(root->fs_info->flush_workers,
10424 if (nr != -1 && ret >= nr)
10427 spin_lock(&root->delalloc_lock);
10429 spin_unlock(&root->delalloc_lock);
10432 list_for_each_entry_safe(work, next, &works, list) {
10433 list_del_init(&work->list);
10434 btrfs_wait_and_free_delalloc_work(work);
10437 if (!list_empty_careful(&splice)) {
10438 spin_lock(&root->delalloc_lock);
10439 list_splice_tail(&splice, &root->delalloc_inodes);
10440 spin_unlock(&root->delalloc_lock);
10442 mutex_unlock(&root->delalloc_mutex);
10446 int btrfs_start_delalloc_inodes(struct btrfs_root *root, int delay_iput)
10448 struct btrfs_fs_info *fs_info = root->fs_info;
10451 if (test_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state))
10454 ret = __start_delalloc_inodes(root, delay_iput, -1);
10458 * the filemap_flush will queue IO into the worker threads, but
10459 * we have to make sure the IO is actually started and that
10460 * ordered extents get created before we return
10462 atomic_inc(&fs_info->async_submit_draining);
10463 while (atomic_read(&fs_info->nr_async_submits) ||
10464 atomic_read(&fs_info->async_delalloc_pages)) {
10465 wait_event(fs_info->async_submit_wait,
10466 (atomic_read(&fs_info->nr_async_submits) == 0 &&
10467 atomic_read(&fs_info->async_delalloc_pages) == 0));
10469 atomic_dec(&fs_info->async_submit_draining);
10473 int btrfs_start_delalloc_roots(struct btrfs_fs_info *fs_info, int delay_iput,
10476 struct btrfs_root *root;
10477 struct list_head splice;
10480 if (test_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state))
10483 INIT_LIST_HEAD(&splice);
10485 mutex_lock(&fs_info->delalloc_root_mutex);
10486 spin_lock(&fs_info->delalloc_root_lock);
10487 list_splice_init(&fs_info->delalloc_roots, &splice);
10488 while (!list_empty(&splice) && nr) {
10489 root = list_first_entry(&splice, struct btrfs_root,
10491 root = btrfs_grab_fs_root(root);
10493 list_move_tail(&root->delalloc_root,
10494 &fs_info->delalloc_roots);
10495 spin_unlock(&fs_info->delalloc_root_lock);
10497 ret = __start_delalloc_inodes(root, delay_iput, nr);
10498 btrfs_put_fs_root(root);
10506 spin_lock(&fs_info->delalloc_root_lock);
10508 spin_unlock(&fs_info->delalloc_root_lock);
10511 atomic_inc(&fs_info->async_submit_draining);
10512 while (atomic_read(&fs_info->nr_async_submits) ||
10513 atomic_read(&fs_info->async_delalloc_pages)) {
10514 wait_event(fs_info->async_submit_wait,
10515 (atomic_read(&fs_info->nr_async_submits) == 0 &&
10516 atomic_read(&fs_info->async_delalloc_pages) == 0));
10518 atomic_dec(&fs_info->async_submit_draining);
10520 if (!list_empty_careful(&splice)) {
10521 spin_lock(&fs_info->delalloc_root_lock);
10522 list_splice_tail(&splice, &fs_info->delalloc_roots);
10523 spin_unlock(&fs_info->delalloc_root_lock);
10525 mutex_unlock(&fs_info->delalloc_root_mutex);
10529 static int btrfs_symlink(struct inode *dir, struct dentry *dentry,
10530 const char *symname)
10532 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
10533 struct btrfs_trans_handle *trans;
10534 struct btrfs_root *root = BTRFS_I(dir)->root;
10535 struct btrfs_path *path;
10536 struct btrfs_key key;
10537 struct inode *inode = NULL;
10539 int drop_inode = 0;
10545 struct btrfs_file_extent_item *ei;
10546 struct extent_buffer *leaf;
10548 name_len = strlen(symname);
10549 if (name_len > BTRFS_MAX_INLINE_DATA_SIZE(fs_info))
10550 return -ENAMETOOLONG;
10553 * 2 items for inode item and ref
10554 * 2 items for dir items
10555 * 1 item for updating parent inode item
10556 * 1 item for the inline extent item
10557 * 1 item for xattr if selinux is on
10559 trans = btrfs_start_transaction(root, 7);
10561 return PTR_ERR(trans);
10563 err = btrfs_find_free_ino(root, &objectid);
10567 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
10568 dentry->d_name.len, btrfs_ino(BTRFS_I(dir)),
10569 objectid, S_IFLNK|S_IRWXUGO, &index);
10570 if (IS_ERR(inode)) {
10571 err = PTR_ERR(inode);
10576 * If the active LSM wants to access the inode during
10577 * d_instantiate it needs these. Smack checks to see
10578 * if the filesystem supports xattrs by looking at the
10581 inode->i_fop = &btrfs_file_operations;
10582 inode->i_op = &btrfs_file_inode_operations;
10583 inode->i_mapping->a_ops = &btrfs_aops;
10584 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
10586 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
10588 goto out_unlock_inode;
10590 path = btrfs_alloc_path();
10593 goto out_unlock_inode;
10595 key.objectid = btrfs_ino(BTRFS_I(inode));
10597 key.type = BTRFS_EXTENT_DATA_KEY;
10598 datasize = btrfs_file_extent_calc_inline_size(name_len);
10599 err = btrfs_insert_empty_item(trans, root, path, &key,
10602 btrfs_free_path(path);
10603 goto out_unlock_inode;
10605 leaf = path->nodes[0];
10606 ei = btrfs_item_ptr(leaf, path->slots[0],
10607 struct btrfs_file_extent_item);
10608 btrfs_set_file_extent_generation(leaf, ei, trans->transid);
10609 btrfs_set_file_extent_type(leaf, ei,
10610 BTRFS_FILE_EXTENT_INLINE);
10611 btrfs_set_file_extent_encryption(leaf, ei, 0);
10612 btrfs_set_file_extent_compression(leaf, ei, 0);
10613 btrfs_set_file_extent_other_encoding(leaf, ei, 0);
10614 btrfs_set_file_extent_ram_bytes(leaf, ei, name_len);
10616 ptr = btrfs_file_extent_inline_start(ei);
10617 write_extent_buffer(leaf, symname, ptr, name_len);
10618 btrfs_mark_buffer_dirty(leaf);
10619 btrfs_free_path(path);
10621 inode->i_op = &btrfs_symlink_inode_operations;
10622 inode_nohighmem(inode);
10623 inode->i_mapping->a_ops = &btrfs_symlink_aops;
10624 inode_set_bytes(inode, name_len);
10625 btrfs_i_size_write(BTRFS_I(inode), name_len);
10626 err = btrfs_update_inode(trans, root, inode);
10628 * Last step, add directory indexes for our symlink inode. This is the
10629 * last step to avoid extra cleanup of these indexes if an error happens
10633 err = btrfs_add_nondir(trans, BTRFS_I(dir), dentry,
10634 BTRFS_I(inode), 0, index);
10637 goto out_unlock_inode;
10640 d_instantiate_new(dentry, inode);
10643 btrfs_end_transaction(trans);
10645 inode_dec_link_count(inode);
10648 btrfs_btree_balance_dirty(fs_info);
10653 unlock_new_inode(inode);
10657 static int __btrfs_prealloc_file_range(struct inode *inode, int mode,
10658 u64 start, u64 num_bytes, u64 min_size,
10659 loff_t actual_len, u64 *alloc_hint,
10660 struct btrfs_trans_handle *trans)
10662 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
10663 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
10664 struct extent_map *em;
10665 struct btrfs_root *root = BTRFS_I(inode)->root;
10666 struct btrfs_key ins;
10667 u64 cur_offset = start;
10668 u64 clear_offset = start;
10671 u64 last_alloc = (u64)-1;
10673 bool own_trans = true;
10674 u64 end = start + num_bytes - 1;
10678 while (num_bytes > 0) {
10680 trans = btrfs_start_transaction(root, 3);
10681 if (IS_ERR(trans)) {
10682 ret = PTR_ERR(trans);
10687 cur_bytes = min_t(u64, num_bytes, SZ_256M);
10688 cur_bytes = max(cur_bytes, min_size);
10690 * If we are severely fragmented we could end up with really
10691 * small allocations, so if the allocator is returning small
10692 * chunks lets make its job easier by only searching for those
10695 cur_bytes = min(cur_bytes, last_alloc);
10696 ret = btrfs_reserve_extent(root, cur_bytes, cur_bytes,
10697 min_size, 0, *alloc_hint, &ins, 1, 0);
10700 btrfs_end_transaction(trans);
10705 * We've reserved this space, and thus converted it from
10706 * ->bytes_may_use to ->bytes_reserved. Any error that happens
10707 * from here on out we will only need to clear our reservation
10708 * for the remaining unreserved area, so advance our
10709 * clear_offset by our extent size.
10711 clear_offset += ins.offset;
10712 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
10714 last_alloc = ins.offset;
10715 ret = insert_reserved_file_extent(trans, inode,
10716 cur_offset, ins.objectid,
10717 ins.offset, ins.offset,
10718 ins.offset, 0, 0, 0,
10719 BTRFS_FILE_EXTENT_PREALLOC);
10721 btrfs_free_reserved_extent(fs_info, ins.objectid,
10723 btrfs_abort_transaction(trans, ret);
10725 btrfs_end_transaction(trans);
10729 btrfs_drop_extent_cache(BTRFS_I(inode), cur_offset,
10730 cur_offset + ins.offset -1, 0);
10732 em = alloc_extent_map();
10734 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
10735 &BTRFS_I(inode)->runtime_flags);
10739 em->start = cur_offset;
10740 em->orig_start = cur_offset;
10741 em->len = ins.offset;
10742 em->block_start = ins.objectid;
10743 em->block_len = ins.offset;
10744 em->orig_block_len = ins.offset;
10745 em->ram_bytes = ins.offset;
10746 em->bdev = fs_info->fs_devices->latest_bdev;
10747 set_bit(EXTENT_FLAG_PREALLOC, &em->flags);
10748 em->generation = trans->transid;
10751 write_lock(&em_tree->lock);
10752 ret = add_extent_mapping(em_tree, em, 1);
10753 write_unlock(&em_tree->lock);
10754 if (ret != -EEXIST)
10756 btrfs_drop_extent_cache(BTRFS_I(inode), cur_offset,
10757 cur_offset + ins.offset - 1,
10760 free_extent_map(em);
10762 num_bytes -= ins.offset;
10763 cur_offset += ins.offset;
10764 *alloc_hint = ins.objectid + ins.offset;
10766 inode_inc_iversion(inode);
10767 inode->i_ctime = current_time(inode);
10768 BTRFS_I(inode)->flags |= BTRFS_INODE_PREALLOC;
10769 if (!(mode & FALLOC_FL_KEEP_SIZE) &&
10770 (actual_len > inode->i_size) &&
10771 (cur_offset > inode->i_size)) {
10772 if (cur_offset > actual_len)
10773 i_size = actual_len;
10775 i_size = cur_offset;
10776 i_size_write(inode, i_size);
10777 btrfs_ordered_update_i_size(inode, i_size, NULL);
10780 ret = btrfs_update_inode(trans, root, inode);
10783 btrfs_abort_transaction(trans, ret);
10785 btrfs_end_transaction(trans);
10790 btrfs_end_transaction(trans);
10792 if (clear_offset < end)
10793 btrfs_free_reserved_data_space(inode, NULL, clear_offset,
10794 end - clear_offset + 1);
10798 int btrfs_prealloc_file_range(struct inode *inode, int mode,
10799 u64 start, u64 num_bytes, u64 min_size,
10800 loff_t actual_len, u64 *alloc_hint)
10802 return __btrfs_prealloc_file_range(inode, mode, start, num_bytes,
10803 min_size, actual_len, alloc_hint,
10807 int btrfs_prealloc_file_range_trans(struct inode *inode,
10808 struct btrfs_trans_handle *trans, int mode,
10809 u64 start, u64 num_bytes, u64 min_size,
10810 loff_t actual_len, u64 *alloc_hint)
10812 return __btrfs_prealloc_file_range(inode, mode, start, num_bytes,
10813 min_size, actual_len, alloc_hint, trans);
10816 static int btrfs_set_page_dirty(struct page *page)
10818 return __set_page_dirty_nobuffers(page);
10821 static int btrfs_permission(struct inode *inode, int mask)
10823 struct btrfs_root *root = BTRFS_I(inode)->root;
10824 umode_t mode = inode->i_mode;
10826 if (mask & MAY_WRITE &&
10827 (S_ISREG(mode) || S_ISDIR(mode) || S_ISLNK(mode))) {
10828 if (btrfs_root_readonly(root))
10830 if (BTRFS_I(inode)->flags & BTRFS_INODE_READONLY)
10833 return generic_permission(inode, mask);
10836 static int btrfs_tmpfile(struct inode *dir, struct dentry *dentry, umode_t mode)
10838 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
10839 struct btrfs_trans_handle *trans;
10840 struct btrfs_root *root = BTRFS_I(dir)->root;
10841 struct inode *inode = NULL;
10847 * 5 units required for adding orphan entry
10849 trans = btrfs_start_transaction(root, 5);
10851 return PTR_ERR(trans);
10853 ret = btrfs_find_free_ino(root, &objectid);
10857 inode = btrfs_new_inode(trans, root, dir, NULL, 0,
10858 btrfs_ino(BTRFS_I(dir)), objectid, mode, &index);
10859 if (IS_ERR(inode)) {
10860 ret = PTR_ERR(inode);
10865 inode->i_fop = &btrfs_file_operations;
10866 inode->i_op = &btrfs_file_inode_operations;
10868 inode->i_mapping->a_ops = &btrfs_aops;
10869 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
10871 ret = btrfs_init_inode_security(trans, inode, dir, NULL);
10875 ret = btrfs_update_inode(trans, root, inode);
10878 ret = btrfs_orphan_add(trans, BTRFS_I(inode));
10883 * We set number of links to 0 in btrfs_new_inode(), and here we set
10884 * it to 1 because d_tmpfile() will issue a warning if the count is 0,
10887 * d_tmpfile() -> inode_dec_link_count() -> drop_nlink()
10889 set_nlink(inode, 1);
10890 unlock_new_inode(inode);
10891 d_tmpfile(dentry, inode);
10892 mark_inode_dirty(inode);
10895 btrfs_end_transaction(trans);
10898 btrfs_balance_delayed_items(fs_info);
10899 btrfs_btree_balance_dirty(fs_info);
10903 unlock_new_inode(inode);
10908 __attribute__((const))
10909 static int btrfs_readpage_io_failed_hook(struct page *page, int failed_mirror)
10914 static struct btrfs_fs_info *iotree_fs_info(void *private_data)
10916 struct inode *inode = private_data;
10917 return btrfs_sb(inode->i_sb);
10920 static void btrfs_check_extent_io_range(void *private_data, const char *caller,
10921 u64 start, u64 end)
10923 struct inode *inode = private_data;
10926 isize = i_size_read(inode);
10927 if (end >= PAGE_SIZE && (end % 2) == 0 && end != isize - 1) {
10928 btrfs_debug_rl(BTRFS_I(inode)->root->fs_info,
10929 "%s: ino %llu isize %llu odd range [%llu,%llu]",
10930 caller, btrfs_ino(BTRFS_I(inode)), isize, start, end);
10934 void btrfs_set_range_writeback(void *private_data, u64 start, u64 end)
10936 struct inode *inode = private_data;
10937 unsigned long index = start >> PAGE_SHIFT;
10938 unsigned long end_index = end >> PAGE_SHIFT;
10941 while (index <= end_index) {
10942 page = find_get_page(inode->i_mapping, index);
10943 ASSERT(page); /* Pages should be in the extent_io_tree */
10944 set_page_writeback(page);
10950 static const struct inode_operations btrfs_dir_inode_operations = {
10951 .getattr = btrfs_getattr,
10952 .lookup = btrfs_lookup,
10953 .create = btrfs_create,
10954 .unlink = btrfs_unlink,
10955 .link = btrfs_link,
10956 .mkdir = btrfs_mkdir,
10957 .rmdir = btrfs_rmdir,
10958 .rename = btrfs_rename2,
10959 .symlink = btrfs_symlink,
10960 .setattr = btrfs_setattr,
10961 .mknod = btrfs_mknod,
10962 .listxattr = btrfs_listxattr,
10963 .permission = btrfs_permission,
10964 .get_acl = btrfs_get_acl,
10965 .set_acl = btrfs_set_acl,
10966 .update_time = btrfs_update_time,
10967 .tmpfile = btrfs_tmpfile,
10969 static const struct inode_operations btrfs_dir_ro_inode_operations = {
10970 .lookup = btrfs_lookup,
10971 .permission = btrfs_permission,
10972 .update_time = btrfs_update_time,
10975 static const struct file_operations btrfs_dir_file_operations = {
10976 .llseek = generic_file_llseek,
10977 .read = generic_read_dir,
10978 .iterate_shared = btrfs_real_readdir,
10979 .open = btrfs_opendir,
10980 .unlocked_ioctl = btrfs_ioctl,
10981 #ifdef CONFIG_COMPAT
10982 .compat_ioctl = btrfs_compat_ioctl,
10984 .release = btrfs_release_file,
10985 .fsync = btrfs_sync_file,
10988 static const struct extent_io_ops btrfs_extent_io_ops = {
10989 /* mandatory callbacks */
10990 .submit_bio_hook = btrfs_submit_bio_hook,
10991 .readpage_end_io_hook = btrfs_readpage_end_io_hook,
10992 .merge_bio_hook = btrfs_merge_bio_hook,
10993 .readpage_io_failed_hook = btrfs_readpage_io_failed_hook,
10994 .tree_fs_info = iotree_fs_info,
10995 .set_range_writeback = btrfs_set_range_writeback,
10997 /* optional callbacks */
10998 .fill_delalloc = run_delalloc_range,
10999 .writepage_end_io_hook = btrfs_writepage_end_io_hook,
11000 .writepage_start_hook = btrfs_writepage_start_hook,
11001 .set_bit_hook = btrfs_set_bit_hook,
11002 .clear_bit_hook = btrfs_clear_bit_hook,
11003 .merge_extent_hook = btrfs_merge_extent_hook,
11004 .split_extent_hook = btrfs_split_extent_hook,
11005 .check_extent_io_range = btrfs_check_extent_io_range,
11009 * btrfs doesn't support the bmap operation because swapfiles
11010 * use bmap to make a mapping of extents in the file. They assume
11011 * these extents won't change over the life of the file and they
11012 * use the bmap result to do IO directly to the drive.
11014 * the btrfs bmap call would return logical addresses that aren't
11015 * suitable for IO and they also will change frequently as COW
11016 * operations happen. So, swapfile + btrfs == corruption.
11018 * For now we're avoiding this by dropping bmap.
11020 static const struct address_space_operations btrfs_aops = {
11021 .readpage = btrfs_readpage,
11022 .writepage = btrfs_writepage,
11023 .writepages = btrfs_writepages,
11024 .readpages = btrfs_readpages,
11025 .direct_IO = btrfs_direct_IO,
11026 .invalidatepage = btrfs_invalidatepage,
11027 .releasepage = btrfs_releasepage,
11028 .set_page_dirty = btrfs_set_page_dirty,
11029 .error_remove_page = generic_error_remove_page,
11032 static const struct address_space_operations btrfs_symlink_aops = {
11033 .readpage = btrfs_readpage,
11034 .writepage = btrfs_writepage,
11035 .invalidatepage = btrfs_invalidatepage,
11036 .releasepage = btrfs_releasepage,
11039 static const struct inode_operations btrfs_file_inode_operations = {
11040 .getattr = btrfs_getattr,
11041 .setattr = btrfs_setattr,
11042 .listxattr = btrfs_listxattr,
11043 .permission = btrfs_permission,
11044 .fiemap = btrfs_fiemap,
11045 .get_acl = btrfs_get_acl,
11046 .set_acl = btrfs_set_acl,
11047 .update_time = btrfs_update_time,
11049 static const struct inode_operations btrfs_special_inode_operations = {
11050 .getattr = btrfs_getattr,
11051 .setattr = btrfs_setattr,
11052 .permission = btrfs_permission,
11053 .listxattr = btrfs_listxattr,
11054 .get_acl = btrfs_get_acl,
11055 .set_acl = btrfs_set_acl,
11056 .update_time = btrfs_update_time,
11058 static const struct inode_operations btrfs_symlink_inode_operations = {
11059 .get_link = page_get_link,
11060 .getattr = btrfs_getattr,
11061 .setattr = btrfs_setattr,
11062 .permission = btrfs_permission,
11063 .listxattr = btrfs_listxattr,
11064 .update_time = btrfs_update_time,
11067 const struct dentry_operations btrfs_dentry_operations = {
11068 .d_delete = btrfs_dentry_delete,
11069 .d_release = btrfs_dentry_release,