2 * Copyright (C) 2007 Oracle. All rights reserved.
4 * This program is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU General Public
6 * License v2 as published by the Free Software Foundation.
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
11 * General Public License for more details.
13 * You should have received a copy of the GNU General Public
14 * License along with this program; if not, write to the
15 * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
16 * Boston, MA 021110-1307, USA.
19 #include <linux/kernel.h>
20 #include <linux/bio.h>
21 #include <linux/buffer_head.h>
22 #include <linux/file.h>
24 #include <linux/pagemap.h>
25 #include <linux/highmem.h>
26 #include <linux/time.h>
27 #include <linux/init.h>
28 #include <linux/string.h>
29 #include <linux/backing-dev.h>
30 #include <linux/mpage.h>
31 #include <linux/swap.h>
32 #include <linux/writeback.h>
33 #include <linux/compat.h>
34 #include <linux/bit_spinlock.h>
35 #include <linux/xattr.h>
36 #include <linux/posix_acl.h>
37 #include <linux/falloc.h>
38 #include <linux/slab.h>
39 #include <linux/ratelimit.h>
40 #include <linux/mount.h>
41 #include <linux/btrfs.h>
42 #include <linux/blkdev.h>
43 #include <linux/posix_acl_xattr.h>
44 #include <linux/uio.h>
45 #include <linux/magic.h>
48 #include "transaction.h"
49 #include "btrfs_inode.h"
50 #include "print-tree.h"
51 #include "ordered-data.h"
55 #include "compression.h"
57 #include "free-space-cache.h"
58 #include "inode-map.h"
65 struct btrfs_iget_args {
66 struct btrfs_key *location;
67 struct btrfs_root *root;
70 struct btrfs_dio_data {
72 u64 unsubmitted_oe_range_start;
73 u64 unsubmitted_oe_range_end;
77 static const struct inode_operations btrfs_dir_inode_operations;
78 static const struct inode_operations btrfs_symlink_inode_operations;
79 static const struct inode_operations btrfs_dir_ro_inode_operations;
80 static const struct inode_operations btrfs_special_inode_operations;
81 static const struct inode_operations btrfs_file_inode_operations;
82 static const struct address_space_operations btrfs_aops;
83 static const struct address_space_operations btrfs_symlink_aops;
84 static const struct file_operations btrfs_dir_file_operations;
85 static const struct extent_io_ops btrfs_extent_io_ops;
87 static struct kmem_cache *btrfs_inode_cachep;
88 struct kmem_cache *btrfs_trans_handle_cachep;
89 struct kmem_cache *btrfs_path_cachep;
90 struct kmem_cache *btrfs_free_space_cachep;
93 static const unsigned char btrfs_type_by_mode[S_IFMT >> S_SHIFT] = {
94 [S_IFREG >> S_SHIFT] = BTRFS_FT_REG_FILE,
95 [S_IFDIR >> S_SHIFT] = BTRFS_FT_DIR,
96 [S_IFCHR >> S_SHIFT] = BTRFS_FT_CHRDEV,
97 [S_IFBLK >> S_SHIFT] = BTRFS_FT_BLKDEV,
98 [S_IFIFO >> S_SHIFT] = BTRFS_FT_FIFO,
99 [S_IFSOCK >> S_SHIFT] = BTRFS_FT_SOCK,
100 [S_IFLNK >> S_SHIFT] = BTRFS_FT_SYMLINK,
103 static int btrfs_setsize(struct inode *inode, struct iattr *attr);
104 static int btrfs_truncate(struct inode *inode);
105 static int btrfs_finish_ordered_io(struct btrfs_ordered_extent *ordered_extent);
106 static noinline int cow_file_range(struct inode *inode,
107 struct page *locked_page,
108 u64 start, u64 end, u64 delalloc_end,
109 int *page_started, unsigned long *nr_written,
110 int unlock, struct btrfs_dedupe_hash *hash);
111 static struct extent_map *create_io_em(struct inode *inode, u64 start, u64 len,
112 u64 orig_start, u64 block_start,
113 u64 block_len, u64 orig_block_len,
114 u64 ram_bytes, int compress_type,
117 static void __endio_write_update_ordered(struct inode *inode,
118 const u64 offset, const u64 bytes,
119 const bool uptodate);
122 * Cleanup all submitted ordered extents in specified range to handle errors
123 * from the fill_dellaloc() callback.
125 * NOTE: caller must ensure that when an error happens, it can not call
126 * extent_clear_unlock_delalloc() to clear both the bits EXTENT_DO_ACCOUNTING
127 * and EXTENT_DELALLOC simultaneously, because that causes the reserved metadata
128 * to be released, which we want to happen only when finishing the ordered
129 * extent (btrfs_finish_ordered_io()). Also note that the caller of the
130 * fill_delalloc() callback already does proper cleanup for the first page of
131 * the range, that is, it invokes the callback writepage_end_io_hook() for the
132 * range of the first page.
134 static inline void btrfs_cleanup_ordered_extents(struct inode *inode,
138 unsigned long index = offset >> PAGE_SHIFT;
139 unsigned long end_index = (offset + bytes - 1) >> PAGE_SHIFT;
142 while (index <= end_index) {
143 page = find_get_page(inode->i_mapping, index);
147 ClearPagePrivate2(page);
150 return __endio_write_update_ordered(inode, offset + PAGE_SIZE,
151 bytes - PAGE_SIZE, false);
154 static int btrfs_dirty_inode(struct inode *inode);
156 #ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
157 void btrfs_test_inode_set_ops(struct inode *inode)
159 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
163 static int btrfs_init_inode_security(struct btrfs_trans_handle *trans,
164 struct inode *inode, struct inode *dir,
165 const struct qstr *qstr)
169 err = btrfs_init_acl(trans, inode, dir);
171 err = btrfs_xattr_security_init(trans, inode, dir, qstr);
176 * this does all the hard work for inserting an inline extent into
177 * the btree. The caller should have done a btrfs_drop_extents so that
178 * no overlapping inline items exist in the btree
180 static int insert_inline_extent(struct btrfs_trans_handle *trans,
181 struct btrfs_path *path, int extent_inserted,
182 struct btrfs_root *root, struct inode *inode,
183 u64 start, size_t size, size_t compressed_size,
185 struct page **compressed_pages)
187 struct extent_buffer *leaf;
188 struct page *page = NULL;
191 struct btrfs_file_extent_item *ei;
193 size_t cur_size = size;
194 unsigned long offset;
196 if (compressed_size && compressed_pages)
197 cur_size = compressed_size;
199 inode_add_bytes(inode, size);
201 if (!extent_inserted) {
202 struct btrfs_key key;
205 key.objectid = btrfs_ino(BTRFS_I(inode));
207 key.type = BTRFS_EXTENT_DATA_KEY;
209 datasize = btrfs_file_extent_calc_inline_size(cur_size);
210 path->leave_spinning = 1;
211 ret = btrfs_insert_empty_item(trans, root, path, &key,
216 leaf = path->nodes[0];
217 ei = btrfs_item_ptr(leaf, path->slots[0],
218 struct btrfs_file_extent_item);
219 btrfs_set_file_extent_generation(leaf, ei, trans->transid);
220 btrfs_set_file_extent_type(leaf, ei, BTRFS_FILE_EXTENT_INLINE);
221 btrfs_set_file_extent_encryption(leaf, ei, 0);
222 btrfs_set_file_extent_other_encoding(leaf, ei, 0);
223 btrfs_set_file_extent_ram_bytes(leaf, ei, size);
224 ptr = btrfs_file_extent_inline_start(ei);
226 if (compress_type != BTRFS_COMPRESS_NONE) {
229 while (compressed_size > 0) {
230 cpage = compressed_pages[i];
231 cur_size = min_t(unsigned long, compressed_size,
234 kaddr = kmap_atomic(cpage);
235 write_extent_buffer(leaf, kaddr, ptr, cur_size);
236 kunmap_atomic(kaddr);
240 compressed_size -= cur_size;
242 btrfs_set_file_extent_compression(leaf, ei,
245 page = find_get_page(inode->i_mapping,
246 start >> PAGE_SHIFT);
247 btrfs_set_file_extent_compression(leaf, ei, 0);
248 kaddr = kmap_atomic(page);
249 offset = start & (PAGE_SIZE - 1);
250 write_extent_buffer(leaf, kaddr + offset, ptr, size);
251 kunmap_atomic(kaddr);
254 btrfs_mark_buffer_dirty(leaf);
255 btrfs_release_path(path);
258 * we're an inline extent, so nobody can
259 * extend the file past i_size without locking
260 * a page we already have locked.
262 * We must do any isize and inode updates
263 * before we unlock the pages. Otherwise we
264 * could end up racing with unlink.
266 BTRFS_I(inode)->disk_i_size = inode->i_size;
267 ret = btrfs_update_inode(trans, root, inode);
275 * conditionally insert an inline extent into the file. This
276 * does the checks required to make sure the data is small enough
277 * to fit as an inline extent.
279 static noinline int cow_file_range_inline(struct btrfs_root *root,
280 struct inode *inode, u64 start,
281 u64 end, size_t compressed_size,
283 struct page **compressed_pages)
285 struct btrfs_fs_info *fs_info = root->fs_info;
286 struct btrfs_trans_handle *trans;
287 u64 isize = i_size_read(inode);
288 u64 actual_end = min(end + 1, isize);
289 u64 inline_len = actual_end - start;
290 u64 aligned_end = ALIGN(end, fs_info->sectorsize);
291 u64 data_len = inline_len;
293 struct btrfs_path *path;
294 int extent_inserted = 0;
295 u32 extent_item_size;
298 data_len = compressed_size;
301 actual_end > fs_info->sectorsize ||
302 data_len > BTRFS_MAX_INLINE_DATA_SIZE(fs_info) ||
304 (actual_end & (fs_info->sectorsize - 1)) == 0) ||
306 data_len > fs_info->max_inline) {
310 path = btrfs_alloc_path();
314 trans = btrfs_join_transaction(root);
316 btrfs_free_path(path);
317 return PTR_ERR(trans);
319 trans->block_rsv = &BTRFS_I(inode)->block_rsv;
321 if (compressed_size && compressed_pages)
322 extent_item_size = btrfs_file_extent_calc_inline_size(
325 extent_item_size = btrfs_file_extent_calc_inline_size(
328 ret = __btrfs_drop_extents(trans, root, inode, path,
329 start, aligned_end, NULL,
330 1, 1, extent_item_size, &extent_inserted);
332 btrfs_abort_transaction(trans, ret);
336 if (isize > actual_end)
337 inline_len = min_t(u64, isize, actual_end);
338 ret = insert_inline_extent(trans, path, extent_inserted,
340 inline_len, compressed_size,
341 compress_type, compressed_pages);
342 if (ret && ret != -ENOSPC) {
343 btrfs_abort_transaction(trans, ret);
345 } else if (ret == -ENOSPC) {
350 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &BTRFS_I(inode)->runtime_flags);
351 btrfs_drop_extent_cache(BTRFS_I(inode), start, aligned_end - 1, 0);
354 * Don't forget to free the reserved space, as for inlined extent
355 * it won't count as data extent, free them directly here.
356 * And at reserve time, it's always aligned to page size, so
357 * just free one page here.
359 btrfs_qgroup_free_data(inode, NULL, 0, PAGE_SIZE);
360 btrfs_free_path(path);
361 btrfs_end_transaction(trans);
365 struct async_extent {
370 unsigned long nr_pages;
372 struct list_head list;
377 struct btrfs_root *root;
378 struct page *locked_page;
381 unsigned int write_flags;
382 struct list_head extents;
383 struct btrfs_work work;
386 static noinline int add_async_extent(struct async_cow *cow,
387 u64 start, u64 ram_size,
390 unsigned long nr_pages,
393 struct async_extent *async_extent;
395 async_extent = kmalloc(sizeof(*async_extent), GFP_NOFS);
396 BUG_ON(!async_extent); /* -ENOMEM */
397 async_extent->start = start;
398 async_extent->ram_size = ram_size;
399 async_extent->compressed_size = compressed_size;
400 async_extent->pages = pages;
401 async_extent->nr_pages = nr_pages;
402 async_extent->compress_type = compress_type;
403 list_add_tail(&async_extent->list, &cow->extents);
407 static inline int inode_need_compress(struct inode *inode, u64 start, u64 end)
409 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
412 if (btrfs_test_opt(fs_info, FORCE_COMPRESS))
415 if (BTRFS_I(inode)->defrag_compress)
417 /* bad compression ratios */
418 if (BTRFS_I(inode)->flags & BTRFS_INODE_NOCOMPRESS)
420 if (btrfs_test_opt(fs_info, COMPRESS) ||
421 BTRFS_I(inode)->flags & BTRFS_INODE_COMPRESS ||
422 BTRFS_I(inode)->prop_compress)
423 return btrfs_compress_heuristic(inode, start, end);
427 static inline void inode_should_defrag(struct btrfs_inode *inode,
428 u64 start, u64 end, u64 num_bytes, u64 small_write)
430 /* If this is a small write inside eof, kick off a defrag */
431 if (num_bytes < small_write &&
432 (start > 0 || end + 1 < inode->disk_i_size))
433 btrfs_add_inode_defrag(NULL, inode);
437 * we create compressed extents in two phases. The first
438 * phase compresses a range of pages that have already been
439 * locked (both pages and state bits are locked).
441 * This is done inside an ordered work queue, and the compression
442 * is spread across many cpus. The actual IO submission is step
443 * two, and the ordered work queue takes care of making sure that
444 * happens in the same order things were put onto the queue by
445 * writepages and friends.
447 * If this code finds it can't get good compression, it puts an
448 * entry onto the work queue to write the uncompressed bytes. This
449 * makes sure that both compressed inodes and uncompressed inodes
450 * are written in the same order that the flusher thread sent them
453 static noinline void compress_file_range(struct inode *inode,
454 struct page *locked_page,
456 struct async_cow *async_cow,
459 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
460 struct btrfs_root *root = BTRFS_I(inode)->root;
461 u64 blocksize = fs_info->sectorsize;
463 u64 isize = i_size_read(inode);
465 struct page **pages = NULL;
466 unsigned long nr_pages;
467 unsigned long total_compressed = 0;
468 unsigned long total_in = 0;
471 int compress_type = fs_info->compress_type;
474 inode_should_defrag(BTRFS_I(inode), start, end, end - start + 1,
477 actual_end = min_t(u64, isize, end + 1);
480 nr_pages = (end >> PAGE_SHIFT) - (start >> PAGE_SHIFT) + 1;
481 BUILD_BUG_ON((BTRFS_MAX_COMPRESSED % PAGE_SIZE) != 0);
482 nr_pages = min_t(unsigned long, nr_pages,
483 BTRFS_MAX_COMPRESSED / PAGE_SIZE);
486 * we don't want to send crud past the end of i_size through
487 * compression, that's just a waste of CPU time. So, if the
488 * end of the file is before the start of our current
489 * requested range of bytes, we bail out to the uncompressed
490 * cleanup code that can deal with all of this.
492 * It isn't really the fastest way to fix things, but this is a
493 * very uncommon corner.
495 if (actual_end <= start)
496 goto cleanup_and_bail_uncompressed;
498 total_compressed = actual_end - start;
501 * skip compression for a small file range(<=blocksize) that
502 * isn't an inline extent, since it doesn't save disk space at all.
504 if (total_compressed <= blocksize &&
505 (start > 0 || end + 1 < BTRFS_I(inode)->disk_i_size))
506 goto cleanup_and_bail_uncompressed;
508 total_compressed = min_t(unsigned long, total_compressed,
509 BTRFS_MAX_UNCOMPRESSED);
514 * we do compression for mount -o compress and when the
515 * inode has not been flagged as nocompress. This flag can
516 * change at any time if we discover bad compression ratios.
518 if (inode_need_compress(inode, start, end)) {
520 pages = kcalloc(nr_pages, sizeof(struct page *), GFP_NOFS);
522 /* just bail out to the uncompressed code */
526 if (BTRFS_I(inode)->defrag_compress)
527 compress_type = BTRFS_I(inode)->defrag_compress;
528 else if (BTRFS_I(inode)->prop_compress)
529 compress_type = BTRFS_I(inode)->prop_compress;
532 * we need to call clear_page_dirty_for_io on each
533 * page in the range. Otherwise applications with the file
534 * mmap'd can wander in and change the page contents while
535 * we are compressing them.
537 * If the compression fails for any reason, we set the pages
538 * dirty again later on.
540 * Note that the remaining part is redirtied, the start pointer
541 * has moved, the end is the original one.
544 extent_range_clear_dirty_for_io(inode, start, end);
548 /* Compression level is applied here and only here */
549 ret = btrfs_compress_pages(
550 compress_type | (fs_info->compress_level << 4),
551 inode->i_mapping, start,
558 unsigned long offset = total_compressed &
560 struct page *page = pages[nr_pages - 1];
563 /* zero the tail end of the last page, we might be
564 * sending it down to disk
567 kaddr = kmap_atomic(page);
568 memset(kaddr + offset, 0,
570 kunmap_atomic(kaddr);
577 /* lets try to make an inline extent */
578 if (ret || total_in < actual_end) {
579 /* we didn't compress the entire range, try
580 * to make an uncompressed inline extent.
582 ret = cow_file_range_inline(root, inode, start, end,
583 0, BTRFS_COMPRESS_NONE, NULL);
585 /* try making a compressed inline extent */
586 ret = cow_file_range_inline(root, inode, start, end,
588 compress_type, pages);
591 unsigned long clear_flags = EXTENT_DELALLOC |
592 EXTENT_DELALLOC_NEW | EXTENT_DEFRAG |
593 EXTENT_DO_ACCOUNTING;
594 unsigned long page_error_op;
596 page_error_op = ret < 0 ? PAGE_SET_ERROR : 0;
599 * inline extent creation worked or returned error,
600 * we don't need to create any more async work items.
601 * Unlock and free up our temp pages.
603 * We use DO_ACCOUNTING here because we need the
604 * delalloc_release_metadata to be done _after_ we drop
605 * our outstanding extent for clearing delalloc for this
608 extent_clear_unlock_delalloc(inode, start, end, end,
621 * we aren't doing an inline extent round the compressed size
622 * up to a block size boundary so the allocator does sane
625 total_compressed = ALIGN(total_compressed, blocksize);
628 * one last check to make sure the compression is really a
629 * win, compare the page count read with the blocks on disk,
630 * compression must free at least one sector size
632 total_in = ALIGN(total_in, PAGE_SIZE);
633 if (total_compressed + blocksize <= total_in) {
637 * The async work queues will take care of doing actual
638 * allocation on disk for these compressed pages, and
639 * will submit them to the elevator.
641 add_async_extent(async_cow, start, total_in,
642 total_compressed, pages, nr_pages,
645 if (start + total_in < end) {
656 * the compression code ran but failed to make things smaller,
657 * free any pages it allocated and our page pointer array
659 for (i = 0; i < nr_pages; i++) {
660 WARN_ON(pages[i]->mapping);
665 total_compressed = 0;
668 /* flag the file so we don't compress in the future */
669 if (!btrfs_test_opt(fs_info, FORCE_COMPRESS) &&
670 !(BTRFS_I(inode)->prop_compress)) {
671 BTRFS_I(inode)->flags |= BTRFS_INODE_NOCOMPRESS;
674 cleanup_and_bail_uncompressed:
676 * No compression, but we still need to write the pages in the file
677 * we've been given so far. redirty the locked page if it corresponds
678 * to our extent and set things up for the async work queue to run
679 * cow_file_range to do the normal delalloc dance.
681 if (page_offset(locked_page) >= start &&
682 page_offset(locked_page) <= end)
683 __set_page_dirty_nobuffers(locked_page);
684 /* unlocked later on in the async handlers */
687 extent_range_redirty_for_io(inode, start, end);
688 add_async_extent(async_cow, start, end - start + 1, 0, NULL, 0,
689 BTRFS_COMPRESS_NONE);
695 for (i = 0; i < nr_pages; i++) {
696 WARN_ON(pages[i]->mapping);
702 static void free_async_extent_pages(struct async_extent *async_extent)
706 if (!async_extent->pages)
709 for (i = 0; i < async_extent->nr_pages; i++) {
710 WARN_ON(async_extent->pages[i]->mapping);
711 put_page(async_extent->pages[i]);
713 kfree(async_extent->pages);
714 async_extent->nr_pages = 0;
715 async_extent->pages = NULL;
719 * phase two of compressed writeback. This is the ordered portion
720 * of the code, which only gets called in the order the work was
721 * queued. We walk all the async extents created by compress_file_range
722 * and send them down to the disk.
724 static noinline void submit_compressed_extents(struct inode *inode,
725 struct async_cow *async_cow)
727 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
728 struct async_extent *async_extent;
730 struct btrfs_key ins;
731 struct extent_map *em;
732 struct btrfs_root *root = BTRFS_I(inode)->root;
733 struct extent_io_tree *io_tree;
737 while (!list_empty(&async_cow->extents)) {
738 async_extent = list_entry(async_cow->extents.next,
739 struct async_extent, list);
740 list_del(&async_extent->list);
742 io_tree = &BTRFS_I(inode)->io_tree;
745 /* did the compression code fall back to uncompressed IO? */
746 if (!async_extent->pages) {
747 int page_started = 0;
748 unsigned long nr_written = 0;
750 lock_extent(io_tree, async_extent->start,
751 async_extent->start +
752 async_extent->ram_size - 1);
754 /* allocate blocks */
755 ret = cow_file_range(inode, async_cow->locked_page,
757 async_extent->start +
758 async_extent->ram_size - 1,
759 async_extent->start +
760 async_extent->ram_size - 1,
761 &page_started, &nr_written, 0,
767 * if page_started, cow_file_range inserted an
768 * inline extent and took care of all the unlocking
769 * and IO for us. Otherwise, we need to submit
770 * all those pages down to the drive.
772 if (!page_started && !ret)
773 extent_write_locked_range(inode,
775 async_extent->start +
776 async_extent->ram_size - 1,
779 unlock_page(async_cow->locked_page);
785 lock_extent(io_tree, async_extent->start,
786 async_extent->start + async_extent->ram_size - 1);
788 ret = btrfs_reserve_extent(root, async_extent->ram_size,
789 async_extent->compressed_size,
790 async_extent->compressed_size,
791 0, alloc_hint, &ins, 1, 1);
793 free_async_extent_pages(async_extent);
795 if (ret == -ENOSPC) {
796 unlock_extent(io_tree, async_extent->start,
797 async_extent->start +
798 async_extent->ram_size - 1);
801 * we need to redirty the pages if we decide to
802 * fallback to uncompressed IO, otherwise we
803 * will not submit these pages down to lower
806 extent_range_redirty_for_io(inode,
808 async_extent->start +
809 async_extent->ram_size - 1);
816 * here we're doing allocation and writeback of the
819 em = create_io_em(inode, async_extent->start,
820 async_extent->ram_size, /* len */
821 async_extent->start, /* orig_start */
822 ins.objectid, /* block_start */
823 ins.offset, /* block_len */
824 ins.offset, /* orig_block_len */
825 async_extent->ram_size, /* ram_bytes */
826 async_extent->compress_type,
827 BTRFS_ORDERED_COMPRESSED);
829 /* ret value is not necessary due to void function */
830 goto out_free_reserve;
833 ret = btrfs_add_ordered_extent_compress(inode,
836 async_extent->ram_size,
838 BTRFS_ORDERED_COMPRESSED,
839 async_extent->compress_type);
841 btrfs_drop_extent_cache(BTRFS_I(inode),
843 async_extent->start +
844 async_extent->ram_size - 1, 0);
845 goto out_free_reserve;
847 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
850 * clear dirty, set writeback and unlock the pages.
852 extent_clear_unlock_delalloc(inode, async_extent->start,
853 async_extent->start +
854 async_extent->ram_size - 1,
855 async_extent->start +
856 async_extent->ram_size - 1,
857 NULL, EXTENT_LOCKED | EXTENT_DELALLOC,
858 PAGE_UNLOCK | PAGE_CLEAR_DIRTY |
860 if (btrfs_submit_compressed_write(inode,
862 async_extent->ram_size,
864 ins.offset, async_extent->pages,
865 async_extent->nr_pages,
866 async_cow->write_flags)) {
867 struct extent_io_tree *tree = &BTRFS_I(inode)->io_tree;
868 struct page *p = async_extent->pages[0];
869 const u64 start = async_extent->start;
870 const u64 end = start + async_extent->ram_size - 1;
872 p->mapping = inode->i_mapping;
873 tree->ops->writepage_end_io_hook(p, start, end,
876 extent_clear_unlock_delalloc(inode, start, end, end,
880 free_async_extent_pages(async_extent);
882 alloc_hint = ins.objectid + ins.offset;
888 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
889 btrfs_free_reserved_extent(fs_info, ins.objectid, ins.offset, 1);
891 extent_clear_unlock_delalloc(inode, async_extent->start,
892 async_extent->start +
893 async_extent->ram_size - 1,
894 async_extent->start +
895 async_extent->ram_size - 1,
896 NULL, EXTENT_LOCKED | EXTENT_DELALLOC |
897 EXTENT_DELALLOC_NEW |
898 EXTENT_DEFRAG | EXTENT_DO_ACCOUNTING,
899 PAGE_UNLOCK | PAGE_CLEAR_DIRTY |
900 PAGE_SET_WRITEBACK | PAGE_END_WRITEBACK |
902 free_async_extent_pages(async_extent);
907 static u64 get_extent_allocation_hint(struct inode *inode, u64 start,
910 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
911 struct extent_map *em;
914 read_lock(&em_tree->lock);
915 em = search_extent_mapping(em_tree, start, num_bytes);
918 * if block start isn't an actual block number then find the
919 * first block in this inode and use that as a hint. If that
920 * block is also bogus then just don't worry about it.
922 if (em->block_start >= EXTENT_MAP_LAST_BYTE) {
924 em = search_extent_mapping(em_tree, 0, 0);
925 if (em && em->block_start < EXTENT_MAP_LAST_BYTE)
926 alloc_hint = em->block_start;
930 alloc_hint = em->block_start;
934 read_unlock(&em_tree->lock);
940 * when extent_io.c finds a delayed allocation range in the file,
941 * the call backs end up in this code. The basic idea is to
942 * allocate extents on disk for the range, and create ordered data structs
943 * in ram to track those extents.
945 * locked_page is the page that writepage had locked already. We use
946 * it to make sure we don't do extra locks or unlocks.
948 * *page_started is set to one if we unlock locked_page and do everything
949 * required to start IO on it. It may be clean and already done with
952 static noinline int cow_file_range(struct inode *inode,
953 struct page *locked_page,
954 u64 start, u64 end, u64 delalloc_end,
955 int *page_started, unsigned long *nr_written,
956 int unlock, struct btrfs_dedupe_hash *hash)
958 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
959 struct btrfs_root *root = BTRFS_I(inode)->root;
962 unsigned long ram_size;
964 u64 cur_alloc_size = 0;
965 u64 blocksize = fs_info->sectorsize;
966 struct btrfs_key ins;
967 struct extent_map *em;
969 unsigned long page_ops;
970 bool extent_reserved = false;
973 if (btrfs_is_free_space_inode(BTRFS_I(inode))) {
979 num_bytes = ALIGN(end - start + 1, blocksize);
980 num_bytes = max(blocksize, num_bytes);
981 disk_num_bytes = num_bytes;
983 inode_should_defrag(BTRFS_I(inode), start, end, num_bytes, SZ_64K);
986 /* lets try to make an inline extent */
987 ret = cow_file_range_inline(root, inode, start, end, 0,
988 BTRFS_COMPRESS_NONE, NULL);
991 * We use DO_ACCOUNTING here because we need the
992 * delalloc_release_metadata to be run _after_ we drop
993 * our outstanding extent for clearing delalloc for this
996 extent_clear_unlock_delalloc(inode, start, end,
998 EXTENT_LOCKED | EXTENT_DELALLOC |
999 EXTENT_DELALLOC_NEW | EXTENT_DEFRAG |
1000 EXTENT_DO_ACCOUNTING, PAGE_UNLOCK |
1001 PAGE_CLEAR_DIRTY | PAGE_SET_WRITEBACK |
1002 PAGE_END_WRITEBACK);
1003 *nr_written = *nr_written +
1004 (end - start + PAGE_SIZE) / PAGE_SIZE;
1007 } else if (ret < 0) {
1012 BUG_ON(disk_num_bytes >
1013 btrfs_super_total_bytes(fs_info->super_copy));
1015 alloc_hint = get_extent_allocation_hint(inode, start, num_bytes);
1016 btrfs_drop_extent_cache(BTRFS_I(inode), start,
1017 start + num_bytes - 1, 0);
1019 while (disk_num_bytes > 0) {
1020 cur_alloc_size = disk_num_bytes;
1021 ret = btrfs_reserve_extent(root, cur_alloc_size, cur_alloc_size,
1022 fs_info->sectorsize, 0, alloc_hint,
1026 cur_alloc_size = ins.offset;
1027 extent_reserved = true;
1029 ram_size = ins.offset;
1030 em = create_io_em(inode, start, ins.offset, /* len */
1031 start, /* orig_start */
1032 ins.objectid, /* block_start */
1033 ins.offset, /* block_len */
1034 ins.offset, /* orig_block_len */
1035 ram_size, /* ram_bytes */
1036 BTRFS_COMPRESS_NONE, /* compress_type */
1037 BTRFS_ORDERED_REGULAR /* type */);
1040 free_extent_map(em);
1042 ret = btrfs_add_ordered_extent(inode, start, ins.objectid,
1043 ram_size, cur_alloc_size, 0);
1045 goto out_drop_extent_cache;
1047 if (root->root_key.objectid ==
1048 BTRFS_DATA_RELOC_TREE_OBJECTID) {
1049 ret = btrfs_reloc_clone_csums(inode, start,
1052 * Only drop cache here, and process as normal.
1054 * We must not allow extent_clear_unlock_delalloc()
1055 * at out_unlock label to free meta of this ordered
1056 * extent, as its meta should be freed by
1057 * btrfs_finish_ordered_io().
1059 * So we must continue until @start is increased to
1060 * skip current ordered extent.
1063 btrfs_drop_extent_cache(BTRFS_I(inode), start,
1064 start + ram_size - 1, 0);
1067 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
1069 /* we're not doing compressed IO, don't unlock the first
1070 * page (which the caller expects to stay locked), don't
1071 * clear any dirty bits and don't set any writeback bits
1073 * Do set the Private2 bit so we know this page was properly
1074 * setup for writepage
1076 page_ops = unlock ? PAGE_UNLOCK : 0;
1077 page_ops |= PAGE_SET_PRIVATE2;
1079 extent_clear_unlock_delalloc(inode, start,
1080 start + ram_size - 1,
1081 delalloc_end, locked_page,
1082 EXTENT_LOCKED | EXTENT_DELALLOC,
1084 if (disk_num_bytes < cur_alloc_size)
1087 disk_num_bytes -= cur_alloc_size;
1088 num_bytes -= cur_alloc_size;
1089 alloc_hint = ins.objectid + ins.offset;
1090 start += cur_alloc_size;
1091 extent_reserved = false;
1094 * btrfs_reloc_clone_csums() error, since start is increased
1095 * extent_clear_unlock_delalloc() at out_unlock label won't
1096 * free metadata of current ordered extent, we're OK to exit.
1104 out_drop_extent_cache:
1105 btrfs_drop_extent_cache(BTRFS_I(inode), start, start + ram_size - 1, 0);
1107 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
1108 btrfs_free_reserved_extent(fs_info, ins.objectid, ins.offset, 1);
1110 clear_bits = EXTENT_LOCKED | EXTENT_DELALLOC | EXTENT_DELALLOC_NEW |
1111 EXTENT_DEFRAG | EXTENT_CLEAR_META_RESV;
1112 page_ops = PAGE_UNLOCK | PAGE_CLEAR_DIRTY | PAGE_SET_WRITEBACK |
1115 * If we reserved an extent for our delalloc range (or a subrange) and
1116 * failed to create the respective ordered extent, then it means that
1117 * when we reserved the extent we decremented the extent's size from
1118 * the data space_info's bytes_may_use counter and incremented the
1119 * space_info's bytes_reserved counter by the same amount. We must make
1120 * sure extent_clear_unlock_delalloc() does not try to decrement again
1121 * the data space_info's bytes_may_use counter, therefore we do not pass
1122 * it the flag EXTENT_CLEAR_DATA_RESV.
1124 if (extent_reserved) {
1125 extent_clear_unlock_delalloc(inode, start,
1126 start + cur_alloc_size,
1127 start + cur_alloc_size,
1131 start += cur_alloc_size;
1135 extent_clear_unlock_delalloc(inode, start, end, delalloc_end,
1137 clear_bits | EXTENT_CLEAR_DATA_RESV,
1143 * work queue call back to started compression on a file and pages
1145 static noinline void async_cow_start(struct btrfs_work *work)
1147 struct async_cow *async_cow;
1149 async_cow = container_of(work, struct async_cow, work);
1151 compress_file_range(async_cow->inode, async_cow->locked_page,
1152 async_cow->start, async_cow->end, async_cow,
1154 if (num_added == 0) {
1155 btrfs_add_delayed_iput(async_cow->inode);
1156 async_cow->inode = NULL;
1161 * work queue call back to submit previously compressed pages
1163 static noinline void async_cow_submit(struct btrfs_work *work)
1165 struct btrfs_fs_info *fs_info;
1166 struct async_cow *async_cow;
1167 struct btrfs_root *root;
1168 unsigned long nr_pages;
1170 async_cow = container_of(work, struct async_cow, work);
1172 root = async_cow->root;
1173 fs_info = root->fs_info;
1174 nr_pages = (async_cow->end - async_cow->start + PAGE_SIZE) >>
1178 * atomic_sub_return implies a barrier for waitqueue_active
1180 if (atomic_sub_return(nr_pages, &fs_info->async_delalloc_pages) <
1182 waitqueue_active(&fs_info->async_submit_wait))
1183 wake_up(&fs_info->async_submit_wait);
1185 if (async_cow->inode)
1186 submit_compressed_extents(async_cow->inode, async_cow);
1189 static noinline void async_cow_free(struct btrfs_work *work)
1191 struct async_cow *async_cow;
1192 async_cow = container_of(work, struct async_cow, work);
1193 if (async_cow->inode)
1194 btrfs_add_delayed_iput(async_cow->inode);
1198 static int cow_file_range_async(struct inode *inode, struct page *locked_page,
1199 u64 start, u64 end, int *page_started,
1200 unsigned long *nr_written,
1201 unsigned int write_flags)
1203 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1204 struct async_cow *async_cow;
1205 struct btrfs_root *root = BTRFS_I(inode)->root;
1206 unsigned long nr_pages;
1209 clear_extent_bit(&BTRFS_I(inode)->io_tree, start, end, EXTENT_LOCKED,
1211 while (start < end) {
1212 async_cow = kmalloc(sizeof(*async_cow), GFP_NOFS);
1213 BUG_ON(!async_cow); /* -ENOMEM */
1214 async_cow->inode = igrab(inode);
1215 async_cow->root = root;
1216 async_cow->locked_page = locked_page;
1217 async_cow->start = start;
1218 async_cow->write_flags = write_flags;
1220 if (BTRFS_I(inode)->flags & BTRFS_INODE_NOCOMPRESS &&
1221 !btrfs_test_opt(fs_info, FORCE_COMPRESS))
1224 cur_end = min(end, start + SZ_512K - 1);
1226 async_cow->end = cur_end;
1227 INIT_LIST_HEAD(&async_cow->extents);
1229 btrfs_init_work(&async_cow->work,
1230 btrfs_delalloc_helper,
1231 async_cow_start, async_cow_submit,
1234 nr_pages = (cur_end - start + PAGE_SIZE) >>
1236 atomic_add(nr_pages, &fs_info->async_delalloc_pages);
1238 btrfs_queue_work(fs_info->delalloc_workers, &async_cow->work);
1240 *nr_written += nr_pages;
1241 start = cur_end + 1;
1247 static noinline int csum_exist_in_range(struct btrfs_fs_info *fs_info,
1248 u64 bytenr, u64 num_bytes)
1251 struct btrfs_ordered_sum *sums;
1254 ret = btrfs_lookup_csums_range(fs_info->csum_root, bytenr,
1255 bytenr + num_bytes - 1, &list, 0);
1256 if (ret == 0 && list_empty(&list))
1259 while (!list_empty(&list)) {
1260 sums = list_entry(list.next, struct btrfs_ordered_sum, list);
1261 list_del(&sums->list);
1268 * when nowcow writeback call back. This checks for snapshots or COW copies
1269 * of the extents that exist in the file, and COWs the file as required.
1271 * If no cow copies or snapshots exist, we write directly to the existing
1274 static noinline int run_delalloc_nocow(struct inode *inode,
1275 struct page *locked_page,
1276 u64 start, u64 end, int *page_started, int force,
1277 unsigned long *nr_written)
1279 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1280 struct btrfs_root *root = BTRFS_I(inode)->root;
1281 struct extent_buffer *leaf;
1282 struct btrfs_path *path;
1283 struct btrfs_file_extent_item *fi;
1284 struct btrfs_key found_key;
1285 struct extent_map *em;
1300 u64 ino = btrfs_ino(BTRFS_I(inode));
1302 path = btrfs_alloc_path();
1304 extent_clear_unlock_delalloc(inode, start, end, end,
1306 EXTENT_LOCKED | EXTENT_DELALLOC |
1307 EXTENT_DO_ACCOUNTING |
1308 EXTENT_DEFRAG, PAGE_UNLOCK |
1310 PAGE_SET_WRITEBACK |
1311 PAGE_END_WRITEBACK);
1315 nolock = btrfs_is_free_space_inode(BTRFS_I(inode));
1317 cow_start = (u64)-1;
1320 ret = btrfs_lookup_file_extent(NULL, root, path, ino,
1324 if (ret > 0 && path->slots[0] > 0 && check_prev) {
1325 leaf = path->nodes[0];
1326 btrfs_item_key_to_cpu(leaf, &found_key,
1327 path->slots[0] - 1);
1328 if (found_key.objectid == ino &&
1329 found_key.type == BTRFS_EXTENT_DATA_KEY)
1334 leaf = path->nodes[0];
1335 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
1336 ret = btrfs_next_leaf(root, path);
1341 leaf = path->nodes[0];
1347 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
1349 if (found_key.objectid > ino)
1351 if (WARN_ON_ONCE(found_key.objectid < ino) ||
1352 found_key.type < BTRFS_EXTENT_DATA_KEY) {
1356 if (found_key.type > BTRFS_EXTENT_DATA_KEY ||
1357 found_key.offset > end)
1360 if (found_key.offset > cur_offset) {
1361 extent_end = found_key.offset;
1366 fi = btrfs_item_ptr(leaf, path->slots[0],
1367 struct btrfs_file_extent_item);
1368 extent_type = btrfs_file_extent_type(leaf, fi);
1370 ram_bytes = btrfs_file_extent_ram_bytes(leaf, fi);
1371 if (extent_type == BTRFS_FILE_EXTENT_REG ||
1372 extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
1373 disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
1374 extent_offset = btrfs_file_extent_offset(leaf, fi);
1375 extent_end = found_key.offset +
1376 btrfs_file_extent_num_bytes(leaf, fi);
1378 btrfs_file_extent_disk_num_bytes(leaf, fi);
1379 if (extent_end <= start) {
1383 if (disk_bytenr == 0)
1385 if (btrfs_file_extent_compression(leaf, fi) ||
1386 btrfs_file_extent_encryption(leaf, fi) ||
1387 btrfs_file_extent_other_encoding(leaf, fi))
1389 if (extent_type == BTRFS_FILE_EXTENT_REG && !force)
1391 if (btrfs_extent_readonly(fs_info, disk_bytenr))
1393 if (btrfs_cross_ref_exist(root, ino,
1395 extent_offset, disk_bytenr))
1397 disk_bytenr += extent_offset;
1398 disk_bytenr += cur_offset - found_key.offset;
1399 num_bytes = min(end + 1, extent_end) - cur_offset;
1401 * if there are pending snapshots for this root,
1402 * we fall into common COW way.
1405 err = btrfs_start_write_no_snapshotting(root);
1410 * force cow if csum exists in the range.
1411 * this ensure that csum for a given extent are
1412 * either valid or do not exist.
1414 if (csum_exist_in_range(fs_info, disk_bytenr,
1417 btrfs_end_write_no_snapshotting(root);
1420 if (!btrfs_inc_nocow_writers(fs_info, disk_bytenr)) {
1422 btrfs_end_write_no_snapshotting(root);
1426 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
1427 extent_end = found_key.offset +
1428 btrfs_file_extent_inline_len(leaf,
1429 path->slots[0], fi);
1430 extent_end = ALIGN(extent_end,
1431 fs_info->sectorsize);
1436 if (extent_end <= start) {
1438 if (!nolock && nocow)
1439 btrfs_end_write_no_snapshotting(root);
1441 btrfs_dec_nocow_writers(fs_info, disk_bytenr);
1445 if (cow_start == (u64)-1)
1446 cow_start = cur_offset;
1447 cur_offset = extent_end;
1448 if (cur_offset > end)
1454 btrfs_release_path(path);
1455 if (cow_start != (u64)-1) {
1456 ret = cow_file_range(inode, locked_page,
1457 cow_start, found_key.offset - 1,
1458 end, page_started, nr_written, 1,
1461 if (!nolock && nocow)
1462 btrfs_end_write_no_snapshotting(root);
1464 btrfs_dec_nocow_writers(fs_info,
1468 cow_start = (u64)-1;
1471 if (extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
1472 u64 orig_start = found_key.offset - extent_offset;
1474 em = create_io_em(inode, cur_offset, num_bytes,
1476 disk_bytenr, /* block_start */
1477 num_bytes, /* block_len */
1478 disk_num_bytes, /* orig_block_len */
1479 ram_bytes, BTRFS_COMPRESS_NONE,
1480 BTRFS_ORDERED_PREALLOC);
1482 if (!nolock && nocow)
1483 btrfs_end_write_no_snapshotting(root);
1485 btrfs_dec_nocow_writers(fs_info,
1490 free_extent_map(em);
1493 if (extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
1494 type = BTRFS_ORDERED_PREALLOC;
1496 type = BTRFS_ORDERED_NOCOW;
1499 ret = btrfs_add_ordered_extent(inode, cur_offset, disk_bytenr,
1500 num_bytes, num_bytes, type);
1502 btrfs_dec_nocow_writers(fs_info, disk_bytenr);
1503 BUG_ON(ret); /* -ENOMEM */
1505 if (root->root_key.objectid ==
1506 BTRFS_DATA_RELOC_TREE_OBJECTID)
1508 * Error handled later, as we must prevent
1509 * extent_clear_unlock_delalloc() in error handler
1510 * from freeing metadata of created ordered extent.
1512 ret = btrfs_reloc_clone_csums(inode, cur_offset,
1515 extent_clear_unlock_delalloc(inode, cur_offset,
1516 cur_offset + num_bytes - 1, end,
1517 locked_page, EXTENT_LOCKED |
1519 EXTENT_CLEAR_DATA_RESV,
1520 PAGE_UNLOCK | PAGE_SET_PRIVATE2);
1522 if (!nolock && nocow)
1523 btrfs_end_write_no_snapshotting(root);
1524 cur_offset = extent_end;
1527 * btrfs_reloc_clone_csums() error, now we're OK to call error
1528 * handler, as metadata for created ordered extent will only
1529 * be freed by btrfs_finish_ordered_io().
1533 if (cur_offset > end)
1536 btrfs_release_path(path);
1538 if (cur_offset <= end && cow_start == (u64)-1) {
1539 cow_start = cur_offset;
1543 if (cow_start != (u64)-1) {
1544 ret = cow_file_range(inode, locked_page, cow_start, end, end,
1545 page_started, nr_written, 1, NULL);
1551 if (ret && cur_offset < end)
1552 extent_clear_unlock_delalloc(inode, cur_offset, end, end,
1553 locked_page, EXTENT_LOCKED |
1554 EXTENT_DELALLOC | EXTENT_DEFRAG |
1555 EXTENT_DO_ACCOUNTING, PAGE_UNLOCK |
1557 PAGE_SET_WRITEBACK |
1558 PAGE_END_WRITEBACK);
1559 btrfs_free_path(path);
1563 static inline int need_force_cow(struct inode *inode, u64 start, u64 end)
1566 if (!(BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW) &&
1567 !(BTRFS_I(inode)->flags & BTRFS_INODE_PREALLOC))
1571 * @defrag_bytes is a hint value, no spinlock held here,
1572 * if is not zero, it means the file is defragging.
1573 * Force cow if given extent needs to be defragged.
1575 if (BTRFS_I(inode)->defrag_bytes &&
1576 test_range_bit(&BTRFS_I(inode)->io_tree, start, end,
1577 EXTENT_DEFRAG, 0, NULL))
1584 * extent_io.c call back to do delayed allocation processing
1586 static int run_delalloc_range(void *private_data, struct page *locked_page,
1587 u64 start, u64 end, int *page_started,
1588 unsigned long *nr_written,
1589 struct writeback_control *wbc)
1591 struct inode *inode = private_data;
1593 int force_cow = need_force_cow(inode, start, end);
1594 unsigned int write_flags = wbc_to_write_flags(wbc);
1596 if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW && !force_cow) {
1597 ret = run_delalloc_nocow(inode, locked_page, start, end,
1598 page_started, 1, nr_written);
1599 } else if (BTRFS_I(inode)->flags & BTRFS_INODE_PREALLOC && !force_cow) {
1600 ret = run_delalloc_nocow(inode, locked_page, start, end,
1601 page_started, 0, nr_written);
1602 } else if (!inode_need_compress(inode, start, end)) {
1603 ret = cow_file_range(inode, locked_page, start, end, end,
1604 page_started, nr_written, 1, NULL);
1606 set_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
1607 &BTRFS_I(inode)->runtime_flags);
1608 ret = cow_file_range_async(inode, locked_page, start, end,
1609 page_started, nr_written,
1613 btrfs_cleanup_ordered_extents(inode, start, end - start + 1);
1617 static void btrfs_split_extent_hook(void *private_data,
1618 struct extent_state *orig, u64 split)
1620 struct inode *inode = private_data;
1623 /* not delalloc, ignore it */
1624 if (!(orig->state & EXTENT_DELALLOC))
1627 size = orig->end - orig->start + 1;
1628 if (size > BTRFS_MAX_EXTENT_SIZE) {
1633 * See the explanation in btrfs_merge_extent_hook, the same
1634 * applies here, just in reverse.
1636 new_size = orig->end - split + 1;
1637 num_extents = count_max_extents(new_size);
1638 new_size = split - orig->start;
1639 num_extents += count_max_extents(new_size);
1640 if (count_max_extents(size) >= num_extents)
1644 spin_lock(&BTRFS_I(inode)->lock);
1645 btrfs_mod_outstanding_extents(BTRFS_I(inode), 1);
1646 spin_unlock(&BTRFS_I(inode)->lock);
1650 * extent_io.c merge_extent_hook, used to track merged delayed allocation
1651 * extents so we can keep track of new extents that are just merged onto old
1652 * extents, such as when we are doing sequential writes, so we can properly
1653 * account for the metadata space we'll need.
1655 static void btrfs_merge_extent_hook(void *private_data,
1656 struct extent_state *new,
1657 struct extent_state *other)
1659 struct inode *inode = private_data;
1660 u64 new_size, old_size;
1663 /* not delalloc, ignore it */
1664 if (!(other->state & EXTENT_DELALLOC))
1667 if (new->start > other->start)
1668 new_size = new->end - other->start + 1;
1670 new_size = other->end - new->start + 1;
1672 /* we're not bigger than the max, unreserve the space and go */
1673 if (new_size <= BTRFS_MAX_EXTENT_SIZE) {
1674 spin_lock(&BTRFS_I(inode)->lock);
1675 btrfs_mod_outstanding_extents(BTRFS_I(inode), -1);
1676 spin_unlock(&BTRFS_I(inode)->lock);
1681 * We have to add up either side to figure out how many extents were
1682 * accounted for before we merged into one big extent. If the number of
1683 * extents we accounted for is <= the amount we need for the new range
1684 * then we can return, otherwise drop. Think of it like this
1688 * So we've grown the extent by a MAX_SIZE extent, this would mean we
1689 * need 2 outstanding extents, on one side we have 1 and the other side
1690 * we have 1 so they are == and we can return. But in this case
1692 * [MAX_SIZE+4k][MAX_SIZE+4k]
1694 * Each range on their own accounts for 2 extents, but merged together
1695 * they are only 3 extents worth of accounting, so we need to drop in
1698 old_size = other->end - other->start + 1;
1699 num_extents = count_max_extents(old_size);
1700 old_size = new->end - new->start + 1;
1701 num_extents += count_max_extents(old_size);
1702 if (count_max_extents(new_size) >= num_extents)
1705 spin_lock(&BTRFS_I(inode)->lock);
1706 btrfs_mod_outstanding_extents(BTRFS_I(inode), -1);
1707 spin_unlock(&BTRFS_I(inode)->lock);
1710 static void btrfs_add_delalloc_inodes(struct btrfs_root *root,
1711 struct inode *inode)
1713 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1715 spin_lock(&root->delalloc_lock);
1716 if (list_empty(&BTRFS_I(inode)->delalloc_inodes)) {
1717 list_add_tail(&BTRFS_I(inode)->delalloc_inodes,
1718 &root->delalloc_inodes);
1719 set_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1720 &BTRFS_I(inode)->runtime_flags);
1721 root->nr_delalloc_inodes++;
1722 if (root->nr_delalloc_inodes == 1) {
1723 spin_lock(&fs_info->delalloc_root_lock);
1724 BUG_ON(!list_empty(&root->delalloc_root));
1725 list_add_tail(&root->delalloc_root,
1726 &fs_info->delalloc_roots);
1727 spin_unlock(&fs_info->delalloc_root_lock);
1730 spin_unlock(&root->delalloc_lock);
1733 static void btrfs_del_delalloc_inode(struct btrfs_root *root,
1734 struct btrfs_inode *inode)
1736 struct btrfs_fs_info *fs_info = btrfs_sb(inode->vfs_inode.i_sb);
1738 spin_lock(&root->delalloc_lock);
1739 if (!list_empty(&inode->delalloc_inodes)) {
1740 list_del_init(&inode->delalloc_inodes);
1741 clear_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1742 &inode->runtime_flags);
1743 root->nr_delalloc_inodes--;
1744 if (!root->nr_delalloc_inodes) {
1745 spin_lock(&fs_info->delalloc_root_lock);
1746 BUG_ON(list_empty(&root->delalloc_root));
1747 list_del_init(&root->delalloc_root);
1748 spin_unlock(&fs_info->delalloc_root_lock);
1751 spin_unlock(&root->delalloc_lock);
1755 * extent_io.c set_bit_hook, used to track delayed allocation
1756 * bytes in this file, and to maintain the list of inodes that
1757 * have pending delalloc work to be done.
1759 static void btrfs_set_bit_hook(void *private_data,
1760 struct extent_state *state, unsigned *bits)
1762 struct inode *inode = private_data;
1764 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1766 if ((*bits & EXTENT_DEFRAG) && !(*bits & EXTENT_DELALLOC))
1769 * set_bit and clear bit hooks normally require _irqsave/restore
1770 * but in this case, we are only testing for the DELALLOC
1771 * bit, which is only set or cleared with irqs on
1773 if (!(state->state & EXTENT_DELALLOC) && (*bits & EXTENT_DELALLOC)) {
1774 struct btrfs_root *root = BTRFS_I(inode)->root;
1775 u64 len = state->end + 1 - state->start;
1776 u32 num_extents = count_max_extents(len);
1777 bool do_list = !btrfs_is_free_space_inode(BTRFS_I(inode));
1779 spin_lock(&BTRFS_I(inode)->lock);
1780 btrfs_mod_outstanding_extents(BTRFS_I(inode), num_extents);
1781 spin_unlock(&BTRFS_I(inode)->lock);
1783 /* For sanity tests */
1784 if (btrfs_is_testing(fs_info))
1787 percpu_counter_add_batch(&fs_info->delalloc_bytes, len,
1788 fs_info->delalloc_batch);
1789 spin_lock(&BTRFS_I(inode)->lock);
1790 BTRFS_I(inode)->delalloc_bytes += len;
1791 if (*bits & EXTENT_DEFRAG)
1792 BTRFS_I(inode)->defrag_bytes += len;
1793 if (do_list && !test_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1794 &BTRFS_I(inode)->runtime_flags))
1795 btrfs_add_delalloc_inodes(root, inode);
1796 spin_unlock(&BTRFS_I(inode)->lock);
1799 if (!(state->state & EXTENT_DELALLOC_NEW) &&
1800 (*bits & EXTENT_DELALLOC_NEW)) {
1801 spin_lock(&BTRFS_I(inode)->lock);
1802 BTRFS_I(inode)->new_delalloc_bytes += state->end + 1 -
1804 spin_unlock(&BTRFS_I(inode)->lock);
1809 * extent_io.c clear_bit_hook, see set_bit_hook for why
1811 static void btrfs_clear_bit_hook(void *private_data,
1812 struct extent_state *state,
1815 struct btrfs_inode *inode = BTRFS_I((struct inode *)private_data);
1816 struct btrfs_fs_info *fs_info = btrfs_sb(inode->vfs_inode.i_sb);
1817 u64 len = state->end + 1 - state->start;
1818 u32 num_extents = count_max_extents(len);
1820 if ((state->state & EXTENT_DEFRAG) && (*bits & EXTENT_DEFRAG)) {
1821 spin_lock(&inode->lock);
1822 inode->defrag_bytes -= len;
1823 spin_unlock(&inode->lock);
1827 * set_bit and clear bit hooks normally require _irqsave/restore
1828 * but in this case, we are only testing for the DELALLOC
1829 * bit, which is only set or cleared with irqs on
1831 if ((state->state & EXTENT_DELALLOC) && (*bits & EXTENT_DELALLOC)) {
1832 struct btrfs_root *root = inode->root;
1833 bool do_list = !btrfs_is_free_space_inode(inode);
1835 spin_lock(&inode->lock);
1836 btrfs_mod_outstanding_extents(inode, -num_extents);
1837 spin_unlock(&inode->lock);
1840 * We don't reserve metadata space for space cache inodes so we
1841 * don't need to call dellalloc_release_metadata if there is an
1844 if (*bits & EXTENT_CLEAR_META_RESV &&
1845 root != fs_info->tree_root)
1846 btrfs_delalloc_release_metadata(inode, len);
1848 /* For sanity tests. */
1849 if (btrfs_is_testing(fs_info))
1852 if (root->root_key.objectid != BTRFS_DATA_RELOC_TREE_OBJECTID &&
1853 do_list && !(state->state & EXTENT_NORESERVE) &&
1854 (*bits & EXTENT_CLEAR_DATA_RESV))
1855 btrfs_free_reserved_data_space_noquota(
1859 percpu_counter_add_batch(&fs_info->delalloc_bytes, -len,
1860 fs_info->delalloc_batch);
1861 spin_lock(&inode->lock);
1862 inode->delalloc_bytes -= len;
1863 if (do_list && inode->delalloc_bytes == 0 &&
1864 test_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1865 &inode->runtime_flags))
1866 btrfs_del_delalloc_inode(root, inode);
1867 spin_unlock(&inode->lock);
1870 if ((state->state & EXTENT_DELALLOC_NEW) &&
1871 (*bits & EXTENT_DELALLOC_NEW)) {
1872 spin_lock(&inode->lock);
1873 ASSERT(inode->new_delalloc_bytes >= len);
1874 inode->new_delalloc_bytes -= len;
1875 spin_unlock(&inode->lock);
1880 * extent_io.c merge_bio_hook, this must check the chunk tree to make sure
1881 * we don't create bios that span stripes or chunks
1883 * return 1 if page cannot be merged to bio
1884 * return 0 if page can be merged to bio
1885 * return error otherwise
1887 int btrfs_merge_bio_hook(struct page *page, unsigned long offset,
1888 size_t size, struct bio *bio,
1889 unsigned long bio_flags)
1891 struct inode *inode = page->mapping->host;
1892 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1893 u64 logical = (u64)bio->bi_iter.bi_sector << 9;
1898 if (bio_flags & EXTENT_BIO_COMPRESSED)
1901 length = bio->bi_iter.bi_size;
1902 map_length = length;
1903 ret = btrfs_map_block(fs_info, btrfs_op(bio), logical, &map_length,
1907 if (map_length < length + size)
1913 * in order to insert checksums into the metadata in large chunks,
1914 * we wait until bio submission time. All the pages in the bio are
1915 * checksummed and sums are attached onto the ordered extent record.
1917 * At IO completion time the cums attached on the ordered extent record
1918 * are inserted into the btree
1920 static blk_status_t __btrfs_submit_bio_start(void *private_data, struct bio *bio,
1921 int mirror_num, unsigned long bio_flags,
1924 struct inode *inode = private_data;
1925 blk_status_t ret = 0;
1927 ret = btrfs_csum_one_bio(inode, bio, 0, 0);
1928 BUG_ON(ret); /* -ENOMEM */
1933 * in order to insert checksums into the metadata in large chunks,
1934 * we wait until bio submission time. All the pages in the bio are
1935 * checksummed and sums are attached onto the ordered extent record.
1937 * At IO completion time the cums attached on the ordered extent record
1938 * are inserted into the btree
1940 static blk_status_t __btrfs_submit_bio_done(void *private_data, struct bio *bio,
1941 int mirror_num, unsigned long bio_flags,
1944 struct inode *inode = private_data;
1945 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1948 ret = btrfs_map_bio(fs_info, bio, mirror_num, 1);
1950 bio->bi_status = ret;
1957 * extent_io.c submission hook. This does the right thing for csum calculation
1958 * on write, or reading the csums from the tree before a read.
1960 * Rules about async/sync submit,
1961 * a) read: sync submit
1963 * b) write without checksum: sync submit
1965 * c) write with checksum:
1966 * c-1) if bio is issued by fsync: sync submit
1967 * (sync_writers != 0)
1969 * c-2) if root is reloc root: sync submit
1970 * (only in case of buffered IO)
1972 * c-3) otherwise: async submit
1974 static blk_status_t btrfs_submit_bio_hook(void *private_data, struct bio *bio,
1975 int mirror_num, unsigned long bio_flags,
1978 struct inode *inode = private_data;
1979 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1980 struct btrfs_root *root = BTRFS_I(inode)->root;
1981 enum btrfs_wq_endio_type metadata = BTRFS_WQ_ENDIO_DATA;
1982 blk_status_t ret = 0;
1984 int async = !atomic_read(&BTRFS_I(inode)->sync_writers);
1986 skip_sum = BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM;
1988 if (btrfs_is_free_space_inode(BTRFS_I(inode)))
1989 metadata = BTRFS_WQ_ENDIO_FREE_SPACE;
1991 if (bio_op(bio) != REQ_OP_WRITE) {
1992 ret = btrfs_bio_wq_end_io(fs_info, bio, metadata);
1996 if (bio_flags & EXTENT_BIO_COMPRESSED) {
1997 ret = btrfs_submit_compressed_read(inode, bio,
2001 } else if (!skip_sum) {
2002 ret = btrfs_lookup_bio_sums(inode, bio, NULL);
2007 } else if (async && !skip_sum) {
2008 /* csum items have already been cloned */
2009 if (root->root_key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID)
2011 /* we're doing a write, do the async checksumming */
2012 ret = btrfs_wq_submit_bio(fs_info, bio, mirror_num, bio_flags,
2014 __btrfs_submit_bio_start,
2015 __btrfs_submit_bio_done);
2017 } else if (!skip_sum) {
2018 ret = btrfs_csum_one_bio(inode, bio, 0, 0);
2024 ret = btrfs_map_bio(fs_info, bio, mirror_num, 0);
2028 bio->bi_status = ret;
2035 * given a list of ordered sums record them in the inode. This happens
2036 * at IO completion time based on sums calculated at bio submission time.
2038 static noinline int add_pending_csums(struct btrfs_trans_handle *trans,
2039 struct inode *inode, struct list_head *list)
2041 struct btrfs_ordered_sum *sum;
2043 list_for_each_entry(sum, list, list) {
2044 trans->adding_csums = true;
2045 btrfs_csum_file_blocks(trans,
2046 BTRFS_I(inode)->root->fs_info->csum_root, sum);
2047 trans->adding_csums = false;
2052 int btrfs_set_extent_delalloc(struct inode *inode, u64 start, u64 end,
2053 unsigned int extra_bits,
2054 struct extent_state **cached_state, int dedupe)
2056 WARN_ON((end & (PAGE_SIZE - 1)) == 0);
2057 return set_extent_delalloc(&BTRFS_I(inode)->io_tree, start, end,
2058 extra_bits, cached_state);
2061 /* see btrfs_writepage_start_hook for details on why this is required */
2062 struct btrfs_writepage_fixup {
2064 struct btrfs_work work;
2067 static void btrfs_writepage_fixup_worker(struct btrfs_work *work)
2069 struct btrfs_writepage_fixup *fixup;
2070 struct btrfs_ordered_extent *ordered;
2071 struct extent_state *cached_state = NULL;
2072 struct extent_changeset *data_reserved = NULL;
2074 struct inode *inode;
2079 fixup = container_of(work, struct btrfs_writepage_fixup, work);
2083 if (!page->mapping || !PageDirty(page) || !PageChecked(page)) {
2084 ClearPageChecked(page);
2088 inode = page->mapping->host;
2089 page_start = page_offset(page);
2090 page_end = page_offset(page) + PAGE_SIZE - 1;
2092 lock_extent_bits(&BTRFS_I(inode)->io_tree, page_start, page_end,
2095 /* already ordered? We're done */
2096 if (PagePrivate2(page))
2099 ordered = btrfs_lookup_ordered_range(BTRFS_I(inode), page_start,
2102 unlock_extent_cached(&BTRFS_I(inode)->io_tree, page_start,
2103 page_end, &cached_state, GFP_NOFS);
2105 btrfs_start_ordered_extent(inode, ordered, 1);
2106 btrfs_put_ordered_extent(ordered);
2110 ret = btrfs_delalloc_reserve_space(inode, &data_reserved, page_start,
2113 mapping_set_error(page->mapping, ret);
2114 end_extent_writepage(page, ret, page_start, page_end);
2115 ClearPageChecked(page);
2119 ret = btrfs_set_extent_delalloc(inode, page_start, page_end, 0,
2122 mapping_set_error(page->mapping, ret);
2123 end_extent_writepage(page, ret, page_start, page_end);
2124 ClearPageChecked(page);
2128 ClearPageChecked(page);
2129 set_page_dirty(page);
2130 btrfs_delalloc_release_extents(BTRFS_I(inode), PAGE_SIZE);
2132 unlock_extent_cached(&BTRFS_I(inode)->io_tree, page_start, page_end,
2133 &cached_state, GFP_NOFS);
2138 extent_changeset_free(data_reserved);
2142 * There are a few paths in the higher layers of the kernel that directly
2143 * set the page dirty bit without asking the filesystem if it is a
2144 * good idea. This causes problems because we want to make sure COW
2145 * properly happens and the data=ordered rules are followed.
2147 * In our case any range that doesn't have the ORDERED bit set
2148 * hasn't been properly setup for IO. We kick off an async process
2149 * to fix it up. The async helper will wait for ordered extents, set
2150 * the delalloc bit and make it safe to write the page.
2152 static int btrfs_writepage_start_hook(struct page *page, u64 start, u64 end)
2154 struct inode *inode = page->mapping->host;
2155 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2156 struct btrfs_writepage_fixup *fixup;
2158 /* this page is properly in the ordered list */
2159 if (TestClearPagePrivate2(page))
2162 if (PageChecked(page))
2165 fixup = kzalloc(sizeof(*fixup), GFP_NOFS);
2169 SetPageChecked(page);
2171 btrfs_init_work(&fixup->work, btrfs_fixup_helper,
2172 btrfs_writepage_fixup_worker, NULL, NULL);
2174 btrfs_queue_work(fs_info->fixup_workers, &fixup->work);
2178 static int insert_reserved_file_extent(struct btrfs_trans_handle *trans,
2179 struct inode *inode, u64 file_pos,
2180 u64 disk_bytenr, u64 disk_num_bytes,
2181 u64 num_bytes, u64 ram_bytes,
2182 u8 compression, u8 encryption,
2183 u16 other_encoding, int extent_type)
2185 struct btrfs_root *root = BTRFS_I(inode)->root;
2186 struct btrfs_file_extent_item *fi;
2187 struct btrfs_path *path;
2188 struct extent_buffer *leaf;
2189 struct btrfs_key ins;
2191 int extent_inserted = 0;
2194 path = btrfs_alloc_path();
2199 * we may be replacing one extent in the tree with another.
2200 * The new extent is pinned in the extent map, and we don't want
2201 * to drop it from the cache until it is completely in the btree.
2203 * So, tell btrfs_drop_extents to leave this extent in the cache.
2204 * the caller is expected to unpin it and allow it to be merged
2207 ret = __btrfs_drop_extents(trans, root, inode, path, file_pos,
2208 file_pos + num_bytes, NULL, 0,
2209 1, sizeof(*fi), &extent_inserted);
2213 if (!extent_inserted) {
2214 ins.objectid = btrfs_ino(BTRFS_I(inode));
2215 ins.offset = file_pos;
2216 ins.type = BTRFS_EXTENT_DATA_KEY;
2218 path->leave_spinning = 1;
2219 ret = btrfs_insert_empty_item(trans, root, path, &ins,
2224 leaf = path->nodes[0];
2225 fi = btrfs_item_ptr(leaf, path->slots[0],
2226 struct btrfs_file_extent_item);
2227 btrfs_set_file_extent_generation(leaf, fi, trans->transid);
2228 btrfs_set_file_extent_type(leaf, fi, extent_type);
2229 btrfs_set_file_extent_disk_bytenr(leaf, fi, disk_bytenr);
2230 btrfs_set_file_extent_disk_num_bytes(leaf, fi, disk_num_bytes);
2231 btrfs_set_file_extent_offset(leaf, fi, 0);
2232 btrfs_set_file_extent_num_bytes(leaf, fi, num_bytes);
2233 btrfs_set_file_extent_ram_bytes(leaf, fi, ram_bytes);
2234 btrfs_set_file_extent_compression(leaf, fi, compression);
2235 btrfs_set_file_extent_encryption(leaf, fi, encryption);
2236 btrfs_set_file_extent_other_encoding(leaf, fi, other_encoding);
2238 btrfs_mark_buffer_dirty(leaf);
2239 btrfs_release_path(path);
2241 inode_add_bytes(inode, num_bytes);
2243 ins.objectid = disk_bytenr;
2244 ins.offset = disk_num_bytes;
2245 ins.type = BTRFS_EXTENT_ITEM_KEY;
2248 * Release the reserved range from inode dirty range map, as it is
2249 * already moved into delayed_ref_head
2251 ret = btrfs_qgroup_release_data(inode, file_pos, ram_bytes);
2255 ret = btrfs_alloc_reserved_file_extent(trans, root,
2256 btrfs_ino(BTRFS_I(inode)),
2257 file_pos, qg_released, &ins);
2259 btrfs_free_path(path);
2264 /* snapshot-aware defrag */
2265 struct sa_defrag_extent_backref {
2266 struct rb_node node;
2267 struct old_sa_defrag_extent *old;
2276 struct old_sa_defrag_extent {
2277 struct list_head list;
2278 struct new_sa_defrag_extent *new;
2287 struct new_sa_defrag_extent {
2288 struct rb_root root;
2289 struct list_head head;
2290 struct btrfs_path *path;
2291 struct inode *inode;
2299 static int backref_comp(struct sa_defrag_extent_backref *b1,
2300 struct sa_defrag_extent_backref *b2)
2302 if (b1->root_id < b2->root_id)
2304 else if (b1->root_id > b2->root_id)
2307 if (b1->inum < b2->inum)
2309 else if (b1->inum > b2->inum)
2312 if (b1->file_pos < b2->file_pos)
2314 else if (b1->file_pos > b2->file_pos)
2318 * [------------------------------] ===> (a range of space)
2319 * |<--->| |<---->| =============> (fs/file tree A)
2320 * |<---------------------------->| ===> (fs/file tree B)
2322 * A range of space can refer to two file extents in one tree while
2323 * refer to only one file extent in another tree.
2325 * So we may process a disk offset more than one time(two extents in A)
2326 * and locate at the same extent(one extent in B), then insert two same
2327 * backrefs(both refer to the extent in B).
2332 static void backref_insert(struct rb_root *root,
2333 struct sa_defrag_extent_backref *backref)
2335 struct rb_node **p = &root->rb_node;
2336 struct rb_node *parent = NULL;
2337 struct sa_defrag_extent_backref *entry;
2342 entry = rb_entry(parent, struct sa_defrag_extent_backref, node);
2344 ret = backref_comp(backref, entry);
2348 p = &(*p)->rb_right;
2351 rb_link_node(&backref->node, parent, p);
2352 rb_insert_color(&backref->node, root);
2356 * Note the backref might has changed, and in this case we just return 0.
2358 static noinline int record_one_backref(u64 inum, u64 offset, u64 root_id,
2361 struct btrfs_file_extent_item *extent;
2362 struct old_sa_defrag_extent *old = ctx;
2363 struct new_sa_defrag_extent *new = old->new;
2364 struct btrfs_path *path = new->path;
2365 struct btrfs_key key;
2366 struct btrfs_root *root;
2367 struct sa_defrag_extent_backref *backref;
2368 struct extent_buffer *leaf;
2369 struct inode *inode = new->inode;
2370 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2376 if (BTRFS_I(inode)->root->root_key.objectid == root_id &&
2377 inum == btrfs_ino(BTRFS_I(inode)))
2380 key.objectid = root_id;
2381 key.type = BTRFS_ROOT_ITEM_KEY;
2382 key.offset = (u64)-1;
2384 root = btrfs_read_fs_root_no_name(fs_info, &key);
2386 if (PTR_ERR(root) == -ENOENT)
2389 btrfs_debug(fs_info, "inum=%llu, offset=%llu, root_id=%llu",
2390 inum, offset, root_id);
2391 return PTR_ERR(root);
2394 key.objectid = inum;
2395 key.type = BTRFS_EXTENT_DATA_KEY;
2396 if (offset > (u64)-1 << 32)
2399 key.offset = offset;
2401 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2402 if (WARN_ON(ret < 0))
2409 leaf = path->nodes[0];
2410 slot = path->slots[0];
2412 if (slot >= btrfs_header_nritems(leaf)) {
2413 ret = btrfs_next_leaf(root, path);
2416 } else if (ret > 0) {
2425 btrfs_item_key_to_cpu(leaf, &key, slot);
2427 if (key.objectid > inum)
2430 if (key.objectid < inum || key.type != BTRFS_EXTENT_DATA_KEY)
2433 extent = btrfs_item_ptr(leaf, slot,
2434 struct btrfs_file_extent_item);
2436 if (btrfs_file_extent_disk_bytenr(leaf, extent) != old->bytenr)
2440 * 'offset' refers to the exact key.offset,
2441 * NOT the 'offset' field in btrfs_extent_data_ref, ie.
2442 * (key.offset - extent_offset).
2444 if (key.offset != offset)
2447 extent_offset = btrfs_file_extent_offset(leaf, extent);
2448 num_bytes = btrfs_file_extent_num_bytes(leaf, extent);
2450 if (extent_offset >= old->extent_offset + old->offset +
2451 old->len || extent_offset + num_bytes <=
2452 old->extent_offset + old->offset)
2457 backref = kmalloc(sizeof(*backref), GFP_NOFS);
2463 backref->root_id = root_id;
2464 backref->inum = inum;
2465 backref->file_pos = offset;
2466 backref->num_bytes = num_bytes;
2467 backref->extent_offset = extent_offset;
2468 backref->generation = btrfs_file_extent_generation(leaf, extent);
2470 backref_insert(&new->root, backref);
2473 btrfs_release_path(path);
2478 static noinline bool record_extent_backrefs(struct btrfs_path *path,
2479 struct new_sa_defrag_extent *new)
2481 struct btrfs_fs_info *fs_info = btrfs_sb(new->inode->i_sb);
2482 struct old_sa_defrag_extent *old, *tmp;
2487 list_for_each_entry_safe(old, tmp, &new->head, list) {
2488 ret = iterate_inodes_from_logical(old->bytenr +
2489 old->extent_offset, fs_info,
2490 path, record_one_backref,
2492 if (ret < 0 && ret != -ENOENT)
2495 /* no backref to be processed for this extent */
2497 list_del(&old->list);
2502 if (list_empty(&new->head))
2508 static int relink_is_mergable(struct extent_buffer *leaf,
2509 struct btrfs_file_extent_item *fi,
2510 struct new_sa_defrag_extent *new)
2512 if (btrfs_file_extent_disk_bytenr(leaf, fi) != new->bytenr)
2515 if (btrfs_file_extent_type(leaf, fi) != BTRFS_FILE_EXTENT_REG)
2518 if (btrfs_file_extent_compression(leaf, fi) != new->compress_type)
2521 if (btrfs_file_extent_encryption(leaf, fi) ||
2522 btrfs_file_extent_other_encoding(leaf, fi))
2529 * Note the backref might has changed, and in this case we just return 0.
2531 static noinline int relink_extent_backref(struct btrfs_path *path,
2532 struct sa_defrag_extent_backref *prev,
2533 struct sa_defrag_extent_backref *backref)
2535 struct btrfs_file_extent_item *extent;
2536 struct btrfs_file_extent_item *item;
2537 struct btrfs_ordered_extent *ordered;
2538 struct btrfs_trans_handle *trans;
2539 struct btrfs_root *root;
2540 struct btrfs_key key;
2541 struct extent_buffer *leaf;
2542 struct old_sa_defrag_extent *old = backref->old;
2543 struct new_sa_defrag_extent *new = old->new;
2544 struct btrfs_fs_info *fs_info = btrfs_sb(new->inode->i_sb);
2545 struct inode *inode;
2546 struct extent_state *cached = NULL;
2555 if (prev && prev->root_id == backref->root_id &&
2556 prev->inum == backref->inum &&
2557 prev->file_pos + prev->num_bytes == backref->file_pos)
2560 /* step 1: get root */
2561 key.objectid = backref->root_id;
2562 key.type = BTRFS_ROOT_ITEM_KEY;
2563 key.offset = (u64)-1;
2565 index = srcu_read_lock(&fs_info->subvol_srcu);
2567 root = btrfs_read_fs_root_no_name(fs_info, &key);
2569 srcu_read_unlock(&fs_info->subvol_srcu, index);
2570 if (PTR_ERR(root) == -ENOENT)
2572 return PTR_ERR(root);
2575 if (btrfs_root_readonly(root)) {
2576 srcu_read_unlock(&fs_info->subvol_srcu, index);
2580 /* step 2: get inode */
2581 key.objectid = backref->inum;
2582 key.type = BTRFS_INODE_ITEM_KEY;
2585 inode = btrfs_iget(fs_info->sb, &key, root, NULL);
2586 if (IS_ERR(inode)) {
2587 srcu_read_unlock(&fs_info->subvol_srcu, index);
2591 srcu_read_unlock(&fs_info->subvol_srcu, index);
2593 /* step 3: relink backref */
2594 lock_start = backref->file_pos;
2595 lock_end = backref->file_pos + backref->num_bytes - 1;
2596 lock_extent_bits(&BTRFS_I(inode)->io_tree, lock_start, lock_end,
2599 ordered = btrfs_lookup_first_ordered_extent(inode, lock_end);
2601 btrfs_put_ordered_extent(ordered);
2605 trans = btrfs_join_transaction(root);
2606 if (IS_ERR(trans)) {
2607 ret = PTR_ERR(trans);
2611 key.objectid = backref->inum;
2612 key.type = BTRFS_EXTENT_DATA_KEY;
2613 key.offset = backref->file_pos;
2615 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2618 } else if (ret > 0) {
2623 extent = btrfs_item_ptr(path->nodes[0], path->slots[0],
2624 struct btrfs_file_extent_item);
2626 if (btrfs_file_extent_generation(path->nodes[0], extent) !=
2627 backref->generation)
2630 btrfs_release_path(path);
2632 start = backref->file_pos;
2633 if (backref->extent_offset < old->extent_offset + old->offset)
2634 start += old->extent_offset + old->offset -
2635 backref->extent_offset;
2637 len = min(backref->extent_offset + backref->num_bytes,
2638 old->extent_offset + old->offset + old->len);
2639 len -= max(backref->extent_offset, old->extent_offset + old->offset);
2641 ret = btrfs_drop_extents(trans, root, inode, start,
2646 key.objectid = btrfs_ino(BTRFS_I(inode));
2647 key.type = BTRFS_EXTENT_DATA_KEY;
2650 path->leave_spinning = 1;
2652 struct btrfs_file_extent_item *fi;
2654 struct btrfs_key found_key;
2656 ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
2661 leaf = path->nodes[0];
2662 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
2664 fi = btrfs_item_ptr(leaf, path->slots[0],
2665 struct btrfs_file_extent_item);
2666 extent_len = btrfs_file_extent_num_bytes(leaf, fi);
2668 if (extent_len + found_key.offset == start &&
2669 relink_is_mergable(leaf, fi, new)) {
2670 btrfs_set_file_extent_num_bytes(leaf, fi,
2672 btrfs_mark_buffer_dirty(leaf);
2673 inode_add_bytes(inode, len);
2679 btrfs_release_path(path);
2684 ret = btrfs_insert_empty_item(trans, root, path, &key,
2687 btrfs_abort_transaction(trans, ret);
2691 leaf = path->nodes[0];
2692 item = btrfs_item_ptr(leaf, path->slots[0],
2693 struct btrfs_file_extent_item);
2694 btrfs_set_file_extent_disk_bytenr(leaf, item, new->bytenr);
2695 btrfs_set_file_extent_disk_num_bytes(leaf, item, new->disk_len);
2696 btrfs_set_file_extent_offset(leaf, item, start - new->file_pos);
2697 btrfs_set_file_extent_num_bytes(leaf, item, len);
2698 btrfs_set_file_extent_ram_bytes(leaf, item, new->len);
2699 btrfs_set_file_extent_generation(leaf, item, trans->transid);
2700 btrfs_set_file_extent_type(leaf, item, BTRFS_FILE_EXTENT_REG);
2701 btrfs_set_file_extent_compression(leaf, item, new->compress_type);
2702 btrfs_set_file_extent_encryption(leaf, item, 0);
2703 btrfs_set_file_extent_other_encoding(leaf, item, 0);
2705 btrfs_mark_buffer_dirty(leaf);
2706 inode_add_bytes(inode, len);
2707 btrfs_release_path(path);
2709 ret = btrfs_inc_extent_ref(trans, root, new->bytenr,
2711 backref->root_id, backref->inum,
2712 new->file_pos); /* start - extent_offset */
2714 btrfs_abort_transaction(trans, ret);
2720 btrfs_release_path(path);
2721 path->leave_spinning = 0;
2722 btrfs_end_transaction(trans);
2724 unlock_extent_cached(&BTRFS_I(inode)->io_tree, lock_start, lock_end,
2730 static void free_sa_defrag_extent(struct new_sa_defrag_extent *new)
2732 struct old_sa_defrag_extent *old, *tmp;
2737 list_for_each_entry_safe(old, tmp, &new->head, list) {
2743 static void relink_file_extents(struct new_sa_defrag_extent *new)
2745 struct btrfs_fs_info *fs_info = btrfs_sb(new->inode->i_sb);
2746 struct btrfs_path *path;
2747 struct sa_defrag_extent_backref *backref;
2748 struct sa_defrag_extent_backref *prev = NULL;
2749 struct inode *inode;
2750 struct btrfs_root *root;
2751 struct rb_node *node;
2755 root = BTRFS_I(inode)->root;
2757 path = btrfs_alloc_path();
2761 if (!record_extent_backrefs(path, new)) {
2762 btrfs_free_path(path);
2765 btrfs_release_path(path);
2768 node = rb_first(&new->root);
2771 rb_erase(node, &new->root);
2773 backref = rb_entry(node, struct sa_defrag_extent_backref, node);
2775 ret = relink_extent_backref(path, prev, backref);
2788 btrfs_free_path(path);
2790 free_sa_defrag_extent(new);
2792 atomic_dec(&fs_info->defrag_running);
2793 wake_up(&fs_info->transaction_wait);
2796 static struct new_sa_defrag_extent *
2797 record_old_file_extents(struct inode *inode,
2798 struct btrfs_ordered_extent *ordered)
2800 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2801 struct btrfs_root *root = BTRFS_I(inode)->root;
2802 struct btrfs_path *path;
2803 struct btrfs_key key;
2804 struct old_sa_defrag_extent *old;
2805 struct new_sa_defrag_extent *new;
2808 new = kmalloc(sizeof(*new), GFP_NOFS);
2813 new->file_pos = ordered->file_offset;
2814 new->len = ordered->len;
2815 new->bytenr = ordered->start;
2816 new->disk_len = ordered->disk_len;
2817 new->compress_type = ordered->compress_type;
2818 new->root = RB_ROOT;
2819 INIT_LIST_HEAD(&new->head);
2821 path = btrfs_alloc_path();
2825 key.objectid = btrfs_ino(BTRFS_I(inode));
2826 key.type = BTRFS_EXTENT_DATA_KEY;
2827 key.offset = new->file_pos;
2829 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2832 if (ret > 0 && path->slots[0] > 0)
2835 /* find out all the old extents for the file range */
2837 struct btrfs_file_extent_item *extent;
2838 struct extent_buffer *l;
2847 slot = path->slots[0];
2849 if (slot >= btrfs_header_nritems(l)) {
2850 ret = btrfs_next_leaf(root, path);
2858 btrfs_item_key_to_cpu(l, &key, slot);
2860 if (key.objectid != btrfs_ino(BTRFS_I(inode)))
2862 if (key.type != BTRFS_EXTENT_DATA_KEY)
2864 if (key.offset >= new->file_pos + new->len)
2867 extent = btrfs_item_ptr(l, slot, struct btrfs_file_extent_item);
2869 num_bytes = btrfs_file_extent_num_bytes(l, extent);
2870 if (key.offset + num_bytes < new->file_pos)
2873 disk_bytenr = btrfs_file_extent_disk_bytenr(l, extent);
2877 extent_offset = btrfs_file_extent_offset(l, extent);
2879 old = kmalloc(sizeof(*old), GFP_NOFS);
2883 offset = max(new->file_pos, key.offset);
2884 end = min(new->file_pos + new->len, key.offset + num_bytes);
2886 old->bytenr = disk_bytenr;
2887 old->extent_offset = extent_offset;
2888 old->offset = offset - key.offset;
2889 old->len = end - offset;
2892 list_add_tail(&old->list, &new->head);
2898 btrfs_free_path(path);
2899 atomic_inc(&fs_info->defrag_running);
2904 btrfs_free_path(path);
2906 free_sa_defrag_extent(new);
2910 static void btrfs_release_delalloc_bytes(struct btrfs_fs_info *fs_info,
2913 struct btrfs_block_group_cache *cache;
2915 cache = btrfs_lookup_block_group(fs_info, start);
2918 spin_lock(&cache->lock);
2919 cache->delalloc_bytes -= len;
2920 spin_unlock(&cache->lock);
2922 btrfs_put_block_group(cache);
2925 /* as ordered data IO finishes, this gets called so we can finish
2926 * an ordered extent if the range of bytes in the file it covers are
2929 static int btrfs_finish_ordered_io(struct btrfs_ordered_extent *ordered_extent)
2931 struct inode *inode = ordered_extent->inode;
2932 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2933 struct btrfs_root *root = BTRFS_I(inode)->root;
2934 struct btrfs_trans_handle *trans = NULL;
2935 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
2936 struct extent_state *cached_state = NULL;
2937 struct new_sa_defrag_extent *new = NULL;
2938 int compress_type = 0;
2940 u64 logical_len = ordered_extent->len;
2942 bool truncated = false;
2943 bool range_locked = false;
2944 bool clear_new_delalloc_bytes = false;
2946 if (!test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags) &&
2947 !test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags) &&
2948 !test_bit(BTRFS_ORDERED_DIRECT, &ordered_extent->flags))
2949 clear_new_delalloc_bytes = true;
2951 nolock = btrfs_is_free_space_inode(BTRFS_I(inode));
2953 if (test_bit(BTRFS_ORDERED_IOERR, &ordered_extent->flags)) {
2958 btrfs_free_io_failure_record(BTRFS_I(inode),
2959 ordered_extent->file_offset,
2960 ordered_extent->file_offset +
2961 ordered_extent->len - 1);
2963 if (test_bit(BTRFS_ORDERED_TRUNCATED, &ordered_extent->flags)) {
2965 logical_len = ordered_extent->truncated_len;
2966 /* Truncated the entire extent, don't bother adding */
2971 if (test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags)) {
2972 BUG_ON(!list_empty(&ordered_extent->list)); /* Logic error */
2975 * For mwrite(mmap + memset to write) case, we still reserve
2976 * space for NOCOW range.
2977 * As NOCOW won't cause a new delayed ref, just free the space
2979 btrfs_qgroup_free_data(inode, NULL, ordered_extent->file_offset,
2980 ordered_extent->len);
2981 btrfs_ordered_update_i_size(inode, 0, ordered_extent);
2983 trans = btrfs_join_transaction_nolock(root);
2985 trans = btrfs_join_transaction(root);
2986 if (IS_ERR(trans)) {
2987 ret = PTR_ERR(trans);
2991 trans->block_rsv = &BTRFS_I(inode)->block_rsv;
2992 ret = btrfs_update_inode_fallback(trans, root, inode);
2993 if (ret) /* -ENOMEM or corruption */
2994 btrfs_abort_transaction(trans, ret);
2998 range_locked = true;
2999 lock_extent_bits(io_tree, ordered_extent->file_offset,
3000 ordered_extent->file_offset + ordered_extent->len - 1,
3003 ret = test_range_bit(io_tree, ordered_extent->file_offset,
3004 ordered_extent->file_offset + ordered_extent->len - 1,
3005 EXTENT_DEFRAG, 0, cached_state);
3007 u64 last_snapshot = btrfs_root_last_snapshot(&root->root_item);
3008 if (0 && last_snapshot >= BTRFS_I(inode)->generation)
3009 /* the inode is shared */
3010 new = record_old_file_extents(inode, ordered_extent);
3012 clear_extent_bit(io_tree, ordered_extent->file_offset,
3013 ordered_extent->file_offset + ordered_extent->len - 1,
3014 EXTENT_DEFRAG, 0, 0, &cached_state);
3018 trans = btrfs_join_transaction_nolock(root);
3020 trans = btrfs_join_transaction(root);
3021 if (IS_ERR(trans)) {
3022 ret = PTR_ERR(trans);
3027 trans->block_rsv = &BTRFS_I(inode)->block_rsv;
3029 if (test_bit(BTRFS_ORDERED_COMPRESSED, &ordered_extent->flags))
3030 compress_type = ordered_extent->compress_type;
3031 if (test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags)) {
3032 BUG_ON(compress_type);
3033 btrfs_qgroup_free_data(inode, NULL, ordered_extent->file_offset,
3034 ordered_extent->len);
3035 ret = btrfs_mark_extent_written(trans, BTRFS_I(inode),
3036 ordered_extent->file_offset,
3037 ordered_extent->file_offset +
3040 BUG_ON(root == fs_info->tree_root);
3041 ret = insert_reserved_file_extent(trans, inode,
3042 ordered_extent->file_offset,
3043 ordered_extent->start,
3044 ordered_extent->disk_len,
3045 logical_len, logical_len,
3046 compress_type, 0, 0,
3047 BTRFS_FILE_EXTENT_REG);
3049 btrfs_release_delalloc_bytes(fs_info,
3050 ordered_extent->start,
3051 ordered_extent->disk_len);
3053 unpin_extent_cache(&BTRFS_I(inode)->extent_tree,
3054 ordered_extent->file_offset, ordered_extent->len,
3057 btrfs_abort_transaction(trans, ret);
3061 add_pending_csums(trans, inode, &ordered_extent->list);
3063 btrfs_ordered_update_i_size(inode, 0, ordered_extent);
3064 ret = btrfs_update_inode_fallback(trans, root, inode);
3065 if (ret) { /* -ENOMEM or corruption */
3066 btrfs_abort_transaction(trans, ret);
3071 if (range_locked || clear_new_delalloc_bytes) {
3072 unsigned int clear_bits = 0;
3075 clear_bits |= EXTENT_LOCKED;
3076 if (clear_new_delalloc_bytes)
3077 clear_bits |= EXTENT_DELALLOC_NEW;
3078 clear_extent_bit(&BTRFS_I(inode)->io_tree,
3079 ordered_extent->file_offset,
3080 ordered_extent->file_offset +
3081 ordered_extent->len - 1,
3083 (clear_bits & EXTENT_LOCKED) ? 1 : 0,
3088 btrfs_end_transaction(trans);
3090 if (ret || truncated) {
3094 start = ordered_extent->file_offset + logical_len;
3096 start = ordered_extent->file_offset;
3097 end = ordered_extent->file_offset + ordered_extent->len - 1;
3098 clear_extent_uptodate(io_tree, start, end, NULL);
3100 /* Drop the cache for the part of the extent we didn't write. */
3101 btrfs_drop_extent_cache(BTRFS_I(inode), start, end, 0);
3104 * If the ordered extent had an IOERR or something else went
3105 * wrong we need to return the space for this ordered extent
3106 * back to the allocator. We only free the extent in the
3107 * truncated case if we didn't write out the extent at all.
3109 if ((ret || !logical_len) &&
3110 !test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags) &&
3111 !test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags))
3112 btrfs_free_reserved_extent(fs_info,
3113 ordered_extent->start,
3114 ordered_extent->disk_len, 1);
3119 * This needs to be done to make sure anybody waiting knows we are done
3120 * updating everything for this ordered extent.
3122 btrfs_remove_ordered_extent(inode, ordered_extent);
3124 /* for snapshot-aware defrag */
3127 free_sa_defrag_extent(new);
3128 atomic_dec(&fs_info->defrag_running);
3130 relink_file_extents(new);
3135 btrfs_put_ordered_extent(ordered_extent);
3136 /* once for the tree */
3137 btrfs_put_ordered_extent(ordered_extent);
3142 static void finish_ordered_fn(struct btrfs_work *work)
3144 struct btrfs_ordered_extent *ordered_extent;
3145 ordered_extent = container_of(work, struct btrfs_ordered_extent, work);
3146 btrfs_finish_ordered_io(ordered_extent);
3149 static void btrfs_writepage_end_io_hook(struct page *page, u64 start, u64 end,
3150 struct extent_state *state, int uptodate)
3152 struct inode *inode = page->mapping->host;
3153 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
3154 struct btrfs_ordered_extent *ordered_extent = NULL;
3155 struct btrfs_workqueue *wq;
3156 btrfs_work_func_t func;
3158 trace_btrfs_writepage_end_io_hook(page, start, end, uptodate);
3160 ClearPagePrivate2(page);
3161 if (!btrfs_dec_test_ordered_pending(inode, &ordered_extent, start,
3162 end - start + 1, uptodate))
3165 if (btrfs_is_free_space_inode(BTRFS_I(inode))) {
3166 wq = fs_info->endio_freespace_worker;
3167 func = btrfs_freespace_write_helper;
3169 wq = fs_info->endio_write_workers;
3170 func = btrfs_endio_write_helper;
3173 btrfs_init_work(&ordered_extent->work, func, finish_ordered_fn, NULL,
3175 btrfs_queue_work(wq, &ordered_extent->work);
3178 static int __readpage_endio_check(struct inode *inode,
3179 struct btrfs_io_bio *io_bio,
3180 int icsum, struct page *page,
3181 int pgoff, u64 start, size_t len)
3187 csum_expected = *(((u32 *)io_bio->csum) + icsum);
3189 kaddr = kmap_atomic(page);
3190 csum = btrfs_csum_data(kaddr + pgoff, csum, len);
3191 btrfs_csum_final(csum, (u8 *)&csum);
3192 if (csum != csum_expected)
3195 kunmap_atomic(kaddr);
3198 btrfs_print_data_csum_error(BTRFS_I(inode), start, csum, csum_expected,
3199 io_bio->mirror_num);
3200 memset(kaddr + pgoff, 1, len);
3201 flush_dcache_page(page);
3202 kunmap_atomic(kaddr);
3207 * when reads are done, we need to check csums to verify the data is correct
3208 * if there's a match, we allow the bio to finish. If not, the code in
3209 * extent_io.c will try to find good copies for us.
3211 static int btrfs_readpage_end_io_hook(struct btrfs_io_bio *io_bio,
3212 u64 phy_offset, struct page *page,
3213 u64 start, u64 end, int mirror)
3215 size_t offset = start - page_offset(page);
3216 struct inode *inode = page->mapping->host;
3217 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
3218 struct btrfs_root *root = BTRFS_I(inode)->root;
3220 if (PageChecked(page)) {
3221 ClearPageChecked(page);
3225 if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)
3228 if (root->root_key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID &&
3229 test_range_bit(io_tree, start, end, EXTENT_NODATASUM, 1, NULL)) {
3230 clear_extent_bits(io_tree, start, end, EXTENT_NODATASUM);
3234 phy_offset >>= inode->i_sb->s_blocksize_bits;
3235 return __readpage_endio_check(inode, io_bio, phy_offset, page, offset,
3236 start, (size_t)(end - start + 1));
3239 void btrfs_add_delayed_iput(struct inode *inode)
3241 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
3242 struct btrfs_inode *binode = BTRFS_I(inode);
3244 if (atomic_add_unless(&inode->i_count, -1, 1))
3247 spin_lock(&fs_info->delayed_iput_lock);
3248 if (binode->delayed_iput_count == 0) {
3249 ASSERT(list_empty(&binode->delayed_iput));
3250 list_add_tail(&binode->delayed_iput, &fs_info->delayed_iputs);
3252 binode->delayed_iput_count++;
3254 spin_unlock(&fs_info->delayed_iput_lock);
3257 void btrfs_run_delayed_iputs(struct btrfs_fs_info *fs_info)
3260 spin_lock(&fs_info->delayed_iput_lock);
3261 while (!list_empty(&fs_info->delayed_iputs)) {
3262 struct btrfs_inode *inode;
3264 inode = list_first_entry(&fs_info->delayed_iputs,
3265 struct btrfs_inode, delayed_iput);
3266 if (inode->delayed_iput_count) {
3267 inode->delayed_iput_count--;
3268 list_move_tail(&inode->delayed_iput,
3269 &fs_info->delayed_iputs);
3271 list_del_init(&inode->delayed_iput);
3273 spin_unlock(&fs_info->delayed_iput_lock);
3274 iput(&inode->vfs_inode);
3275 spin_lock(&fs_info->delayed_iput_lock);
3277 spin_unlock(&fs_info->delayed_iput_lock);
3281 * This is called in transaction commit time. If there are no orphan
3282 * files in the subvolume, it removes orphan item and frees block_rsv
3285 void btrfs_orphan_commit_root(struct btrfs_trans_handle *trans,
3286 struct btrfs_root *root)
3288 struct btrfs_fs_info *fs_info = root->fs_info;
3289 struct btrfs_block_rsv *block_rsv;
3292 if (atomic_read(&root->orphan_inodes) ||
3293 root->orphan_cleanup_state != ORPHAN_CLEANUP_DONE)
3296 spin_lock(&root->orphan_lock);
3297 if (atomic_read(&root->orphan_inodes)) {
3298 spin_unlock(&root->orphan_lock);
3302 if (root->orphan_cleanup_state != ORPHAN_CLEANUP_DONE) {
3303 spin_unlock(&root->orphan_lock);
3307 block_rsv = root->orphan_block_rsv;
3308 root->orphan_block_rsv = NULL;
3309 spin_unlock(&root->orphan_lock);
3311 if (test_bit(BTRFS_ROOT_ORPHAN_ITEM_INSERTED, &root->state) &&
3312 btrfs_root_refs(&root->root_item) > 0) {
3313 ret = btrfs_del_orphan_item(trans, fs_info->tree_root,
3314 root->root_key.objectid);
3316 btrfs_abort_transaction(trans, ret);
3318 clear_bit(BTRFS_ROOT_ORPHAN_ITEM_INSERTED,
3323 WARN_ON(block_rsv->size > 0);
3324 btrfs_free_block_rsv(fs_info, block_rsv);
3329 * This creates an orphan entry for the given inode in case something goes
3330 * wrong in the middle of an unlink/truncate.
3332 * NOTE: caller of this function should reserve 5 units of metadata for
3335 int btrfs_orphan_add(struct btrfs_trans_handle *trans,
3336 struct btrfs_inode *inode)
3338 struct btrfs_fs_info *fs_info = btrfs_sb(inode->vfs_inode.i_sb);
3339 struct btrfs_root *root = inode->root;
3340 struct btrfs_block_rsv *block_rsv = NULL;
3345 if (!root->orphan_block_rsv) {
3346 block_rsv = btrfs_alloc_block_rsv(fs_info,
3347 BTRFS_BLOCK_RSV_TEMP);
3352 spin_lock(&root->orphan_lock);
3353 if (!root->orphan_block_rsv) {
3354 root->orphan_block_rsv = block_rsv;
3355 } else if (block_rsv) {
3356 btrfs_free_block_rsv(fs_info, block_rsv);
3360 if (!test_and_set_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
3361 &inode->runtime_flags)) {
3364 * For proper ENOSPC handling, we should do orphan
3365 * cleanup when mounting. But this introduces backward
3366 * compatibility issue.
3368 if (!xchg(&root->orphan_item_inserted, 1))
3374 atomic_inc(&root->orphan_inodes);
3377 if (!test_and_set_bit(BTRFS_INODE_ORPHAN_META_RESERVED,
3378 &inode->runtime_flags))
3380 spin_unlock(&root->orphan_lock);
3382 /* grab metadata reservation from transaction handle */
3384 ret = btrfs_orphan_reserve_metadata(trans, inode);
3387 atomic_dec(&root->orphan_inodes);
3388 clear_bit(BTRFS_INODE_ORPHAN_META_RESERVED,
3389 &inode->runtime_flags);
3391 clear_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
3392 &inode->runtime_flags);
3397 /* insert an orphan item to track this unlinked/truncated file */
3399 ret = btrfs_insert_orphan_item(trans, root, btrfs_ino(inode));
3401 atomic_dec(&root->orphan_inodes);
3403 clear_bit(BTRFS_INODE_ORPHAN_META_RESERVED,
3404 &inode->runtime_flags);
3405 btrfs_orphan_release_metadata(inode);
3407 if (ret != -EEXIST) {
3408 clear_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
3409 &inode->runtime_flags);
3410 btrfs_abort_transaction(trans, ret);
3417 /* insert an orphan item to track subvolume contains orphan files */
3419 ret = btrfs_insert_orphan_item(trans, fs_info->tree_root,
3420 root->root_key.objectid);
3421 if (ret && ret != -EEXIST) {
3422 btrfs_abort_transaction(trans, ret);
3430 * We have done the truncate/delete so we can go ahead and remove the orphan
3431 * item for this particular inode.
3433 static int btrfs_orphan_del(struct btrfs_trans_handle *trans,
3434 struct btrfs_inode *inode)
3436 struct btrfs_root *root = inode->root;
3437 int delete_item = 0;
3438 int release_rsv = 0;
3441 spin_lock(&root->orphan_lock);
3442 if (test_and_clear_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
3443 &inode->runtime_flags))
3446 if (test_and_clear_bit(BTRFS_INODE_ORPHAN_META_RESERVED,
3447 &inode->runtime_flags))
3449 spin_unlock(&root->orphan_lock);
3452 atomic_dec(&root->orphan_inodes);
3454 ret = btrfs_del_orphan_item(trans, root,
3459 btrfs_orphan_release_metadata(inode);
3465 * this cleans up any orphans that may be left on the list from the last use
3468 int btrfs_orphan_cleanup(struct btrfs_root *root)
3470 struct btrfs_fs_info *fs_info = root->fs_info;
3471 struct btrfs_path *path;
3472 struct extent_buffer *leaf;
3473 struct btrfs_key key, found_key;
3474 struct btrfs_trans_handle *trans;
3475 struct inode *inode;
3476 u64 last_objectid = 0;
3477 int ret = 0, nr_unlink = 0, nr_truncate = 0;
3479 if (cmpxchg(&root->orphan_cleanup_state, 0, ORPHAN_CLEANUP_STARTED))
3482 path = btrfs_alloc_path();
3487 path->reada = READA_BACK;
3489 key.objectid = BTRFS_ORPHAN_OBJECTID;
3490 key.type = BTRFS_ORPHAN_ITEM_KEY;
3491 key.offset = (u64)-1;
3494 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
3499 * if ret == 0 means we found what we were searching for, which
3500 * is weird, but possible, so only screw with path if we didn't
3501 * find the key and see if we have stuff that matches
3505 if (path->slots[0] == 0)
3510 /* pull out the item */
3511 leaf = path->nodes[0];
3512 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
3514 /* make sure the item matches what we want */
3515 if (found_key.objectid != BTRFS_ORPHAN_OBJECTID)
3517 if (found_key.type != BTRFS_ORPHAN_ITEM_KEY)
3520 /* release the path since we're done with it */
3521 btrfs_release_path(path);
3524 * this is where we are basically btrfs_lookup, without the
3525 * crossing root thing. we store the inode number in the
3526 * offset of the orphan item.
3529 if (found_key.offset == last_objectid) {
3531 "Error removing orphan entry, stopping orphan cleanup");
3536 last_objectid = found_key.offset;
3538 found_key.objectid = found_key.offset;
3539 found_key.type = BTRFS_INODE_ITEM_KEY;
3540 found_key.offset = 0;
3541 inode = btrfs_iget(fs_info->sb, &found_key, root, NULL);
3542 ret = PTR_ERR_OR_ZERO(inode);
3543 if (ret && ret != -ENOENT)
3546 if (ret == -ENOENT && root == fs_info->tree_root) {
3547 struct btrfs_root *dead_root;
3548 struct btrfs_fs_info *fs_info = root->fs_info;
3549 int is_dead_root = 0;
3552 * this is an orphan in the tree root. Currently these
3553 * could come from 2 sources:
3554 * a) a snapshot deletion in progress
3555 * b) a free space cache inode
3556 * We need to distinguish those two, as the snapshot
3557 * orphan must not get deleted.
3558 * find_dead_roots already ran before us, so if this
3559 * is a snapshot deletion, we should find the root
3560 * in the dead_roots list
3562 spin_lock(&fs_info->trans_lock);
3563 list_for_each_entry(dead_root, &fs_info->dead_roots,
3565 if (dead_root->root_key.objectid ==
3566 found_key.objectid) {
3571 spin_unlock(&fs_info->trans_lock);
3573 /* prevent this orphan from being found again */
3574 key.offset = found_key.objectid - 1;
3579 * Inode is already gone but the orphan item is still there,
3580 * kill the orphan item.
3582 if (ret == -ENOENT) {
3583 trans = btrfs_start_transaction(root, 1);
3584 if (IS_ERR(trans)) {
3585 ret = PTR_ERR(trans);
3588 btrfs_debug(fs_info, "auto deleting %Lu",
3589 found_key.objectid);
3590 ret = btrfs_del_orphan_item(trans, root,
3591 found_key.objectid);
3592 btrfs_end_transaction(trans);
3599 * add this inode to the orphan list so btrfs_orphan_del does
3600 * the proper thing when we hit it
3602 set_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
3603 &BTRFS_I(inode)->runtime_flags);
3604 atomic_inc(&root->orphan_inodes);
3606 /* if we have links, this was a truncate, lets do that */
3607 if (inode->i_nlink) {
3608 if (WARN_ON(!S_ISREG(inode->i_mode))) {
3614 /* 1 for the orphan item deletion. */
3615 trans = btrfs_start_transaction(root, 1);
3616 if (IS_ERR(trans)) {
3618 ret = PTR_ERR(trans);
3621 ret = btrfs_orphan_add(trans, BTRFS_I(inode));
3622 btrfs_end_transaction(trans);
3628 ret = btrfs_truncate(inode);
3630 btrfs_orphan_del(NULL, BTRFS_I(inode));
3635 /* this will do delete_inode and everything for us */
3640 /* release the path since we're done with it */
3641 btrfs_release_path(path);
3643 root->orphan_cleanup_state = ORPHAN_CLEANUP_DONE;
3645 if (root->orphan_block_rsv)
3646 btrfs_block_rsv_release(fs_info, root->orphan_block_rsv,
3649 if (root->orphan_block_rsv ||
3650 test_bit(BTRFS_ROOT_ORPHAN_ITEM_INSERTED, &root->state)) {
3651 trans = btrfs_join_transaction(root);
3653 btrfs_end_transaction(trans);
3657 btrfs_debug(fs_info, "unlinked %d orphans", nr_unlink);
3659 btrfs_debug(fs_info, "truncated %d orphans", nr_truncate);
3663 btrfs_err(fs_info, "could not do orphan cleanup %d", ret);
3664 btrfs_free_path(path);
3669 * very simple check to peek ahead in the leaf looking for xattrs. If we
3670 * don't find any xattrs, we know there can't be any acls.
3672 * slot is the slot the inode is in, objectid is the objectid of the inode
3674 static noinline int acls_after_inode_item(struct extent_buffer *leaf,
3675 int slot, u64 objectid,
3676 int *first_xattr_slot)
3678 u32 nritems = btrfs_header_nritems(leaf);
3679 struct btrfs_key found_key;
3680 static u64 xattr_access = 0;
3681 static u64 xattr_default = 0;
3684 if (!xattr_access) {
3685 xattr_access = btrfs_name_hash(XATTR_NAME_POSIX_ACL_ACCESS,
3686 strlen(XATTR_NAME_POSIX_ACL_ACCESS));
3687 xattr_default = btrfs_name_hash(XATTR_NAME_POSIX_ACL_DEFAULT,
3688 strlen(XATTR_NAME_POSIX_ACL_DEFAULT));
3692 *first_xattr_slot = -1;
3693 while (slot < nritems) {
3694 btrfs_item_key_to_cpu(leaf, &found_key, slot);
3696 /* we found a different objectid, there must not be acls */
3697 if (found_key.objectid != objectid)
3700 /* we found an xattr, assume we've got an acl */
3701 if (found_key.type == BTRFS_XATTR_ITEM_KEY) {
3702 if (*first_xattr_slot == -1)
3703 *first_xattr_slot = slot;
3704 if (found_key.offset == xattr_access ||
3705 found_key.offset == xattr_default)
3710 * we found a key greater than an xattr key, there can't
3711 * be any acls later on
3713 if (found_key.type > BTRFS_XATTR_ITEM_KEY)
3720 * it goes inode, inode backrefs, xattrs, extents,
3721 * so if there are a ton of hard links to an inode there can
3722 * be a lot of backrefs. Don't waste time searching too hard,
3723 * this is just an optimization
3728 /* we hit the end of the leaf before we found an xattr or
3729 * something larger than an xattr. We have to assume the inode
3732 if (*first_xattr_slot == -1)
3733 *first_xattr_slot = slot;
3738 * read an inode from the btree into the in-memory inode
3740 static int btrfs_read_locked_inode(struct inode *inode)
3742 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
3743 struct btrfs_path *path;
3744 struct extent_buffer *leaf;
3745 struct btrfs_inode_item *inode_item;
3746 struct btrfs_root *root = BTRFS_I(inode)->root;
3747 struct btrfs_key location;
3752 bool filled = false;
3753 int first_xattr_slot;
3755 ret = btrfs_fill_inode(inode, &rdev);
3759 path = btrfs_alloc_path();
3765 memcpy(&location, &BTRFS_I(inode)->location, sizeof(location));
3767 ret = btrfs_lookup_inode(NULL, root, path, &location, 0);
3774 leaf = path->nodes[0];
3779 inode_item = btrfs_item_ptr(leaf, path->slots[0],
3780 struct btrfs_inode_item);
3781 inode->i_mode = btrfs_inode_mode(leaf, inode_item);
3782 set_nlink(inode, btrfs_inode_nlink(leaf, inode_item));
3783 i_uid_write(inode, btrfs_inode_uid(leaf, inode_item));
3784 i_gid_write(inode, btrfs_inode_gid(leaf, inode_item));
3785 btrfs_i_size_write(BTRFS_I(inode), btrfs_inode_size(leaf, inode_item));
3787 inode->i_atime.tv_sec = btrfs_timespec_sec(leaf, &inode_item->atime);
3788 inode->i_atime.tv_nsec = btrfs_timespec_nsec(leaf, &inode_item->atime);
3790 inode->i_mtime.tv_sec = btrfs_timespec_sec(leaf, &inode_item->mtime);
3791 inode->i_mtime.tv_nsec = btrfs_timespec_nsec(leaf, &inode_item->mtime);
3793 inode->i_ctime.tv_sec = btrfs_timespec_sec(leaf, &inode_item->ctime);
3794 inode->i_ctime.tv_nsec = btrfs_timespec_nsec(leaf, &inode_item->ctime);
3796 BTRFS_I(inode)->i_otime.tv_sec =
3797 btrfs_timespec_sec(leaf, &inode_item->otime);
3798 BTRFS_I(inode)->i_otime.tv_nsec =
3799 btrfs_timespec_nsec(leaf, &inode_item->otime);
3801 inode_set_bytes(inode, btrfs_inode_nbytes(leaf, inode_item));
3802 BTRFS_I(inode)->generation = btrfs_inode_generation(leaf, inode_item);
3803 BTRFS_I(inode)->last_trans = btrfs_inode_transid(leaf, inode_item);
3805 inode->i_version = btrfs_inode_sequence(leaf, inode_item);
3806 inode->i_generation = BTRFS_I(inode)->generation;
3808 rdev = btrfs_inode_rdev(leaf, inode_item);
3810 BTRFS_I(inode)->index_cnt = (u64)-1;
3811 BTRFS_I(inode)->flags = btrfs_inode_flags(leaf, inode_item);
3815 * If we were modified in the current generation and evicted from memory
3816 * and then re-read we need to do a full sync since we don't have any
3817 * idea about which extents were modified before we were evicted from
3820 * This is required for both inode re-read from disk and delayed inode
3821 * in delayed_nodes_tree.
3823 if (BTRFS_I(inode)->last_trans == fs_info->generation)
3824 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
3825 &BTRFS_I(inode)->runtime_flags);
3828 * We don't persist the id of the transaction where an unlink operation
3829 * against the inode was last made. So here we assume the inode might
3830 * have been evicted, and therefore the exact value of last_unlink_trans
3831 * lost, and set it to last_trans to avoid metadata inconsistencies
3832 * between the inode and its parent if the inode is fsync'ed and the log
3833 * replayed. For example, in the scenario:
3836 * ln mydir/foo mydir/bar
3839 * echo 2 > /proc/sys/vm/drop_caches # evicts inode
3840 * xfs_io -c fsync mydir/foo
3842 * mount fs, triggers fsync log replay
3844 * We must make sure that when we fsync our inode foo we also log its
3845 * parent inode, otherwise after log replay the parent still has the
3846 * dentry with the "bar" name but our inode foo has a link count of 1
3847 * and doesn't have an inode ref with the name "bar" anymore.
3849 * Setting last_unlink_trans to last_trans is a pessimistic approach,
3850 * but it guarantees correctness at the expense of occasional full
3851 * transaction commits on fsync if our inode is a directory, or if our
3852 * inode is not a directory, logging its parent unnecessarily.
3854 BTRFS_I(inode)->last_unlink_trans = BTRFS_I(inode)->last_trans;
3857 if (inode->i_nlink != 1 ||
3858 path->slots[0] >= btrfs_header_nritems(leaf))
3861 btrfs_item_key_to_cpu(leaf, &location, path->slots[0]);
3862 if (location.objectid != btrfs_ino(BTRFS_I(inode)))
3865 ptr = btrfs_item_ptr_offset(leaf, path->slots[0]);
3866 if (location.type == BTRFS_INODE_REF_KEY) {
3867 struct btrfs_inode_ref *ref;
3869 ref = (struct btrfs_inode_ref *)ptr;
3870 BTRFS_I(inode)->dir_index = btrfs_inode_ref_index(leaf, ref);
3871 } else if (location.type == BTRFS_INODE_EXTREF_KEY) {
3872 struct btrfs_inode_extref *extref;
3874 extref = (struct btrfs_inode_extref *)ptr;
3875 BTRFS_I(inode)->dir_index = btrfs_inode_extref_index(leaf,
3880 * try to precache a NULL acl entry for files that don't have
3881 * any xattrs or acls
3883 maybe_acls = acls_after_inode_item(leaf, path->slots[0],
3884 btrfs_ino(BTRFS_I(inode)), &first_xattr_slot);
3885 if (first_xattr_slot != -1) {
3886 path->slots[0] = first_xattr_slot;
3887 ret = btrfs_load_inode_props(inode, path);
3890 "error loading props for ino %llu (root %llu): %d",
3891 btrfs_ino(BTRFS_I(inode)),
3892 root->root_key.objectid, ret);
3894 btrfs_free_path(path);
3897 cache_no_acl(inode);
3899 switch (inode->i_mode & S_IFMT) {
3901 inode->i_mapping->a_ops = &btrfs_aops;
3902 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
3903 inode->i_fop = &btrfs_file_operations;
3904 inode->i_op = &btrfs_file_inode_operations;
3907 inode->i_fop = &btrfs_dir_file_operations;
3908 inode->i_op = &btrfs_dir_inode_operations;
3911 inode->i_op = &btrfs_symlink_inode_operations;
3912 inode_nohighmem(inode);
3913 inode->i_mapping->a_ops = &btrfs_symlink_aops;
3916 inode->i_op = &btrfs_special_inode_operations;
3917 init_special_inode(inode, inode->i_mode, rdev);
3921 btrfs_update_iflags(inode);
3925 btrfs_free_path(path);
3926 make_bad_inode(inode);
3931 * given a leaf and an inode, copy the inode fields into the leaf
3933 static void fill_inode_item(struct btrfs_trans_handle *trans,
3934 struct extent_buffer *leaf,
3935 struct btrfs_inode_item *item,
3936 struct inode *inode)
3938 struct btrfs_map_token token;
3940 btrfs_init_map_token(&token);
3942 btrfs_set_token_inode_uid(leaf, item, i_uid_read(inode), &token);
3943 btrfs_set_token_inode_gid(leaf, item, i_gid_read(inode), &token);
3944 btrfs_set_token_inode_size(leaf, item, BTRFS_I(inode)->disk_i_size,
3946 btrfs_set_token_inode_mode(leaf, item, inode->i_mode, &token);
3947 btrfs_set_token_inode_nlink(leaf, item, inode->i_nlink, &token);
3949 btrfs_set_token_timespec_sec(leaf, &item->atime,
3950 inode->i_atime.tv_sec, &token);
3951 btrfs_set_token_timespec_nsec(leaf, &item->atime,
3952 inode->i_atime.tv_nsec, &token);
3954 btrfs_set_token_timespec_sec(leaf, &item->mtime,
3955 inode->i_mtime.tv_sec, &token);
3956 btrfs_set_token_timespec_nsec(leaf, &item->mtime,
3957 inode->i_mtime.tv_nsec, &token);
3959 btrfs_set_token_timespec_sec(leaf, &item->ctime,
3960 inode->i_ctime.tv_sec, &token);
3961 btrfs_set_token_timespec_nsec(leaf, &item->ctime,
3962 inode->i_ctime.tv_nsec, &token);
3964 btrfs_set_token_timespec_sec(leaf, &item->otime,
3965 BTRFS_I(inode)->i_otime.tv_sec, &token);
3966 btrfs_set_token_timespec_nsec(leaf, &item->otime,
3967 BTRFS_I(inode)->i_otime.tv_nsec, &token);
3969 btrfs_set_token_inode_nbytes(leaf, item, inode_get_bytes(inode),
3971 btrfs_set_token_inode_generation(leaf, item, BTRFS_I(inode)->generation,
3973 btrfs_set_token_inode_sequence(leaf, item, inode->i_version, &token);
3974 btrfs_set_token_inode_transid(leaf, item, trans->transid, &token);
3975 btrfs_set_token_inode_rdev(leaf, item, inode->i_rdev, &token);
3976 btrfs_set_token_inode_flags(leaf, item, BTRFS_I(inode)->flags, &token);
3977 btrfs_set_token_inode_block_group(leaf, item, 0, &token);
3981 * copy everything in the in-memory inode into the btree.
3983 static noinline int btrfs_update_inode_item(struct btrfs_trans_handle *trans,
3984 struct btrfs_root *root, struct inode *inode)
3986 struct btrfs_inode_item *inode_item;
3987 struct btrfs_path *path;
3988 struct extent_buffer *leaf;
3991 path = btrfs_alloc_path();
3995 path->leave_spinning = 1;
3996 ret = btrfs_lookup_inode(trans, root, path, &BTRFS_I(inode)->location,
4004 leaf = path->nodes[0];
4005 inode_item = btrfs_item_ptr(leaf, path->slots[0],
4006 struct btrfs_inode_item);
4008 fill_inode_item(trans, leaf, inode_item, inode);
4009 btrfs_mark_buffer_dirty(leaf);
4010 btrfs_set_inode_last_trans(trans, inode);
4013 btrfs_free_path(path);
4018 * copy everything in the in-memory inode into the btree.
4020 noinline int btrfs_update_inode(struct btrfs_trans_handle *trans,
4021 struct btrfs_root *root, struct inode *inode)
4023 struct btrfs_fs_info *fs_info = root->fs_info;
4027 * If the inode is a free space inode, we can deadlock during commit
4028 * if we put it into the delayed code.
4030 * The data relocation inode should also be directly updated
4033 if (!btrfs_is_free_space_inode(BTRFS_I(inode))
4034 && root->root_key.objectid != BTRFS_DATA_RELOC_TREE_OBJECTID
4035 && !test_bit(BTRFS_FS_LOG_RECOVERING, &fs_info->flags)) {
4036 btrfs_update_root_times(trans, root);
4038 ret = btrfs_delayed_update_inode(trans, root, inode);
4040 btrfs_set_inode_last_trans(trans, inode);
4044 return btrfs_update_inode_item(trans, root, inode);
4047 noinline int btrfs_update_inode_fallback(struct btrfs_trans_handle *trans,
4048 struct btrfs_root *root,
4049 struct inode *inode)
4053 ret = btrfs_update_inode(trans, root, inode);
4055 return btrfs_update_inode_item(trans, root, inode);
4060 * unlink helper that gets used here in inode.c and in the tree logging
4061 * recovery code. It remove a link in a directory with a given name, and
4062 * also drops the back refs in the inode to the directory
4064 static int __btrfs_unlink_inode(struct btrfs_trans_handle *trans,
4065 struct btrfs_root *root,
4066 struct btrfs_inode *dir,
4067 struct btrfs_inode *inode,
4068 const char *name, int name_len)
4070 struct btrfs_fs_info *fs_info = root->fs_info;
4071 struct btrfs_path *path;
4073 struct extent_buffer *leaf;
4074 struct btrfs_dir_item *di;
4075 struct btrfs_key key;
4077 u64 ino = btrfs_ino(inode);
4078 u64 dir_ino = btrfs_ino(dir);
4080 path = btrfs_alloc_path();
4086 path->leave_spinning = 1;
4087 di = btrfs_lookup_dir_item(trans, root, path, dir_ino,
4088 name, name_len, -1);
4097 leaf = path->nodes[0];
4098 btrfs_dir_item_key_to_cpu(leaf, di, &key);
4099 ret = btrfs_delete_one_dir_name(trans, root, path, di);
4102 btrfs_release_path(path);
4105 * If we don't have dir index, we have to get it by looking up
4106 * the inode ref, since we get the inode ref, remove it directly,
4107 * it is unnecessary to do delayed deletion.
4109 * But if we have dir index, needn't search inode ref to get it.
4110 * Since the inode ref is close to the inode item, it is better
4111 * that we delay to delete it, and just do this deletion when
4112 * we update the inode item.
4114 if (inode->dir_index) {
4115 ret = btrfs_delayed_delete_inode_ref(inode);
4117 index = inode->dir_index;
4122 ret = btrfs_del_inode_ref(trans, root, name, name_len, ino,
4126 "failed to delete reference to %.*s, inode %llu parent %llu",
4127 name_len, name, ino, dir_ino);
4128 btrfs_abort_transaction(trans, ret);
4132 ret = btrfs_delete_delayed_dir_index(trans, fs_info, dir, index);
4134 btrfs_abort_transaction(trans, ret);
4138 ret = btrfs_del_inode_ref_in_log(trans, root, name, name_len, inode,
4140 if (ret != 0 && ret != -ENOENT) {
4141 btrfs_abort_transaction(trans, ret);
4145 ret = btrfs_del_dir_entries_in_log(trans, root, name, name_len, dir,
4150 btrfs_abort_transaction(trans, ret);
4152 btrfs_free_path(path);
4156 btrfs_i_size_write(dir, dir->vfs_inode.i_size - name_len * 2);
4157 inode_inc_iversion(&inode->vfs_inode);
4158 inode_inc_iversion(&dir->vfs_inode);
4159 inode->vfs_inode.i_ctime = dir->vfs_inode.i_mtime =
4160 dir->vfs_inode.i_ctime = current_time(&inode->vfs_inode);
4161 ret = btrfs_update_inode(trans, root, &dir->vfs_inode);
4166 int btrfs_unlink_inode(struct btrfs_trans_handle *trans,
4167 struct btrfs_root *root,
4168 struct btrfs_inode *dir, struct btrfs_inode *inode,
4169 const char *name, int name_len)
4172 ret = __btrfs_unlink_inode(trans, root, dir, inode, name, name_len);
4174 drop_nlink(&inode->vfs_inode);
4175 ret = btrfs_update_inode(trans, root, &inode->vfs_inode);
4181 * helper to start transaction for unlink and rmdir.
4183 * unlink and rmdir are special in btrfs, they do not always free space, so
4184 * if we cannot make our reservations the normal way try and see if there is
4185 * plenty of slack room in the global reserve to migrate, otherwise we cannot
4186 * allow the unlink to occur.
4188 static struct btrfs_trans_handle *__unlink_start_trans(struct inode *dir)
4190 struct btrfs_root *root = BTRFS_I(dir)->root;
4193 * 1 for the possible orphan item
4194 * 1 for the dir item
4195 * 1 for the dir index
4196 * 1 for the inode ref
4199 return btrfs_start_transaction_fallback_global_rsv(root, 5, 5);
4202 static int btrfs_unlink(struct inode *dir, struct dentry *dentry)
4204 struct btrfs_root *root = BTRFS_I(dir)->root;
4205 struct btrfs_trans_handle *trans;
4206 struct inode *inode = d_inode(dentry);
4209 trans = __unlink_start_trans(dir);
4211 return PTR_ERR(trans);
4213 btrfs_record_unlink_dir(trans, BTRFS_I(dir), BTRFS_I(d_inode(dentry)),
4216 ret = btrfs_unlink_inode(trans, root, BTRFS_I(dir),
4217 BTRFS_I(d_inode(dentry)), dentry->d_name.name,
4218 dentry->d_name.len);
4222 if (inode->i_nlink == 0) {
4223 ret = btrfs_orphan_add(trans, BTRFS_I(inode));
4229 btrfs_end_transaction(trans);
4230 btrfs_btree_balance_dirty(root->fs_info);
4234 int btrfs_unlink_subvol(struct btrfs_trans_handle *trans,
4235 struct btrfs_root *root,
4236 struct inode *dir, u64 objectid,
4237 const char *name, int name_len)
4239 struct btrfs_fs_info *fs_info = root->fs_info;
4240 struct btrfs_path *path;
4241 struct extent_buffer *leaf;
4242 struct btrfs_dir_item *di;
4243 struct btrfs_key key;
4246 u64 dir_ino = btrfs_ino(BTRFS_I(dir));
4248 path = btrfs_alloc_path();
4252 di = btrfs_lookup_dir_item(trans, root, path, dir_ino,
4253 name, name_len, -1);
4254 if (IS_ERR_OR_NULL(di)) {
4262 leaf = path->nodes[0];
4263 btrfs_dir_item_key_to_cpu(leaf, di, &key);
4264 WARN_ON(key.type != BTRFS_ROOT_ITEM_KEY || key.objectid != objectid);
4265 ret = btrfs_delete_one_dir_name(trans, root, path, di);
4267 btrfs_abort_transaction(trans, ret);
4270 btrfs_release_path(path);
4272 ret = btrfs_del_root_ref(trans, fs_info, objectid,
4273 root->root_key.objectid, dir_ino,
4274 &index, name, name_len);
4276 if (ret != -ENOENT) {
4277 btrfs_abort_transaction(trans, ret);
4280 di = btrfs_search_dir_index_item(root, path, dir_ino,
4282 if (IS_ERR_OR_NULL(di)) {
4287 btrfs_abort_transaction(trans, ret);
4291 leaf = path->nodes[0];
4292 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
4293 btrfs_release_path(path);
4296 btrfs_release_path(path);
4298 ret = btrfs_delete_delayed_dir_index(trans, fs_info, BTRFS_I(dir), index);
4300 btrfs_abort_transaction(trans, ret);
4304 btrfs_i_size_write(BTRFS_I(dir), dir->i_size - name_len * 2);
4305 inode_inc_iversion(dir);
4306 dir->i_mtime = dir->i_ctime = current_time(dir);
4307 ret = btrfs_update_inode_fallback(trans, root, dir);
4309 btrfs_abort_transaction(trans, ret);
4311 btrfs_free_path(path);
4315 static int btrfs_rmdir(struct inode *dir, struct dentry *dentry)
4317 struct inode *inode = d_inode(dentry);
4319 struct btrfs_root *root = BTRFS_I(dir)->root;
4320 struct btrfs_trans_handle *trans;
4321 u64 last_unlink_trans;
4323 if (inode->i_size > BTRFS_EMPTY_DIR_SIZE)
4325 if (btrfs_ino(BTRFS_I(inode)) == BTRFS_FIRST_FREE_OBJECTID)
4328 trans = __unlink_start_trans(dir);
4330 return PTR_ERR(trans);
4332 if (unlikely(btrfs_ino(BTRFS_I(inode)) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)) {
4333 err = btrfs_unlink_subvol(trans, root, dir,
4334 BTRFS_I(inode)->location.objectid,
4335 dentry->d_name.name,
4336 dentry->d_name.len);
4340 err = btrfs_orphan_add(trans, BTRFS_I(inode));
4344 last_unlink_trans = BTRFS_I(inode)->last_unlink_trans;
4346 /* now the directory is empty */
4347 err = btrfs_unlink_inode(trans, root, BTRFS_I(dir),
4348 BTRFS_I(d_inode(dentry)), dentry->d_name.name,
4349 dentry->d_name.len);
4351 btrfs_i_size_write(BTRFS_I(inode), 0);
4353 * Propagate the last_unlink_trans value of the deleted dir to
4354 * its parent directory. This is to prevent an unrecoverable
4355 * log tree in the case we do something like this:
4357 * 2) create snapshot under dir foo
4358 * 3) delete the snapshot
4361 * 6) fsync foo or some file inside foo
4363 if (last_unlink_trans >= trans->transid)
4364 BTRFS_I(dir)->last_unlink_trans = last_unlink_trans;
4367 btrfs_end_transaction(trans);
4368 btrfs_btree_balance_dirty(root->fs_info);
4373 static int truncate_space_check(struct btrfs_trans_handle *trans,
4374 struct btrfs_root *root,
4377 struct btrfs_fs_info *fs_info = root->fs_info;
4381 * This is only used to apply pressure to the enospc system, we don't
4382 * intend to use this reservation at all.
4384 bytes_deleted = btrfs_csum_bytes_to_leaves(fs_info, bytes_deleted);
4385 bytes_deleted *= fs_info->nodesize;
4386 ret = btrfs_block_rsv_add(root, &fs_info->trans_block_rsv,
4387 bytes_deleted, BTRFS_RESERVE_NO_FLUSH);
4389 trace_btrfs_space_reservation(fs_info, "transaction",
4392 trans->bytes_reserved += bytes_deleted;
4399 * Return this if we need to call truncate_block for the last bit of the
4402 #define NEED_TRUNCATE_BLOCK 1
4405 * this can truncate away extent items, csum items and directory items.
4406 * It starts at a high offset and removes keys until it can't find
4407 * any higher than new_size
4409 * csum items that cross the new i_size are truncated to the new size
4412 * min_type is the minimum key type to truncate down to. If set to 0, this
4413 * will kill all the items on this inode, including the INODE_ITEM_KEY.
4415 int btrfs_truncate_inode_items(struct btrfs_trans_handle *trans,
4416 struct btrfs_root *root,
4417 struct inode *inode,
4418 u64 new_size, u32 min_type)
4420 struct btrfs_fs_info *fs_info = root->fs_info;
4421 struct btrfs_path *path;
4422 struct extent_buffer *leaf;
4423 struct btrfs_file_extent_item *fi;
4424 struct btrfs_key key;
4425 struct btrfs_key found_key;
4426 u64 extent_start = 0;
4427 u64 extent_num_bytes = 0;
4428 u64 extent_offset = 0;
4430 u64 last_size = new_size;
4431 u32 found_type = (u8)-1;
4434 int pending_del_nr = 0;
4435 int pending_del_slot = 0;
4436 int extent_type = -1;
4439 u64 ino = btrfs_ino(BTRFS_I(inode));
4440 u64 bytes_deleted = 0;
4441 bool be_nice = false;
4442 bool should_throttle = false;
4443 bool should_end = false;
4445 BUG_ON(new_size > 0 && min_type != BTRFS_EXTENT_DATA_KEY);
4448 * for non-free space inodes and ref cows, we want to back off from
4451 if (!btrfs_is_free_space_inode(BTRFS_I(inode)) &&
4452 test_bit(BTRFS_ROOT_REF_COWS, &root->state))
4455 path = btrfs_alloc_path();
4458 path->reada = READA_BACK;
4461 * We want to drop from the next block forward in case this new size is
4462 * not block aligned since we will be keeping the last block of the
4463 * extent just the way it is.
4465 if (test_bit(BTRFS_ROOT_REF_COWS, &root->state) ||
4466 root == fs_info->tree_root)
4467 btrfs_drop_extent_cache(BTRFS_I(inode), ALIGN(new_size,
4468 fs_info->sectorsize),
4472 * This function is also used to drop the items in the log tree before
4473 * we relog the inode, so if root != BTRFS_I(inode)->root, it means
4474 * it is used to drop the loged items. So we shouldn't kill the delayed
4477 if (min_type == 0 && root == BTRFS_I(inode)->root)
4478 btrfs_kill_delayed_inode_items(BTRFS_I(inode));
4481 key.offset = (u64)-1;
4486 * with a 16K leaf size and 128MB extents, you can actually queue
4487 * up a huge file in a single leaf. Most of the time that
4488 * bytes_deleted is > 0, it will be huge by the time we get here
4490 if (be_nice && bytes_deleted > SZ_32M) {
4491 if (btrfs_should_end_transaction(trans)) {
4498 path->leave_spinning = 1;
4499 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
4506 /* there are no items in the tree for us to truncate, we're
4509 if (path->slots[0] == 0)
4516 leaf = path->nodes[0];
4517 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
4518 found_type = found_key.type;
4520 if (found_key.objectid != ino)
4523 if (found_type < min_type)
4526 item_end = found_key.offset;
4527 if (found_type == BTRFS_EXTENT_DATA_KEY) {
4528 fi = btrfs_item_ptr(leaf, path->slots[0],
4529 struct btrfs_file_extent_item);
4530 extent_type = btrfs_file_extent_type(leaf, fi);
4531 if (extent_type != BTRFS_FILE_EXTENT_INLINE) {
4533 btrfs_file_extent_num_bytes(leaf, fi);
4535 trace_btrfs_truncate_show_fi_regular(
4536 BTRFS_I(inode), leaf, fi,
4538 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
4539 item_end += btrfs_file_extent_inline_len(leaf,
4540 path->slots[0], fi);
4542 trace_btrfs_truncate_show_fi_inline(
4543 BTRFS_I(inode), leaf, fi, path->slots[0],
4548 if (found_type > min_type) {
4551 if (item_end < new_size)
4553 if (found_key.offset >= new_size)
4559 /* FIXME, shrink the extent if the ref count is only 1 */
4560 if (found_type != BTRFS_EXTENT_DATA_KEY)
4563 if (extent_type != BTRFS_FILE_EXTENT_INLINE) {
4565 extent_start = btrfs_file_extent_disk_bytenr(leaf, fi);
4567 u64 orig_num_bytes =
4568 btrfs_file_extent_num_bytes(leaf, fi);
4569 extent_num_bytes = ALIGN(new_size -
4571 fs_info->sectorsize);
4572 btrfs_set_file_extent_num_bytes(leaf, fi,
4574 num_dec = (orig_num_bytes -
4576 if (test_bit(BTRFS_ROOT_REF_COWS,
4579 inode_sub_bytes(inode, num_dec);
4580 btrfs_mark_buffer_dirty(leaf);
4583 btrfs_file_extent_disk_num_bytes(leaf,
4585 extent_offset = found_key.offset -
4586 btrfs_file_extent_offset(leaf, fi);
4588 /* FIXME blocksize != 4096 */
4589 num_dec = btrfs_file_extent_num_bytes(leaf, fi);
4590 if (extent_start != 0) {
4592 if (test_bit(BTRFS_ROOT_REF_COWS,
4594 inode_sub_bytes(inode, num_dec);
4597 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
4599 * we can't truncate inline items that have had
4603 btrfs_file_extent_encryption(leaf, fi) == 0 &&
4604 btrfs_file_extent_other_encoding(leaf, fi) == 0 &&
4605 btrfs_file_extent_compression(leaf, fi) == 0) {
4606 u32 size = (u32)(new_size - found_key.offset);
4608 btrfs_set_file_extent_ram_bytes(leaf, fi, size);
4609 size = btrfs_file_extent_calc_inline_size(size);
4610 btrfs_truncate_item(root->fs_info, path, size, 1);
4611 } else if (!del_item) {
4613 * We have to bail so the last_size is set to
4614 * just before this extent.
4616 err = NEED_TRUNCATE_BLOCK;
4620 if (test_bit(BTRFS_ROOT_REF_COWS, &root->state))
4621 inode_sub_bytes(inode, item_end + 1 - new_size);
4625 last_size = found_key.offset;
4627 last_size = new_size;
4629 if (!pending_del_nr) {
4630 /* no pending yet, add ourselves */
4631 pending_del_slot = path->slots[0];
4633 } else if (pending_del_nr &&
4634 path->slots[0] + 1 == pending_del_slot) {
4635 /* hop on the pending chunk */
4637 pending_del_slot = path->slots[0];
4644 should_throttle = false;
4647 (test_bit(BTRFS_ROOT_REF_COWS, &root->state) ||
4648 root == fs_info->tree_root)) {
4649 btrfs_set_path_blocking(path);
4650 bytes_deleted += extent_num_bytes;
4651 ret = btrfs_free_extent(trans, root, extent_start,
4652 extent_num_bytes, 0,
4653 btrfs_header_owner(leaf),
4654 ino, extent_offset);
4656 if (btrfs_should_throttle_delayed_refs(trans, fs_info))
4657 btrfs_async_run_delayed_refs(fs_info,
4658 trans->delayed_ref_updates * 2,
4661 if (truncate_space_check(trans, root,
4662 extent_num_bytes)) {
4665 if (btrfs_should_throttle_delayed_refs(trans,
4667 should_throttle = true;
4671 if (found_type == BTRFS_INODE_ITEM_KEY)
4674 if (path->slots[0] == 0 ||
4675 path->slots[0] != pending_del_slot ||
4676 should_throttle || should_end) {
4677 if (pending_del_nr) {
4678 ret = btrfs_del_items(trans, root, path,
4682 btrfs_abort_transaction(trans, ret);
4687 btrfs_release_path(path);
4688 if (should_throttle) {
4689 unsigned long updates = trans->delayed_ref_updates;
4691 trans->delayed_ref_updates = 0;
4692 ret = btrfs_run_delayed_refs(trans,
4700 * if we failed to refill our space rsv, bail out
4701 * and let the transaction restart
4713 if (pending_del_nr) {
4714 ret = btrfs_del_items(trans, root, path, pending_del_slot,
4717 btrfs_abort_transaction(trans, ret);
4720 if (root->root_key.objectid != BTRFS_TREE_LOG_OBJECTID) {
4721 ASSERT(last_size >= new_size);
4722 if (!err && last_size > new_size)
4723 last_size = new_size;
4724 btrfs_ordered_update_i_size(inode, last_size, NULL);
4727 btrfs_free_path(path);
4729 if (be_nice && bytes_deleted > SZ_32M) {
4730 unsigned long updates = trans->delayed_ref_updates;
4732 trans->delayed_ref_updates = 0;
4733 ret = btrfs_run_delayed_refs(trans, fs_info,
4743 * btrfs_truncate_block - read, zero a chunk and write a block
4744 * @inode - inode that we're zeroing
4745 * @from - the offset to start zeroing
4746 * @len - the length to zero, 0 to zero the entire range respective to the
4748 * @front - zero up to the offset instead of from the offset on
4750 * This will find the block for the "from" offset and cow the block and zero the
4751 * part we want to zero. This is used with truncate and hole punching.
4753 int btrfs_truncate_block(struct inode *inode, loff_t from, loff_t len,
4756 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
4757 struct address_space *mapping = inode->i_mapping;
4758 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
4759 struct btrfs_ordered_extent *ordered;
4760 struct extent_state *cached_state = NULL;
4761 struct extent_changeset *data_reserved = NULL;
4763 u32 blocksize = fs_info->sectorsize;
4764 pgoff_t index = from >> PAGE_SHIFT;
4765 unsigned offset = from & (blocksize - 1);
4767 gfp_t mask = btrfs_alloc_write_mask(mapping);
4772 if ((offset & (blocksize - 1)) == 0 &&
4773 (!len || ((len & (blocksize - 1)) == 0)))
4776 block_start = round_down(from, blocksize);
4777 block_end = block_start + blocksize - 1;
4779 ret = btrfs_delalloc_reserve_space(inode, &data_reserved,
4780 block_start, blocksize);
4785 page = find_or_create_page(mapping, index, mask);
4787 btrfs_delalloc_release_space(inode, data_reserved,
4788 block_start, blocksize);
4789 btrfs_delalloc_release_extents(BTRFS_I(inode), blocksize);
4794 if (!PageUptodate(page)) {
4795 ret = btrfs_readpage(NULL, page);
4797 if (page->mapping != mapping) {
4802 if (!PageUptodate(page)) {
4807 wait_on_page_writeback(page);
4809 lock_extent_bits(io_tree, block_start, block_end, &cached_state);
4810 set_page_extent_mapped(page);
4812 ordered = btrfs_lookup_ordered_extent(inode, block_start);
4814 unlock_extent_cached(io_tree, block_start, block_end,
4815 &cached_state, GFP_NOFS);
4818 btrfs_start_ordered_extent(inode, ordered, 1);
4819 btrfs_put_ordered_extent(ordered);
4823 clear_extent_bit(&BTRFS_I(inode)->io_tree, block_start, block_end,
4824 EXTENT_DIRTY | EXTENT_DELALLOC |
4825 EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG,
4826 0, 0, &cached_state);
4828 ret = btrfs_set_extent_delalloc(inode, block_start, block_end, 0,
4831 unlock_extent_cached(io_tree, block_start, block_end,
4832 &cached_state, GFP_NOFS);
4836 if (offset != blocksize) {
4838 len = blocksize - offset;
4841 memset(kaddr + (block_start - page_offset(page)),
4844 memset(kaddr + (block_start - page_offset(page)) + offset,
4846 flush_dcache_page(page);
4849 ClearPageChecked(page);
4850 set_page_dirty(page);
4851 unlock_extent_cached(io_tree, block_start, block_end, &cached_state,
4856 btrfs_delalloc_release_space(inode, data_reserved, block_start,
4858 btrfs_delalloc_release_extents(BTRFS_I(inode), blocksize);
4862 extent_changeset_free(data_reserved);
4866 static int maybe_insert_hole(struct btrfs_root *root, struct inode *inode,
4867 u64 offset, u64 len)
4869 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
4870 struct btrfs_trans_handle *trans;
4874 * Still need to make sure the inode looks like it's been updated so
4875 * that any holes get logged if we fsync.
4877 if (btrfs_fs_incompat(fs_info, NO_HOLES)) {
4878 BTRFS_I(inode)->last_trans = fs_info->generation;
4879 BTRFS_I(inode)->last_sub_trans = root->log_transid;
4880 BTRFS_I(inode)->last_log_commit = root->last_log_commit;
4885 * 1 - for the one we're dropping
4886 * 1 - for the one we're adding
4887 * 1 - for updating the inode.
4889 trans = btrfs_start_transaction(root, 3);
4891 return PTR_ERR(trans);
4893 ret = btrfs_drop_extents(trans, root, inode, offset, offset + len, 1);
4895 btrfs_abort_transaction(trans, ret);
4896 btrfs_end_transaction(trans);
4900 ret = btrfs_insert_file_extent(trans, root, btrfs_ino(BTRFS_I(inode)),
4901 offset, 0, 0, len, 0, len, 0, 0, 0);
4903 btrfs_abort_transaction(trans, ret);
4905 btrfs_update_inode(trans, root, inode);
4906 btrfs_end_transaction(trans);
4911 * This function puts in dummy file extents for the area we're creating a hole
4912 * for. So if we are truncating this file to a larger size we need to insert
4913 * these file extents so that btrfs_get_extent will return a EXTENT_MAP_HOLE for
4914 * the range between oldsize and size
4916 int btrfs_cont_expand(struct inode *inode, loff_t oldsize, loff_t size)
4918 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
4919 struct btrfs_root *root = BTRFS_I(inode)->root;
4920 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
4921 struct extent_map *em = NULL;
4922 struct extent_state *cached_state = NULL;
4923 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
4924 u64 hole_start = ALIGN(oldsize, fs_info->sectorsize);
4925 u64 block_end = ALIGN(size, fs_info->sectorsize);
4932 * If our size started in the middle of a block we need to zero out the
4933 * rest of the block before we expand the i_size, otherwise we could
4934 * expose stale data.
4936 err = btrfs_truncate_block(inode, oldsize, 0, 0);
4940 if (size <= hole_start)
4944 struct btrfs_ordered_extent *ordered;
4946 lock_extent_bits(io_tree, hole_start, block_end - 1,
4948 ordered = btrfs_lookup_ordered_range(BTRFS_I(inode), hole_start,
4949 block_end - hole_start);
4952 unlock_extent_cached(io_tree, hole_start, block_end - 1,
4953 &cached_state, GFP_NOFS);
4954 btrfs_start_ordered_extent(inode, ordered, 1);
4955 btrfs_put_ordered_extent(ordered);
4958 cur_offset = hole_start;
4960 em = btrfs_get_extent(BTRFS_I(inode), NULL, 0, cur_offset,
4961 block_end - cur_offset, 0);
4967 last_byte = min(extent_map_end(em), block_end);
4968 last_byte = ALIGN(last_byte, fs_info->sectorsize);
4969 if (!test_bit(EXTENT_FLAG_PREALLOC, &em->flags)) {
4970 struct extent_map *hole_em;
4971 hole_size = last_byte - cur_offset;
4973 err = maybe_insert_hole(root, inode, cur_offset,
4977 btrfs_drop_extent_cache(BTRFS_I(inode), cur_offset,
4978 cur_offset + hole_size - 1, 0);
4979 hole_em = alloc_extent_map();
4981 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
4982 &BTRFS_I(inode)->runtime_flags);
4985 hole_em->start = cur_offset;
4986 hole_em->len = hole_size;
4987 hole_em->orig_start = cur_offset;
4989 hole_em->block_start = EXTENT_MAP_HOLE;
4990 hole_em->block_len = 0;
4991 hole_em->orig_block_len = 0;
4992 hole_em->ram_bytes = hole_size;
4993 hole_em->bdev = fs_info->fs_devices->latest_bdev;
4994 hole_em->compress_type = BTRFS_COMPRESS_NONE;
4995 hole_em->generation = fs_info->generation;
4998 write_lock(&em_tree->lock);
4999 err = add_extent_mapping(em_tree, hole_em, 1);
5000 write_unlock(&em_tree->lock);
5003 btrfs_drop_extent_cache(BTRFS_I(inode),
5008 free_extent_map(hole_em);
5011 free_extent_map(em);
5013 cur_offset = last_byte;
5014 if (cur_offset >= block_end)
5017 free_extent_map(em);
5018 unlock_extent_cached(io_tree, hole_start, block_end - 1, &cached_state,
5023 static int btrfs_setsize(struct inode *inode, struct iattr *attr)
5025 struct btrfs_root *root = BTRFS_I(inode)->root;
5026 struct btrfs_trans_handle *trans;
5027 loff_t oldsize = i_size_read(inode);
5028 loff_t newsize = attr->ia_size;
5029 int mask = attr->ia_valid;
5033 * The regular truncate() case without ATTR_CTIME and ATTR_MTIME is a
5034 * special case where we need to update the times despite not having
5035 * these flags set. For all other operations the VFS set these flags
5036 * explicitly if it wants a timestamp update.
5038 if (newsize != oldsize) {
5039 inode_inc_iversion(inode);
5040 if (!(mask & (ATTR_CTIME | ATTR_MTIME)))
5041 inode->i_ctime = inode->i_mtime =
5042 current_time(inode);
5045 if (newsize > oldsize) {
5047 * Don't do an expanding truncate while snapshotting is ongoing.
5048 * This is to ensure the snapshot captures a fully consistent
5049 * state of this file - if the snapshot captures this expanding
5050 * truncation, it must capture all writes that happened before
5053 btrfs_wait_for_snapshot_creation(root);
5054 ret = btrfs_cont_expand(inode, oldsize, newsize);
5056 btrfs_end_write_no_snapshotting(root);
5060 trans = btrfs_start_transaction(root, 1);
5061 if (IS_ERR(trans)) {
5062 btrfs_end_write_no_snapshotting(root);
5063 return PTR_ERR(trans);
5066 i_size_write(inode, newsize);
5067 btrfs_ordered_update_i_size(inode, i_size_read(inode), NULL);
5068 pagecache_isize_extended(inode, oldsize, newsize);
5069 ret = btrfs_update_inode(trans, root, inode);
5070 btrfs_end_write_no_snapshotting(root);
5071 btrfs_end_transaction(trans);
5075 * We're truncating a file that used to have good data down to
5076 * zero. Make sure it gets into the ordered flush list so that
5077 * any new writes get down to disk quickly.
5080 set_bit(BTRFS_INODE_ORDERED_DATA_CLOSE,
5081 &BTRFS_I(inode)->runtime_flags);
5084 * 1 for the orphan item we're going to add
5085 * 1 for the orphan item deletion.
5087 trans = btrfs_start_transaction(root, 2);
5089 return PTR_ERR(trans);
5092 * We need to do this in case we fail at _any_ point during the
5093 * actual truncate. Once we do the truncate_setsize we could
5094 * invalidate pages which forces any outstanding ordered io to
5095 * be instantly completed which will give us extents that need
5096 * to be truncated. If we fail to get an orphan inode down we
5097 * could have left over extents that were never meant to live,
5098 * so we need to guarantee from this point on that everything
5099 * will be consistent.
5101 ret = btrfs_orphan_add(trans, BTRFS_I(inode));
5102 btrfs_end_transaction(trans);
5106 /* we don't support swapfiles, so vmtruncate shouldn't fail */
5107 truncate_setsize(inode, newsize);
5109 /* Disable nonlocked read DIO to avoid the end less truncate */
5110 btrfs_inode_block_unlocked_dio(BTRFS_I(inode));
5111 inode_dio_wait(inode);
5112 btrfs_inode_resume_unlocked_dio(BTRFS_I(inode));
5114 ret = btrfs_truncate(inode);
5115 if (ret && inode->i_nlink) {
5118 /* To get a stable disk_i_size */
5119 err = btrfs_wait_ordered_range(inode, 0, (u64)-1);
5121 btrfs_orphan_del(NULL, BTRFS_I(inode));
5126 * failed to truncate, disk_i_size is only adjusted down
5127 * as we remove extents, so it should represent the true
5128 * size of the inode, so reset the in memory size and
5129 * delete our orphan entry.
5131 trans = btrfs_join_transaction(root);
5132 if (IS_ERR(trans)) {
5133 btrfs_orphan_del(NULL, BTRFS_I(inode));
5136 i_size_write(inode, BTRFS_I(inode)->disk_i_size);
5137 err = btrfs_orphan_del(trans, BTRFS_I(inode));
5139 btrfs_abort_transaction(trans, err);
5140 btrfs_end_transaction(trans);
5147 static int btrfs_setattr(struct dentry *dentry, struct iattr *attr)
5149 struct inode *inode = d_inode(dentry);
5150 struct btrfs_root *root = BTRFS_I(inode)->root;
5153 if (btrfs_root_readonly(root))
5156 err = setattr_prepare(dentry, attr);
5160 if (S_ISREG(inode->i_mode) && (attr->ia_valid & ATTR_SIZE)) {
5161 err = btrfs_setsize(inode, attr);
5166 if (attr->ia_valid) {
5167 setattr_copy(inode, attr);
5168 inode_inc_iversion(inode);
5169 err = btrfs_dirty_inode(inode);
5171 if (!err && attr->ia_valid & ATTR_MODE)
5172 err = posix_acl_chmod(inode, inode->i_mode);
5179 * While truncating the inode pages during eviction, we get the VFS calling
5180 * btrfs_invalidatepage() against each page of the inode. This is slow because
5181 * the calls to btrfs_invalidatepage() result in a huge amount of calls to
5182 * lock_extent_bits() and clear_extent_bit(), which keep merging and splitting
5183 * extent_state structures over and over, wasting lots of time.
5185 * Therefore if the inode is being evicted, let btrfs_invalidatepage() skip all
5186 * those expensive operations on a per page basis and do only the ordered io
5187 * finishing, while we release here the extent_map and extent_state structures,
5188 * without the excessive merging and splitting.
5190 static void evict_inode_truncate_pages(struct inode *inode)
5192 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
5193 struct extent_map_tree *map_tree = &BTRFS_I(inode)->extent_tree;
5194 struct rb_node *node;
5196 ASSERT(inode->i_state & I_FREEING);
5197 truncate_inode_pages_final(&inode->i_data);
5199 write_lock(&map_tree->lock);
5200 while (!RB_EMPTY_ROOT(&map_tree->map)) {
5201 struct extent_map *em;
5203 node = rb_first(&map_tree->map);
5204 em = rb_entry(node, struct extent_map, rb_node);
5205 clear_bit(EXTENT_FLAG_PINNED, &em->flags);
5206 clear_bit(EXTENT_FLAG_LOGGING, &em->flags);
5207 remove_extent_mapping(map_tree, em);
5208 free_extent_map(em);
5209 if (need_resched()) {
5210 write_unlock(&map_tree->lock);
5212 write_lock(&map_tree->lock);
5215 write_unlock(&map_tree->lock);
5218 * Keep looping until we have no more ranges in the io tree.
5219 * We can have ongoing bios started by readpages (called from readahead)
5220 * that have their endio callback (extent_io.c:end_bio_extent_readpage)
5221 * still in progress (unlocked the pages in the bio but did not yet
5222 * unlocked the ranges in the io tree). Therefore this means some
5223 * ranges can still be locked and eviction started because before
5224 * submitting those bios, which are executed by a separate task (work
5225 * queue kthread), inode references (inode->i_count) were not taken
5226 * (which would be dropped in the end io callback of each bio).
5227 * Therefore here we effectively end up waiting for those bios and
5228 * anyone else holding locked ranges without having bumped the inode's
5229 * reference count - if we don't do it, when they access the inode's
5230 * io_tree to unlock a range it may be too late, leading to an
5231 * use-after-free issue.
5233 spin_lock(&io_tree->lock);
5234 while (!RB_EMPTY_ROOT(&io_tree->state)) {
5235 struct extent_state *state;
5236 struct extent_state *cached_state = NULL;
5240 node = rb_first(&io_tree->state);
5241 state = rb_entry(node, struct extent_state, rb_node);
5242 start = state->start;
5244 spin_unlock(&io_tree->lock);
5246 lock_extent_bits(io_tree, start, end, &cached_state);
5249 * If still has DELALLOC flag, the extent didn't reach disk,
5250 * and its reserved space won't be freed by delayed_ref.
5251 * So we need to free its reserved space here.
5252 * (Refer to comment in btrfs_invalidatepage, case 2)
5254 * Note, end is the bytenr of last byte, so we need + 1 here.
5256 if (state->state & EXTENT_DELALLOC)
5257 btrfs_qgroup_free_data(inode, NULL, start, end - start + 1);
5259 clear_extent_bit(io_tree, start, end,
5260 EXTENT_LOCKED | EXTENT_DIRTY |
5261 EXTENT_DELALLOC | EXTENT_DO_ACCOUNTING |
5262 EXTENT_DEFRAG, 1, 1, &cached_state);
5265 spin_lock(&io_tree->lock);
5267 spin_unlock(&io_tree->lock);
5270 void btrfs_evict_inode(struct inode *inode)
5272 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
5273 struct btrfs_trans_handle *trans;
5274 struct btrfs_root *root = BTRFS_I(inode)->root;
5275 struct btrfs_block_rsv *rsv, *global_rsv;
5276 int steal_from_global = 0;
5280 trace_btrfs_inode_evict(inode);
5283 kmem_cache_free(btrfs_inode_cachep, BTRFS_I(inode));
5287 min_size = btrfs_calc_trunc_metadata_size(fs_info, 1);
5289 evict_inode_truncate_pages(inode);
5291 if (inode->i_nlink &&
5292 ((btrfs_root_refs(&root->root_item) != 0 &&
5293 root->root_key.objectid != BTRFS_ROOT_TREE_OBJECTID) ||
5294 btrfs_is_free_space_inode(BTRFS_I(inode))))
5297 if (is_bad_inode(inode)) {
5298 btrfs_orphan_del(NULL, BTRFS_I(inode));
5301 /* do we really want it for ->i_nlink > 0 and zero btrfs_root_refs? */
5302 if (!special_file(inode->i_mode))
5303 btrfs_wait_ordered_range(inode, 0, (u64)-1);
5305 btrfs_free_io_failure_record(BTRFS_I(inode), 0, (u64)-1);
5307 if (test_bit(BTRFS_FS_LOG_RECOVERING, &fs_info->flags)) {
5308 BUG_ON(test_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
5309 &BTRFS_I(inode)->runtime_flags));
5313 if (inode->i_nlink > 0) {
5314 BUG_ON(btrfs_root_refs(&root->root_item) != 0 &&
5315 root->root_key.objectid != BTRFS_ROOT_TREE_OBJECTID);
5319 ret = btrfs_commit_inode_delayed_inode(BTRFS_I(inode));
5321 btrfs_orphan_del(NULL, BTRFS_I(inode));
5325 rsv = btrfs_alloc_block_rsv(fs_info, BTRFS_BLOCK_RSV_TEMP);
5327 btrfs_orphan_del(NULL, BTRFS_I(inode));
5330 rsv->size = min_size;
5332 global_rsv = &fs_info->global_block_rsv;
5334 btrfs_i_size_write(BTRFS_I(inode), 0);
5337 * This is a bit simpler than btrfs_truncate since we've already
5338 * reserved our space for our orphan item in the unlink, so we just
5339 * need to reserve some slack space in case we add bytes and update
5340 * inode item when doing the truncate.
5343 ret = btrfs_block_rsv_refill(root, rsv, min_size,
5344 BTRFS_RESERVE_FLUSH_LIMIT);
5347 * Try and steal from the global reserve since we will
5348 * likely not use this space anyway, we want to try as
5349 * hard as possible to get this to work.
5352 steal_from_global++;
5354 steal_from_global = 0;
5358 * steal_from_global == 0: we reserved stuff, hooray!
5359 * steal_from_global == 1: we didn't reserve stuff, boo!
5360 * steal_from_global == 2: we've committed, still not a lot of
5361 * room but maybe we'll have room in the global reserve this
5363 * steal_from_global == 3: abandon all hope!
5365 if (steal_from_global > 2) {
5367 "Could not get space for a delete, will truncate on mount %d",
5369 btrfs_orphan_del(NULL, BTRFS_I(inode));
5370 btrfs_free_block_rsv(fs_info, rsv);
5374 trans = btrfs_join_transaction(root);
5375 if (IS_ERR(trans)) {
5376 btrfs_orphan_del(NULL, BTRFS_I(inode));
5377 btrfs_free_block_rsv(fs_info, rsv);
5382 * We can't just steal from the global reserve, we need to make
5383 * sure there is room to do it, if not we need to commit and try
5386 if (steal_from_global) {
5387 if (!btrfs_check_space_for_delayed_refs(trans, fs_info))
5388 ret = btrfs_block_rsv_migrate(global_rsv, rsv,
5395 * Couldn't steal from the global reserve, we have too much
5396 * pending stuff built up, commit the transaction and try it
5400 ret = btrfs_commit_transaction(trans);
5402 btrfs_orphan_del(NULL, BTRFS_I(inode));
5403 btrfs_free_block_rsv(fs_info, rsv);
5408 steal_from_global = 0;
5411 trans->block_rsv = rsv;
5413 ret = btrfs_truncate_inode_items(trans, root, inode, 0, 0);
5414 if (ret != -ENOSPC && ret != -EAGAIN)
5417 trans->block_rsv = &fs_info->trans_block_rsv;
5418 btrfs_end_transaction(trans);
5420 btrfs_btree_balance_dirty(fs_info);
5423 btrfs_free_block_rsv(fs_info, rsv);
5426 * Errors here aren't a big deal, it just means we leave orphan items
5427 * in the tree. They will be cleaned up on the next mount.
5430 trans->block_rsv = root->orphan_block_rsv;
5431 btrfs_orphan_del(trans, BTRFS_I(inode));
5433 btrfs_orphan_del(NULL, BTRFS_I(inode));
5436 trans->block_rsv = &fs_info->trans_block_rsv;
5437 if (!(root == fs_info->tree_root ||
5438 root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID))
5439 btrfs_return_ino(root, btrfs_ino(BTRFS_I(inode)));
5441 btrfs_end_transaction(trans);
5442 btrfs_btree_balance_dirty(fs_info);
5444 btrfs_remove_delayed_node(BTRFS_I(inode));
5449 * this returns the key found in the dir entry in the location pointer.
5450 * If no dir entries were found, location->objectid is 0.
5452 static int btrfs_inode_by_name(struct inode *dir, struct dentry *dentry,
5453 struct btrfs_key *location)
5455 const char *name = dentry->d_name.name;
5456 int namelen = dentry->d_name.len;
5457 struct btrfs_dir_item *di;
5458 struct btrfs_path *path;
5459 struct btrfs_root *root = BTRFS_I(dir)->root;
5462 path = btrfs_alloc_path();
5466 di = btrfs_lookup_dir_item(NULL, root, path, btrfs_ino(BTRFS_I(dir)),
5471 if (IS_ERR_OR_NULL(di))
5474 btrfs_dir_item_key_to_cpu(path->nodes[0], di, location);
5475 if (location->type != BTRFS_INODE_ITEM_KEY &&
5476 location->type != BTRFS_ROOT_ITEM_KEY) {
5477 btrfs_warn(root->fs_info,
5478 "%s gets something invalid in DIR_ITEM (name %s, directory ino %llu, location(%llu %u %llu))",
5479 __func__, name, btrfs_ino(BTRFS_I(dir)),
5480 location->objectid, location->type, location->offset);
5484 btrfs_free_path(path);
5487 location->objectid = 0;
5492 * when we hit a tree root in a directory, the btrfs part of the inode
5493 * needs to be changed to reflect the root directory of the tree root. This
5494 * is kind of like crossing a mount point.
5496 static int fixup_tree_root_location(struct btrfs_fs_info *fs_info,
5498 struct dentry *dentry,
5499 struct btrfs_key *location,
5500 struct btrfs_root **sub_root)
5502 struct btrfs_path *path;
5503 struct btrfs_root *new_root;
5504 struct btrfs_root_ref *ref;
5505 struct extent_buffer *leaf;
5506 struct btrfs_key key;
5510 path = btrfs_alloc_path();
5517 key.objectid = BTRFS_I(dir)->root->root_key.objectid;
5518 key.type = BTRFS_ROOT_REF_KEY;
5519 key.offset = location->objectid;
5521 ret = btrfs_search_slot(NULL, fs_info->tree_root, &key, path, 0, 0);
5528 leaf = path->nodes[0];
5529 ref = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_root_ref);
5530 if (btrfs_root_ref_dirid(leaf, ref) != btrfs_ino(BTRFS_I(dir)) ||
5531 btrfs_root_ref_name_len(leaf, ref) != dentry->d_name.len)
5534 ret = memcmp_extent_buffer(leaf, dentry->d_name.name,
5535 (unsigned long)(ref + 1),
5536 dentry->d_name.len);
5540 btrfs_release_path(path);
5542 new_root = btrfs_read_fs_root_no_name(fs_info, location);
5543 if (IS_ERR(new_root)) {
5544 err = PTR_ERR(new_root);
5548 *sub_root = new_root;
5549 location->objectid = btrfs_root_dirid(&new_root->root_item);
5550 location->type = BTRFS_INODE_ITEM_KEY;
5551 location->offset = 0;
5554 btrfs_free_path(path);
5558 static void inode_tree_add(struct inode *inode)
5560 struct btrfs_root *root = BTRFS_I(inode)->root;
5561 struct btrfs_inode *entry;
5563 struct rb_node *parent;
5564 struct rb_node *new = &BTRFS_I(inode)->rb_node;
5565 u64 ino = btrfs_ino(BTRFS_I(inode));
5567 if (inode_unhashed(inode))
5570 spin_lock(&root->inode_lock);
5571 p = &root->inode_tree.rb_node;
5574 entry = rb_entry(parent, struct btrfs_inode, rb_node);
5576 if (ino < btrfs_ino(BTRFS_I(&entry->vfs_inode)))
5577 p = &parent->rb_left;
5578 else if (ino > btrfs_ino(BTRFS_I(&entry->vfs_inode)))
5579 p = &parent->rb_right;
5581 WARN_ON(!(entry->vfs_inode.i_state &
5582 (I_WILL_FREE | I_FREEING)));
5583 rb_replace_node(parent, new, &root->inode_tree);
5584 RB_CLEAR_NODE(parent);
5585 spin_unlock(&root->inode_lock);
5589 rb_link_node(new, parent, p);
5590 rb_insert_color(new, &root->inode_tree);
5591 spin_unlock(&root->inode_lock);
5594 static void inode_tree_del(struct inode *inode)
5596 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
5597 struct btrfs_root *root = BTRFS_I(inode)->root;
5600 spin_lock(&root->inode_lock);
5601 if (!RB_EMPTY_NODE(&BTRFS_I(inode)->rb_node)) {
5602 rb_erase(&BTRFS_I(inode)->rb_node, &root->inode_tree);
5603 RB_CLEAR_NODE(&BTRFS_I(inode)->rb_node);
5604 empty = RB_EMPTY_ROOT(&root->inode_tree);
5606 spin_unlock(&root->inode_lock);
5608 if (empty && btrfs_root_refs(&root->root_item) == 0) {
5609 synchronize_srcu(&fs_info->subvol_srcu);
5610 spin_lock(&root->inode_lock);
5611 empty = RB_EMPTY_ROOT(&root->inode_tree);
5612 spin_unlock(&root->inode_lock);
5614 btrfs_add_dead_root(root);
5618 void btrfs_invalidate_inodes(struct btrfs_root *root)
5620 struct btrfs_fs_info *fs_info = root->fs_info;
5621 struct rb_node *node;
5622 struct rb_node *prev;
5623 struct btrfs_inode *entry;
5624 struct inode *inode;
5627 if (!test_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state))
5628 WARN_ON(btrfs_root_refs(&root->root_item) != 0);
5630 spin_lock(&root->inode_lock);
5632 node = root->inode_tree.rb_node;
5636 entry = rb_entry(node, struct btrfs_inode, rb_node);
5638 if (objectid < btrfs_ino(BTRFS_I(&entry->vfs_inode)))
5639 node = node->rb_left;
5640 else if (objectid > btrfs_ino(BTRFS_I(&entry->vfs_inode)))
5641 node = node->rb_right;
5647 entry = rb_entry(prev, struct btrfs_inode, rb_node);
5648 if (objectid <= btrfs_ino(BTRFS_I(&entry->vfs_inode))) {
5652 prev = rb_next(prev);
5656 entry = rb_entry(node, struct btrfs_inode, rb_node);
5657 objectid = btrfs_ino(BTRFS_I(&entry->vfs_inode)) + 1;
5658 inode = igrab(&entry->vfs_inode);
5660 spin_unlock(&root->inode_lock);
5661 if (atomic_read(&inode->i_count) > 1)
5662 d_prune_aliases(inode);
5664 * btrfs_drop_inode will have it removed from
5665 * the inode cache when its usage count
5670 spin_lock(&root->inode_lock);
5674 if (cond_resched_lock(&root->inode_lock))
5677 node = rb_next(node);
5679 spin_unlock(&root->inode_lock);
5682 static int btrfs_init_locked_inode(struct inode *inode, void *p)
5684 struct btrfs_iget_args *args = p;
5685 inode->i_ino = args->location->objectid;
5686 memcpy(&BTRFS_I(inode)->location, args->location,
5687 sizeof(*args->location));
5688 BTRFS_I(inode)->root = args->root;
5692 static int btrfs_find_actor(struct inode *inode, void *opaque)
5694 struct btrfs_iget_args *args = opaque;
5695 return args->location->objectid == BTRFS_I(inode)->location.objectid &&
5696 args->root == BTRFS_I(inode)->root;
5699 static struct inode *btrfs_iget_locked(struct super_block *s,
5700 struct btrfs_key *location,
5701 struct btrfs_root *root)
5703 struct inode *inode;
5704 struct btrfs_iget_args args;
5705 unsigned long hashval = btrfs_inode_hash(location->objectid, root);
5707 args.location = location;
5710 inode = iget5_locked(s, hashval, btrfs_find_actor,
5711 btrfs_init_locked_inode,
5716 /* Get an inode object given its location and corresponding root.
5717 * Returns in *is_new if the inode was read from disk
5719 struct inode *btrfs_iget(struct super_block *s, struct btrfs_key *location,
5720 struct btrfs_root *root, int *new)
5722 struct inode *inode;
5724 inode = btrfs_iget_locked(s, location, root);
5726 return ERR_PTR(-ENOMEM);
5728 if (inode->i_state & I_NEW) {
5731 ret = btrfs_read_locked_inode(inode);
5732 if (!is_bad_inode(inode)) {
5733 inode_tree_add(inode);
5734 unlock_new_inode(inode);
5738 unlock_new_inode(inode);
5741 inode = ERR_PTR(ret < 0 ? ret : -ESTALE);
5748 static struct inode *new_simple_dir(struct super_block *s,
5749 struct btrfs_key *key,
5750 struct btrfs_root *root)
5752 struct inode *inode = new_inode(s);
5755 return ERR_PTR(-ENOMEM);
5757 BTRFS_I(inode)->root = root;
5758 memcpy(&BTRFS_I(inode)->location, key, sizeof(*key));
5759 set_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags);
5761 inode->i_ino = BTRFS_EMPTY_SUBVOL_DIR_OBJECTID;
5762 inode->i_op = &btrfs_dir_ro_inode_operations;
5763 inode->i_opflags &= ~IOP_XATTR;
5764 inode->i_fop = &simple_dir_operations;
5765 inode->i_mode = S_IFDIR | S_IRUGO | S_IWUSR | S_IXUGO;
5766 inode->i_mtime = current_time(inode);
5767 inode->i_atime = inode->i_mtime;
5768 inode->i_ctime = inode->i_mtime;
5769 BTRFS_I(inode)->i_otime = inode->i_mtime;
5774 struct inode *btrfs_lookup_dentry(struct inode *dir, struct dentry *dentry)
5776 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
5777 struct inode *inode;
5778 struct btrfs_root *root = BTRFS_I(dir)->root;
5779 struct btrfs_root *sub_root = root;
5780 struct btrfs_key location;
5784 if (dentry->d_name.len > BTRFS_NAME_LEN)
5785 return ERR_PTR(-ENAMETOOLONG);
5787 ret = btrfs_inode_by_name(dir, dentry, &location);
5789 return ERR_PTR(ret);
5791 if (location.objectid == 0)
5792 return ERR_PTR(-ENOENT);
5794 if (location.type == BTRFS_INODE_ITEM_KEY) {
5795 inode = btrfs_iget(dir->i_sb, &location, root, NULL);
5799 index = srcu_read_lock(&fs_info->subvol_srcu);
5800 ret = fixup_tree_root_location(fs_info, dir, dentry,
5801 &location, &sub_root);
5804 inode = ERR_PTR(ret);
5806 inode = new_simple_dir(dir->i_sb, &location, sub_root);
5808 inode = btrfs_iget(dir->i_sb, &location, sub_root, NULL);
5810 srcu_read_unlock(&fs_info->subvol_srcu, index);
5812 if (!IS_ERR(inode) && root != sub_root) {
5813 down_read(&fs_info->cleanup_work_sem);
5814 if (!sb_rdonly(inode->i_sb))
5815 ret = btrfs_orphan_cleanup(sub_root);
5816 up_read(&fs_info->cleanup_work_sem);
5819 inode = ERR_PTR(ret);
5826 static int btrfs_dentry_delete(const struct dentry *dentry)
5828 struct btrfs_root *root;
5829 struct inode *inode = d_inode(dentry);
5831 if (!inode && !IS_ROOT(dentry))
5832 inode = d_inode(dentry->d_parent);
5835 root = BTRFS_I(inode)->root;
5836 if (btrfs_root_refs(&root->root_item) == 0)
5839 if (btrfs_ino(BTRFS_I(inode)) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)
5845 static void btrfs_dentry_release(struct dentry *dentry)
5847 kfree(dentry->d_fsdata);
5850 static struct dentry *btrfs_lookup(struct inode *dir, struct dentry *dentry,
5853 struct inode *inode;
5855 inode = btrfs_lookup_dentry(dir, dentry);
5856 if (IS_ERR(inode)) {
5857 if (PTR_ERR(inode) == -ENOENT)
5860 return ERR_CAST(inode);
5863 return d_splice_alias(inode, dentry);
5866 unsigned char btrfs_filetype_table[] = {
5867 DT_UNKNOWN, DT_REG, DT_DIR, DT_CHR, DT_BLK, DT_FIFO, DT_SOCK, DT_LNK
5871 * All this infrastructure exists because dir_emit can fault, and we are holding
5872 * the tree lock when doing readdir. For now just allocate a buffer and copy
5873 * our information into that, and then dir_emit from the buffer. This is
5874 * similar to what NFS does, only we don't keep the buffer around in pagecache
5875 * because I'm afraid I'll mess that up. Long term we need to make filldir do
5876 * copy_to_user_inatomic so we don't have to worry about page faulting under the
5879 static int btrfs_opendir(struct inode *inode, struct file *file)
5881 struct btrfs_file_private *private;
5883 private = kzalloc(sizeof(struct btrfs_file_private), GFP_KERNEL);
5886 private->filldir_buf = kzalloc(PAGE_SIZE, GFP_KERNEL);
5887 if (!private->filldir_buf) {
5891 file->private_data = private;
5902 static int btrfs_filldir(void *addr, int entries, struct dir_context *ctx)
5905 struct dir_entry *entry = addr;
5906 char *name = (char *)(entry + 1);
5908 ctx->pos = entry->offset;
5909 if (!dir_emit(ctx, name, entry->name_len, entry->ino,
5912 addr += sizeof(struct dir_entry) + entry->name_len;
5918 static int btrfs_real_readdir(struct file *file, struct dir_context *ctx)
5920 struct inode *inode = file_inode(file);
5921 struct btrfs_root *root = BTRFS_I(inode)->root;
5922 struct btrfs_file_private *private = file->private_data;
5923 struct btrfs_dir_item *di;
5924 struct btrfs_key key;
5925 struct btrfs_key found_key;
5926 struct btrfs_path *path;
5928 struct list_head ins_list;
5929 struct list_head del_list;
5931 struct extent_buffer *leaf;
5938 struct btrfs_key location;
5940 if (!dir_emit_dots(file, ctx))
5943 path = btrfs_alloc_path();
5947 addr = private->filldir_buf;
5948 path->reada = READA_FORWARD;
5950 INIT_LIST_HEAD(&ins_list);
5951 INIT_LIST_HEAD(&del_list);
5952 put = btrfs_readdir_get_delayed_items(inode, &ins_list, &del_list);
5955 key.type = BTRFS_DIR_INDEX_KEY;
5956 key.offset = ctx->pos;
5957 key.objectid = btrfs_ino(BTRFS_I(inode));
5959 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
5964 struct dir_entry *entry;
5966 leaf = path->nodes[0];
5967 slot = path->slots[0];
5968 if (slot >= btrfs_header_nritems(leaf)) {
5969 ret = btrfs_next_leaf(root, path);
5977 btrfs_item_key_to_cpu(leaf, &found_key, slot);
5979 if (found_key.objectid != key.objectid)
5981 if (found_key.type != BTRFS_DIR_INDEX_KEY)
5983 if (found_key.offset < ctx->pos)
5985 if (btrfs_should_delete_dir_index(&del_list, found_key.offset))
5987 di = btrfs_item_ptr(leaf, slot, struct btrfs_dir_item);
5988 name_len = btrfs_dir_name_len(leaf, di);
5989 if ((total_len + sizeof(struct dir_entry) + name_len) >=
5991 btrfs_release_path(path);
5992 ret = btrfs_filldir(private->filldir_buf, entries, ctx);
5995 addr = private->filldir_buf;
6002 entry->name_len = name_len;
6003 name_ptr = (char *)(entry + 1);
6004 read_extent_buffer(leaf, name_ptr, (unsigned long)(di + 1),
6006 entry->type = btrfs_filetype_table[btrfs_dir_type(leaf, di)];
6007 btrfs_dir_item_key_to_cpu(leaf, di, &location);
6008 entry->ino = location.objectid;
6009 entry->offset = found_key.offset;
6011 addr += sizeof(struct dir_entry) + name_len;
6012 total_len += sizeof(struct dir_entry) + name_len;
6016 btrfs_release_path(path);
6018 ret = btrfs_filldir(private->filldir_buf, entries, ctx);
6022 ret = btrfs_readdir_delayed_dir_index(ctx, &ins_list);
6027 * Stop new entries from being returned after we return the last
6030 * New directory entries are assigned a strictly increasing
6031 * offset. This means that new entries created during readdir
6032 * are *guaranteed* to be seen in the future by that readdir.
6033 * This has broken buggy programs which operate on names as
6034 * they're returned by readdir. Until we re-use freed offsets
6035 * we have this hack to stop new entries from being returned
6036 * under the assumption that they'll never reach this huge
6039 * This is being careful not to overflow 32bit loff_t unless the
6040 * last entry requires it because doing so has broken 32bit apps
6043 if (ctx->pos >= INT_MAX)
6044 ctx->pos = LLONG_MAX;
6051 btrfs_readdir_put_delayed_items(inode, &ins_list, &del_list);
6052 btrfs_free_path(path);
6056 int btrfs_write_inode(struct inode *inode, struct writeback_control *wbc)
6058 struct btrfs_root *root = BTRFS_I(inode)->root;
6059 struct btrfs_trans_handle *trans;
6061 bool nolock = false;
6063 if (test_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags))
6066 if (btrfs_fs_closing(root->fs_info) &&
6067 btrfs_is_free_space_inode(BTRFS_I(inode)))
6070 if (wbc->sync_mode == WB_SYNC_ALL) {
6072 trans = btrfs_join_transaction_nolock(root);
6074 trans = btrfs_join_transaction(root);
6076 return PTR_ERR(trans);
6077 ret = btrfs_commit_transaction(trans);
6083 * This is somewhat expensive, updating the tree every time the
6084 * inode changes. But, it is most likely to find the inode in cache.
6085 * FIXME, needs more benchmarking...there are no reasons other than performance
6086 * to keep or drop this code.
6088 static int btrfs_dirty_inode(struct inode *inode)
6090 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
6091 struct btrfs_root *root = BTRFS_I(inode)->root;
6092 struct btrfs_trans_handle *trans;
6095 if (test_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags))
6098 trans = btrfs_join_transaction(root);
6100 return PTR_ERR(trans);
6102 ret = btrfs_update_inode(trans, root, inode);
6103 if (ret && ret == -ENOSPC) {
6104 /* whoops, lets try again with the full transaction */
6105 btrfs_end_transaction(trans);
6106 trans = btrfs_start_transaction(root, 1);
6108 return PTR_ERR(trans);
6110 ret = btrfs_update_inode(trans, root, inode);
6112 btrfs_end_transaction(trans);
6113 if (BTRFS_I(inode)->delayed_node)
6114 btrfs_balance_delayed_items(fs_info);
6120 * This is a copy of file_update_time. We need this so we can return error on
6121 * ENOSPC for updating the inode in the case of file write and mmap writes.
6123 static int btrfs_update_time(struct inode *inode, struct timespec *now,
6126 struct btrfs_root *root = BTRFS_I(inode)->root;
6128 if (btrfs_root_readonly(root))
6131 if (flags & S_VERSION)
6132 inode_inc_iversion(inode);
6133 if (flags & S_CTIME)
6134 inode->i_ctime = *now;
6135 if (flags & S_MTIME)
6136 inode->i_mtime = *now;
6137 if (flags & S_ATIME)
6138 inode->i_atime = *now;
6139 return btrfs_dirty_inode(inode);
6143 * find the highest existing sequence number in a directory
6144 * and then set the in-memory index_cnt variable to reflect
6145 * free sequence numbers
6147 static int btrfs_set_inode_index_count(struct btrfs_inode *inode)
6149 struct btrfs_root *root = inode->root;
6150 struct btrfs_key key, found_key;
6151 struct btrfs_path *path;
6152 struct extent_buffer *leaf;
6155 key.objectid = btrfs_ino(inode);
6156 key.type = BTRFS_DIR_INDEX_KEY;
6157 key.offset = (u64)-1;
6159 path = btrfs_alloc_path();
6163 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
6166 /* FIXME: we should be able to handle this */
6172 * MAGIC NUMBER EXPLANATION:
6173 * since we search a directory based on f_pos we have to start at 2
6174 * since '.' and '..' have f_pos of 0 and 1 respectively, so everybody
6175 * else has to start at 2
6177 if (path->slots[0] == 0) {
6178 inode->index_cnt = 2;
6184 leaf = path->nodes[0];
6185 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
6187 if (found_key.objectid != btrfs_ino(inode) ||
6188 found_key.type != BTRFS_DIR_INDEX_KEY) {
6189 inode->index_cnt = 2;
6193 inode->index_cnt = found_key.offset + 1;
6195 btrfs_free_path(path);
6200 * helper to find a free sequence number in a given directory. This current
6201 * code is very simple, later versions will do smarter things in the btree
6203 int btrfs_set_inode_index(struct btrfs_inode *dir, u64 *index)
6207 if (dir->index_cnt == (u64)-1) {
6208 ret = btrfs_inode_delayed_dir_index_count(dir);
6210 ret = btrfs_set_inode_index_count(dir);
6216 *index = dir->index_cnt;
6222 static int btrfs_insert_inode_locked(struct inode *inode)
6224 struct btrfs_iget_args args;
6225 args.location = &BTRFS_I(inode)->location;
6226 args.root = BTRFS_I(inode)->root;
6228 return insert_inode_locked4(inode,
6229 btrfs_inode_hash(inode->i_ino, BTRFS_I(inode)->root),
6230 btrfs_find_actor, &args);
6234 * Inherit flags from the parent inode.
6236 * Currently only the compression flags and the cow flags are inherited.
6238 static void btrfs_inherit_iflags(struct inode *inode, struct inode *dir)
6245 flags = BTRFS_I(dir)->flags;
6247 if (flags & BTRFS_INODE_NOCOMPRESS) {
6248 BTRFS_I(inode)->flags &= ~BTRFS_INODE_COMPRESS;
6249 BTRFS_I(inode)->flags |= BTRFS_INODE_NOCOMPRESS;
6250 } else if (flags & BTRFS_INODE_COMPRESS) {
6251 BTRFS_I(inode)->flags &= ~BTRFS_INODE_NOCOMPRESS;
6252 BTRFS_I(inode)->flags |= BTRFS_INODE_COMPRESS;
6255 if (flags & BTRFS_INODE_NODATACOW) {
6256 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATACOW;
6257 if (S_ISREG(inode->i_mode))
6258 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATASUM;
6261 btrfs_update_iflags(inode);
6264 static struct inode *btrfs_new_inode(struct btrfs_trans_handle *trans,
6265 struct btrfs_root *root,
6267 const char *name, int name_len,
6268 u64 ref_objectid, u64 objectid,
6269 umode_t mode, u64 *index)
6271 struct btrfs_fs_info *fs_info = root->fs_info;
6272 struct inode *inode;
6273 struct btrfs_inode_item *inode_item;
6274 struct btrfs_key *location;
6275 struct btrfs_path *path;
6276 struct btrfs_inode_ref *ref;
6277 struct btrfs_key key[2];
6279 int nitems = name ? 2 : 1;
6283 path = btrfs_alloc_path();
6285 return ERR_PTR(-ENOMEM);
6287 inode = new_inode(fs_info->sb);
6289 btrfs_free_path(path);
6290 return ERR_PTR(-ENOMEM);
6294 * O_TMPFILE, set link count to 0, so that after this point,
6295 * we fill in an inode item with the correct link count.
6298 set_nlink(inode, 0);
6301 * we have to initialize this early, so we can reclaim the inode
6302 * number if we fail afterwards in this function.
6304 inode->i_ino = objectid;
6307 trace_btrfs_inode_request(dir);
6309 ret = btrfs_set_inode_index(BTRFS_I(dir), index);
6311 btrfs_free_path(path);
6313 return ERR_PTR(ret);
6319 * index_cnt is ignored for everything but a dir,
6320 * btrfs_get_inode_index_count has an explanation for the magic
6323 BTRFS_I(inode)->index_cnt = 2;
6324 BTRFS_I(inode)->dir_index = *index;
6325 BTRFS_I(inode)->root = root;
6326 BTRFS_I(inode)->generation = trans->transid;
6327 inode->i_generation = BTRFS_I(inode)->generation;
6330 * We could have gotten an inode number from somebody who was fsynced
6331 * and then removed in this same transaction, so let's just set full
6332 * sync since it will be a full sync anyway and this will blow away the
6333 * old info in the log.
6335 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &BTRFS_I(inode)->runtime_flags);
6337 key[0].objectid = objectid;
6338 key[0].type = BTRFS_INODE_ITEM_KEY;
6341 sizes[0] = sizeof(struct btrfs_inode_item);
6345 * Start new inodes with an inode_ref. This is slightly more
6346 * efficient for small numbers of hard links since they will
6347 * be packed into one item. Extended refs will kick in if we
6348 * add more hard links than can fit in the ref item.
6350 key[1].objectid = objectid;
6351 key[1].type = BTRFS_INODE_REF_KEY;
6352 key[1].offset = ref_objectid;
6354 sizes[1] = name_len + sizeof(*ref);
6357 location = &BTRFS_I(inode)->location;
6358 location->objectid = objectid;
6359 location->offset = 0;
6360 location->type = BTRFS_INODE_ITEM_KEY;
6362 ret = btrfs_insert_inode_locked(inode);
6366 path->leave_spinning = 1;
6367 ret = btrfs_insert_empty_items(trans, root, path, key, sizes, nitems);
6371 inode_init_owner(inode, dir, mode);
6372 inode_set_bytes(inode, 0);
6374 inode->i_mtime = current_time(inode);
6375 inode->i_atime = inode->i_mtime;
6376 inode->i_ctime = inode->i_mtime;
6377 BTRFS_I(inode)->i_otime = inode->i_mtime;
6379 inode_item = btrfs_item_ptr(path->nodes[0], path->slots[0],
6380 struct btrfs_inode_item);
6381 memzero_extent_buffer(path->nodes[0], (unsigned long)inode_item,
6382 sizeof(*inode_item));
6383 fill_inode_item(trans, path->nodes[0], inode_item, inode);
6386 ref = btrfs_item_ptr(path->nodes[0], path->slots[0] + 1,
6387 struct btrfs_inode_ref);
6388 btrfs_set_inode_ref_name_len(path->nodes[0], ref, name_len);
6389 btrfs_set_inode_ref_index(path->nodes[0], ref, *index);
6390 ptr = (unsigned long)(ref + 1);
6391 write_extent_buffer(path->nodes[0], name, ptr, name_len);
6394 btrfs_mark_buffer_dirty(path->nodes[0]);
6395 btrfs_free_path(path);
6397 btrfs_inherit_iflags(inode, dir);
6399 if (S_ISREG(mode)) {
6400 if (btrfs_test_opt(fs_info, NODATASUM))
6401 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATASUM;
6402 if (btrfs_test_opt(fs_info, NODATACOW))
6403 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATACOW |
6404 BTRFS_INODE_NODATASUM;
6407 inode_tree_add(inode);
6409 trace_btrfs_inode_new(inode);
6410 btrfs_set_inode_last_trans(trans, inode);
6412 btrfs_update_root_times(trans, root);
6414 ret = btrfs_inode_inherit_props(trans, inode, dir);
6417 "error inheriting props for ino %llu (root %llu): %d",
6418 btrfs_ino(BTRFS_I(inode)), root->root_key.objectid, ret);
6423 unlock_new_inode(inode);
6426 BTRFS_I(dir)->index_cnt--;
6427 btrfs_free_path(path);
6429 return ERR_PTR(ret);
6432 static inline u8 btrfs_inode_type(struct inode *inode)
6434 return btrfs_type_by_mode[(inode->i_mode & S_IFMT) >> S_SHIFT];
6438 * utility function to add 'inode' into 'parent_inode' with
6439 * a give name and a given sequence number.
6440 * if 'add_backref' is true, also insert a backref from the
6441 * inode to the parent directory.
6443 int btrfs_add_link(struct btrfs_trans_handle *trans,
6444 struct btrfs_inode *parent_inode, struct btrfs_inode *inode,
6445 const char *name, int name_len, int add_backref, u64 index)
6447 struct btrfs_fs_info *fs_info = btrfs_sb(inode->vfs_inode.i_sb);
6449 struct btrfs_key key;
6450 struct btrfs_root *root = parent_inode->root;
6451 u64 ino = btrfs_ino(inode);
6452 u64 parent_ino = btrfs_ino(parent_inode);
6454 if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
6455 memcpy(&key, &inode->root->root_key, sizeof(key));
6458 key.type = BTRFS_INODE_ITEM_KEY;
6462 if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
6463 ret = btrfs_add_root_ref(trans, fs_info, key.objectid,
6464 root->root_key.objectid, parent_ino,
6465 index, name, name_len);
6466 } else if (add_backref) {
6467 ret = btrfs_insert_inode_ref(trans, root, name, name_len, ino,
6471 /* Nothing to clean up yet */
6475 ret = btrfs_insert_dir_item(trans, root, name, name_len,
6477 btrfs_inode_type(&inode->vfs_inode), index);
6478 if (ret == -EEXIST || ret == -EOVERFLOW)
6481 btrfs_abort_transaction(trans, ret);
6485 btrfs_i_size_write(parent_inode, parent_inode->vfs_inode.i_size +
6487 inode_inc_iversion(&parent_inode->vfs_inode);
6488 parent_inode->vfs_inode.i_mtime = parent_inode->vfs_inode.i_ctime =
6489 current_time(&parent_inode->vfs_inode);
6490 ret = btrfs_update_inode(trans, root, &parent_inode->vfs_inode);
6492 btrfs_abort_transaction(trans, ret);
6496 if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
6499 err = btrfs_del_root_ref(trans, fs_info, key.objectid,
6500 root->root_key.objectid, parent_ino,
6501 &local_index, name, name_len);
6503 } else if (add_backref) {
6507 err = btrfs_del_inode_ref(trans, root, name, name_len,
6508 ino, parent_ino, &local_index);
6513 static int btrfs_add_nondir(struct btrfs_trans_handle *trans,
6514 struct btrfs_inode *dir, struct dentry *dentry,
6515 struct btrfs_inode *inode, int backref, u64 index)
6517 int err = btrfs_add_link(trans, dir, inode,
6518 dentry->d_name.name, dentry->d_name.len,
6525 static int btrfs_mknod(struct inode *dir, struct dentry *dentry,
6526 umode_t mode, dev_t rdev)
6528 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
6529 struct btrfs_trans_handle *trans;
6530 struct btrfs_root *root = BTRFS_I(dir)->root;
6531 struct inode *inode = NULL;
6538 * 2 for inode item and ref
6540 * 1 for xattr if selinux is on
6542 trans = btrfs_start_transaction(root, 5);
6544 return PTR_ERR(trans);
6546 err = btrfs_find_free_ino(root, &objectid);
6550 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
6551 dentry->d_name.len, btrfs_ino(BTRFS_I(dir)), objectid,
6553 if (IS_ERR(inode)) {
6554 err = PTR_ERR(inode);
6559 * If the active LSM wants to access the inode during
6560 * d_instantiate it needs these. Smack checks to see
6561 * if the filesystem supports xattrs by looking at the
6564 inode->i_op = &btrfs_special_inode_operations;
6565 init_special_inode(inode, inode->i_mode, rdev);
6567 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
6569 goto out_unlock_inode;
6571 err = btrfs_add_nondir(trans, BTRFS_I(dir), dentry, BTRFS_I(inode),
6574 goto out_unlock_inode;
6576 btrfs_update_inode(trans, root, inode);
6577 unlock_new_inode(inode);
6578 d_instantiate(dentry, inode);
6582 btrfs_end_transaction(trans);
6583 btrfs_btree_balance_dirty(fs_info);
6585 inode_dec_link_count(inode);
6592 unlock_new_inode(inode);
6597 static int btrfs_create(struct inode *dir, struct dentry *dentry,
6598 umode_t mode, bool excl)
6600 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
6601 struct btrfs_trans_handle *trans;
6602 struct btrfs_root *root = BTRFS_I(dir)->root;
6603 struct inode *inode = NULL;
6604 int drop_inode_on_err = 0;
6610 * 2 for inode item and ref
6612 * 1 for xattr if selinux is on
6614 trans = btrfs_start_transaction(root, 5);
6616 return PTR_ERR(trans);
6618 err = btrfs_find_free_ino(root, &objectid);
6622 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
6623 dentry->d_name.len, btrfs_ino(BTRFS_I(dir)), objectid,
6625 if (IS_ERR(inode)) {
6626 err = PTR_ERR(inode);
6629 drop_inode_on_err = 1;
6631 * If the active LSM wants to access the inode during
6632 * d_instantiate it needs these. Smack checks to see
6633 * if the filesystem supports xattrs by looking at the
6636 inode->i_fop = &btrfs_file_operations;
6637 inode->i_op = &btrfs_file_inode_operations;
6638 inode->i_mapping->a_ops = &btrfs_aops;
6640 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
6642 goto out_unlock_inode;
6644 err = btrfs_update_inode(trans, root, inode);
6646 goto out_unlock_inode;
6648 err = btrfs_add_nondir(trans, BTRFS_I(dir), dentry, BTRFS_I(inode),
6651 goto out_unlock_inode;
6653 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
6654 unlock_new_inode(inode);
6655 d_instantiate(dentry, inode);
6658 btrfs_end_transaction(trans);
6659 if (err && drop_inode_on_err) {
6660 inode_dec_link_count(inode);
6663 btrfs_btree_balance_dirty(fs_info);
6667 unlock_new_inode(inode);
6672 static int btrfs_link(struct dentry *old_dentry, struct inode *dir,
6673 struct dentry *dentry)
6675 struct btrfs_trans_handle *trans = NULL;
6676 struct btrfs_root *root = BTRFS_I(dir)->root;
6677 struct inode *inode = d_inode(old_dentry);
6678 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
6683 /* do not allow sys_link's with other subvols of the same device */
6684 if (root->objectid != BTRFS_I(inode)->root->objectid)
6687 if (inode->i_nlink >= BTRFS_LINK_MAX)
6690 err = btrfs_set_inode_index(BTRFS_I(dir), &index);
6695 * 2 items for inode and inode ref
6696 * 2 items for dir items
6697 * 1 item for parent inode
6699 trans = btrfs_start_transaction(root, 5);
6700 if (IS_ERR(trans)) {
6701 err = PTR_ERR(trans);
6706 /* There are several dir indexes for this inode, clear the cache. */
6707 BTRFS_I(inode)->dir_index = 0ULL;
6709 inode_inc_iversion(inode);
6710 inode->i_ctime = current_time(inode);
6712 set_bit(BTRFS_INODE_COPY_EVERYTHING, &BTRFS_I(inode)->runtime_flags);
6714 err = btrfs_add_nondir(trans, BTRFS_I(dir), dentry, BTRFS_I(inode),
6720 struct dentry *parent = dentry->d_parent;
6721 err = btrfs_update_inode(trans, root, inode);
6724 if (inode->i_nlink == 1) {
6726 * If new hard link count is 1, it's a file created
6727 * with open(2) O_TMPFILE flag.
6729 err = btrfs_orphan_del(trans, BTRFS_I(inode));
6733 d_instantiate(dentry, inode);
6734 btrfs_log_new_name(trans, BTRFS_I(inode), NULL, parent);
6739 btrfs_end_transaction(trans);
6741 inode_dec_link_count(inode);
6744 btrfs_btree_balance_dirty(fs_info);
6748 static int btrfs_mkdir(struct inode *dir, struct dentry *dentry, umode_t mode)
6750 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
6751 struct inode *inode = NULL;
6752 struct btrfs_trans_handle *trans;
6753 struct btrfs_root *root = BTRFS_I(dir)->root;
6755 int drop_on_err = 0;
6760 * 2 items for inode and ref
6761 * 2 items for dir items
6762 * 1 for xattr if selinux is on
6764 trans = btrfs_start_transaction(root, 5);
6766 return PTR_ERR(trans);
6768 err = btrfs_find_free_ino(root, &objectid);
6772 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
6773 dentry->d_name.len, btrfs_ino(BTRFS_I(dir)), objectid,
6774 S_IFDIR | mode, &index);
6775 if (IS_ERR(inode)) {
6776 err = PTR_ERR(inode);
6781 /* these must be set before we unlock the inode */
6782 inode->i_op = &btrfs_dir_inode_operations;
6783 inode->i_fop = &btrfs_dir_file_operations;
6785 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
6787 goto out_fail_inode;
6789 btrfs_i_size_write(BTRFS_I(inode), 0);
6790 err = btrfs_update_inode(trans, root, inode);
6792 goto out_fail_inode;
6794 err = btrfs_add_link(trans, BTRFS_I(dir), BTRFS_I(inode),
6795 dentry->d_name.name,
6796 dentry->d_name.len, 0, index);
6798 goto out_fail_inode;
6800 d_instantiate(dentry, inode);
6802 * mkdir is special. We're unlocking after we call d_instantiate
6803 * to avoid a race with nfsd calling d_instantiate.
6805 unlock_new_inode(inode);
6809 btrfs_end_transaction(trans);
6811 inode_dec_link_count(inode);
6814 btrfs_btree_balance_dirty(fs_info);
6818 unlock_new_inode(inode);
6822 /* Find next extent map of a given extent map, caller needs to ensure locks */
6823 static struct extent_map *next_extent_map(struct extent_map *em)
6825 struct rb_node *next;
6827 next = rb_next(&em->rb_node);
6830 return container_of(next, struct extent_map, rb_node);
6833 static struct extent_map *prev_extent_map(struct extent_map *em)
6835 struct rb_node *prev;
6837 prev = rb_prev(&em->rb_node);
6840 return container_of(prev, struct extent_map, rb_node);
6843 /* helper for btfs_get_extent. Given an existing extent in the tree,
6844 * the existing extent is the nearest extent to map_start,
6845 * and an extent that you want to insert, deal with overlap and insert
6846 * the best fitted new extent into the tree.
6848 static int merge_extent_mapping(struct extent_map_tree *em_tree,
6849 struct extent_map *existing,
6850 struct extent_map *em,
6853 struct extent_map *prev;
6854 struct extent_map *next;
6859 BUG_ON(map_start < em->start || map_start >= extent_map_end(em));
6861 if (existing->start > map_start) {
6863 prev = prev_extent_map(next);
6866 next = next_extent_map(prev);
6869 start = prev ? extent_map_end(prev) : em->start;
6870 start = max_t(u64, start, em->start);
6871 end = next ? next->start : extent_map_end(em);
6872 end = min_t(u64, end, extent_map_end(em));
6873 start_diff = start - em->start;
6875 em->len = end - start;
6876 if (em->block_start < EXTENT_MAP_LAST_BYTE &&
6877 !test_bit(EXTENT_FLAG_COMPRESSED, &em->flags)) {
6878 em->block_start += start_diff;
6879 em->block_len -= start_diff;
6881 return add_extent_mapping(em_tree, em, 0);
6884 static noinline int uncompress_inline(struct btrfs_path *path,
6886 size_t pg_offset, u64 extent_offset,
6887 struct btrfs_file_extent_item *item)
6890 struct extent_buffer *leaf = path->nodes[0];
6893 unsigned long inline_size;
6897 WARN_ON(pg_offset != 0);
6898 compress_type = btrfs_file_extent_compression(leaf, item);
6899 max_size = btrfs_file_extent_ram_bytes(leaf, item);
6900 inline_size = btrfs_file_extent_inline_item_len(leaf,
6901 btrfs_item_nr(path->slots[0]));
6902 tmp = kmalloc(inline_size, GFP_NOFS);
6905 ptr = btrfs_file_extent_inline_start(item);
6907 read_extent_buffer(leaf, tmp, ptr, inline_size);
6909 max_size = min_t(unsigned long, PAGE_SIZE, max_size);
6910 ret = btrfs_decompress(compress_type, tmp, page,
6911 extent_offset, inline_size, max_size);
6914 * decompression code contains a memset to fill in any space between the end
6915 * of the uncompressed data and the end of max_size in case the decompressed
6916 * data ends up shorter than ram_bytes. That doesn't cover the hole between
6917 * the end of an inline extent and the beginning of the next block, so we
6918 * cover that region here.
6921 if (max_size + pg_offset < PAGE_SIZE) {
6922 char *map = kmap(page);
6923 memset(map + pg_offset + max_size, 0, PAGE_SIZE - max_size - pg_offset);
6931 * a bit scary, this does extent mapping from logical file offset to the disk.
6932 * the ugly parts come from merging extents from the disk with the in-ram
6933 * representation. This gets more complex because of the data=ordered code,
6934 * where the in-ram extents might be locked pending data=ordered completion.
6936 * This also copies inline extents directly into the page.
6938 struct extent_map *btrfs_get_extent(struct btrfs_inode *inode,
6940 size_t pg_offset, u64 start, u64 len,
6943 struct btrfs_fs_info *fs_info = btrfs_sb(inode->vfs_inode.i_sb);
6946 u64 extent_start = 0;
6948 u64 objectid = btrfs_ino(inode);
6950 struct btrfs_path *path = NULL;
6951 struct btrfs_root *root = inode->root;
6952 struct btrfs_file_extent_item *item;
6953 struct extent_buffer *leaf;
6954 struct btrfs_key found_key;
6955 struct extent_map *em = NULL;
6956 struct extent_map_tree *em_tree = &inode->extent_tree;
6957 struct extent_io_tree *io_tree = &inode->io_tree;
6958 const bool new_inline = !page || create;
6960 read_lock(&em_tree->lock);
6961 em = lookup_extent_mapping(em_tree, start, len);
6963 em->bdev = fs_info->fs_devices->latest_bdev;
6964 read_unlock(&em_tree->lock);
6967 if (em->start > start || em->start + em->len <= start)
6968 free_extent_map(em);
6969 else if (em->block_start == EXTENT_MAP_INLINE && page)
6970 free_extent_map(em);
6974 em = alloc_extent_map();
6979 em->bdev = fs_info->fs_devices->latest_bdev;
6980 em->start = EXTENT_MAP_HOLE;
6981 em->orig_start = EXTENT_MAP_HOLE;
6983 em->block_len = (u64)-1;
6986 path = btrfs_alloc_path();
6992 * Chances are we'll be called again, so go ahead and do
6995 path->reada = READA_FORWARD;
6998 ret = btrfs_lookup_file_extent(NULL, root, path, objectid, start, 0);
7005 if (path->slots[0] == 0)
7010 leaf = path->nodes[0];
7011 item = btrfs_item_ptr(leaf, path->slots[0],
7012 struct btrfs_file_extent_item);
7013 /* are we inside the extent that was found? */
7014 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
7015 found_type = found_key.type;
7016 if (found_key.objectid != objectid ||
7017 found_type != BTRFS_EXTENT_DATA_KEY) {
7019 * If we backup past the first extent we want to move forward
7020 * and see if there is an extent in front of us, otherwise we'll
7021 * say there is a hole for our whole search range which can
7028 found_type = btrfs_file_extent_type(leaf, item);
7029 extent_start = found_key.offset;
7030 if (found_type == BTRFS_FILE_EXTENT_REG ||
7031 found_type == BTRFS_FILE_EXTENT_PREALLOC) {
7032 extent_end = extent_start +
7033 btrfs_file_extent_num_bytes(leaf, item);
7035 trace_btrfs_get_extent_show_fi_regular(inode, leaf, item,
7037 } else if (found_type == BTRFS_FILE_EXTENT_INLINE) {
7039 size = btrfs_file_extent_inline_len(leaf, path->slots[0], item);
7040 extent_end = ALIGN(extent_start + size,
7041 fs_info->sectorsize);
7043 trace_btrfs_get_extent_show_fi_inline(inode, leaf, item,
7048 if (start >= extent_end) {
7050 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
7051 ret = btrfs_next_leaf(root, path);
7058 leaf = path->nodes[0];
7060 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
7061 if (found_key.objectid != objectid ||
7062 found_key.type != BTRFS_EXTENT_DATA_KEY)
7064 if (start + len <= found_key.offset)
7066 if (start > found_key.offset)
7069 em->orig_start = start;
7070 em->len = found_key.offset - start;
7074 btrfs_extent_item_to_extent_map(inode, path, item,
7077 if (found_type == BTRFS_FILE_EXTENT_REG ||
7078 found_type == BTRFS_FILE_EXTENT_PREALLOC) {
7080 } else if (found_type == BTRFS_FILE_EXTENT_INLINE) {
7084 size_t extent_offset;
7090 size = btrfs_file_extent_inline_len(leaf, path->slots[0], item);
7091 extent_offset = page_offset(page) + pg_offset - extent_start;
7092 copy_size = min_t(u64, PAGE_SIZE - pg_offset,
7093 size - extent_offset);
7094 em->start = extent_start + extent_offset;
7095 em->len = ALIGN(copy_size, fs_info->sectorsize);
7096 em->orig_block_len = em->len;
7097 em->orig_start = em->start;
7098 ptr = btrfs_file_extent_inline_start(item) + extent_offset;
7099 if (!PageUptodate(page)) {
7100 if (btrfs_file_extent_compression(leaf, item) !=
7101 BTRFS_COMPRESS_NONE) {
7102 ret = uncompress_inline(path, page, pg_offset,
7103 extent_offset, item);
7110 read_extent_buffer(leaf, map + pg_offset, ptr,
7112 if (pg_offset + copy_size < PAGE_SIZE) {
7113 memset(map + pg_offset + copy_size, 0,
7114 PAGE_SIZE - pg_offset -
7119 flush_dcache_page(page);
7121 set_extent_uptodate(io_tree, em->start,
7122 extent_map_end(em) - 1, NULL, GFP_NOFS);
7127 em->orig_start = start;
7130 em->block_start = EXTENT_MAP_HOLE;
7132 btrfs_release_path(path);
7133 if (em->start > start || extent_map_end(em) <= start) {
7135 "bad extent! em: [%llu %llu] passed [%llu %llu]",
7136 em->start, em->len, start, len);
7142 write_lock(&em_tree->lock);
7143 ret = add_extent_mapping(em_tree, em, 0);
7144 /* it is possible that someone inserted the extent into the tree
7145 * while we had the lock dropped. It is also possible that
7146 * an overlapping map exists in the tree
7148 if (ret == -EEXIST) {
7149 struct extent_map *existing;
7153 existing = search_extent_mapping(em_tree, start, len);
7155 * existing will always be non-NULL, since there must be
7156 * extent causing the -EEXIST.
7158 if (existing->start == em->start &&
7159 extent_map_end(existing) >= extent_map_end(em) &&
7160 em->block_start == existing->block_start) {
7162 * The existing extent map already encompasses the
7163 * entire extent map we tried to add.
7165 free_extent_map(em);
7169 } else if (start >= extent_map_end(existing) ||
7170 start <= existing->start) {
7172 * The existing extent map is the one nearest to
7173 * the [start, start + len) range which overlaps
7175 err = merge_extent_mapping(em_tree, existing,
7177 free_extent_map(existing);
7179 free_extent_map(em);
7183 free_extent_map(em);
7188 write_unlock(&em_tree->lock);
7191 trace_btrfs_get_extent(root, inode, em);
7193 btrfs_free_path(path);
7195 free_extent_map(em);
7196 return ERR_PTR(err);
7198 BUG_ON(!em); /* Error is always set */
7202 struct extent_map *btrfs_get_extent_fiemap(struct btrfs_inode *inode,
7204 size_t pg_offset, u64 start, u64 len,
7207 struct extent_map *em;
7208 struct extent_map *hole_em = NULL;
7209 u64 range_start = start;
7215 em = btrfs_get_extent(inode, page, pg_offset, start, len, create);
7219 * If our em maps to:
7221 * - a pre-alloc extent,
7222 * there might actually be delalloc bytes behind it.
7224 if (em->block_start != EXTENT_MAP_HOLE &&
7225 !test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
7230 /* check to see if we've wrapped (len == -1 or similar) */
7239 /* ok, we didn't find anything, lets look for delalloc */
7240 found = count_range_bits(&inode->io_tree, &range_start,
7241 end, len, EXTENT_DELALLOC, 1);
7242 found_end = range_start + found;
7243 if (found_end < range_start)
7244 found_end = (u64)-1;
7247 * we didn't find anything useful, return
7248 * the original results from get_extent()
7250 if (range_start > end || found_end <= start) {
7256 /* adjust the range_start to make sure it doesn't
7257 * go backwards from the start they passed in
7259 range_start = max(start, range_start);
7260 found = found_end - range_start;
7263 u64 hole_start = start;
7266 em = alloc_extent_map();
7272 * when btrfs_get_extent can't find anything it
7273 * returns one huge hole
7275 * make sure what it found really fits our range, and
7276 * adjust to make sure it is based on the start from
7280 u64 calc_end = extent_map_end(hole_em);
7282 if (calc_end <= start || (hole_em->start > end)) {
7283 free_extent_map(hole_em);
7286 hole_start = max(hole_em->start, start);
7287 hole_len = calc_end - hole_start;
7291 if (hole_em && range_start > hole_start) {
7292 /* our hole starts before our delalloc, so we
7293 * have to return just the parts of the hole
7294 * that go until the delalloc starts
7296 em->len = min(hole_len,
7297 range_start - hole_start);
7298 em->start = hole_start;
7299 em->orig_start = hole_start;
7301 * don't adjust block start at all,
7302 * it is fixed at EXTENT_MAP_HOLE
7304 em->block_start = hole_em->block_start;
7305 em->block_len = hole_len;
7306 if (test_bit(EXTENT_FLAG_PREALLOC, &hole_em->flags))
7307 set_bit(EXTENT_FLAG_PREALLOC, &em->flags);
7309 em->start = range_start;
7311 em->orig_start = range_start;
7312 em->block_start = EXTENT_MAP_DELALLOC;
7313 em->block_len = found;
7320 free_extent_map(hole_em);
7322 free_extent_map(em);
7323 return ERR_PTR(err);
7328 static struct extent_map *btrfs_create_dio_extent(struct inode *inode,
7331 const u64 orig_start,
7332 const u64 block_start,
7333 const u64 block_len,
7334 const u64 orig_block_len,
7335 const u64 ram_bytes,
7338 struct extent_map *em = NULL;
7341 if (type != BTRFS_ORDERED_NOCOW) {
7342 em = create_io_em(inode, start, len, orig_start,
7343 block_start, block_len, orig_block_len,
7345 BTRFS_COMPRESS_NONE, /* compress_type */
7350 ret = btrfs_add_ordered_extent_dio(inode, start, block_start,
7351 len, block_len, type);
7354 free_extent_map(em);
7355 btrfs_drop_extent_cache(BTRFS_I(inode), start,
7356 start + len - 1, 0);
7365 static struct extent_map *btrfs_new_extent_direct(struct inode *inode,
7368 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7369 struct btrfs_root *root = BTRFS_I(inode)->root;
7370 struct extent_map *em;
7371 struct btrfs_key ins;
7375 alloc_hint = get_extent_allocation_hint(inode, start, len);
7376 ret = btrfs_reserve_extent(root, len, len, fs_info->sectorsize,
7377 0, alloc_hint, &ins, 1, 1);
7379 return ERR_PTR(ret);
7381 em = btrfs_create_dio_extent(inode, start, ins.offset, start,
7382 ins.objectid, ins.offset, ins.offset,
7383 ins.offset, BTRFS_ORDERED_REGULAR);
7384 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
7386 btrfs_free_reserved_extent(fs_info, ins.objectid,
7393 * returns 1 when the nocow is safe, < 1 on error, 0 if the
7394 * block must be cow'd
7396 noinline int can_nocow_extent(struct inode *inode, u64 offset, u64 *len,
7397 u64 *orig_start, u64 *orig_block_len,
7400 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7401 struct btrfs_path *path;
7403 struct extent_buffer *leaf;
7404 struct btrfs_root *root = BTRFS_I(inode)->root;
7405 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
7406 struct btrfs_file_extent_item *fi;
7407 struct btrfs_key key;
7414 bool nocow = (BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW);
7416 path = btrfs_alloc_path();
7420 ret = btrfs_lookup_file_extent(NULL, root, path,
7421 btrfs_ino(BTRFS_I(inode)), offset, 0);
7425 slot = path->slots[0];
7428 /* can't find the item, must cow */
7435 leaf = path->nodes[0];
7436 btrfs_item_key_to_cpu(leaf, &key, slot);
7437 if (key.objectid != btrfs_ino(BTRFS_I(inode)) ||
7438 key.type != BTRFS_EXTENT_DATA_KEY) {
7439 /* not our file or wrong item type, must cow */
7443 if (key.offset > offset) {
7444 /* Wrong offset, must cow */
7448 fi = btrfs_item_ptr(leaf, slot, struct btrfs_file_extent_item);
7449 found_type = btrfs_file_extent_type(leaf, fi);
7450 if (found_type != BTRFS_FILE_EXTENT_REG &&
7451 found_type != BTRFS_FILE_EXTENT_PREALLOC) {
7452 /* not a regular extent, must cow */
7456 if (!nocow && found_type == BTRFS_FILE_EXTENT_REG)
7459 extent_end = key.offset + btrfs_file_extent_num_bytes(leaf, fi);
7460 if (extent_end <= offset)
7463 disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
7464 if (disk_bytenr == 0)
7467 if (btrfs_file_extent_compression(leaf, fi) ||
7468 btrfs_file_extent_encryption(leaf, fi) ||
7469 btrfs_file_extent_other_encoding(leaf, fi))
7472 backref_offset = btrfs_file_extent_offset(leaf, fi);
7475 *orig_start = key.offset - backref_offset;
7476 *orig_block_len = btrfs_file_extent_disk_num_bytes(leaf, fi);
7477 *ram_bytes = btrfs_file_extent_ram_bytes(leaf, fi);
7480 if (btrfs_extent_readonly(fs_info, disk_bytenr))
7483 num_bytes = min(offset + *len, extent_end) - offset;
7484 if (!nocow && found_type == BTRFS_FILE_EXTENT_PREALLOC) {
7487 range_end = round_up(offset + num_bytes,
7488 root->fs_info->sectorsize) - 1;
7489 ret = test_range_bit(io_tree, offset, range_end,
7490 EXTENT_DELALLOC, 0, NULL);
7497 btrfs_release_path(path);
7500 * look for other files referencing this extent, if we
7501 * find any we must cow
7504 ret = btrfs_cross_ref_exist(root, btrfs_ino(BTRFS_I(inode)),
7505 key.offset - backref_offset, disk_bytenr);
7512 * adjust disk_bytenr and num_bytes to cover just the bytes
7513 * in this extent we are about to write. If there
7514 * are any csums in that range we have to cow in order
7515 * to keep the csums correct
7517 disk_bytenr += backref_offset;
7518 disk_bytenr += offset - key.offset;
7519 if (csum_exist_in_range(fs_info, disk_bytenr, num_bytes))
7522 * all of the above have passed, it is safe to overwrite this extent
7528 btrfs_free_path(path);
7532 bool btrfs_page_exists_in_range(struct inode *inode, loff_t start, loff_t end)
7534 struct radix_tree_root *root = &inode->i_mapping->page_tree;
7536 void **pagep = NULL;
7537 struct page *page = NULL;
7538 unsigned long start_idx;
7539 unsigned long end_idx;
7541 start_idx = start >> PAGE_SHIFT;
7544 * end is the last byte in the last page. end == start is legal
7546 end_idx = end >> PAGE_SHIFT;
7550 /* Most of the code in this while loop is lifted from
7551 * find_get_page. It's been modified to begin searching from a
7552 * page and return just the first page found in that range. If the
7553 * found idx is less than or equal to the end idx then we know that
7554 * a page exists. If no pages are found or if those pages are
7555 * outside of the range then we're fine (yay!) */
7556 while (page == NULL &&
7557 radix_tree_gang_lookup_slot(root, &pagep, NULL, start_idx, 1)) {
7558 page = radix_tree_deref_slot(pagep);
7559 if (unlikely(!page))
7562 if (radix_tree_exception(page)) {
7563 if (radix_tree_deref_retry(page)) {
7568 * Otherwise, shmem/tmpfs must be storing a swap entry
7569 * here as an exceptional entry: so return it without
7570 * attempting to raise page count.
7573 break; /* TODO: Is this relevant for this use case? */
7576 if (!page_cache_get_speculative(page)) {
7582 * Has the page moved?
7583 * This is part of the lockless pagecache protocol. See
7584 * include/linux/pagemap.h for details.
7586 if (unlikely(page != *pagep)) {
7593 if (page->index <= end_idx)
7602 static int lock_extent_direct(struct inode *inode, u64 lockstart, u64 lockend,
7603 struct extent_state **cached_state, int writing)
7605 struct btrfs_ordered_extent *ordered;
7609 lock_extent_bits(&BTRFS_I(inode)->io_tree, lockstart, lockend,
7612 * We're concerned with the entire range that we're going to be
7613 * doing DIO to, so we need to make sure there's no ordered
7614 * extents in this range.
7616 ordered = btrfs_lookup_ordered_range(BTRFS_I(inode), lockstart,
7617 lockend - lockstart + 1);
7620 * We need to make sure there are no buffered pages in this
7621 * range either, we could have raced between the invalidate in
7622 * generic_file_direct_write and locking the extent. The
7623 * invalidate needs to happen so that reads after a write do not
7628 !btrfs_page_exists_in_range(inode, lockstart, lockend)))
7631 unlock_extent_cached(&BTRFS_I(inode)->io_tree, lockstart, lockend,
7632 cached_state, GFP_NOFS);
7636 * If we are doing a DIO read and the ordered extent we
7637 * found is for a buffered write, we can not wait for it
7638 * to complete and retry, because if we do so we can
7639 * deadlock with concurrent buffered writes on page
7640 * locks. This happens only if our DIO read covers more
7641 * than one extent map, if at this point has already
7642 * created an ordered extent for a previous extent map
7643 * and locked its range in the inode's io tree, and a
7644 * concurrent write against that previous extent map's
7645 * range and this range started (we unlock the ranges
7646 * in the io tree only when the bios complete and
7647 * buffered writes always lock pages before attempting
7648 * to lock range in the io tree).
7651 test_bit(BTRFS_ORDERED_DIRECT, &ordered->flags))
7652 btrfs_start_ordered_extent(inode, ordered, 1);
7655 btrfs_put_ordered_extent(ordered);
7658 * We could trigger writeback for this range (and wait
7659 * for it to complete) and then invalidate the pages for
7660 * this range (through invalidate_inode_pages2_range()),
7661 * but that can lead us to a deadlock with a concurrent
7662 * call to readpages() (a buffered read or a defrag call
7663 * triggered a readahead) on a page lock due to an
7664 * ordered dio extent we created before but did not have
7665 * yet a corresponding bio submitted (whence it can not
7666 * complete), which makes readpages() wait for that
7667 * ordered extent to complete while holding a lock on
7682 /* The callers of this must take lock_extent() */
7683 static struct extent_map *create_io_em(struct inode *inode, u64 start, u64 len,
7684 u64 orig_start, u64 block_start,
7685 u64 block_len, u64 orig_block_len,
7686 u64 ram_bytes, int compress_type,
7689 struct extent_map_tree *em_tree;
7690 struct extent_map *em;
7691 struct btrfs_root *root = BTRFS_I(inode)->root;
7694 ASSERT(type == BTRFS_ORDERED_PREALLOC ||
7695 type == BTRFS_ORDERED_COMPRESSED ||
7696 type == BTRFS_ORDERED_NOCOW ||
7697 type == BTRFS_ORDERED_REGULAR);
7699 em_tree = &BTRFS_I(inode)->extent_tree;
7700 em = alloc_extent_map();
7702 return ERR_PTR(-ENOMEM);
7705 em->orig_start = orig_start;
7707 em->block_len = block_len;
7708 em->block_start = block_start;
7709 em->bdev = root->fs_info->fs_devices->latest_bdev;
7710 em->orig_block_len = orig_block_len;
7711 em->ram_bytes = ram_bytes;
7712 em->generation = -1;
7713 set_bit(EXTENT_FLAG_PINNED, &em->flags);
7714 if (type == BTRFS_ORDERED_PREALLOC) {
7715 set_bit(EXTENT_FLAG_FILLING, &em->flags);
7716 } else if (type == BTRFS_ORDERED_COMPRESSED) {
7717 set_bit(EXTENT_FLAG_COMPRESSED, &em->flags);
7718 em->compress_type = compress_type;
7722 btrfs_drop_extent_cache(BTRFS_I(inode), em->start,
7723 em->start + em->len - 1, 0);
7724 write_lock(&em_tree->lock);
7725 ret = add_extent_mapping(em_tree, em, 1);
7726 write_unlock(&em_tree->lock);
7728 * The caller has taken lock_extent(), who could race with us
7731 } while (ret == -EEXIST);
7734 free_extent_map(em);
7735 return ERR_PTR(ret);
7738 /* em got 2 refs now, callers needs to do free_extent_map once. */
7742 static int btrfs_get_blocks_direct(struct inode *inode, sector_t iblock,
7743 struct buffer_head *bh_result, int create)
7745 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7746 struct extent_map *em;
7747 struct extent_state *cached_state = NULL;
7748 struct btrfs_dio_data *dio_data = NULL;
7749 u64 start = iblock << inode->i_blkbits;
7750 u64 lockstart, lockend;
7751 u64 len = bh_result->b_size;
7752 int unlock_bits = EXTENT_LOCKED;
7756 unlock_bits |= EXTENT_DIRTY;
7758 len = min_t(u64, len, fs_info->sectorsize);
7761 lockend = start + len - 1;
7763 if (current->journal_info) {
7765 * Need to pull our outstanding extents and set journal_info to NULL so
7766 * that anything that needs to check if there's a transaction doesn't get
7769 dio_data = current->journal_info;
7770 current->journal_info = NULL;
7774 * If this errors out it's because we couldn't invalidate pagecache for
7775 * this range and we need to fallback to buffered.
7777 if (lock_extent_direct(inode, lockstart, lockend, &cached_state,
7783 em = btrfs_get_extent(BTRFS_I(inode), NULL, 0, start, len, 0);
7790 * Ok for INLINE and COMPRESSED extents we need to fallback on buffered
7791 * io. INLINE is special, and we could probably kludge it in here, but
7792 * it's still buffered so for safety lets just fall back to the generic
7795 * For COMPRESSED we _have_ to read the entire extent in so we can
7796 * decompress it, so there will be buffering required no matter what we
7797 * do, so go ahead and fallback to buffered.
7799 * We return -ENOTBLK because that's what makes DIO go ahead and go back
7800 * to buffered IO. Don't blame me, this is the price we pay for using
7803 if (test_bit(EXTENT_FLAG_COMPRESSED, &em->flags) ||
7804 em->block_start == EXTENT_MAP_INLINE) {
7805 free_extent_map(em);
7810 /* Just a good old fashioned hole, return */
7811 if (!create && (em->block_start == EXTENT_MAP_HOLE ||
7812 test_bit(EXTENT_FLAG_PREALLOC, &em->flags))) {
7813 free_extent_map(em);
7818 * We don't allocate a new extent in the following cases
7820 * 1) The inode is marked as NODATACOW. In this case we'll just use the
7822 * 2) The extent is marked as PREALLOC. We're good to go here and can
7823 * just use the extent.
7827 len = min(len, em->len - (start - em->start));
7828 lockstart = start + len;
7832 if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags) ||
7833 ((BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW) &&
7834 em->block_start != EXTENT_MAP_HOLE)) {
7836 u64 block_start, orig_start, orig_block_len, ram_bytes;
7838 if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
7839 type = BTRFS_ORDERED_PREALLOC;
7841 type = BTRFS_ORDERED_NOCOW;
7842 len = min(len, em->len - (start - em->start));
7843 block_start = em->block_start + (start - em->start);
7845 if (can_nocow_extent(inode, start, &len, &orig_start,
7846 &orig_block_len, &ram_bytes) == 1 &&
7847 btrfs_inc_nocow_writers(fs_info, block_start)) {
7848 struct extent_map *em2;
7850 em2 = btrfs_create_dio_extent(inode, start, len,
7851 orig_start, block_start,
7852 len, orig_block_len,
7854 btrfs_dec_nocow_writers(fs_info, block_start);
7855 if (type == BTRFS_ORDERED_PREALLOC) {
7856 free_extent_map(em);
7859 if (em2 && IS_ERR(em2)) {
7864 * For inode marked NODATACOW or extent marked PREALLOC,
7865 * use the existing or preallocated extent, so does not
7866 * need to adjust btrfs_space_info's bytes_may_use.
7868 btrfs_free_reserved_data_space_noquota(inode,
7875 * this will cow the extent, reset the len in case we changed
7878 len = bh_result->b_size;
7879 free_extent_map(em);
7880 em = btrfs_new_extent_direct(inode, start, len);
7885 len = min(len, em->len - (start - em->start));
7887 bh_result->b_blocknr = (em->block_start + (start - em->start)) >>
7889 bh_result->b_size = len;
7890 bh_result->b_bdev = em->bdev;
7891 set_buffer_mapped(bh_result);
7893 if (!test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
7894 set_buffer_new(bh_result);
7897 * Need to update the i_size under the extent lock so buffered
7898 * readers will get the updated i_size when we unlock.
7900 if (!dio_data->overwrite && start + len > i_size_read(inode))
7901 i_size_write(inode, start + len);
7903 WARN_ON(dio_data->reserve < len);
7904 dio_data->reserve -= len;
7905 dio_data->unsubmitted_oe_range_end = start + len;
7906 current->journal_info = dio_data;
7910 * In the case of write we need to clear and unlock the entire range,
7911 * in the case of read we need to unlock only the end area that we
7912 * aren't using if there is any left over space.
7914 if (lockstart < lockend) {
7915 clear_extent_bit(&BTRFS_I(inode)->io_tree, lockstart,
7916 lockend, unlock_bits, 1, 0,
7919 free_extent_state(cached_state);
7922 free_extent_map(em);
7927 clear_extent_bit(&BTRFS_I(inode)->io_tree, lockstart, lockend,
7928 unlock_bits, 1, 0, &cached_state);
7931 current->journal_info = dio_data;
7935 static inline blk_status_t submit_dio_repair_bio(struct inode *inode,
7939 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7942 BUG_ON(bio_op(bio) == REQ_OP_WRITE);
7946 ret = btrfs_bio_wq_end_io(fs_info, bio, BTRFS_WQ_ENDIO_DIO_REPAIR);
7950 ret = btrfs_map_bio(fs_info, bio, mirror_num, 0);
7956 static int btrfs_check_dio_repairable(struct inode *inode,
7957 struct bio *failed_bio,
7958 struct io_failure_record *failrec,
7961 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7964 num_copies = btrfs_num_copies(fs_info, failrec->logical, failrec->len);
7965 if (num_copies == 1) {
7967 * we only have a single copy of the data, so don't bother with
7968 * all the retry and error correction code that follows. no
7969 * matter what the error is, it is very likely to persist.
7971 btrfs_debug(fs_info,
7972 "Check DIO Repairable: cannot repair, num_copies=%d, next_mirror %d, failed_mirror %d",
7973 num_copies, failrec->this_mirror, failed_mirror);
7977 failrec->failed_mirror = failed_mirror;
7978 failrec->this_mirror++;
7979 if (failrec->this_mirror == failed_mirror)
7980 failrec->this_mirror++;
7982 if (failrec->this_mirror > num_copies) {
7983 btrfs_debug(fs_info,
7984 "Check DIO Repairable: (fail) num_copies=%d, next_mirror %d, failed_mirror %d",
7985 num_copies, failrec->this_mirror, failed_mirror);
7992 static blk_status_t dio_read_error(struct inode *inode, struct bio *failed_bio,
7993 struct page *page, unsigned int pgoff,
7994 u64 start, u64 end, int failed_mirror,
7995 bio_end_io_t *repair_endio, void *repair_arg)
7997 struct io_failure_record *failrec;
7998 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
7999 struct extent_io_tree *failure_tree = &BTRFS_I(inode)->io_failure_tree;
8002 unsigned int read_mode = 0;
8005 blk_status_t status;
8007 BUG_ON(bio_op(failed_bio) == REQ_OP_WRITE);
8009 ret = btrfs_get_io_failure_record(inode, start, end, &failrec);
8011 return errno_to_blk_status(ret);
8013 ret = btrfs_check_dio_repairable(inode, failed_bio, failrec,
8016 free_io_failure(failure_tree, io_tree, failrec);
8017 return BLK_STS_IOERR;
8020 segs = bio_segments(failed_bio);
8022 (failed_bio->bi_io_vec->bv_len > btrfs_inode_sectorsize(inode)))
8023 read_mode |= REQ_FAILFAST_DEV;
8025 isector = start - btrfs_io_bio(failed_bio)->logical;
8026 isector >>= inode->i_sb->s_blocksize_bits;
8027 bio = btrfs_create_repair_bio(inode, failed_bio, failrec, page,
8028 pgoff, isector, repair_endio, repair_arg);
8029 bio_set_op_attrs(bio, REQ_OP_READ, read_mode);
8031 btrfs_debug(BTRFS_I(inode)->root->fs_info,
8032 "repair DIO read error: submitting new dio read[%#x] to this_mirror=%d, in_validation=%d",
8033 read_mode, failrec->this_mirror, failrec->in_validation);
8035 status = submit_dio_repair_bio(inode, bio, failrec->this_mirror);
8037 free_io_failure(failure_tree, io_tree, failrec);
8044 struct btrfs_retry_complete {
8045 struct completion done;
8046 struct inode *inode;
8051 static void btrfs_retry_endio_nocsum(struct bio *bio)
8053 struct btrfs_retry_complete *done = bio->bi_private;
8054 struct inode *inode = done->inode;
8055 struct bio_vec *bvec;
8056 struct extent_io_tree *io_tree, *failure_tree;
8062 ASSERT(bio->bi_vcnt == 1);
8063 io_tree = &BTRFS_I(inode)->io_tree;
8064 failure_tree = &BTRFS_I(inode)->io_failure_tree;
8065 ASSERT(bio->bi_io_vec->bv_len == btrfs_inode_sectorsize(inode));
8068 ASSERT(!bio_flagged(bio, BIO_CLONED));
8069 bio_for_each_segment_all(bvec, bio, i)
8070 clean_io_failure(BTRFS_I(inode)->root->fs_info, failure_tree,
8071 io_tree, done->start, bvec->bv_page,
8072 btrfs_ino(BTRFS_I(inode)), 0);
8074 complete(&done->done);
8078 static blk_status_t __btrfs_correct_data_nocsum(struct inode *inode,
8079 struct btrfs_io_bio *io_bio)
8081 struct btrfs_fs_info *fs_info;
8082 struct bio_vec bvec;
8083 struct bvec_iter iter;
8084 struct btrfs_retry_complete done;
8090 blk_status_t err = BLK_STS_OK;
8092 fs_info = BTRFS_I(inode)->root->fs_info;
8093 sectorsize = fs_info->sectorsize;
8095 start = io_bio->logical;
8097 io_bio->bio.bi_iter = io_bio->iter;
8099 bio_for_each_segment(bvec, &io_bio->bio, iter) {
8100 nr_sectors = BTRFS_BYTES_TO_BLKS(fs_info, bvec.bv_len);
8101 pgoff = bvec.bv_offset;
8103 next_block_or_try_again:
8106 init_completion(&done.done);
8108 ret = dio_read_error(inode, &io_bio->bio, bvec.bv_page,
8109 pgoff, start, start + sectorsize - 1,
8111 btrfs_retry_endio_nocsum, &done);
8117 wait_for_completion_io(&done.done);
8119 if (!done.uptodate) {
8120 /* We might have another mirror, so try again */
8121 goto next_block_or_try_again;
8125 start += sectorsize;
8129 pgoff += sectorsize;
8130 ASSERT(pgoff < PAGE_SIZE);
8131 goto next_block_or_try_again;
8138 static void btrfs_retry_endio(struct bio *bio)
8140 struct btrfs_retry_complete *done = bio->bi_private;
8141 struct btrfs_io_bio *io_bio = btrfs_io_bio(bio);
8142 struct extent_io_tree *io_tree, *failure_tree;
8143 struct inode *inode = done->inode;
8144 struct bio_vec *bvec;
8154 ASSERT(bio->bi_vcnt == 1);
8155 ASSERT(bio->bi_io_vec->bv_len == btrfs_inode_sectorsize(done->inode));
8157 io_tree = &BTRFS_I(inode)->io_tree;
8158 failure_tree = &BTRFS_I(inode)->io_failure_tree;
8160 ASSERT(!bio_flagged(bio, BIO_CLONED));
8161 bio_for_each_segment_all(bvec, bio, i) {
8162 ret = __readpage_endio_check(inode, io_bio, i, bvec->bv_page,
8163 bvec->bv_offset, done->start,
8166 clean_io_failure(BTRFS_I(inode)->root->fs_info,
8167 failure_tree, io_tree, done->start,
8169 btrfs_ino(BTRFS_I(inode)),
8175 done->uptodate = uptodate;
8177 complete(&done->done);
8181 static blk_status_t __btrfs_subio_endio_read(struct inode *inode,
8182 struct btrfs_io_bio *io_bio, blk_status_t err)
8184 struct btrfs_fs_info *fs_info;
8185 struct bio_vec bvec;
8186 struct bvec_iter iter;
8187 struct btrfs_retry_complete done;
8194 bool uptodate = (err == 0);
8196 blk_status_t status;
8198 fs_info = BTRFS_I(inode)->root->fs_info;
8199 sectorsize = fs_info->sectorsize;
8202 start = io_bio->logical;
8204 io_bio->bio.bi_iter = io_bio->iter;
8206 bio_for_each_segment(bvec, &io_bio->bio, iter) {
8207 nr_sectors = BTRFS_BYTES_TO_BLKS(fs_info, bvec.bv_len);
8209 pgoff = bvec.bv_offset;
8212 csum_pos = BTRFS_BYTES_TO_BLKS(fs_info, offset);
8213 ret = __readpage_endio_check(inode, io_bio, csum_pos,
8214 bvec.bv_page, pgoff, start, sectorsize);
8221 init_completion(&done.done);
8223 status = dio_read_error(inode, &io_bio->bio, bvec.bv_page,
8224 pgoff, start, start + sectorsize - 1,
8225 io_bio->mirror_num, btrfs_retry_endio,
8232 wait_for_completion_io(&done.done);
8234 if (!done.uptodate) {
8235 /* We might have another mirror, so try again */
8239 offset += sectorsize;
8240 start += sectorsize;
8246 pgoff += sectorsize;
8247 ASSERT(pgoff < PAGE_SIZE);
8255 static blk_status_t btrfs_subio_endio_read(struct inode *inode,
8256 struct btrfs_io_bio *io_bio, blk_status_t err)
8258 bool skip_csum = BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM;
8262 return __btrfs_correct_data_nocsum(inode, io_bio);
8266 return __btrfs_subio_endio_read(inode, io_bio, err);
8270 static void btrfs_endio_direct_read(struct bio *bio)
8272 struct btrfs_dio_private *dip = bio->bi_private;
8273 struct inode *inode = dip->inode;
8274 struct bio *dio_bio;
8275 struct btrfs_io_bio *io_bio = btrfs_io_bio(bio);
8276 blk_status_t err = bio->bi_status;
8278 if (dip->flags & BTRFS_DIO_ORIG_BIO_SUBMITTED)
8279 err = btrfs_subio_endio_read(inode, io_bio, err);
8281 unlock_extent(&BTRFS_I(inode)->io_tree, dip->logical_offset,
8282 dip->logical_offset + dip->bytes - 1);
8283 dio_bio = dip->dio_bio;
8287 dio_bio->bi_status = err;
8288 dio_end_io(dio_bio);
8291 io_bio->end_io(io_bio, blk_status_to_errno(err));
8295 static void __endio_write_update_ordered(struct inode *inode,
8296 const u64 offset, const u64 bytes,
8297 const bool uptodate)
8299 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
8300 struct btrfs_ordered_extent *ordered = NULL;
8301 struct btrfs_workqueue *wq;
8302 btrfs_work_func_t func;
8303 u64 ordered_offset = offset;
8304 u64 ordered_bytes = bytes;
8308 if (btrfs_is_free_space_inode(BTRFS_I(inode))) {
8309 wq = fs_info->endio_freespace_worker;
8310 func = btrfs_freespace_write_helper;
8312 wq = fs_info->endio_write_workers;
8313 func = btrfs_endio_write_helper;
8317 last_offset = ordered_offset;
8318 ret = btrfs_dec_test_first_ordered_pending(inode, &ordered,
8325 btrfs_init_work(&ordered->work, func, finish_ordered_fn, NULL, NULL);
8326 btrfs_queue_work(wq, &ordered->work);
8329 * If btrfs_dec_test_ordered_pending does not find any ordered extent
8330 * in the range, we can exit.
8332 if (ordered_offset == last_offset)
8335 * our bio might span multiple ordered extents. If we haven't
8336 * completed the accounting for the whole dio, go back and try again
8338 if (ordered_offset < offset + bytes) {
8339 ordered_bytes = offset + bytes - ordered_offset;
8345 static void btrfs_endio_direct_write(struct bio *bio)
8347 struct btrfs_dio_private *dip = bio->bi_private;
8348 struct bio *dio_bio = dip->dio_bio;
8350 __endio_write_update_ordered(dip->inode, dip->logical_offset,
8351 dip->bytes, !bio->bi_status);
8355 dio_bio->bi_status = bio->bi_status;
8356 dio_end_io(dio_bio);
8360 static blk_status_t __btrfs_submit_bio_start_direct_io(void *private_data,
8361 struct bio *bio, int mirror_num,
8362 unsigned long bio_flags, u64 offset)
8364 struct inode *inode = private_data;
8366 ret = btrfs_csum_one_bio(inode, bio, offset, 1);
8367 BUG_ON(ret); /* -ENOMEM */
8371 static void btrfs_end_dio_bio(struct bio *bio)
8373 struct btrfs_dio_private *dip = bio->bi_private;
8374 blk_status_t err = bio->bi_status;
8377 btrfs_warn(BTRFS_I(dip->inode)->root->fs_info,
8378 "direct IO failed ino %llu rw %d,%u sector %#Lx len %u err no %d",
8379 btrfs_ino(BTRFS_I(dip->inode)), bio_op(bio),
8381 (unsigned long long)bio->bi_iter.bi_sector,
8382 bio->bi_iter.bi_size, err);
8384 if (dip->subio_endio)
8385 err = dip->subio_endio(dip->inode, btrfs_io_bio(bio), err);
8391 * before atomic variable goto zero, we must make sure
8392 * dip->errors is perceived to be set.
8394 smp_mb__before_atomic();
8397 /* if there are more bios still pending for this dio, just exit */
8398 if (!atomic_dec_and_test(&dip->pending_bios))
8402 bio_io_error(dip->orig_bio);
8404 dip->dio_bio->bi_status = BLK_STS_OK;
8405 bio_endio(dip->orig_bio);
8411 static inline blk_status_t btrfs_lookup_and_bind_dio_csum(struct inode *inode,
8412 struct btrfs_dio_private *dip,
8416 struct btrfs_io_bio *io_bio = btrfs_io_bio(bio);
8417 struct btrfs_io_bio *orig_io_bio = btrfs_io_bio(dip->orig_bio);
8421 * We load all the csum data we need when we submit
8422 * the first bio to reduce the csum tree search and
8425 if (dip->logical_offset == file_offset) {
8426 ret = btrfs_lookup_bio_sums_dio(inode, dip->orig_bio,
8432 if (bio == dip->orig_bio)
8435 file_offset -= dip->logical_offset;
8436 file_offset >>= inode->i_sb->s_blocksize_bits;
8437 io_bio->csum = (u8 *)(((u32 *)orig_io_bio->csum) + file_offset);
8442 static inline blk_status_t
8443 __btrfs_submit_dio_bio(struct bio *bio, struct inode *inode, u64 file_offset,
8446 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
8447 struct btrfs_dio_private *dip = bio->bi_private;
8448 bool write = bio_op(bio) == REQ_OP_WRITE;
8451 /* Check btrfs_submit_bio_hook() for rules about async submit. */
8453 async_submit = !atomic_read(&BTRFS_I(inode)->sync_writers);
8458 ret = btrfs_bio_wq_end_io(fs_info, bio, BTRFS_WQ_ENDIO_DATA);
8463 if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)
8466 if (write && async_submit) {
8467 ret = btrfs_wq_submit_bio(fs_info, bio, 0, 0,
8469 __btrfs_submit_bio_start_direct_io,
8470 __btrfs_submit_bio_done);
8474 * If we aren't doing async submit, calculate the csum of the
8477 ret = btrfs_csum_one_bio(inode, bio, file_offset, 1);
8481 ret = btrfs_lookup_and_bind_dio_csum(inode, dip, bio,
8487 ret = btrfs_map_bio(fs_info, bio, 0, 0);
8493 static int btrfs_submit_direct_hook(struct btrfs_dio_private *dip)
8495 struct inode *inode = dip->inode;
8496 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
8498 struct bio *orig_bio = dip->orig_bio;
8499 u64 start_sector = orig_bio->bi_iter.bi_sector;
8500 u64 file_offset = dip->logical_offset;
8502 int async_submit = 0;
8504 int clone_offset = 0;
8507 blk_status_t status;
8509 map_length = orig_bio->bi_iter.bi_size;
8510 submit_len = map_length;
8511 ret = btrfs_map_block(fs_info, btrfs_op(orig_bio), start_sector << 9,
8512 &map_length, NULL, 0);
8516 if (map_length >= submit_len) {
8518 dip->flags |= BTRFS_DIO_ORIG_BIO_SUBMITTED;
8522 /* async crcs make it difficult to collect full stripe writes. */
8523 if (btrfs_data_alloc_profile(fs_info) & BTRFS_BLOCK_GROUP_RAID56_MASK)
8529 ASSERT(map_length <= INT_MAX);
8530 atomic_inc(&dip->pending_bios);
8532 clone_len = min_t(int, submit_len, map_length);
8535 * This will never fail as it's passing GPF_NOFS and
8536 * the allocation is backed by btrfs_bioset.
8538 bio = btrfs_bio_clone_partial(orig_bio, clone_offset,
8540 bio->bi_private = dip;
8541 bio->bi_end_io = btrfs_end_dio_bio;
8542 btrfs_io_bio(bio)->logical = file_offset;
8544 ASSERT(submit_len >= clone_len);
8545 submit_len -= clone_len;
8546 if (submit_len == 0)
8550 * Increase the count before we submit the bio so we know
8551 * the end IO handler won't happen before we increase the
8552 * count. Otherwise, the dip might get freed before we're
8553 * done setting it up.
8555 atomic_inc(&dip->pending_bios);
8557 status = __btrfs_submit_dio_bio(bio, inode, file_offset,
8561 atomic_dec(&dip->pending_bios);
8565 clone_offset += clone_len;
8566 start_sector += clone_len >> 9;
8567 file_offset += clone_len;
8569 map_length = submit_len;
8570 ret = btrfs_map_block(fs_info, btrfs_op(orig_bio),
8571 start_sector << 9, &map_length, NULL, 0);
8574 } while (submit_len > 0);
8577 status = __btrfs_submit_dio_bio(bio, inode, file_offset, async_submit);
8585 * before atomic variable goto zero, we must
8586 * make sure dip->errors is perceived to be set.
8588 smp_mb__before_atomic();
8589 if (atomic_dec_and_test(&dip->pending_bios))
8590 bio_io_error(dip->orig_bio);
8592 /* bio_end_io() will handle error, so we needn't return it */
8596 static void btrfs_submit_direct(struct bio *dio_bio, struct inode *inode,
8599 struct btrfs_dio_private *dip = NULL;
8600 struct bio *bio = NULL;
8601 struct btrfs_io_bio *io_bio;
8602 bool write = (bio_op(dio_bio) == REQ_OP_WRITE);
8605 bio = btrfs_bio_clone(dio_bio);
8607 dip = kzalloc(sizeof(*dip), GFP_NOFS);
8613 dip->private = dio_bio->bi_private;
8615 dip->logical_offset = file_offset;
8616 dip->bytes = dio_bio->bi_iter.bi_size;
8617 dip->disk_bytenr = (u64)dio_bio->bi_iter.bi_sector << 9;
8618 bio->bi_private = dip;
8619 dip->orig_bio = bio;
8620 dip->dio_bio = dio_bio;
8621 atomic_set(&dip->pending_bios, 0);
8622 io_bio = btrfs_io_bio(bio);
8623 io_bio->logical = file_offset;
8626 bio->bi_end_io = btrfs_endio_direct_write;
8628 bio->bi_end_io = btrfs_endio_direct_read;
8629 dip->subio_endio = btrfs_subio_endio_read;
8633 * Reset the range for unsubmitted ordered extents (to a 0 length range)
8634 * even if we fail to submit a bio, because in such case we do the
8635 * corresponding error handling below and it must not be done a second
8636 * time by btrfs_direct_IO().
8639 struct btrfs_dio_data *dio_data = current->journal_info;
8641 dio_data->unsubmitted_oe_range_end = dip->logical_offset +
8643 dio_data->unsubmitted_oe_range_start =
8644 dio_data->unsubmitted_oe_range_end;
8647 ret = btrfs_submit_direct_hook(dip);
8652 io_bio->end_io(io_bio, ret);
8656 * If we arrived here it means either we failed to submit the dip
8657 * or we either failed to clone the dio_bio or failed to allocate the
8658 * dip. If we cloned the dio_bio and allocated the dip, we can just
8659 * call bio_endio against our io_bio so that we get proper resource
8660 * cleanup if we fail to submit the dip, otherwise, we must do the
8661 * same as btrfs_endio_direct_[write|read] because we can't call these
8662 * callbacks - they require an allocated dip and a clone of dio_bio.
8667 * The end io callbacks free our dip, do the final put on bio
8668 * and all the cleanup and final put for dio_bio (through
8675 __endio_write_update_ordered(inode,
8677 dio_bio->bi_iter.bi_size,
8680 unlock_extent(&BTRFS_I(inode)->io_tree, file_offset,
8681 file_offset + dio_bio->bi_iter.bi_size - 1);
8683 dio_bio->bi_status = BLK_STS_IOERR;
8685 * Releases and cleans up our dio_bio, no need to bio_put()
8686 * nor bio_endio()/bio_io_error() against dio_bio.
8688 dio_end_io(dio_bio);
8695 static ssize_t check_direct_IO(struct btrfs_fs_info *fs_info,
8696 const struct iov_iter *iter, loff_t offset)
8700 unsigned int blocksize_mask = fs_info->sectorsize - 1;
8701 ssize_t retval = -EINVAL;
8703 if (offset & blocksize_mask)
8706 if (iov_iter_alignment(iter) & blocksize_mask)
8709 /* If this is a write we don't need to check anymore */
8710 if (iov_iter_rw(iter) != READ || !iter_is_iovec(iter))
8713 * Check to make sure we don't have duplicate iov_base's in this
8714 * iovec, if so return EINVAL, otherwise we'll get csum errors
8715 * when reading back.
8717 for (seg = 0; seg < iter->nr_segs; seg++) {
8718 for (i = seg + 1; i < iter->nr_segs; i++) {
8719 if (iter->iov[seg].iov_base == iter->iov[i].iov_base)
8728 static ssize_t btrfs_direct_IO(struct kiocb *iocb, struct iov_iter *iter)
8730 struct file *file = iocb->ki_filp;
8731 struct inode *inode = file->f_mapping->host;
8732 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
8733 struct btrfs_dio_data dio_data = { 0 };
8734 struct extent_changeset *data_reserved = NULL;
8735 loff_t offset = iocb->ki_pos;
8739 bool relock = false;
8742 if (check_direct_IO(fs_info, iter, offset))
8745 inode_dio_begin(inode);
8748 * The generic stuff only does filemap_write_and_wait_range, which
8749 * isn't enough if we've written compressed pages to this area, so
8750 * we need to flush the dirty pages again to make absolutely sure
8751 * that any outstanding dirty pages are on disk.
8753 count = iov_iter_count(iter);
8754 if (test_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
8755 &BTRFS_I(inode)->runtime_flags))
8756 filemap_fdatawrite_range(inode->i_mapping, offset,
8757 offset + count - 1);
8759 if (iov_iter_rw(iter) == WRITE) {
8761 * If the write DIO is beyond the EOF, we need update
8762 * the isize, but it is protected by i_mutex. So we can
8763 * not unlock the i_mutex at this case.
8765 if (offset + count <= inode->i_size) {
8766 dio_data.overwrite = 1;
8767 inode_unlock(inode);
8769 } else if (iocb->ki_flags & IOCB_NOWAIT) {
8773 ret = btrfs_delalloc_reserve_space(inode, &data_reserved,
8779 * We need to know how many extents we reserved so that we can
8780 * do the accounting properly if we go over the number we
8781 * originally calculated. Abuse current->journal_info for this.
8783 dio_data.reserve = round_up(count,
8784 fs_info->sectorsize);
8785 dio_data.unsubmitted_oe_range_start = (u64)offset;
8786 dio_data.unsubmitted_oe_range_end = (u64)offset;
8787 current->journal_info = &dio_data;
8788 down_read(&BTRFS_I(inode)->dio_sem);
8789 } else if (test_bit(BTRFS_INODE_READDIO_NEED_LOCK,
8790 &BTRFS_I(inode)->runtime_flags)) {
8791 inode_dio_end(inode);
8792 flags = DIO_LOCKING | DIO_SKIP_HOLES;
8796 ret = __blockdev_direct_IO(iocb, inode,
8797 fs_info->fs_devices->latest_bdev,
8798 iter, btrfs_get_blocks_direct, NULL,
8799 btrfs_submit_direct, flags);
8800 if (iov_iter_rw(iter) == WRITE) {
8801 up_read(&BTRFS_I(inode)->dio_sem);
8802 current->journal_info = NULL;
8803 if (ret < 0 && ret != -EIOCBQUEUED) {
8804 if (dio_data.reserve)
8805 btrfs_delalloc_release_space(inode, data_reserved,
8806 offset, dio_data.reserve);
8808 * On error we might have left some ordered extents
8809 * without submitting corresponding bios for them, so
8810 * cleanup them up to avoid other tasks getting them
8811 * and waiting for them to complete forever.
8813 if (dio_data.unsubmitted_oe_range_start <
8814 dio_data.unsubmitted_oe_range_end)
8815 __endio_write_update_ordered(inode,
8816 dio_data.unsubmitted_oe_range_start,
8817 dio_data.unsubmitted_oe_range_end -
8818 dio_data.unsubmitted_oe_range_start,
8820 } else if (ret >= 0 && (size_t)ret < count)
8821 btrfs_delalloc_release_space(inode, data_reserved,
8822 offset, count - (size_t)ret);
8823 btrfs_delalloc_release_extents(BTRFS_I(inode), count);
8827 inode_dio_end(inode);
8831 extent_changeset_free(data_reserved);
8835 #define BTRFS_FIEMAP_FLAGS (FIEMAP_FLAG_SYNC)
8837 static int btrfs_fiemap(struct inode *inode, struct fiemap_extent_info *fieinfo,
8838 __u64 start, __u64 len)
8842 ret = fiemap_check_flags(fieinfo, BTRFS_FIEMAP_FLAGS);
8846 return extent_fiemap(inode, fieinfo, start, len);
8849 int btrfs_readpage(struct file *file, struct page *page)
8851 struct extent_io_tree *tree;
8852 tree = &BTRFS_I(page->mapping->host)->io_tree;
8853 return extent_read_full_page(tree, page, btrfs_get_extent, 0);
8856 static int btrfs_writepage(struct page *page, struct writeback_control *wbc)
8858 struct extent_io_tree *tree;
8859 struct inode *inode = page->mapping->host;
8862 if (current->flags & PF_MEMALLOC) {
8863 redirty_page_for_writepage(wbc, page);
8869 * If we are under memory pressure we will call this directly from the
8870 * VM, we need to make sure we have the inode referenced for the ordered
8871 * extent. If not just return like we didn't do anything.
8873 if (!igrab(inode)) {
8874 redirty_page_for_writepage(wbc, page);
8875 return AOP_WRITEPAGE_ACTIVATE;
8877 tree = &BTRFS_I(page->mapping->host)->io_tree;
8878 ret = extent_write_full_page(tree, page, wbc);
8879 btrfs_add_delayed_iput(inode);
8883 static int btrfs_writepages(struct address_space *mapping,
8884 struct writeback_control *wbc)
8886 struct extent_io_tree *tree;
8888 tree = &BTRFS_I(mapping->host)->io_tree;
8889 return extent_writepages(tree, mapping, wbc);
8893 btrfs_readpages(struct file *file, struct address_space *mapping,
8894 struct list_head *pages, unsigned nr_pages)
8896 struct extent_io_tree *tree;
8897 tree = &BTRFS_I(mapping->host)->io_tree;
8898 return extent_readpages(tree, mapping, pages, nr_pages);
8900 static int __btrfs_releasepage(struct page *page, gfp_t gfp_flags)
8902 struct extent_io_tree *tree;
8903 struct extent_map_tree *map;
8906 tree = &BTRFS_I(page->mapping->host)->io_tree;
8907 map = &BTRFS_I(page->mapping->host)->extent_tree;
8908 ret = try_release_extent_mapping(map, tree, page, gfp_flags);
8910 ClearPagePrivate(page);
8911 set_page_private(page, 0);
8917 static int btrfs_releasepage(struct page *page, gfp_t gfp_flags)
8919 if (PageWriteback(page) || PageDirty(page))
8921 return __btrfs_releasepage(page, gfp_flags);
8924 static void btrfs_invalidatepage(struct page *page, unsigned int offset,
8925 unsigned int length)
8927 struct inode *inode = page->mapping->host;
8928 struct extent_io_tree *tree;
8929 struct btrfs_ordered_extent *ordered;
8930 struct extent_state *cached_state = NULL;
8931 u64 page_start = page_offset(page);
8932 u64 page_end = page_start + PAGE_SIZE - 1;
8935 int inode_evicting = inode->i_state & I_FREEING;
8938 * we have the page locked, so new writeback can't start,
8939 * and the dirty bit won't be cleared while we are here.
8941 * Wait for IO on this page so that we can safely clear
8942 * the PagePrivate2 bit and do ordered accounting
8944 wait_on_page_writeback(page);
8946 tree = &BTRFS_I(inode)->io_tree;
8948 btrfs_releasepage(page, GFP_NOFS);
8952 if (!inode_evicting)
8953 lock_extent_bits(tree, page_start, page_end, &cached_state);
8956 ordered = btrfs_lookup_ordered_range(BTRFS_I(inode), start,
8957 page_end - start + 1);
8959 end = min(page_end, ordered->file_offset + ordered->len - 1);
8961 * IO on this page will never be started, so we need
8962 * to account for any ordered extents now
8964 if (!inode_evicting)
8965 clear_extent_bit(tree, start, end,
8966 EXTENT_DIRTY | EXTENT_DELALLOC |
8967 EXTENT_DELALLOC_NEW |
8968 EXTENT_LOCKED | EXTENT_DO_ACCOUNTING |
8969 EXTENT_DEFRAG, 1, 0, &cached_state);
8971 * whoever cleared the private bit is responsible
8972 * for the finish_ordered_io
8974 if (TestClearPagePrivate2(page)) {
8975 struct btrfs_ordered_inode_tree *tree;
8978 tree = &BTRFS_I(inode)->ordered_tree;
8980 spin_lock_irq(&tree->lock);
8981 set_bit(BTRFS_ORDERED_TRUNCATED, &ordered->flags);
8982 new_len = start - ordered->file_offset;
8983 if (new_len < ordered->truncated_len)
8984 ordered->truncated_len = new_len;
8985 spin_unlock_irq(&tree->lock);
8987 if (btrfs_dec_test_ordered_pending(inode, &ordered,
8989 end - start + 1, 1))
8990 btrfs_finish_ordered_io(ordered);
8992 btrfs_put_ordered_extent(ordered);
8993 if (!inode_evicting) {
8994 cached_state = NULL;
8995 lock_extent_bits(tree, start, end,
9000 if (start < page_end)
9005 * Qgroup reserved space handler
9006 * Page here will be either
9007 * 1) Already written to disk
9008 * In this case, its reserved space is released from data rsv map
9009 * and will be freed by delayed_ref handler finally.
9010 * So even we call qgroup_free_data(), it won't decrease reserved
9012 * 2) Not written to disk
9013 * This means the reserved space should be freed here. However,
9014 * if a truncate invalidates the page (by clearing PageDirty)
9015 * and the page is accounted for while allocating extent
9016 * in btrfs_check_data_free_space() we let delayed_ref to
9017 * free the entire extent.
9019 if (PageDirty(page))
9020 btrfs_qgroup_free_data(inode, NULL, page_start, PAGE_SIZE);
9021 if (!inode_evicting) {
9022 clear_extent_bit(tree, page_start, page_end,
9023 EXTENT_LOCKED | EXTENT_DIRTY |
9024 EXTENT_DELALLOC | EXTENT_DELALLOC_NEW |
9025 EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG, 1, 1,
9028 __btrfs_releasepage(page, GFP_NOFS);
9031 ClearPageChecked(page);
9032 if (PagePrivate(page)) {
9033 ClearPagePrivate(page);
9034 set_page_private(page, 0);
9040 * btrfs_page_mkwrite() is not allowed to change the file size as it gets
9041 * called from a page fault handler when a page is first dirtied. Hence we must
9042 * be careful to check for EOF conditions here. We set the page up correctly
9043 * for a written page which means we get ENOSPC checking when writing into
9044 * holes and correct delalloc and unwritten extent mapping on filesystems that
9045 * support these features.
9047 * We are not allowed to take the i_mutex here so we have to play games to
9048 * protect against truncate races as the page could now be beyond EOF. Because
9049 * vmtruncate() writes the inode size before removing pages, once we have the
9050 * page lock we can determine safely if the page is beyond EOF. If it is not
9051 * beyond EOF, then the page is guaranteed safe against truncation until we
9054 int btrfs_page_mkwrite(struct vm_fault *vmf)
9056 struct page *page = vmf->page;
9057 struct inode *inode = file_inode(vmf->vma->vm_file);
9058 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
9059 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
9060 struct btrfs_ordered_extent *ordered;
9061 struct extent_state *cached_state = NULL;
9062 struct extent_changeset *data_reserved = NULL;
9064 unsigned long zero_start;
9073 reserved_space = PAGE_SIZE;
9075 sb_start_pagefault(inode->i_sb);
9076 page_start = page_offset(page);
9077 page_end = page_start + PAGE_SIZE - 1;
9081 * Reserving delalloc space after obtaining the page lock can lead to
9082 * deadlock. For example, if a dirty page is locked by this function
9083 * and the call to btrfs_delalloc_reserve_space() ends up triggering
9084 * dirty page write out, then the btrfs_writepage() function could
9085 * end up waiting indefinitely to get a lock on the page currently
9086 * being processed by btrfs_page_mkwrite() function.
9088 ret = btrfs_delalloc_reserve_space(inode, &data_reserved, page_start,
9091 ret = file_update_time(vmf->vma->vm_file);
9097 else /* -ENOSPC, -EIO, etc */
9098 ret = VM_FAULT_SIGBUS;
9104 ret = VM_FAULT_NOPAGE; /* make the VM retry the fault */
9107 size = i_size_read(inode);
9109 if ((page->mapping != inode->i_mapping) ||
9110 (page_start >= size)) {
9111 /* page got truncated out from underneath us */
9114 wait_on_page_writeback(page);
9116 lock_extent_bits(io_tree, page_start, page_end, &cached_state);
9117 set_page_extent_mapped(page);
9120 * we can't set the delalloc bits if there are pending ordered
9121 * extents. Drop our locks and wait for them to finish
9123 ordered = btrfs_lookup_ordered_range(BTRFS_I(inode), page_start,
9126 unlock_extent_cached(io_tree, page_start, page_end,
9127 &cached_state, GFP_NOFS);
9129 btrfs_start_ordered_extent(inode, ordered, 1);
9130 btrfs_put_ordered_extent(ordered);
9134 if (page->index == ((size - 1) >> PAGE_SHIFT)) {
9135 reserved_space = round_up(size - page_start,
9136 fs_info->sectorsize);
9137 if (reserved_space < PAGE_SIZE) {
9138 end = page_start + reserved_space - 1;
9139 btrfs_delalloc_release_space(inode, data_reserved,
9140 page_start, PAGE_SIZE - reserved_space);
9145 * page_mkwrite gets called when the page is firstly dirtied after it's
9146 * faulted in, but write(2) could also dirty a page and set delalloc
9147 * bits, thus in this case for space account reason, we still need to
9148 * clear any delalloc bits within this page range since we have to
9149 * reserve data&meta space before lock_page() (see above comments).
9151 clear_extent_bit(&BTRFS_I(inode)->io_tree, page_start, end,
9152 EXTENT_DIRTY | EXTENT_DELALLOC |
9153 EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG,
9154 0, 0, &cached_state);
9156 ret = btrfs_set_extent_delalloc(inode, page_start, end, 0,
9159 unlock_extent_cached(io_tree, page_start, page_end,
9160 &cached_state, GFP_NOFS);
9161 ret = VM_FAULT_SIGBUS;
9166 /* page is wholly or partially inside EOF */
9167 if (page_start + PAGE_SIZE > size)
9168 zero_start = size & ~PAGE_MASK;
9170 zero_start = PAGE_SIZE;
9172 if (zero_start != PAGE_SIZE) {
9174 memset(kaddr + zero_start, 0, PAGE_SIZE - zero_start);
9175 flush_dcache_page(page);
9178 ClearPageChecked(page);
9179 set_page_dirty(page);
9180 SetPageUptodate(page);
9182 BTRFS_I(inode)->last_trans = fs_info->generation;
9183 BTRFS_I(inode)->last_sub_trans = BTRFS_I(inode)->root->log_transid;
9184 BTRFS_I(inode)->last_log_commit = BTRFS_I(inode)->root->last_log_commit;
9186 unlock_extent_cached(io_tree, page_start, page_end, &cached_state, GFP_NOFS);
9190 btrfs_delalloc_release_extents(BTRFS_I(inode), PAGE_SIZE);
9191 sb_end_pagefault(inode->i_sb);
9192 extent_changeset_free(data_reserved);
9193 return VM_FAULT_LOCKED;
9197 btrfs_delalloc_release_extents(BTRFS_I(inode), PAGE_SIZE);
9198 btrfs_delalloc_release_space(inode, data_reserved, page_start,
9201 sb_end_pagefault(inode->i_sb);
9202 extent_changeset_free(data_reserved);
9206 static int btrfs_truncate(struct inode *inode)
9208 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
9209 struct btrfs_root *root = BTRFS_I(inode)->root;
9210 struct btrfs_block_rsv *rsv;
9213 struct btrfs_trans_handle *trans;
9214 u64 mask = fs_info->sectorsize - 1;
9215 u64 min_size = btrfs_calc_trunc_metadata_size(fs_info, 1);
9217 ret = btrfs_wait_ordered_range(inode, inode->i_size & (~mask),
9223 * Yes ladies and gentlemen, this is indeed ugly. The fact is we have
9224 * 3 things going on here
9226 * 1) We need to reserve space for our orphan item and the space to
9227 * delete our orphan item. Lord knows we don't want to have a dangling
9228 * orphan item because we didn't reserve space to remove it.
9230 * 2) We need to reserve space to update our inode.
9232 * 3) We need to have something to cache all the space that is going to
9233 * be free'd up by the truncate operation, but also have some slack
9234 * space reserved in case it uses space during the truncate (thank you
9235 * very much snapshotting).
9237 * And we need these to all be separate. The fact is we can use a lot of
9238 * space doing the truncate, and we have no earthly idea how much space
9239 * we will use, so we need the truncate reservation to be separate so it
9240 * doesn't end up using space reserved for updating the inode or
9241 * removing the orphan item. We also need to be able to stop the
9242 * transaction and start a new one, which means we need to be able to
9243 * update the inode several times, and we have no idea of knowing how
9244 * many times that will be, so we can't just reserve 1 item for the
9245 * entirety of the operation, so that has to be done separately as well.
9246 * Then there is the orphan item, which does indeed need to be held on
9247 * to for the whole operation, and we need nobody to touch this reserved
9248 * space except the orphan code.
9250 * So that leaves us with
9252 * 1) root->orphan_block_rsv - for the orphan deletion.
9253 * 2) rsv - for the truncate reservation, which we will steal from the
9254 * transaction reservation.
9255 * 3) fs_info->trans_block_rsv - this will have 1 items worth left for
9256 * updating the inode.
9258 rsv = btrfs_alloc_block_rsv(fs_info, BTRFS_BLOCK_RSV_TEMP);
9261 rsv->size = min_size;
9265 * 1 for the truncate slack space
9266 * 1 for updating the inode.
9268 trans = btrfs_start_transaction(root, 2);
9269 if (IS_ERR(trans)) {
9270 err = PTR_ERR(trans);
9274 /* Migrate the slack space for the truncate to our reserve */
9275 ret = btrfs_block_rsv_migrate(&fs_info->trans_block_rsv, rsv,
9280 * So if we truncate and then write and fsync we normally would just
9281 * write the extents that changed, which is a problem if we need to
9282 * first truncate that entire inode. So set this flag so we write out
9283 * all of the extents in the inode to the sync log so we're completely
9286 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &BTRFS_I(inode)->runtime_flags);
9287 trans->block_rsv = rsv;
9290 ret = btrfs_truncate_inode_items(trans, root, inode,
9292 BTRFS_EXTENT_DATA_KEY);
9293 trans->block_rsv = &fs_info->trans_block_rsv;
9294 if (ret != -ENOSPC && ret != -EAGAIN) {
9299 ret = btrfs_update_inode(trans, root, inode);
9305 btrfs_end_transaction(trans);
9306 btrfs_btree_balance_dirty(fs_info);
9308 trans = btrfs_start_transaction(root, 2);
9309 if (IS_ERR(trans)) {
9310 ret = err = PTR_ERR(trans);
9315 btrfs_block_rsv_release(fs_info, rsv, -1);
9316 ret = btrfs_block_rsv_migrate(&fs_info->trans_block_rsv,
9318 BUG_ON(ret); /* shouldn't happen */
9319 trans->block_rsv = rsv;
9323 * We can't call btrfs_truncate_block inside a trans handle as we could
9324 * deadlock with freeze, if we got NEED_TRUNCATE_BLOCK then we know
9325 * we've truncated everything except the last little bit, and can do
9326 * btrfs_truncate_block and then update the disk_i_size.
9328 if (ret == NEED_TRUNCATE_BLOCK) {
9329 btrfs_end_transaction(trans);
9330 btrfs_btree_balance_dirty(fs_info);
9332 ret = btrfs_truncate_block(inode, inode->i_size, 0, 0);
9335 trans = btrfs_start_transaction(root, 1);
9336 if (IS_ERR(trans)) {
9337 ret = PTR_ERR(trans);
9340 btrfs_ordered_update_i_size(inode, inode->i_size, NULL);
9343 if (ret == 0 && inode->i_nlink > 0) {
9344 trans->block_rsv = root->orphan_block_rsv;
9345 ret = btrfs_orphan_del(trans, BTRFS_I(inode));
9351 trans->block_rsv = &fs_info->trans_block_rsv;
9352 ret = btrfs_update_inode(trans, root, inode);
9356 ret = btrfs_end_transaction(trans);
9357 btrfs_btree_balance_dirty(fs_info);
9360 btrfs_free_block_rsv(fs_info, rsv);
9369 * create a new subvolume directory/inode (helper for the ioctl).
9371 int btrfs_create_subvol_root(struct btrfs_trans_handle *trans,
9372 struct btrfs_root *new_root,
9373 struct btrfs_root *parent_root,
9376 struct inode *inode;
9380 inode = btrfs_new_inode(trans, new_root, NULL, "..", 2,
9381 new_dirid, new_dirid,
9382 S_IFDIR | (~current_umask() & S_IRWXUGO),
9385 return PTR_ERR(inode);
9386 inode->i_op = &btrfs_dir_inode_operations;
9387 inode->i_fop = &btrfs_dir_file_operations;
9389 set_nlink(inode, 1);
9390 btrfs_i_size_write(BTRFS_I(inode), 0);
9391 unlock_new_inode(inode);
9393 err = btrfs_subvol_inherit_props(trans, new_root, parent_root);
9395 btrfs_err(new_root->fs_info,
9396 "error inheriting subvolume %llu properties: %d",
9397 new_root->root_key.objectid, err);
9399 err = btrfs_update_inode(trans, new_root, inode);
9405 struct inode *btrfs_alloc_inode(struct super_block *sb)
9407 struct btrfs_fs_info *fs_info = btrfs_sb(sb);
9408 struct btrfs_inode *ei;
9409 struct inode *inode;
9411 ei = kmem_cache_alloc(btrfs_inode_cachep, GFP_KERNEL);
9418 ei->last_sub_trans = 0;
9419 ei->logged_trans = 0;
9420 ei->delalloc_bytes = 0;
9421 ei->new_delalloc_bytes = 0;
9422 ei->defrag_bytes = 0;
9423 ei->disk_i_size = 0;
9426 ei->index_cnt = (u64)-1;
9428 ei->last_unlink_trans = 0;
9429 ei->last_log_commit = 0;
9430 ei->delayed_iput_count = 0;
9432 spin_lock_init(&ei->lock);
9433 ei->outstanding_extents = 0;
9434 if (sb->s_magic != BTRFS_TEST_MAGIC)
9435 btrfs_init_metadata_block_rsv(fs_info, &ei->block_rsv,
9436 BTRFS_BLOCK_RSV_DELALLOC);
9437 ei->runtime_flags = 0;
9438 ei->prop_compress = BTRFS_COMPRESS_NONE;
9439 ei->defrag_compress = BTRFS_COMPRESS_NONE;
9441 ei->delayed_node = NULL;
9443 ei->i_otime.tv_sec = 0;
9444 ei->i_otime.tv_nsec = 0;
9446 inode = &ei->vfs_inode;
9447 extent_map_tree_init(&ei->extent_tree);
9448 extent_io_tree_init(&ei->io_tree, inode);
9449 extent_io_tree_init(&ei->io_failure_tree, inode);
9450 ei->io_tree.track_uptodate = 1;
9451 ei->io_failure_tree.track_uptodate = 1;
9452 atomic_set(&ei->sync_writers, 0);
9453 mutex_init(&ei->log_mutex);
9454 mutex_init(&ei->delalloc_mutex);
9455 btrfs_ordered_inode_tree_init(&ei->ordered_tree);
9456 INIT_LIST_HEAD(&ei->delalloc_inodes);
9457 INIT_LIST_HEAD(&ei->delayed_iput);
9458 RB_CLEAR_NODE(&ei->rb_node);
9459 init_rwsem(&ei->dio_sem);
9464 #ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
9465 void btrfs_test_destroy_inode(struct inode *inode)
9467 btrfs_drop_extent_cache(BTRFS_I(inode), 0, (u64)-1, 0);
9468 kmem_cache_free(btrfs_inode_cachep, BTRFS_I(inode));
9472 static void btrfs_i_callback(struct rcu_head *head)
9474 struct inode *inode = container_of(head, struct inode, i_rcu);
9475 kmem_cache_free(btrfs_inode_cachep, BTRFS_I(inode));
9478 void btrfs_destroy_inode(struct inode *inode)
9480 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
9481 struct btrfs_ordered_extent *ordered;
9482 struct btrfs_root *root = BTRFS_I(inode)->root;
9484 WARN_ON(!hlist_empty(&inode->i_dentry));
9485 WARN_ON(inode->i_data.nrpages);
9486 WARN_ON(BTRFS_I(inode)->block_rsv.reserved);
9487 WARN_ON(BTRFS_I(inode)->block_rsv.size);
9488 WARN_ON(BTRFS_I(inode)->outstanding_extents);
9489 WARN_ON(BTRFS_I(inode)->delalloc_bytes);
9490 WARN_ON(BTRFS_I(inode)->new_delalloc_bytes);
9491 WARN_ON(BTRFS_I(inode)->csum_bytes);
9492 WARN_ON(BTRFS_I(inode)->defrag_bytes);
9495 * This can happen where we create an inode, but somebody else also
9496 * created the same inode and we need to destroy the one we already
9502 if (test_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
9503 &BTRFS_I(inode)->runtime_flags)) {
9504 btrfs_info(fs_info, "inode %llu still on the orphan list",
9505 btrfs_ino(BTRFS_I(inode)));
9506 atomic_dec(&root->orphan_inodes);
9510 ordered = btrfs_lookup_first_ordered_extent(inode, (u64)-1);
9515 "found ordered extent %llu %llu on inode cleanup",
9516 ordered->file_offset, ordered->len);
9517 btrfs_remove_ordered_extent(inode, ordered);
9518 btrfs_put_ordered_extent(ordered);
9519 btrfs_put_ordered_extent(ordered);
9522 btrfs_qgroup_check_reserved_leak(inode);
9523 inode_tree_del(inode);
9524 btrfs_drop_extent_cache(BTRFS_I(inode), 0, (u64)-1, 0);
9526 call_rcu(&inode->i_rcu, btrfs_i_callback);
9529 int btrfs_drop_inode(struct inode *inode)
9531 struct btrfs_root *root = BTRFS_I(inode)->root;
9536 /* the snap/subvol tree is on deleting */
9537 if (btrfs_root_refs(&root->root_item) == 0)
9540 return generic_drop_inode(inode);
9543 static void init_once(void *foo)
9545 struct btrfs_inode *ei = (struct btrfs_inode *) foo;
9547 inode_init_once(&ei->vfs_inode);
9550 void btrfs_destroy_cachep(void)
9553 * Make sure all delayed rcu free inodes are flushed before we
9557 kmem_cache_destroy(btrfs_inode_cachep);
9558 kmem_cache_destroy(btrfs_trans_handle_cachep);
9559 kmem_cache_destroy(btrfs_path_cachep);
9560 kmem_cache_destroy(btrfs_free_space_cachep);
9563 int __init btrfs_init_cachep(void)
9565 btrfs_inode_cachep = kmem_cache_create("btrfs_inode",
9566 sizeof(struct btrfs_inode), 0,
9567 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD | SLAB_ACCOUNT,
9569 if (!btrfs_inode_cachep)
9572 btrfs_trans_handle_cachep = kmem_cache_create("btrfs_trans_handle",
9573 sizeof(struct btrfs_trans_handle), 0,
9574 SLAB_TEMPORARY | SLAB_MEM_SPREAD, NULL);
9575 if (!btrfs_trans_handle_cachep)
9578 btrfs_path_cachep = kmem_cache_create("btrfs_path",
9579 sizeof(struct btrfs_path), 0,
9580 SLAB_MEM_SPREAD, NULL);
9581 if (!btrfs_path_cachep)
9584 btrfs_free_space_cachep = kmem_cache_create("btrfs_free_space",
9585 sizeof(struct btrfs_free_space), 0,
9586 SLAB_MEM_SPREAD, NULL);
9587 if (!btrfs_free_space_cachep)
9592 btrfs_destroy_cachep();
9596 static int btrfs_getattr(const struct path *path, struct kstat *stat,
9597 u32 request_mask, unsigned int flags)
9600 struct inode *inode = d_inode(path->dentry);
9601 u32 blocksize = inode->i_sb->s_blocksize;
9602 u32 bi_flags = BTRFS_I(inode)->flags;
9604 stat->result_mask |= STATX_BTIME;
9605 stat->btime.tv_sec = BTRFS_I(inode)->i_otime.tv_sec;
9606 stat->btime.tv_nsec = BTRFS_I(inode)->i_otime.tv_nsec;
9607 if (bi_flags & BTRFS_INODE_APPEND)
9608 stat->attributes |= STATX_ATTR_APPEND;
9609 if (bi_flags & BTRFS_INODE_COMPRESS)
9610 stat->attributes |= STATX_ATTR_COMPRESSED;
9611 if (bi_flags & BTRFS_INODE_IMMUTABLE)
9612 stat->attributes |= STATX_ATTR_IMMUTABLE;
9613 if (bi_flags & BTRFS_INODE_NODUMP)
9614 stat->attributes |= STATX_ATTR_NODUMP;
9616 stat->attributes_mask |= (STATX_ATTR_APPEND |
9617 STATX_ATTR_COMPRESSED |
9618 STATX_ATTR_IMMUTABLE |
9621 generic_fillattr(inode, stat);
9622 stat->dev = BTRFS_I(inode)->root->anon_dev;
9624 spin_lock(&BTRFS_I(inode)->lock);
9625 delalloc_bytes = BTRFS_I(inode)->new_delalloc_bytes;
9626 spin_unlock(&BTRFS_I(inode)->lock);
9627 stat->blocks = (ALIGN(inode_get_bytes(inode), blocksize) +
9628 ALIGN(delalloc_bytes, blocksize)) >> 9;
9632 static int btrfs_rename_exchange(struct inode *old_dir,
9633 struct dentry *old_dentry,
9634 struct inode *new_dir,
9635 struct dentry *new_dentry)
9637 struct btrfs_fs_info *fs_info = btrfs_sb(old_dir->i_sb);
9638 struct btrfs_trans_handle *trans;
9639 struct btrfs_root *root = BTRFS_I(old_dir)->root;
9640 struct btrfs_root *dest = BTRFS_I(new_dir)->root;
9641 struct inode *new_inode = new_dentry->d_inode;
9642 struct inode *old_inode = old_dentry->d_inode;
9643 struct timespec ctime = current_time(old_inode);
9644 struct dentry *parent;
9645 u64 old_ino = btrfs_ino(BTRFS_I(old_inode));
9646 u64 new_ino = btrfs_ino(BTRFS_I(new_inode));
9651 bool root_log_pinned = false;
9652 bool dest_log_pinned = false;
9654 /* we only allow rename subvolume link between subvolumes */
9655 if (old_ino != BTRFS_FIRST_FREE_OBJECTID && root != dest)
9658 /* close the race window with snapshot create/destroy ioctl */
9659 if (old_ino == BTRFS_FIRST_FREE_OBJECTID)
9660 down_read(&fs_info->subvol_sem);
9661 if (new_ino == BTRFS_FIRST_FREE_OBJECTID)
9662 down_read(&fs_info->subvol_sem);
9665 * We want to reserve the absolute worst case amount of items. So if
9666 * both inodes are subvols and we need to unlink them then that would
9667 * require 4 item modifications, but if they are both normal inodes it
9668 * would require 5 item modifications, so we'll assume their normal
9669 * inodes. So 5 * 2 is 10, plus 2 for the new links, so 12 total items
9670 * should cover the worst case number of items we'll modify.
9672 trans = btrfs_start_transaction(root, 12);
9673 if (IS_ERR(trans)) {
9674 ret = PTR_ERR(trans);
9679 * We need to find a free sequence number both in the source and
9680 * in the destination directory for the exchange.
9682 ret = btrfs_set_inode_index(BTRFS_I(new_dir), &old_idx);
9685 ret = btrfs_set_inode_index(BTRFS_I(old_dir), &new_idx);
9689 BTRFS_I(old_inode)->dir_index = 0ULL;
9690 BTRFS_I(new_inode)->dir_index = 0ULL;
9692 /* Reference for the source. */
9693 if (old_ino == BTRFS_FIRST_FREE_OBJECTID) {
9694 /* force full log commit if subvolume involved. */
9695 btrfs_set_log_full_commit(fs_info, trans);
9697 btrfs_pin_log_trans(root);
9698 root_log_pinned = true;
9699 ret = btrfs_insert_inode_ref(trans, dest,
9700 new_dentry->d_name.name,
9701 new_dentry->d_name.len,
9703 btrfs_ino(BTRFS_I(new_dir)),
9709 /* And now for the dest. */
9710 if (new_ino == BTRFS_FIRST_FREE_OBJECTID) {
9711 /* force full log commit if subvolume involved. */
9712 btrfs_set_log_full_commit(fs_info, trans);
9714 btrfs_pin_log_trans(dest);
9715 dest_log_pinned = true;
9716 ret = btrfs_insert_inode_ref(trans, root,
9717 old_dentry->d_name.name,
9718 old_dentry->d_name.len,
9720 btrfs_ino(BTRFS_I(old_dir)),
9726 /* Update inode version and ctime/mtime. */
9727 inode_inc_iversion(old_dir);
9728 inode_inc_iversion(new_dir);
9729 inode_inc_iversion(old_inode);
9730 inode_inc_iversion(new_inode);
9731 old_dir->i_ctime = old_dir->i_mtime = ctime;
9732 new_dir->i_ctime = new_dir->i_mtime = ctime;
9733 old_inode->i_ctime = ctime;
9734 new_inode->i_ctime = ctime;
9736 if (old_dentry->d_parent != new_dentry->d_parent) {
9737 btrfs_record_unlink_dir(trans, BTRFS_I(old_dir),
9738 BTRFS_I(old_inode), 1);
9739 btrfs_record_unlink_dir(trans, BTRFS_I(new_dir),
9740 BTRFS_I(new_inode), 1);
9743 /* src is a subvolume */
9744 if (old_ino == BTRFS_FIRST_FREE_OBJECTID) {
9745 root_objectid = BTRFS_I(old_inode)->root->root_key.objectid;
9746 ret = btrfs_unlink_subvol(trans, root, old_dir,
9748 old_dentry->d_name.name,
9749 old_dentry->d_name.len);
9750 } else { /* src is an inode */
9751 ret = __btrfs_unlink_inode(trans, root, BTRFS_I(old_dir),
9752 BTRFS_I(old_dentry->d_inode),
9753 old_dentry->d_name.name,
9754 old_dentry->d_name.len);
9756 ret = btrfs_update_inode(trans, root, old_inode);
9759 btrfs_abort_transaction(trans, ret);
9763 /* dest is a subvolume */
9764 if (new_ino == BTRFS_FIRST_FREE_OBJECTID) {
9765 root_objectid = BTRFS_I(new_inode)->root->root_key.objectid;
9766 ret = btrfs_unlink_subvol(trans, dest, new_dir,
9768 new_dentry->d_name.name,
9769 new_dentry->d_name.len);
9770 } else { /* dest is an inode */
9771 ret = __btrfs_unlink_inode(trans, dest, BTRFS_I(new_dir),
9772 BTRFS_I(new_dentry->d_inode),
9773 new_dentry->d_name.name,
9774 new_dentry->d_name.len);
9776 ret = btrfs_update_inode(trans, dest, new_inode);
9779 btrfs_abort_transaction(trans, ret);
9783 ret = btrfs_add_link(trans, BTRFS_I(new_dir), BTRFS_I(old_inode),
9784 new_dentry->d_name.name,
9785 new_dentry->d_name.len, 0, old_idx);
9787 btrfs_abort_transaction(trans, ret);
9791 ret = btrfs_add_link(trans, BTRFS_I(old_dir), BTRFS_I(new_inode),
9792 old_dentry->d_name.name,
9793 old_dentry->d_name.len, 0, new_idx);
9795 btrfs_abort_transaction(trans, ret);
9799 if (old_inode->i_nlink == 1)
9800 BTRFS_I(old_inode)->dir_index = old_idx;
9801 if (new_inode->i_nlink == 1)
9802 BTRFS_I(new_inode)->dir_index = new_idx;
9804 if (root_log_pinned) {
9805 parent = new_dentry->d_parent;
9806 btrfs_log_new_name(trans, BTRFS_I(old_inode), BTRFS_I(old_dir),
9808 btrfs_end_log_trans(root);
9809 root_log_pinned = false;
9811 if (dest_log_pinned) {
9812 parent = old_dentry->d_parent;
9813 btrfs_log_new_name(trans, BTRFS_I(new_inode), BTRFS_I(new_dir),
9815 btrfs_end_log_trans(dest);
9816 dest_log_pinned = false;
9820 * If we have pinned a log and an error happened, we unpin tasks
9821 * trying to sync the log and force them to fallback to a transaction
9822 * commit if the log currently contains any of the inodes involved in
9823 * this rename operation (to ensure we do not persist a log with an
9824 * inconsistent state for any of these inodes or leading to any
9825 * inconsistencies when replayed). If the transaction was aborted, the
9826 * abortion reason is propagated to userspace when attempting to commit
9827 * the transaction. If the log does not contain any of these inodes, we
9828 * allow the tasks to sync it.
9830 if (ret && (root_log_pinned || dest_log_pinned)) {
9831 if (btrfs_inode_in_log(BTRFS_I(old_dir), fs_info->generation) ||
9832 btrfs_inode_in_log(BTRFS_I(new_dir), fs_info->generation) ||
9833 btrfs_inode_in_log(BTRFS_I(old_inode), fs_info->generation) ||
9835 btrfs_inode_in_log(BTRFS_I(new_inode), fs_info->generation)))
9836 btrfs_set_log_full_commit(fs_info, trans);
9838 if (root_log_pinned) {
9839 btrfs_end_log_trans(root);
9840 root_log_pinned = false;
9842 if (dest_log_pinned) {
9843 btrfs_end_log_trans(dest);
9844 dest_log_pinned = false;
9847 ret = btrfs_end_transaction(trans);
9849 if (new_ino == BTRFS_FIRST_FREE_OBJECTID)
9850 up_read(&fs_info->subvol_sem);
9851 if (old_ino == BTRFS_FIRST_FREE_OBJECTID)
9852 up_read(&fs_info->subvol_sem);
9857 static int btrfs_whiteout_for_rename(struct btrfs_trans_handle *trans,
9858 struct btrfs_root *root,
9860 struct dentry *dentry)
9863 struct inode *inode;
9867 ret = btrfs_find_free_ino(root, &objectid);
9871 inode = btrfs_new_inode(trans, root, dir,
9872 dentry->d_name.name,
9874 btrfs_ino(BTRFS_I(dir)),
9876 S_IFCHR | WHITEOUT_MODE,
9879 if (IS_ERR(inode)) {
9880 ret = PTR_ERR(inode);
9884 inode->i_op = &btrfs_special_inode_operations;
9885 init_special_inode(inode, inode->i_mode,
9888 ret = btrfs_init_inode_security(trans, inode, dir,
9893 ret = btrfs_add_nondir(trans, BTRFS_I(dir), dentry,
9894 BTRFS_I(inode), 0, index);
9898 ret = btrfs_update_inode(trans, root, inode);
9900 unlock_new_inode(inode);
9902 inode_dec_link_count(inode);
9908 static int btrfs_rename(struct inode *old_dir, struct dentry *old_dentry,
9909 struct inode *new_dir, struct dentry *new_dentry,
9912 struct btrfs_fs_info *fs_info = btrfs_sb(old_dir->i_sb);
9913 struct btrfs_trans_handle *trans;
9914 unsigned int trans_num_items;
9915 struct btrfs_root *root = BTRFS_I(old_dir)->root;
9916 struct btrfs_root *dest = BTRFS_I(new_dir)->root;
9917 struct inode *new_inode = d_inode(new_dentry);
9918 struct inode *old_inode = d_inode(old_dentry);
9922 u64 old_ino = btrfs_ino(BTRFS_I(old_inode));
9923 bool log_pinned = false;
9925 if (btrfs_ino(BTRFS_I(new_dir)) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)
9928 /* we only allow rename subvolume link between subvolumes */
9929 if (old_ino != BTRFS_FIRST_FREE_OBJECTID && root != dest)
9932 if (old_ino == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID ||
9933 (new_inode && btrfs_ino(BTRFS_I(new_inode)) == BTRFS_FIRST_FREE_OBJECTID))
9936 if (S_ISDIR(old_inode->i_mode) && new_inode &&
9937 new_inode->i_size > BTRFS_EMPTY_DIR_SIZE)
9941 /* check for collisions, even if the name isn't there */
9942 ret = btrfs_check_dir_item_collision(dest, new_dir->i_ino,
9943 new_dentry->d_name.name,
9944 new_dentry->d_name.len);
9947 if (ret == -EEXIST) {
9949 * eexist without a new_inode */
9950 if (WARN_ON(!new_inode)) {
9954 /* maybe -EOVERFLOW */
9961 * we're using rename to replace one file with another. Start IO on it
9962 * now so we don't add too much work to the end of the transaction
9964 if (new_inode && S_ISREG(old_inode->i_mode) && new_inode->i_size)
9965 filemap_flush(old_inode->i_mapping);
9967 /* close the racy window with snapshot create/destroy ioctl */
9968 if (old_ino == BTRFS_FIRST_FREE_OBJECTID)
9969 down_read(&fs_info->subvol_sem);
9971 * We want to reserve the absolute worst case amount of items. So if
9972 * both inodes are subvols and we need to unlink them then that would
9973 * require 4 item modifications, but if they are both normal inodes it
9974 * would require 5 item modifications, so we'll assume they are normal
9975 * inodes. So 5 * 2 is 10, plus 1 for the new link, so 11 total items
9976 * should cover the worst case number of items we'll modify.
9977 * If our rename has the whiteout flag, we need more 5 units for the
9978 * new inode (1 inode item, 1 inode ref, 2 dir items and 1 xattr item
9979 * when selinux is enabled).
9981 trans_num_items = 11;
9982 if (flags & RENAME_WHITEOUT)
9983 trans_num_items += 5;
9984 trans = btrfs_start_transaction(root, trans_num_items);
9985 if (IS_ERR(trans)) {
9986 ret = PTR_ERR(trans);
9991 btrfs_record_root_in_trans(trans, dest);
9993 ret = btrfs_set_inode_index(BTRFS_I(new_dir), &index);
9997 BTRFS_I(old_inode)->dir_index = 0ULL;
9998 if (unlikely(old_ino == BTRFS_FIRST_FREE_OBJECTID)) {
9999 /* force full log commit if subvolume involved. */
10000 btrfs_set_log_full_commit(fs_info, trans);
10002 btrfs_pin_log_trans(root);
10004 ret = btrfs_insert_inode_ref(trans, dest,
10005 new_dentry->d_name.name,
10006 new_dentry->d_name.len,
10008 btrfs_ino(BTRFS_I(new_dir)), index);
10013 inode_inc_iversion(old_dir);
10014 inode_inc_iversion(new_dir);
10015 inode_inc_iversion(old_inode);
10016 old_dir->i_ctime = old_dir->i_mtime =
10017 new_dir->i_ctime = new_dir->i_mtime =
10018 old_inode->i_ctime = current_time(old_dir);
10020 if (old_dentry->d_parent != new_dentry->d_parent)
10021 btrfs_record_unlink_dir(trans, BTRFS_I(old_dir),
10022 BTRFS_I(old_inode), 1);
10024 if (unlikely(old_ino == BTRFS_FIRST_FREE_OBJECTID)) {
10025 root_objectid = BTRFS_I(old_inode)->root->root_key.objectid;
10026 ret = btrfs_unlink_subvol(trans, root, old_dir, root_objectid,
10027 old_dentry->d_name.name,
10028 old_dentry->d_name.len);
10030 ret = __btrfs_unlink_inode(trans, root, BTRFS_I(old_dir),
10031 BTRFS_I(d_inode(old_dentry)),
10032 old_dentry->d_name.name,
10033 old_dentry->d_name.len);
10035 ret = btrfs_update_inode(trans, root, old_inode);
10038 btrfs_abort_transaction(trans, ret);
10043 inode_inc_iversion(new_inode);
10044 new_inode->i_ctime = current_time(new_inode);
10045 if (unlikely(btrfs_ino(BTRFS_I(new_inode)) ==
10046 BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)) {
10047 root_objectid = BTRFS_I(new_inode)->location.objectid;
10048 ret = btrfs_unlink_subvol(trans, dest, new_dir,
10050 new_dentry->d_name.name,
10051 new_dentry->d_name.len);
10052 BUG_ON(new_inode->i_nlink == 0);
10054 ret = btrfs_unlink_inode(trans, dest, BTRFS_I(new_dir),
10055 BTRFS_I(d_inode(new_dentry)),
10056 new_dentry->d_name.name,
10057 new_dentry->d_name.len);
10059 if (!ret && new_inode->i_nlink == 0)
10060 ret = btrfs_orphan_add(trans,
10061 BTRFS_I(d_inode(new_dentry)));
10063 btrfs_abort_transaction(trans, ret);
10068 ret = btrfs_add_link(trans, BTRFS_I(new_dir), BTRFS_I(old_inode),
10069 new_dentry->d_name.name,
10070 new_dentry->d_name.len, 0, index);
10072 btrfs_abort_transaction(trans, ret);
10076 if (old_inode->i_nlink == 1)
10077 BTRFS_I(old_inode)->dir_index = index;
10080 struct dentry *parent = new_dentry->d_parent;
10082 btrfs_log_new_name(trans, BTRFS_I(old_inode), BTRFS_I(old_dir),
10084 btrfs_end_log_trans(root);
10085 log_pinned = false;
10088 if (flags & RENAME_WHITEOUT) {
10089 ret = btrfs_whiteout_for_rename(trans, root, old_dir,
10093 btrfs_abort_transaction(trans, ret);
10099 * If we have pinned the log and an error happened, we unpin tasks
10100 * trying to sync the log and force them to fallback to a transaction
10101 * commit if the log currently contains any of the inodes involved in
10102 * this rename operation (to ensure we do not persist a log with an
10103 * inconsistent state for any of these inodes or leading to any
10104 * inconsistencies when replayed). If the transaction was aborted, the
10105 * abortion reason is propagated to userspace when attempting to commit
10106 * the transaction. If the log does not contain any of these inodes, we
10107 * allow the tasks to sync it.
10109 if (ret && log_pinned) {
10110 if (btrfs_inode_in_log(BTRFS_I(old_dir), fs_info->generation) ||
10111 btrfs_inode_in_log(BTRFS_I(new_dir), fs_info->generation) ||
10112 btrfs_inode_in_log(BTRFS_I(old_inode), fs_info->generation) ||
10114 btrfs_inode_in_log(BTRFS_I(new_inode), fs_info->generation)))
10115 btrfs_set_log_full_commit(fs_info, trans);
10117 btrfs_end_log_trans(root);
10118 log_pinned = false;
10120 btrfs_end_transaction(trans);
10122 if (old_ino == BTRFS_FIRST_FREE_OBJECTID)
10123 up_read(&fs_info->subvol_sem);
10128 static int btrfs_rename2(struct inode *old_dir, struct dentry *old_dentry,
10129 struct inode *new_dir, struct dentry *new_dentry,
10130 unsigned int flags)
10132 if (flags & ~(RENAME_NOREPLACE | RENAME_EXCHANGE | RENAME_WHITEOUT))
10135 if (flags & RENAME_EXCHANGE)
10136 return btrfs_rename_exchange(old_dir, old_dentry, new_dir,
10139 return btrfs_rename(old_dir, old_dentry, new_dir, new_dentry, flags);
10142 static void btrfs_run_delalloc_work(struct btrfs_work *work)
10144 struct btrfs_delalloc_work *delalloc_work;
10145 struct inode *inode;
10147 delalloc_work = container_of(work, struct btrfs_delalloc_work,
10149 inode = delalloc_work->inode;
10150 filemap_flush(inode->i_mapping);
10151 if (test_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
10152 &BTRFS_I(inode)->runtime_flags))
10153 filemap_flush(inode->i_mapping);
10155 if (delalloc_work->delay_iput)
10156 btrfs_add_delayed_iput(inode);
10159 complete(&delalloc_work->completion);
10162 struct btrfs_delalloc_work *btrfs_alloc_delalloc_work(struct inode *inode,
10165 struct btrfs_delalloc_work *work;
10167 work = kmalloc(sizeof(*work), GFP_NOFS);
10171 init_completion(&work->completion);
10172 INIT_LIST_HEAD(&work->list);
10173 work->inode = inode;
10174 work->delay_iput = delay_iput;
10175 WARN_ON_ONCE(!inode);
10176 btrfs_init_work(&work->work, btrfs_flush_delalloc_helper,
10177 btrfs_run_delalloc_work, NULL, NULL);
10182 void btrfs_wait_and_free_delalloc_work(struct btrfs_delalloc_work *work)
10184 wait_for_completion(&work->completion);
10189 * some fairly slow code that needs optimization. This walks the list
10190 * of all the inodes with pending delalloc and forces them to disk.
10192 static int __start_delalloc_inodes(struct btrfs_root *root, int delay_iput,
10195 struct btrfs_inode *binode;
10196 struct inode *inode;
10197 struct btrfs_delalloc_work *work, *next;
10198 struct list_head works;
10199 struct list_head splice;
10202 INIT_LIST_HEAD(&works);
10203 INIT_LIST_HEAD(&splice);
10205 mutex_lock(&root->delalloc_mutex);
10206 spin_lock(&root->delalloc_lock);
10207 list_splice_init(&root->delalloc_inodes, &splice);
10208 while (!list_empty(&splice)) {
10209 binode = list_entry(splice.next, struct btrfs_inode,
10212 list_move_tail(&binode->delalloc_inodes,
10213 &root->delalloc_inodes);
10214 inode = igrab(&binode->vfs_inode);
10216 cond_resched_lock(&root->delalloc_lock);
10219 spin_unlock(&root->delalloc_lock);
10221 work = btrfs_alloc_delalloc_work(inode, delay_iput);
10224 btrfs_add_delayed_iput(inode);
10230 list_add_tail(&work->list, &works);
10231 btrfs_queue_work(root->fs_info->flush_workers,
10234 if (nr != -1 && ret >= nr)
10237 spin_lock(&root->delalloc_lock);
10239 spin_unlock(&root->delalloc_lock);
10242 list_for_each_entry_safe(work, next, &works, list) {
10243 list_del_init(&work->list);
10244 btrfs_wait_and_free_delalloc_work(work);
10247 if (!list_empty_careful(&splice)) {
10248 spin_lock(&root->delalloc_lock);
10249 list_splice_tail(&splice, &root->delalloc_inodes);
10250 spin_unlock(&root->delalloc_lock);
10252 mutex_unlock(&root->delalloc_mutex);
10256 int btrfs_start_delalloc_inodes(struct btrfs_root *root, int delay_iput)
10258 struct btrfs_fs_info *fs_info = root->fs_info;
10261 if (test_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state))
10264 ret = __start_delalloc_inodes(root, delay_iput, -1);
10270 int btrfs_start_delalloc_roots(struct btrfs_fs_info *fs_info, int delay_iput,
10273 struct btrfs_root *root;
10274 struct list_head splice;
10277 if (test_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state))
10280 INIT_LIST_HEAD(&splice);
10282 mutex_lock(&fs_info->delalloc_root_mutex);
10283 spin_lock(&fs_info->delalloc_root_lock);
10284 list_splice_init(&fs_info->delalloc_roots, &splice);
10285 while (!list_empty(&splice) && nr) {
10286 root = list_first_entry(&splice, struct btrfs_root,
10288 root = btrfs_grab_fs_root(root);
10290 list_move_tail(&root->delalloc_root,
10291 &fs_info->delalloc_roots);
10292 spin_unlock(&fs_info->delalloc_root_lock);
10294 ret = __start_delalloc_inodes(root, delay_iput, nr);
10295 btrfs_put_fs_root(root);
10303 spin_lock(&fs_info->delalloc_root_lock);
10305 spin_unlock(&fs_info->delalloc_root_lock);
10309 if (!list_empty_careful(&splice)) {
10310 spin_lock(&fs_info->delalloc_root_lock);
10311 list_splice_tail(&splice, &fs_info->delalloc_roots);
10312 spin_unlock(&fs_info->delalloc_root_lock);
10314 mutex_unlock(&fs_info->delalloc_root_mutex);
10318 static int btrfs_symlink(struct inode *dir, struct dentry *dentry,
10319 const char *symname)
10321 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
10322 struct btrfs_trans_handle *trans;
10323 struct btrfs_root *root = BTRFS_I(dir)->root;
10324 struct btrfs_path *path;
10325 struct btrfs_key key;
10326 struct inode *inode = NULL;
10328 int drop_inode = 0;
10334 struct btrfs_file_extent_item *ei;
10335 struct extent_buffer *leaf;
10337 name_len = strlen(symname);
10338 if (name_len > BTRFS_MAX_INLINE_DATA_SIZE(fs_info))
10339 return -ENAMETOOLONG;
10342 * 2 items for inode item and ref
10343 * 2 items for dir items
10344 * 1 item for updating parent inode item
10345 * 1 item for the inline extent item
10346 * 1 item for xattr if selinux is on
10348 trans = btrfs_start_transaction(root, 7);
10350 return PTR_ERR(trans);
10352 err = btrfs_find_free_ino(root, &objectid);
10356 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
10357 dentry->d_name.len, btrfs_ino(BTRFS_I(dir)),
10358 objectid, S_IFLNK|S_IRWXUGO, &index);
10359 if (IS_ERR(inode)) {
10360 err = PTR_ERR(inode);
10365 * If the active LSM wants to access the inode during
10366 * d_instantiate it needs these. Smack checks to see
10367 * if the filesystem supports xattrs by looking at the
10370 inode->i_fop = &btrfs_file_operations;
10371 inode->i_op = &btrfs_file_inode_operations;
10372 inode->i_mapping->a_ops = &btrfs_aops;
10373 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
10375 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
10377 goto out_unlock_inode;
10379 path = btrfs_alloc_path();
10382 goto out_unlock_inode;
10384 key.objectid = btrfs_ino(BTRFS_I(inode));
10386 key.type = BTRFS_EXTENT_DATA_KEY;
10387 datasize = btrfs_file_extent_calc_inline_size(name_len);
10388 err = btrfs_insert_empty_item(trans, root, path, &key,
10391 btrfs_free_path(path);
10392 goto out_unlock_inode;
10394 leaf = path->nodes[0];
10395 ei = btrfs_item_ptr(leaf, path->slots[0],
10396 struct btrfs_file_extent_item);
10397 btrfs_set_file_extent_generation(leaf, ei, trans->transid);
10398 btrfs_set_file_extent_type(leaf, ei,
10399 BTRFS_FILE_EXTENT_INLINE);
10400 btrfs_set_file_extent_encryption(leaf, ei, 0);
10401 btrfs_set_file_extent_compression(leaf, ei, 0);
10402 btrfs_set_file_extent_other_encoding(leaf, ei, 0);
10403 btrfs_set_file_extent_ram_bytes(leaf, ei, name_len);
10405 ptr = btrfs_file_extent_inline_start(ei);
10406 write_extent_buffer(leaf, symname, ptr, name_len);
10407 btrfs_mark_buffer_dirty(leaf);
10408 btrfs_free_path(path);
10410 inode->i_op = &btrfs_symlink_inode_operations;
10411 inode_nohighmem(inode);
10412 inode->i_mapping->a_ops = &btrfs_symlink_aops;
10413 inode_set_bytes(inode, name_len);
10414 btrfs_i_size_write(BTRFS_I(inode), name_len);
10415 err = btrfs_update_inode(trans, root, inode);
10417 * Last step, add directory indexes for our symlink inode. This is the
10418 * last step to avoid extra cleanup of these indexes if an error happens
10422 err = btrfs_add_nondir(trans, BTRFS_I(dir), dentry,
10423 BTRFS_I(inode), 0, index);
10426 goto out_unlock_inode;
10429 unlock_new_inode(inode);
10430 d_instantiate(dentry, inode);
10433 btrfs_end_transaction(trans);
10435 inode_dec_link_count(inode);
10438 btrfs_btree_balance_dirty(fs_info);
10443 unlock_new_inode(inode);
10447 static int __btrfs_prealloc_file_range(struct inode *inode, int mode,
10448 u64 start, u64 num_bytes, u64 min_size,
10449 loff_t actual_len, u64 *alloc_hint,
10450 struct btrfs_trans_handle *trans)
10452 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
10453 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
10454 struct extent_map *em;
10455 struct btrfs_root *root = BTRFS_I(inode)->root;
10456 struct btrfs_key ins;
10457 u64 cur_offset = start;
10460 u64 last_alloc = (u64)-1;
10462 bool own_trans = true;
10463 u64 end = start + num_bytes - 1;
10467 while (num_bytes > 0) {
10469 trans = btrfs_start_transaction(root, 3);
10470 if (IS_ERR(trans)) {
10471 ret = PTR_ERR(trans);
10476 cur_bytes = min_t(u64, num_bytes, SZ_256M);
10477 cur_bytes = max(cur_bytes, min_size);
10479 * If we are severely fragmented we could end up with really
10480 * small allocations, so if the allocator is returning small
10481 * chunks lets make its job easier by only searching for those
10484 cur_bytes = min(cur_bytes, last_alloc);
10485 ret = btrfs_reserve_extent(root, cur_bytes, cur_bytes,
10486 min_size, 0, *alloc_hint, &ins, 1, 0);
10489 btrfs_end_transaction(trans);
10492 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
10494 last_alloc = ins.offset;
10495 ret = insert_reserved_file_extent(trans, inode,
10496 cur_offset, ins.objectid,
10497 ins.offset, ins.offset,
10498 ins.offset, 0, 0, 0,
10499 BTRFS_FILE_EXTENT_PREALLOC);
10501 btrfs_free_reserved_extent(fs_info, ins.objectid,
10503 btrfs_abort_transaction(trans, ret);
10505 btrfs_end_transaction(trans);
10509 btrfs_drop_extent_cache(BTRFS_I(inode), cur_offset,
10510 cur_offset + ins.offset -1, 0);
10512 em = alloc_extent_map();
10514 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
10515 &BTRFS_I(inode)->runtime_flags);
10519 em->start = cur_offset;
10520 em->orig_start = cur_offset;
10521 em->len = ins.offset;
10522 em->block_start = ins.objectid;
10523 em->block_len = ins.offset;
10524 em->orig_block_len = ins.offset;
10525 em->ram_bytes = ins.offset;
10526 em->bdev = fs_info->fs_devices->latest_bdev;
10527 set_bit(EXTENT_FLAG_PREALLOC, &em->flags);
10528 em->generation = trans->transid;
10531 write_lock(&em_tree->lock);
10532 ret = add_extent_mapping(em_tree, em, 1);
10533 write_unlock(&em_tree->lock);
10534 if (ret != -EEXIST)
10536 btrfs_drop_extent_cache(BTRFS_I(inode), cur_offset,
10537 cur_offset + ins.offset - 1,
10540 free_extent_map(em);
10542 num_bytes -= ins.offset;
10543 cur_offset += ins.offset;
10544 *alloc_hint = ins.objectid + ins.offset;
10546 inode_inc_iversion(inode);
10547 inode->i_ctime = current_time(inode);
10548 BTRFS_I(inode)->flags |= BTRFS_INODE_PREALLOC;
10549 if (!(mode & FALLOC_FL_KEEP_SIZE) &&
10550 (actual_len > inode->i_size) &&
10551 (cur_offset > inode->i_size)) {
10552 if (cur_offset > actual_len)
10553 i_size = actual_len;
10555 i_size = cur_offset;
10556 i_size_write(inode, i_size);
10557 btrfs_ordered_update_i_size(inode, i_size, NULL);
10560 ret = btrfs_update_inode(trans, root, inode);
10563 btrfs_abort_transaction(trans, ret);
10565 btrfs_end_transaction(trans);
10570 btrfs_end_transaction(trans);
10572 if (cur_offset < end)
10573 btrfs_free_reserved_data_space(inode, NULL, cur_offset,
10574 end - cur_offset + 1);
10578 int btrfs_prealloc_file_range(struct inode *inode, int mode,
10579 u64 start, u64 num_bytes, u64 min_size,
10580 loff_t actual_len, u64 *alloc_hint)
10582 return __btrfs_prealloc_file_range(inode, mode, start, num_bytes,
10583 min_size, actual_len, alloc_hint,
10587 int btrfs_prealloc_file_range_trans(struct inode *inode,
10588 struct btrfs_trans_handle *trans, int mode,
10589 u64 start, u64 num_bytes, u64 min_size,
10590 loff_t actual_len, u64 *alloc_hint)
10592 return __btrfs_prealloc_file_range(inode, mode, start, num_bytes,
10593 min_size, actual_len, alloc_hint, trans);
10596 static int btrfs_set_page_dirty(struct page *page)
10598 return __set_page_dirty_nobuffers(page);
10601 static int btrfs_permission(struct inode *inode, int mask)
10603 struct btrfs_root *root = BTRFS_I(inode)->root;
10604 umode_t mode = inode->i_mode;
10606 if (mask & MAY_WRITE &&
10607 (S_ISREG(mode) || S_ISDIR(mode) || S_ISLNK(mode))) {
10608 if (btrfs_root_readonly(root))
10610 if (BTRFS_I(inode)->flags & BTRFS_INODE_READONLY)
10613 return generic_permission(inode, mask);
10616 static int btrfs_tmpfile(struct inode *dir, struct dentry *dentry, umode_t mode)
10618 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
10619 struct btrfs_trans_handle *trans;
10620 struct btrfs_root *root = BTRFS_I(dir)->root;
10621 struct inode *inode = NULL;
10627 * 5 units required for adding orphan entry
10629 trans = btrfs_start_transaction(root, 5);
10631 return PTR_ERR(trans);
10633 ret = btrfs_find_free_ino(root, &objectid);
10637 inode = btrfs_new_inode(trans, root, dir, NULL, 0,
10638 btrfs_ino(BTRFS_I(dir)), objectid, mode, &index);
10639 if (IS_ERR(inode)) {
10640 ret = PTR_ERR(inode);
10645 inode->i_fop = &btrfs_file_operations;
10646 inode->i_op = &btrfs_file_inode_operations;
10648 inode->i_mapping->a_ops = &btrfs_aops;
10649 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
10651 ret = btrfs_init_inode_security(trans, inode, dir, NULL);
10655 ret = btrfs_update_inode(trans, root, inode);
10658 ret = btrfs_orphan_add(trans, BTRFS_I(inode));
10663 * We set number of links to 0 in btrfs_new_inode(), and here we set
10664 * it to 1 because d_tmpfile() will issue a warning if the count is 0,
10667 * d_tmpfile() -> inode_dec_link_count() -> drop_nlink()
10669 set_nlink(inode, 1);
10670 unlock_new_inode(inode);
10671 d_tmpfile(dentry, inode);
10672 mark_inode_dirty(inode);
10675 btrfs_end_transaction(trans);
10678 btrfs_btree_balance_dirty(fs_info);
10682 unlock_new_inode(inode);
10687 __attribute__((const))
10688 static int btrfs_readpage_io_failed_hook(struct page *page, int failed_mirror)
10693 static struct btrfs_fs_info *iotree_fs_info(void *private_data)
10695 struct inode *inode = private_data;
10696 return btrfs_sb(inode->i_sb);
10699 static void btrfs_check_extent_io_range(void *private_data, const char *caller,
10700 u64 start, u64 end)
10702 struct inode *inode = private_data;
10705 isize = i_size_read(inode);
10706 if (end >= PAGE_SIZE && (end % 2) == 0 && end != isize - 1) {
10707 btrfs_debug_rl(BTRFS_I(inode)->root->fs_info,
10708 "%s: ino %llu isize %llu odd range [%llu,%llu]",
10709 caller, btrfs_ino(BTRFS_I(inode)), isize, start, end);
10713 void btrfs_set_range_writeback(void *private_data, u64 start, u64 end)
10715 struct inode *inode = private_data;
10716 unsigned long index = start >> PAGE_SHIFT;
10717 unsigned long end_index = end >> PAGE_SHIFT;
10720 while (index <= end_index) {
10721 page = find_get_page(inode->i_mapping, index);
10722 ASSERT(page); /* Pages should be in the extent_io_tree */
10723 set_page_writeback(page);
10729 static const struct inode_operations btrfs_dir_inode_operations = {
10730 .getattr = btrfs_getattr,
10731 .lookup = btrfs_lookup,
10732 .create = btrfs_create,
10733 .unlink = btrfs_unlink,
10734 .link = btrfs_link,
10735 .mkdir = btrfs_mkdir,
10736 .rmdir = btrfs_rmdir,
10737 .rename = btrfs_rename2,
10738 .symlink = btrfs_symlink,
10739 .setattr = btrfs_setattr,
10740 .mknod = btrfs_mknod,
10741 .listxattr = btrfs_listxattr,
10742 .permission = btrfs_permission,
10743 .get_acl = btrfs_get_acl,
10744 .set_acl = btrfs_set_acl,
10745 .update_time = btrfs_update_time,
10746 .tmpfile = btrfs_tmpfile,
10748 static const struct inode_operations btrfs_dir_ro_inode_operations = {
10749 .lookup = btrfs_lookup,
10750 .permission = btrfs_permission,
10751 .update_time = btrfs_update_time,
10754 static const struct file_operations btrfs_dir_file_operations = {
10755 .llseek = generic_file_llseek,
10756 .read = generic_read_dir,
10757 .iterate_shared = btrfs_real_readdir,
10758 .open = btrfs_opendir,
10759 .unlocked_ioctl = btrfs_ioctl,
10760 #ifdef CONFIG_COMPAT
10761 .compat_ioctl = btrfs_compat_ioctl,
10763 .release = btrfs_release_file,
10764 .fsync = btrfs_sync_file,
10767 static const struct extent_io_ops btrfs_extent_io_ops = {
10768 /* mandatory callbacks */
10769 .submit_bio_hook = btrfs_submit_bio_hook,
10770 .readpage_end_io_hook = btrfs_readpage_end_io_hook,
10771 .merge_bio_hook = btrfs_merge_bio_hook,
10772 .readpage_io_failed_hook = btrfs_readpage_io_failed_hook,
10773 .tree_fs_info = iotree_fs_info,
10774 .set_range_writeback = btrfs_set_range_writeback,
10776 /* optional callbacks */
10777 .fill_delalloc = run_delalloc_range,
10778 .writepage_end_io_hook = btrfs_writepage_end_io_hook,
10779 .writepage_start_hook = btrfs_writepage_start_hook,
10780 .set_bit_hook = btrfs_set_bit_hook,
10781 .clear_bit_hook = btrfs_clear_bit_hook,
10782 .merge_extent_hook = btrfs_merge_extent_hook,
10783 .split_extent_hook = btrfs_split_extent_hook,
10784 .check_extent_io_range = btrfs_check_extent_io_range,
10788 * btrfs doesn't support the bmap operation because swapfiles
10789 * use bmap to make a mapping of extents in the file. They assume
10790 * these extents won't change over the life of the file and they
10791 * use the bmap result to do IO directly to the drive.
10793 * the btrfs bmap call would return logical addresses that aren't
10794 * suitable for IO and they also will change frequently as COW
10795 * operations happen. So, swapfile + btrfs == corruption.
10797 * For now we're avoiding this by dropping bmap.
10799 static const struct address_space_operations btrfs_aops = {
10800 .readpage = btrfs_readpage,
10801 .writepage = btrfs_writepage,
10802 .writepages = btrfs_writepages,
10803 .readpages = btrfs_readpages,
10804 .direct_IO = btrfs_direct_IO,
10805 .invalidatepage = btrfs_invalidatepage,
10806 .releasepage = btrfs_releasepage,
10807 .set_page_dirty = btrfs_set_page_dirty,
10808 .error_remove_page = generic_error_remove_page,
10811 static const struct address_space_operations btrfs_symlink_aops = {
10812 .readpage = btrfs_readpage,
10813 .writepage = btrfs_writepage,
10814 .invalidatepage = btrfs_invalidatepage,
10815 .releasepage = btrfs_releasepage,
10818 static const struct inode_operations btrfs_file_inode_operations = {
10819 .getattr = btrfs_getattr,
10820 .setattr = btrfs_setattr,
10821 .listxattr = btrfs_listxattr,
10822 .permission = btrfs_permission,
10823 .fiemap = btrfs_fiemap,
10824 .get_acl = btrfs_get_acl,
10825 .set_acl = btrfs_set_acl,
10826 .update_time = btrfs_update_time,
10828 static const struct inode_operations btrfs_special_inode_operations = {
10829 .getattr = btrfs_getattr,
10830 .setattr = btrfs_setattr,
10831 .permission = btrfs_permission,
10832 .listxattr = btrfs_listxattr,
10833 .get_acl = btrfs_get_acl,
10834 .set_acl = btrfs_set_acl,
10835 .update_time = btrfs_update_time,
10837 static const struct inode_operations btrfs_symlink_inode_operations = {
10838 .get_link = page_get_link,
10839 .getattr = btrfs_getattr,
10840 .setattr = btrfs_setattr,
10841 .permission = btrfs_permission,
10842 .listxattr = btrfs_listxattr,
10843 .update_time = btrfs_update_time,
10846 const struct dentry_operations btrfs_dentry_operations = {
10847 .d_delete = btrfs_dentry_delete,
10848 .d_release = btrfs_dentry_release,