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>
47 #include "transaction.h"
48 #include "btrfs_inode.h"
49 #include "print-tree.h"
50 #include "ordered-data.h"
54 #include "compression.h"
56 #include "free-space-cache.h"
57 #include "inode-map.h"
64 struct btrfs_iget_args {
65 struct btrfs_key *location;
66 struct btrfs_root *root;
69 struct btrfs_dio_data {
70 u64 outstanding_extents;
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 = &fs_info->delalloc_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_delalloc_release_metadata(BTRFS_I(inode), end + 1 - start);
352 btrfs_drop_extent_cache(BTRFS_I(inode), start, aligned_end - 1, 0);
355 * Don't forget to free the reserved space, as for inlined extent
356 * it won't count as data extent, free them directly here.
357 * And at reserve time, it's always aligned to page size, so
358 * just free one page here.
360 btrfs_qgroup_free_data(inode, NULL, 0, PAGE_SIZE);
361 btrfs_free_path(path);
362 btrfs_end_transaction(trans);
366 struct async_extent {
371 unsigned long nr_pages;
373 struct list_head list;
378 struct btrfs_root *root;
379 struct page *locked_page;
382 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;
462 u64 blocksize = fs_info->sectorsize;
464 u64 isize = i_size_read(inode);
466 struct page **pages = NULL;
467 unsigned long nr_pages;
468 unsigned long total_compressed = 0;
469 unsigned long total_in = 0;
472 int compress_type = fs_info->compress_type;
475 inode_should_defrag(BTRFS_I(inode), start, end, end - start + 1,
478 actual_end = min_t(u64, isize, end + 1);
481 nr_pages = (end >> PAGE_SHIFT) - (start >> PAGE_SHIFT) + 1;
482 BUILD_BUG_ON((BTRFS_MAX_COMPRESSED % PAGE_SIZE) != 0);
483 nr_pages = min_t(unsigned long, nr_pages,
484 BTRFS_MAX_COMPRESSED / PAGE_SIZE);
487 * we don't want to send crud past the end of i_size through
488 * compression, that's just a waste of CPU time. So, if the
489 * end of the file is before the start of our current
490 * requested range of bytes, we bail out to the uncompressed
491 * cleanup code that can deal with all of this.
493 * It isn't really the fastest way to fix things, but this is a
494 * very uncommon corner.
496 if (actual_end <= start)
497 goto cleanup_and_bail_uncompressed;
499 total_compressed = actual_end - start;
502 * skip compression for a small file range(<=blocksize) that
503 * isn't an inline extent, since it doesn't save disk space at all.
505 if (total_compressed <= blocksize &&
506 (start > 0 || end + 1 < BTRFS_I(inode)->disk_i_size))
507 goto cleanup_and_bail_uncompressed;
509 total_compressed = min_t(unsigned long, total_compressed,
510 BTRFS_MAX_UNCOMPRESSED);
511 num_bytes = ALIGN(end - start + 1, blocksize);
512 num_bytes = max(blocksize, num_bytes);
517 * we do compression for mount -o compress and when the
518 * inode has not been flagged as nocompress. This flag can
519 * change at any time if we discover bad compression ratios.
521 if (inode_need_compress(inode, start, end)) {
523 pages = kcalloc(nr_pages, sizeof(struct page *), GFP_NOFS);
525 /* just bail out to the uncompressed code */
529 if (BTRFS_I(inode)->defrag_compress)
530 compress_type = BTRFS_I(inode)->defrag_compress;
531 else if (BTRFS_I(inode)->prop_compress)
532 compress_type = BTRFS_I(inode)->prop_compress;
535 * we need to call clear_page_dirty_for_io on each
536 * page in the range. Otherwise applications with the file
537 * mmap'd can wander in and change the page contents while
538 * we are compressing them.
540 * If the compression fails for any reason, we set the pages
541 * dirty again later on.
543 extent_range_clear_dirty_for_io(inode, start, end);
545 ret = btrfs_compress_pages(compress_type,
546 inode->i_mapping, start,
553 unsigned long offset = total_compressed &
555 struct page *page = pages[nr_pages - 1];
558 /* zero the tail end of the last page, we might be
559 * sending it down to disk
562 kaddr = kmap_atomic(page);
563 memset(kaddr + offset, 0,
565 kunmap_atomic(kaddr);
572 /* lets try to make an inline extent */
573 if (ret || total_in < (actual_end - start)) {
574 /* we didn't compress the entire range, try
575 * to make an uncompressed inline extent.
577 ret = cow_file_range_inline(root, inode, start, end,
578 0, BTRFS_COMPRESS_NONE, NULL);
580 /* try making a compressed inline extent */
581 ret = cow_file_range_inline(root, inode, start, end,
583 compress_type, pages);
586 unsigned long clear_flags = EXTENT_DELALLOC |
587 EXTENT_DELALLOC_NEW | EXTENT_DEFRAG;
588 unsigned long page_error_op;
590 clear_flags |= (ret < 0) ? EXTENT_DO_ACCOUNTING : 0;
591 page_error_op = ret < 0 ? PAGE_SET_ERROR : 0;
594 * inline extent creation worked or returned error,
595 * we don't need to create any more async work items.
596 * Unlock and free up our temp pages.
598 extent_clear_unlock_delalloc(inode, start, end, end,
606 btrfs_free_reserved_data_space_noquota(inode,
615 * we aren't doing an inline extent round the compressed size
616 * up to a block size boundary so the allocator does sane
619 total_compressed = ALIGN(total_compressed, blocksize);
622 * one last check to make sure the compression is really a
623 * win, compare the page count read with the blocks on disk,
624 * compression must free at least one sector size
626 total_in = ALIGN(total_in, PAGE_SIZE);
627 if (total_compressed + blocksize <= total_in) {
628 num_bytes = total_in;
632 * The async work queues will take care of doing actual
633 * allocation on disk for these compressed pages, and
634 * will submit them to the elevator.
636 add_async_extent(async_cow, start, num_bytes,
637 total_compressed, pages, nr_pages,
640 if (start + num_bytes < end) {
651 * the compression code ran but failed to make things smaller,
652 * free any pages it allocated and our page pointer array
654 for (i = 0; i < nr_pages; i++) {
655 WARN_ON(pages[i]->mapping);
660 total_compressed = 0;
663 /* flag the file so we don't compress in the future */
664 if (!btrfs_test_opt(fs_info, FORCE_COMPRESS) &&
665 !(BTRFS_I(inode)->prop_compress)) {
666 BTRFS_I(inode)->flags |= BTRFS_INODE_NOCOMPRESS;
669 cleanup_and_bail_uncompressed:
671 * No compression, but we still need to write the pages in the file
672 * we've been given so far. redirty the locked page if it corresponds
673 * to our extent and set things up for the async work queue to run
674 * cow_file_range to do the normal delalloc dance.
676 if (page_offset(locked_page) >= start &&
677 page_offset(locked_page) <= end)
678 __set_page_dirty_nobuffers(locked_page);
679 /* unlocked later on in the async handlers */
682 extent_range_redirty_for_io(inode, start, end);
683 add_async_extent(async_cow, start, end - start + 1, 0, NULL, 0,
684 BTRFS_COMPRESS_NONE);
690 for (i = 0; i < nr_pages; i++) {
691 WARN_ON(pages[i]->mapping);
697 static void free_async_extent_pages(struct async_extent *async_extent)
701 if (!async_extent->pages)
704 for (i = 0; i < async_extent->nr_pages; i++) {
705 WARN_ON(async_extent->pages[i]->mapping);
706 put_page(async_extent->pages[i]);
708 kfree(async_extent->pages);
709 async_extent->nr_pages = 0;
710 async_extent->pages = NULL;
714 * phase two of compressed writeback. This is the ordered portion
715 * of the code, which only gets called in the order the work was
716 * queued. We walk all the async extents created by compress_file_range
717 * and send them down to the disk.
719 static noinline void submit_compressed_extents(struct inode *inode,
720 struct async_cow *async_cow)
722 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
723 struct async_extent *async_extent;
725 struct btrfs_key ins;
726 struct extent_map *em;
727 struct btrfs_root *root = BTRFS_I(inode)->root;
728 struct extent_io_tree *io_tree;
732 while (!list_empty(&async_cow->extents)) {
733 async_extent = list_entry(async_cow->extents.next,
734 struct async_extent, list);
735 list_del(&async_extent->list);
737 io_tree = &BTRFS_I(inode)->io_tree;
740 /* did the compression code fall back to uncompressed IO? */
741 if (!async_extent->pages) {
742 int page_started = 0;
743 unsigned long nr_written = 0;
745 lock_extent(io_tree, async_extent->start,
746 async_extent->start +
747 async_extent->ram_size - 1);
749 /* allocate blocks */
750 ret = cow_file_range(inode, async_cow->locked_page,
752 async_extent->start +
753 async_extent->ram_size - 1,
754 async_extent->start +
755 async_extent->ram_size - 1,
756 &page_started, &nr_written, 0,
762 * if page_started, cow_file_range inserted an
763 * inline extent and took care of all the unlocking
764 * and IO for us. Otherwise, we need to submit
765 * all those pages down to the drive.
767 if (!page_started && !ret)
768 extent_write_locked_range(io_tree,
769 inode, async_extent->start,
770 async_extent->start +
771 async_extent->ram_size - 1,
775 unlock_page(async_cow->locked_page);
781 lock_extent(io_tree, async_extent->start,
782 async_extent->start + async_extent->ram_size - 1);
784 ret = btrfs_reserve_extent(root, async_extent->ram_size,
785 async_extent->compressed_size,
786 async_extent->compressed_size,
787 0, alloc_hint, &ins, 1, 1);
789 free_async_extent_pages(async_extent);
791 if (ret == -ENOSPC) {
792 unlock_extent(io_tree, async_extent->start,
793 async_extent->start +
794 async_extent->ram_size - 1);
797 * we need to redirty the pages if we decide to
798 * fallback to uncompressed IO, otherwise we
799 * will not submit these pages down to lower
802 extent_range_redirty_for_io(inode,
804 async_extent->start +
805 async_extent->ram_size - 1);
812 * here we're doing allocation and writeback of the
815 em = create_io_em(inode, async_extent->start,
816 async_extent->ram_size, /* len */
817 async_extent->start, /* orig_start */
818 ins.objectid, /* block_start */
819 ins.offset, /* block_len */
820 ins.offset, /* orig_block_len */
821 async_extent->ram_size, /* ram_bytes */
822 async_extent->compress_type,
823 BTRFS_ORDERED_COMPRESSED);
825 /* ret value is not necessary due to void function */
826 goto out_free_reserve;
829 ret = btrfs_add_ordered_extent_compress(inode,
832 async_extent->ram_size,
834 BTRFS_ORDERED_COMPRESSED,
835 async_extent->compress_type);
837 btrfs_drop_extent_cache(BTRFS_I(inode),
839 async_extent->start +
840 async_extent->ram_size - 1, 0);
841 goto out_free_reserve;
843 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
846 * clear dirty, set writeback and unlock the pages.
848 extent_clear_unlock_delalloc(inode, async_extent->start,
849 async_extent->start +
850 async_extent->ram_size - 1,
851 async_extent->start +
852 async_extent->ram_size - 1,
853 NULL, EXTENT_LOCKED | EXTENT_DELALLOC,
854 PAGE_UNLOCK | PAGE_CLEAR_DIRTY |
856 if (btrfs_submit_compressed_write(inode,
858 async_extent->ram_size,
860 ins.offset, async_extent->pages,
861 async_extent->nr_pages)) {
862 struct extent_io_tree *tree = &BTRFS_I(inode)->io_tree;
863 struct page *p = async_extent->pages[0];
864 const u64 start = async_extent->start;
865 const u64 end = start + async_extent->ram_size - 1;
867 p->mapping = inode->i_mapping;
868 tree->ops->writepage_end_io_hook(p, start, end,
871 extent_clear_unlock_delalloc(inode, start, end, end,
875 free_async_extent_pages(async_extent);
877 alloc_hint = ins.objectid + ins.offset;
883 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
884 btrfs_free_reserved_extent(fs_info, ins.objectid, ins.offset, 1);
886 extent_clear_unlock_delalloc(inode, async_extent->start,
887 async_extent->start +
888 async_extent->ram_size - 1,
889 async_extent->start +
890 async_extent->ram_size - 1,
891 NULL, EXTENT_LOCKED | EXTENT_DELALLOC |
892 EXTENT_DELALLOC_NEW |
893 EXTENT_DEFRAG | EXTENT_DO_ACCOUNTING,
894 PAGE_UNLOCK | PAGE_CLEAR_DIRTY |
895 PAGE_SET_WRITEBACK | PAGE_END_WRITEBACK |
897 free_async_extent_pages(async_extent);
902 static u64 get_extent_allocation_hint(struct inode *inode, u64 start,
905 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
906 struct extent_map *em;
909 read_lock(&em_tree->lock);
910 em = search_extent_mapping(em_tree, start, num_bytes);
913 * if block start isn't an actual block number then find the
914 * first block in this inode and use that as a hint. If that
915 * block is also bogus then just don't worry about it.
917 if (em->block_start >= EXTENT_MAP_LAST_BYTE) {
919 em = search_extent_mapping(em_tree, 0, 0);
920 if (em && em->block_start < EXTENT_MAP_LAST_BYTE)
921 alloc_hint = em->block_start;
925 alloc_hint = em->block_start;
929 read_unlock(&em_tree->lock);
935 * when extent_io.c finds a delayed allocation range in the file,
936 * the call backs end up in this code. The basic idea is to
937 * allocate extents on disk for the range, and create ordered data structs
938 * in ram to track those extents.
940 * locked_page is the page that writepage had locked already. We use
941 * it to make sure we don't do extra locks or unlocks.
943 * *page_started is set to one if we unlock locked_page and do everything
944 * required to start IO on it. It may be clean and already done with
947 static noinline int cow_file_range(struct inode *inode,
948 struct page *locked_page,
949 u64 start, u64 end, u64 delalloc_end,
950 int *page_started, unsigned long *nr_written,
951 int unlock, struct btrfs_dedupe_hash *hash)
953 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
954 struct btrfs_root *root = BTRFS_I(inode)->root;
957 unsigned long ram_size;
959 u64 cur_alloc_size = 0;
960 u64 blocksize = fs_info->sectorsize;
961 struct btrfs_key ins;
962 struct extent_map *em;
964 unsigned long page_ops;
965 bool extent_reserved = false;
968 if (btrfs_is_free_space_inode(BTRFS_I(inode))) {
974 num_bytes = ALIGN(end - start + 1, blocksize);
975 num_bytes = max(blocksize, num_bytes);
976 disk_num_bytes = num_bytes;
978 inode_should_defrag(BTRFS_I(inode), start, end, num_bytes, SZ_64K);
981 /* lets try to make an inline extent */
982 ret = cow_file_range_inline(root, inode, start, end, 0,
983 BTRFS_COMPRESS_NONE, NULL);
985 extent_clear_unlock_delalloc(inode, start, end,
987 EXTENT_LOCKED | EXTENT_DELALLOC |
988 EXTENT_DELALLOC_NEW |
989 EXTENT_DEFRAG, PAGE_UNLOCK |
990 PAGE_CLEAR_DIRTY | PAGE_SET_WRITEBACK |
992 btrfs_free_reserved_data_space_noquota(inode, start,
994 *nr_written = *nr_written +
995 (end - start + PAGE_SIZE) / PAGE_SIZE;
998 } else if (ret < 0) {
1003 BUG_ON(disk_num_bytes >
1004 btrfs_super_total_bytes(fs_info->super_copy));
1006 alloc_hint = get_extent_allocation_hint(inode, start, num_bytes);
1007 btrfs_drop_extent_cache(BTRFS_I(inode), start,
1008 start + num_bytes - 1, 0);
1010 while (disk_num_bytes > 0) {
1011 cur_alloc_size = disk_num_bytes;
1012 ret = btrfs_reserve_extent(root, cur_alloc_size, cur_alloc_size,
1013 fs_info->sectorsize, 0, alloc_hint,
1017 cur_alloc_size = ins.offset;
1018 extent_reserved = true;
1020 ram_size = ins.offset;
1021 em = create_io_em(inode, start, ins.offset, /* len */
1022 start, /* orig_start */
1023 ins.objectid, /* block_start */
1024 ins.offset, /* block_len */
1025 ins.offset, /* orig_block_len */
1026 ram_size, /* ram_bytes */
1027 BTRFS_COMPRESS_NONE, /* compress_type */
1028 BTRFS_ORDERED_REGULAR /* type */);
1031 free_extent_map(em);
1033 ret = btrfs_add_ordered_extent(inode, start, ins.objectid,
1034 ram_size, cur_alloc_size, 0);
1036 goto out_drop_extent_cache;
1038 if (root->root_key.objectid ==
1039 BTRFS_DATA_RELOC_TREE_OBJECTID) {
1040 ret = btrfs_reloc_clone_csums(inode, start,
1043 * Only drop cache here, and process as normal.
1045 * We must not allow extent_clear_unlock_delalloc()
1046 * at out_unlock label to free meta of this ordered
1047 * extent, as its meta should be freed by
1048 * btrfs_finish_ordered_io().
1050 * So we must continue until @start is increased to
1051 * skip current ordered extent.
1054 btrfs_drop_extent_cache(BTRFS_I(inode), start,
1055 start + ram_size - 1, 0);
1058 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
1060 /* we're not doing compressed IO, don't unlock the first
1061 * page (which the caller expects to stay locked), don't
1062 * clear any dirty bits and don't set any writeback bits
1064 * Do set the Private2 bit so we know this page was properly
1065 * setup for writepage
1067 page_ops = unlock ? PAGE_UNLOCK : 0;
1068 page_ops |= PAGE_SET_PRIVATE2;
1070 extent_clear_unlock_delalloc(inode, start,
1071 start + ram_size - 1,
1072 delalloc_end, locked_page,
1073 EXTENT_LOCKED | EXTENT_DELALLOC,
1075 if (disk_num_bytes < cur_alloc_size)
1078 disk_num_bytes -= cur_alloc_size;
1079 num_bytes -= cur_alloc_size;
1080 alloc_hint = ins.objectid + ins.offset;
1081 start += cur_alloc_size;
1082 extent_reserved = false;
1085 * btrfs_reloc_clone_csums() error, since start is increased
1086 * extent_clear_unlock_delalloc() at out_unlock label won't
1087 * free metadata of current ordered extent, we're OK to exit.
1095 out_drop_extent_cache:
1096 btrfs_drop_extent_cache(BTRFS_I(inode), start, start + ram_size - 1, 0);
1098 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
1099 btrfs_free_reserved_extent(fs_info, ins.objectid, ins.offset, 1);
1101 clear_bits = EXTENT_LOCKED | EXTENT_DELALLOC | EXTENT_DELALLOC_NEW |
1102 EXTENT_DEFRAG | EXTENT_CLEAR_META_RESV;
1103 page_ops = PAGE_UNLOCK | PAGE_CLEAR_DIRTY | PAGE_SET_WRITEBACK |
1106 * If we reserved an extent for our delalloc range (or a subrange) and
1107 * failed to create the respective ordered extent, then it means that
1108 * when we reserved the extent we decremented the extent's size from
1109 * the data space_info's bytes_may_use counter and incremented the
1110 * space_info's bytes_reserved counter by the same amount. We must make
1111 * sure extent_clear_unlock_delalloc() does not try to decrement again
1112 * the data space_info's bytes_may_use counter, therefore we do not pass
1113 * it the flag EXTENT_CLEAR_DATA_RESV.
1115 if (extent_reserved) {
1116 extent_clear_unlock_delalloc(inode, start,
1117 start + cur_alloc_size,
1118 start + cur_alloc_size,
1122 start += cur_alloc_size;
1126 extent_clear_unlock_delalloc(inode, start, end, delalloc_end,
1128 clear_bits | EXTENT_CLEAR_DATA_RESV,
1134 * work queue call back to started compression on a file and pages
1136 static noinline void async_cow_start(struct btrfs_work *work)
1138 struct async_cow *async_cow;
1140 async_cow = container_of(work, struct async_cow, work);
1142 compress_file_range(async_cow->inode, async_cow->locked_page,
1143 async_cow->start, async_cow->end, async_cow,
1145 if (num_added == 0) {
1146 btrfs_add_delayed_iput(async_cow->inode);
1147 async_cow->inode = NULL;
1152 * work queue call back to submit previously compressed pages
1154 static noinline void async_cow_submit(struct btrfs_work *work)
1156 struct btrfs_fs_info *fs_info;
1157 struct async_cow *async_cow;
1158 struct btrfs_root *root;
1159 unsigned long nr_pages;
1161 async_cow = container_of(work, struct async_cow, work);
1163 root = async_cow->root;
1164 fs_info = root->fs_info;
1165 nr_pages = (async_cow->end - async_cow->start + PAGE_SIZE) >>
1169 * atomic_sub_return implies a barrier for waitqueue_active
1171 if (atomic_sub_return(nr_pages, &fs_info->async_delalloc_pages) <
1173 waitqueue_active(&fs_info->async_submit_wait))
1174 wake_up(&fs_info->async_submit_wait);
1176 if (async_cow->inode)
1177 submit_compressed_extents(async_cow->inode, async_cow);
1180 static noinline void async_cow_free(struct btrfs_work *work)
1182 struct async_cow *async_cow;
1183 async_cow = container_of(work, struct async_cow, work);
1184 if (async_cow->inode)
1185 btrfs_add_delayed_iput(async_cow->inode);
1189 static int cow_file_range_async(struct inode *inode, struct page *locked_page,
1190 u64 start, u64 end, int *page_started,
1191 unsigned long *nr_written)
1193 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1194 struct async_cow *async_cow;
1195 struct btrfs_root *root = BTRFS_I(inode)->root;
1196 unsigned long nr_pages;
1199 clear_extent_bit(&BTRFS_I(inode)->io_tree, start, end, EXTENT_LOCKED,
1200 1, 0, NULL, GFP_NOFS);
1201 while (start < end) {
1202 async_cow = kmalloc(sizeof(*async_cow), GFP_NOFS);
1203 BUG_ON(!async_cow); /* -ENOMEM */
1204 async_cow->inode = igrab(inode);
1205 async_cow->root = root;
1206 async_cow->locked_page = locked_page;
1207 async_cow->start = start;
1209 if (BTRFS_I(inode)->flags & BTRFS_INODE_NOCOMPRESS &&
1210 !btrfs_test_opt(fs_info, FORCE_COMPRESS))
1213 cur_end = min(end, start + SZ_512K - 1);
1215 async_cow->end = cur_end;
1216 INIT_LIST_HEAD(&async_cow->extents);
1218 btrfs_init_work(&async_cow->work,
1219 btrfs_delalloc_helper,
1220 async_cow_start, async_cow_submit,
1223 nr_pages = (cur_end - start + PAGE_SIZE) >>
1225 atomic_add(nr_pages, &fs_info->async_delalloc_pages);
1227 btrfs_queue_work(fs_info->delalloc_workers, &async_cow->work);
1229 while (atomic_read(&fs_info->async_submit_draining) &&
1230 atomic_read(&fs_info->async_delalloc_pages)) {
1231 wait_event(fs_info->async_submit_wait,
1232 (atomic_read(&fs_info->async_delalloc_pages) ==
1236 *nr_written += nr_pages;
1237 start = cur_end + 1;
1243 static noinline int csum_exist_in_range(struct btrfs_fs_info *fs_info,
1244 u64 bytenr, u64 num_bytes)
1247 struct btrfs_ordered_sum *sums;
1250 ret = btrfs_lookup_csums_range(fs_info->csum_root, bytenr,
1251 bytenr + num_bytes - 1, &list, 0);
1252 if (ret == 0 && list_empty(&list))
1255 while (!list_empty(&list)) {
1256 sums = list_entry(list.next, struct btrfs_ordered_sum, list);
1257 list_del(&sums->list);
1264 * when nowcow writeback call back. This checks for snapshots or COW copies
1265 * of the extents that exist in the file, and COWs the file as required.
1267 * If no cow copies or snapshots exist, we write directly to the existing
1270 static noinline int run_delalloc_nocow(struct inode *inode,
1271 struct page *locked_page,
1272 u64 start, u64 end, int *page_started, int force,
1273 unsigned long *nr_written)
1275 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1276 struct btrfs_root *root = BTRFS_I(inode)->root;
1277 struct extent_buffer *leaf;
1278 struct btrfs_path *path;
1279 struct btrfs_file_extent_item *fi;
1280 struct btrfs_key found_key;
1281 struct extent_map *em;
1296 u64 ino = btrfs_ino(BTRFS_I(inode));
1298 path = btrfs_alloc_path();
1300 extent_clear_unlock_delalloc(inode, start, end, end,
1302 EXTENT_LOCKED | EXTENT_DELALLOC |
1303 EXTENT_DO_ACCOUNTING |
1304 EXTENT_DEFRAG, PAGE_UNLOCK |
1306 PAGE_SET_WRITEBACK |
1307 PAGE_END_WRITEBACK);
1311 nolock = btrfs_is_free_space_inode(BTRFS_I(inode));
1313 cow_start = (u64)-1;
1316 ret = btrfs_lookup_file_extent(NULL, root, path, ino,
1320 if (ret > 0 && path->slots[0] > 0 && check_prev) {
1321 leaf = path->nodes[0];
1322 btrfs_item_key_to_cpu(leaf, &found_key,
1323 path->slots[0] - 1);
1324 if (found_key.objectid == ino &&
1325 found_key.type == BTRFS_EXTENT_DATA_KEY)
1330 leaf = path->nodes[0];
1331 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
1332 ret = btrfs_next_leaf(root, path);
1337 leaf = path->nodes[0];
1343 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
1345 if (found_key.objectid > ino)
1347 if (WARN_ON_ONCE(found_key.objectid < ino) ||
1348 found_key.type < BTRFS_EXTENT_DATA_KEY) {
1352 if (found_key.type > BTRFS_EXTENT_DATA_KEY ||
1353 found_key.offset > end)
1356 if (found_key.offset > cur_offset) {
1357 extent_end = found_key.offset;
1362 fi = btrfs_item_ptr(leaf, path->slots[0],
1363 struct btrfs_file_extent_item);
1364 extent_type = btrfs_file_extent_type(leaf, fi);
1366 ram_bytes = btrfs_file_extent_ram_bytes(leaf, fi);
1367 if (extent_type == BTRFS_FILE_EXTENT_REG ||
1368 extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
1369 disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
1370 extent_offset = btrfs_file_extent_offset(leaf, fi);
1371 extent_end = found_key.offset +
1372 btrfs_file_extent_num_bytes(leaf, fi);
1374 btrfs_file_extent_disk_num_bytes(leaf, fi);
1375 if (extent_end <= start) {
1379 if (disk_bytenr == 0)
1381 if (btrfs_file_extent_compression(leaf, fi) ||
1382 btrfs_file_extent_encryption(leaf, fi) ||
1383 btrfs_file_extent_other_encoding(leaf, fi))
1385 if (extent_type == BTRFS_FILE_EXTENT_REG && !force)
1387 if (btrfs_extent_readonly(fs_info, disk_bytenr))
1389 if (btrfs_cross_ref_exist(root, ino,
1391 extent_offset, disk_bytenr))
1393 disk_bytenr += extent_offset;
1394 disk_bytenr += cur_offset - found_key.offset;
1395 num_bytes = min(end + 1, extent_end) - cur_offset;
1397 * if there are pending snapshots for this root,
1398 * we fall into common COW way.
1401 err = btrfs_start_write_no_snapshotting(root);
1406 * force cow if csum exists in the range.
1407 * this ensure that csum for a given extent are
1408 * either valid or do not exist.
1410 if (csum_exist_in_range(fs_info, disk_bytenr,
1413 btrfs_end_write_no_snapshotting(root);
1416 if (!btrfs_inc_nocow_writers(fs_info, disk_bytenr)) {
1418 btrfs_end_write_no_snapshotting(root);
1422 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
1423 extent_end = found_key.offset +
1424 btrfs_file_extent_inline_len(leaf,
1425 path->slots[0], fi);
1426 extent_end = ALIGN(extent_end,
1427 fs_info->sectorsize);
1432 if (extent_end <= start) {
1434 if (!nolock && nocow)
1435 btrfs_end_write_no_snapshotting(root);
1437 btrfs_dec_nocow_writers(fs_info, disk_bytenr);
1441 if (cow_start == (u64)-1)
1442 cow_start = cur_offset;
1443 cur_offset = extent_end;
1444 if (cur_offset > end)
1450 btrfs_release_path(path);
1451 if (cow_start != (u64)-1) {
1452 ret = cow_file_range(inode, locked_page,
1453 cow_start, found_key.offset - 1,
1454 end, page_started, nr_written, 1,
1457 if (!nolock && nocow)
1458 btrfs_end_write_no_snapshotting(root);
1460 btrfs_dec_nocow_writers(fs_info,
1464 cow_start = (u64)-1;
1467 if (extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
1468 u64 orig_start = found_key.offset - extent_offset;
1470 em = create_io_em(inode, cur_offset, num_bytes,
1472 disk_bytenr, /* block_start */
1473 num_bytes, /* block_len */
1474 disk_num_bytes, /* orig_block_len */
1475 ram_bytes, BTRFS_COMPRESS_NONE,
1476 BTRFS_ORDERED_PREALLOC);
1478 if (!nolock && nocow)
1479 btrfs_end_write_no_snapshotting(root);
1481 btrfs_dec_nocow_writers(fs_info,
1486 free_extent_map(em);
1489 if (extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
1490 type = BTRFS_ORDERED_PREALLOC;
1492 type = BTRFS_ORDERED_NOCOW;
1495 ret = btrfs_add_ordered_extent(inode, cur_offset, disk_bytenr,
1496 num_bytes, num_bytes, type);
1498 btrfs_dec_nocow_writers(fs_info, disk_bytenr);
1499 BUG_ON(ret); /* -ENOMEM */
1501 if (root->root_key.objectid ==
1502 BTRFS_DATA_RELOC_TREE_OBJECTID)
1504 * Error handled later, as we must prevent
1505 * extent_clear_unlock_delalloc() in error handler
1506 * from freeing metadata of created ordered extent.
1508 ret = btrfs_reloc_clone_csums(inode, cur_offset,
1511 extent_clear_unlock_delalloc(inode, cur_offset,
1512 cur_offset + num_bytes - 1, end,
1513 locked_page, EXTENT_LOCKED |
1515 EXTENT_CLEAR_DATA_RESV,
1516 PAGE_UNLOCK | PAGE_SET_PRIVATE2);
1518 if (!nolock && nocow)
1519 btrfs_end_write_no_snapshotting(root);
1520 cur_offset = extent_end;
1523 * btrfs_reloc_clone_csums() error, now we're OK to call error
1524 * handler, as metadata for created ordered extent will only
1525 * be freed by btrfs_finish_ordered_io().
1529 if (cur_offset > end)
1532 btrfs_release_path(path);
1534 if (cur_offset <= end && cow_start == (u64)-1) {
1535 cow_start = cur_offset;
1539 if (cow_start != (u64)-1) {
1540 ret = cow_file_range(inode, locked_page, cow_start, end, end,
1541 page_started, nr_written, 1, NULL);
1547 if (ret && cur_offset < end)
1548 extent_clear_unlock_delalloc(inode, cur_offset, end, end,
1549 locked_page, EXTENT_LOCKED |
1550 EXTENT_DELALLOC | EXTENT_DEFRAG |
1551 EXTENT_DO_ACCOUNTING, PAGE_UNLOCK |
1553 PAGE_SET_WRITEBACK |
1554 PAGE_END_WRITEBACK);
1555 btrfs_free_path(path);
1559 static inline int need_force_cow(struct inode *inode, u64 start, u64 end)
1562 if (!(BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW) &&
1563 !(BTRFS_I(inode)->flags & BTRFS_INODE_PREALLOC))
1567 * @defrag_bytes is a hint value, no spinlock held here,
1568 * if is not zero, it means the file is defragging.
1569 * Force cow if given extent needs to be defragged.
1571 if (BTRFS_I(inode)->defrag_bytes &&
1572 test_range_bit(&BTRFS_I(inode)->io_tree, start, end,
1573 EXTENT_DEFRAG, 0, NULL))
1580 * extent_io.c call back to do delayed allocation processing
1582 static int run_delalloc_range(void *private_data, struct page *locked_page,
1583 u64 start, u64 end, int *page_started,
1584 unsigned long *nr_written)
1586 struct inode *inode = private_data;
1588 int force_cow = need_force_cow(inode, start, end);
1590 if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW && !force_cow) {
1591 ret = run_delalloc_nocow(inode, locked_page, start, end,
1592 page_started, 1, nr_written);
1593 } else if (BTRFS_I(inode)->flags & BTRFS_INODE_PREALLOC && !force_cow) {
1594 ret = run_delalloc_nocow(inode, locked_page, start, end,
1595 page_started, 0, nr_written);
1596 } else if (!inode_need_compress(inode, start, end)) {
1597 ret = cow_file_range(inode, locked_page, start, end, end,
1598 page_started, nr_written, 1, NULL);
1600 set_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
1601 &BTRFS_I(inode)->runtime_flags);
1602 ret = cow_file_range_async(inode, locked_page, start, end,
1603 page_started, nr_written);
1606 btrfs_cleanup_ordered_extents(inode, start, end - start + 1);
1610 static void btrfs_split_extent_hook(void *private_data,
1611 struct extent_state *orig, u64 split)
1613 struct inode *inode = private_data;
1616 /* not delalloc, ignore it */
1617 if (!(orig->state & EXTENT_DELALLOC))
1620 size = orig->end - orig->start + 1;
1621 if (size > BTRFS_MAX_EXTENT_SIZE) {
1626 * See the explanation in btrfs_merge_extent_hook, the same
1627 * applies here, just in reverse.
1629 new_size = orig->end - split + 1;
1630 num_extents = count_max_extents(new_size);
1631 new_size = split - orig->start;
1632 num_extents += count_max_extents(new_size);
1633 if (count_max_extents(size) >= num_extents)
1637 spin_lock(&BTRFS_I(inode)->lock);
1638 BTRFS_I(inode)->outstanding_extents++;
1639 spin_unlock(&BTRFS_I(inode)->lock);
1643 * extent_io.c merge_extent_hook, used to track merged delayed allocation
1644 * extents so we can keep track of new extents that are just merged onto old
1645 * extents, such as when we are doing sequential writes, so we can properly
1646 * account for the metadata space we'll need.
1648 static void btrfs_merge_extent_hook(void *private_data,
1649 struct extent_state *new,
1650 struct extent_state *other)
1652 struct inode *inode = private_data;
1653 u64 new_size, old_size;
1656 /* not delalloc, ignore it */
1657 if (!(other->state & EXTENT_DELALLOC))
1660 if (new->start > other->start)
1661 new_size = new->end - other->start + 1;
1663 new_size = other->end - new->start + 1;
1665 /* we're not bigger than the max, unreserve the space and go */
1666 if (new_size <= BTRFS_MAX_EXTENT_SIZE) {
1667 spin_lock(&BTRFS_I(inode)->lock);
1668 BTRFS_I(inode)->outstanding_extents--;
1669 spin_unlock(&BTRFS_I(inode)->lock);
1674 * We have to add up either side to figure out how many extents were
1675 * accounted for before we merged into one big extent. If the number of
1676 * extents we accounted for is <= the amount we need for the new range
1677 * then we can return, otherwise drop. Think of it like this
1681 * So we've grown the extent by a MAX_SIZE extent, this would mean we
1682 * need 2 outstanding extents, on one side we have 1 and the other side
1683 * we have 1 so they are == and we can return. But in this case
1685 * [MAX_SIZE+4k][MAX_SIZE+4k]
1687 * Each range on their own accounts for 2 extents, but merged together
1688 * they are only 3 extents worth of accounting, so we need to drop in
1691 old_size = other->end - other->start + 1;
1692 num_extents = count_max_extents(old_size);
1693 old_size = new->end - new->start + 1;
1694 num_extents += count_max_extents(old_size);
1695 if (count_max_extents(new_size) >= num_extents)
1698 spin_lock(&BTRFS_I(inode)->lock);
1699 BTRFS_I(inode)->outstanding_extents--;
1700 spin_unlock(&BTRFS_I(inode)->lock);
1703 static void btrfs_add_delalloc_inodes(struct btrfs_root *root,
1704 struct inode *inode)
1706 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1708 spin_lock(&root->delalloc_lock);
1709 if (list_empty(&BTRFS_I(inode)->delalloc_inodes)) {
1710 list_add_tail(&BTRFS_I(inode)->delalloc_inodes,
1711 &root->delalloc_inodes);
1712 set_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1713 &BTRFS_I(inode)->runtime_flags);
1714 root->nr_delalloc_inodes++;
1715 if (root->nr_delalloc_inodes == 1) {
1716 spin_lock(&fs_info->delalloc_root_lock);
1717 BUG_ON(!list_empty(&root->delalloc_root));
1718 list_add_tail(&root->delalloc_root,
1719 &fs_info->delalloc_roots);
1720 spin_unlock(&fs_info->delalloc_root_lock);
1723 spin_unlock(&root->delalloc_lock);
1726 static void btrfs_del_delalloc_inode(struct btrfs_root *root,
1727 struct btrfs_inode *inode)
1729 struct btrfs_fs_info *fs_info = btrfs_sb(inode->vfs_inode.i_sb);
1731 spin_lock(&root->delalloc_lock);
1732 if (!list_empty(&inode->delalloc_inodes)) {
1733 list_del_init(&inode->delalloc_inodes);
1734 clear_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1735 &inode->runtime_flags);
1736 root->nr_delalloc_inodes--;
1737 if (!root->nr_delalloc_inodes) {
1738 spin_lock(&fs_info->delalloc_root_lock);
1739 BUG_ON(list_empty(&root->delalloc_root));
1740 list_del_init(&root->delalloc_root);
1741 spin_unlock(&fs_info->delalloc_root_lock);
1744 spin_unlock(&root->delalloc_lock);
1748 * extent_io.c set_bit_hook, used to track delayed allocation
1749 * bytes in this file, and to maintain the list of inodes that
1750 * have pending delalloc work to be done.
1752 static void btrfs_set_bit_hook(void *private_data,
1753 struct extent_state *state, unsigned *bits)
1755 struct inode *inode = private_data;
1757 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1759 if ((*bits & EXTENT_DEFRAG) && !(*bits & EXTENT_DELALLOC))
1762 * set_bit and clear bit hooks normally require _irqsave/restore
1763 * but in this case, we are only testing for the DELALLOC
1764 * bit, which is only set or cleared with irqs on
1766 if (!(state->state & EXTENT_DELALLOC) && (*bits & EXTENT_DELALLOC)) {
1767 struct btrfs_root *root = BTRFS_I(inode)->root;
1768 u64 len = state->end + 1 - state->start;
1769 bool do_list = !btrfs_is_free_space_inode(BTRFS_I(inode));
1771 if (*bits & EXTENT_FIRST_DELALLOC) {
1772 *bits &= ~EXTENT_FIRST_DELALLOC;
1774 spin_lock(&BTRFS_I(inode)->lock);
1775 BTRFS_I(inode)->outstanding_extents++;
1776 spin_unlock(&BTRFS_I(inode)->lock);
1779 /* For sanity tests */
1780 if (btrfs_is_testing(fs_info))
1783 percpu_counter_add_batch(&fs_info->delalloc_bytes, len,
1784 fs_info->delalloc_batch);
1785 spin_lock(&BTRFS_I(inode)->lock);
1786 BTRFS_I(inode)->delalloc_bytes += len;
1787 if (*bits & EXTENT_DEFRAG)
1788 BTRFS_I(inode)->defrag_bytes += len;
1789 if (do_list && !test_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1790 &BTRFS_I(inode)->runtime_flags))
1791 btrfs_add_delalloc_inodes(root, inode);
1792 spin_unlock(&BTRFS_I(inode)->lock);
1795 if (!(state->state & EXTENT_DELALLOC_NEW) &&
1796 (*bits & EXTENT_DELALLOC_NEW)) {
1797 spin_lock(&BTRFS_I(inode)->lock);
1798 BTRFS_I(inode)->new_delalloc_bytes += state->end + 1 -
1800 spin_unlock(&BTRFS_I(inode)->lock);
1805 * extent_io.c clear_bit_hook, see set_bit_hook for why
1807 static void btrfs_clear_bit_hook(void *private_data,
1808 struct extent_state *state,
1811 struct btrfs_inode *inode = BTRFS_I((struct inode *)private_data);
1812 struct btrfs_fs_info *fs_info = btrfs_sb(inode->vfs_inode.i_sb);
1813 u64 len = state->end + 1 - state->start;
1814 u32 num_extents = count_max_extents(len);
1816 if ((state->state & EXTENT_DEFRAG) && (*bits & EXTENT_DEFRAG)) {
1817 spin_lock(&inode->lock);
1818 inode->defrag_bytes -= len;
1819 spin_unlock(&inode->lock);
1823 * set_bit and clear bit hooks normally require _irqsave/restore
1824 * but in this case, we are only testing for the DELALLOC
1825 * bit, which is only set or cleared with irqs on
1827 if ((state->state & EXTENT_DELALLOC) && (*bits & EXTENT_DELALLOC)) {
1828 struct btrfs_root *root = inode->root;
1829 bool do_list = !btrfs_is_free_space_inode(inode);
1831 if (*bits & EXTENT_FIRST_DELALLOC) {
1832 *bits &= ~EXTENT_FIRST_DELALLOC;
1833 } else if (!(*bits & EXTENT_CLEAR_META_RESV)) {
1834 spin_lock(&inode->lock);
1835 inode->outstanding_extents -= num_extents;
1836 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 static blk_status_t btrfs_submit_bio_hook(void *private_data, struct bio *bio,
1961 int mirror_num, unsigned long bio_flags,
1964 struct inode *inode = private_data;
1965 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1966 struct btrfs_root *root = BTRFS_I(inode)->root;
1967 enum btrfs_wq_endio_type metadata = BTRFS_WQ_ENDIO_DATA;
1968 blk_status_t ret = 0;
1970 int async = !atomic_read(&BTRFS_I(inode)->sync_writers);
1972 skip_sum = BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM;
1974 if (btrfs_is_free_space_inode(BTRFS_I(inode)))
1975 metadata = BTRFS_WQ_ENDIO_FREE_SPACE;
1977 if (bio_op(bio) != REQ_OP_WRITE) {
1978 ret = btrfs_bio_wq_end_io(fs_info, bio, metadata);
1982 if (bio_flags & EXTENT_BIO_COMPRESSED) {
1983 ret = btrfs_submit_compressed_read(inode, bio,
1987 } else if (!skip_sum) {
1988 ret = btrfs_lookup_bio_sums(inode, bio, NULL);
1993 } else if (async && !skip_sum) {
1994 /* csum items have already been cloned */
1995 if (root->root_key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID)
1997 /* we're doing a write, do the async checksumming */
1998 ret = btrfs_wq_submit_bio(fs_info, bio, mirror_num, bio_flags,
2000 __btrfs_submit_bio_start,
2001 __btrfs_submit_bio_done);
2003 } else if (!skip_sum) {
2004 ret = btrfs_csum_one_bio(inode, bio, 0, 0);
2010 ret = btrfs_map_bio(fs_info, bio, mirror_num, 0);
2014 bio->bi_status = ret;
2021 * given a list of ordered sums record them in the inode. This happens
2022 * at IO completion time based on sums calculated at bio submission time.
2024 static noinline int add_pending_csums(struct btrfs_trans_handle *trans,
2025 struct inode *inode, struct list_head *list)
2027 struct btrfs_ordered_sum *sum;
2029 list_for_each_entry(sum, list, list) {
2030 trans->adding_csums = 1;
2031 btrfs_csum_file_blocks(trans,
2032 BTRFS_I(inode)->root->fs_info->csum_root, sum);
2033 trans->adding_csums = 0;
2038 int btrfs_set_extent_delalloc(struct inode *inode, u64 start, u64 end,
2039 struct extent_state **cached_state, int dedupe)
2041 WARN_ON((end & (PAGE_SIZE - 1)) == 0);
2042 return set_extent_delalloc(&BTRFS_I(inode)->io_tree, start, end,
2046 /* see btrfs_writepage_start_hook for details on why this is required */
2047 struct btrfs_writepage_fixup {
2049 struct btrfs_work work;
2052 static void btrfs_writepage_fixup_worker(struct btrfs_work *work)
2054 struct btrfs_writepage_fixup *fixup;
2055 struct btrfs_ordered_extent *ordered;
2056 struct extent_state *cached_state = NULL;
2057 struct extent_changeset *data_reserved = NULL;
2059 struct inode *inode;
2064 fixup = container_of(work, struct btrfs_writepage_fixup, work);
2068 if (!page->mapping || !PageDirty(page) || !PageChecked(page)) {
2069 ClearPageChecked(page);
2073 inode = page->mapping->host;
2074 page_start = page_offset(page);
2075 page_end = page_offset(page) + PAGE_SIZE - 1;
2077 lock_extent_bits(&BTRFS_I(inode)->io_tree, page_start, page_end,
2080 /* already ordered? We're done */
2081 if (PagePrivate2(page))
2084 ordered = btrfs_lookup_ordered_range(BTRFS_I(inode), page_start,
2087 unlock_extent_cached(&BTRFS_I(inode)->io_tree, page_start,
2088 page_end, &cached_state, GFP_NOFS);
2090 btrfs_start_ordered_extent(inode, ordered, 1);
2091 btrfs_put_ordered_extent(ordered);
2095 ret = btrfs_delalloc_reserve_space(inode, &data_reserved, page_start,
2098 mapping_set_error(page->mapping, ret);
2099 end_extent_writepage(page, ret, page_start, page_end);
2100 ClearPageChecked(page);
2104 btrfs_set_extent_delalloc(inode, page_start, page_end, &cached_state,
2106 ClearPageChecked(page);
2107 set_page_dirty(page);
2109 unlock_extent_cached(&BTRFS_I(inode)->io_tree, page_start, page_end,
2110 &cached_state, GFP_NOFS);
2115 extent_changeset_free(data_reserved);
2119 * There are a few paths in the higher layers of the kernel that directly
2120 * set the page dirty bit without asking the filesystem if it is a
2121 * good idea. This causes problems because we want to make sure COW
2122 * properly happens and the data=ordered rules are followed.
2124 * In our case any range that doesn't have the ORDERED bit set
2125 * hasn't been properly setup for IO. We kick off an async process
2126 * to fix it up. The async helper will wait for ordered extents, set
2127 * the delalloc bit and make it safe to write the page.
2129 static int btrfs_writepage_start_hook(struct page *page, u64 start, u64 end)
2131 struct inode *inode = page->mapping->host;
2132 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2133 struct btrfs_writepage_fixup *fixup;
2135 /* this page is properly in the ordered list */
2136 if (TestClearPagePrivate2(page))
2139 if (PageChecked(page))
2142 fixup = kzalloc(sizeof(*fixup), GFP_NOFS);
2146 SetPageChecked(page);
2148 btrfs_init_work(&fixup->work, btrfs_fixup_helper,
2149 btrfs_writepage_fixup_worker, NULL, NULL);
2151 btrfs_queue_work(fs_info->fixup_workers, &fixup->work);
2155 static int insert_reserved_file_extent(struct btrfs_trans_handle *trans,
2156 struct inode *inode, u64 file_pos,
2157 u64 disk_bytenr, u64 disk_num_bytes,
2158 u64 num_bytes, u64 ram_bytes,
2159 u8 compression, u8 encryption,
2160 u16 other_encoding, int extent_type)
2162 struct btrfs_root *root = BTRFS_I(inode)->root;
2163 struct btrfs_file_extent_item *fi;
2164 struct btrfs_path *path;
2165 struct extent_buffer *leaf;
2166 struct btrfs_key ins;
2168 int extent_inserted = 0;
2171 path = btrfs_alloc_path();
2176 * we may be replacing one extent in the tree with another.
2177 * The new extent is pinned in the extent map, and we don't want
2178 * to drop it from the cache until it is completely in the btree.
2180 * So, tell btrfs_drop_extents to leave this extent in the cache.
2181 * the caller is expected to unpin it and allow it to be merged
2184 ret = __btrfs_drop_extents(trans, root, inode, path, file_pos,
2185 file_pos + num_bytes, NULL, 0,
2186 1, sizeof(*fi), &extent_inserted);
2190 if (!extent_inserted) {
2191 ins.objectid = btrfs_ino(BTRFS_I(inode));
2192 ins.offset = file_pos;
2193 ins.type = BTRFS_EXTENT_DATA_KEY;
2195 path->leave_spinning = 1;
2196 ret = btrfs_insert_empty_item(trans, root, path, &ins,
2201 leaf = path->nodes[0];
2202 fi = btrfs_item_ptr(leaf, path->slots[0],
2203 struct btrfs_file_extent_item);
2204 btrfs_set_file_extent_generation(leaf, fi, trans->transid);
2205 btrfs_set_file_extent_type(leaf, fi, extent_type);
2206 btrfs_set_file_extent_disk_bytenr(leaf, fi, disk_bytenr);
2207 btrfs_set_file_extent_disk_num_bytes(leaf, fi, disk_num_bytes);
2208 btrfs_set_file_extent_offset(leaf, fi, 0);
2209 btrfs_set_file_extent_num_bytes(leaf, fi, num_bytes);
2210 btrfs_set_file_extent_ram_bytes(leaf, fi, ram_bytes);
2211 btrfs_set_file_extent_compression(leaf, fi, compression);
2212 btrfs_set_file_extent_encryption(leaf, fi, encryption);
2213 btrfs_set_file_extent_other_encoding(leaf, fi, other_encoding);
2215 btrfs_mark_buffer_dirty(leaf);
2216 btrfs_release_path(path);
2218 inode_add_bytes(inode, num_bytes);
2220 ins.objectid = disk_bytenr;
2221 ins.offset = disk_num_bytes;
2222 ins.type = BTRFS_EXTENT_ITEM_KEY;
2225 * Release the reserved range from inode dirty range map, as it is
2226 * already moved into delayed_ref_head
2228 ret = btrfs_qgroup_release_data(inode, file_pos, ram_bytes);
2232 ret = btrfs_alloc_reserved_file_extent(trans, root->root_key.objectid,
2233 btrfs_ino(BTRFS_I(inode)), file_pos, qg_released, &ins);
2235 btrfs_free_path(path);
2240 /* snapshot-aware defrag */
2241 struct sa_defrag_extent_backref {
2242 struct rb_node node;
2243 struct old_sa_defrag_extent *old;
2252 struct old_sa_defrag_extent {
2253 struct list_head list;
2254 struct new_sa_defrag_extent *new;
2263 struct new_sa_defrag_extent {
2264 struct rb_root root;
2265 struct list_head head;
2266 struct btrfs_path *path;
2267 struct inode *inode;
2275 static int backref_comp(struct sa_defrag_extent_backref *b1,
2276 struct sa_defrag_extent_backref *b2)
2278 if (b1->root_id < b2->root_id)
2280 else if (b1->root_id > b2->root_id)
2283 if (b1->inum < b2->inum)
2285 else if (b1->inum > b2->inum)
2288 if (b1->file_pos < b2->file_pos)
2290 else if (b1->file_pos > b2->file_pos)
2294 * [------------------------------] ===> (a range of space)
2295 * |<--->| |<---->| =============> (fs/file tree A)
2296 * |<---------------------------->| ===> (fs/file tree B)
2298 * A range of space can refer to two file extents in one tree while
2299 * refer to only one file extent in another tree.
2301 * So we may process a disk offset more than one time(two extents in A)
2302 * and locate at the same extent(one extent in B), then insert two same
2303 * backrefs(both refer to the extent in B).
2308 static void backref_insert(struct rb_root *root,
2309 struct sa_defrag_extent_backref *backref)
2311 struct rb_node **p = &root->rb_node;
2312 struct rb_node *parent = NULL;
2313 struct sa_defrag_extent_backref *entry;
2318 entry = rb_entry(parent, struct sa_defrag_extent_backref, node);
2320 ret = backref_comp(backref, entry);
2324 p = &(*p)->rb_right;
2327 rb_link_node(&backref->node, parent, p);
2328 rb_insert_color(&backref->node, root);
2332 * Note the backref might has changed, and in this case we just return 0.
2334 static noinline int record_one_backref(u64 inum, u64 offset, u64 root_id,
2337 struct btrfs_file_extent_item *extent;
2338 struct old_sa_defrag_extent *old = ctx;
2339 struct new_sa_defrag_extent *new = old->new;
2340 struct btrfs_path *path = new->path;
2341 struct btrfs_key key;
2342 struct btrfs_root *root;
2343 struct sa_defrag_extent_backref *backref;
2344 struct extent_buffer *leaf;
2345 struct inode *inode = new->inode;
2346 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2352 if (BTRFS_I(inode)->root->root_key.objectid == root_id &&
2353 inum == btrfs_ino(BTRFS_I(inode)))
2356 key.objectid = root_id;
2357 key.type = BTRFS_ROOT_ITEM_KEY;
2358 key.offset = (u64)-1;
2360 root = btrfs_read_fs_root_no_name(fs_info, &key);
2362 if (PTR_ERR(root) == -ENOENT)
2365 btrfs_debug(fs_info, "inum=%llu, offset=%llu, root_id=%llu",
2366 inum, offset, root_id);
2367 return PTR_ERR(root);
2370 key.objectid = inum;
2371 key.type = BTRFS_EXTENT_DATA_KEY;
2372 if (offset > (u64)-1 << 32)
2375 key.offset = offset;
2377 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2378 if (WARN_ON(ret < 0))
2385 leaf = path->nodes[0];
2386 slot = path->slots[0];
2388 if (slot >= btrfs_header_nritems(leaf)) {
2389 ret = btrfs_next_leaf(root, path);
2392 } else if (ret > 0) {
2401 btrfs_item_key_to_cpu(leaf, &key, slot);
2403 if (key.objectid > inum)
2406 if (key.objectid < inum || key.type != BTRFS_EXTENT_DATA_KEY)
2409 extent = btrfs_item_ptr(leaf, slot,
2410 struct btrfs_file_extent_item);
2412 if (btrfs_file_extent_disk_bytenr(leaf, extent) != old->bytenr)
2416 * 'offset' refers to the exact key.offset,
2417 * NOT the 'offset' field in btrfs_extent_data_ref, ie.
2418 * (key.offset - extent_offset).
2420 if (key.offset != offset)
2423 extent_offset = btrfs_file_extent_offset(leaf, extent);
2424 num_bytes = btrfs_file_extent_num_bytes(leaf, extent);
2426 if (extent_offset >= old->extent_offset + old->offset +
2427 old->len || extent_offset + num_bytes <=
2428 old->extent_offset + old->offset)
2433 backref = kmalloc(sizeof(*backref), GFP_NOFS);
2439 backref->root_id = root_id;
2440 backref->inum = inum;
2441 backref->file_pos = offset;
2442 backref->num_bytes = num_bytes;
2443 backref->extent_offset = extent_offset;
2444 backref->generation = btrfs_file_extent_generation(leaf, extent);
2446 backref_insert(&new->root, backref);
2449 btrfs_release_path(path);
2454 static noinline bool record_extent_backrefs(struct btrfs_path *path,
2455 struct new_sa_defrag_extent *new)
2457 struct btrfs_fs_info *fs_info = btrfs_sb(new->inode->i_sb);
2458 struct old_sa_defrag_extent *old, *tmp;
2463 list_for_each_entry_safe(old, tmp, &new->head, list) {
2464 ret = iterate_inodes_from_logical(old->bytenr +
2465 old->extent_offset, fs_info,
2466 path, record_one_backref,
2468 if (ret < 0 && ret != -ENOENT)
2471 /* no backref to be processed for this extent */
2473 list_del(&old->list);
2478 if (list_empty(&new->head))
2484 static int relink_is_mergable(struct extent_buffer *leaf,
2485 struct btrfs_file_extent_item *fi,
2486 struct new_sa_defrag_extent *new)
2488 if (btrfs_file_extent_disk_bytenr(leaf, fi) != new->bytenr)
2491 if (btrfs_file_extent_type(leaf, fi) != BTRFS_FILE_EXTENT_REG)
2494 if (btrfs_file_extent_compression(leaf, fi) != new->compress_type)
2497 if (btrfs_file_extent_encryption(leaf, fi) ||
2498 btrfs_file_extent_other_encoding(leaf, fi))
2505 * Note the backref might has changed, and in this case we just return 0.
2507 static noinline int relink_extent_backref(struct btrfs_path *path,
2508 struct sa_defrag_extent_backref *prev,
2509 struct sa_defrag_extent_backref *backref)
2511 struct btrfs_file_extent_item *extent;
2512 struct btrfs_file_extent_item *item;
2513 struct btrfs_ordered_extent *ordered;
2514 struct btrfs_trans_handle *trans;
2515 struct btrfs_root *root;
2516 struct btrfs_key key;
2517 struct extent_buffer *leaf;
2518 struct old_sa_defrag_extent *old = backref->old;
2519 struct new_sa_defrag_extent *new = old->new;
2520 struct btrfs_fs_info *fs_info = btrfs_sb(new->inode->i_sb);
2521 struct inode *inode;
2522 struct extent_state *cached = NULL;
2531 if (prev && prev->root_id == backref->root_id &&
2532 prev->inum == backref->inum &&
2533 prev->file_pos + prev->num_bytes == backref->file_pos)
2536 /* step 1: get root */
2537 key.objectid = backref->root_id;
2538 key.type = BTRFS_ROOT_ITEM_KEY;
2539 key.offset = (u64)-1;
2541 index = srcu_read_lock(&fs_info->subvol_srcu);
2543 root = btrfs_read_fs_root_no_name(fs_info, &key);
2545 srcu_read_unlock(&fs_info->subvol_srcu, index);
2546 if (PTR_ERR(root) == -ENOENT)
2548 return PTR_ERR(root);
2551 if (btrfs_root_readonly(root)) {
2552 srcu_read_unlock(&fs_info->subvol_srcu, index);
2556 /* step 2: get inode */
2557 key.objectid = backref->inum;
2558 key.type = BTRFS_INODE_ITEM_KEY;
2561 inode = btrfs_iget(fs_info->sb, &key, root, NULL);
2562 if (IS_ERR(inode)) {
2563 srcu_read_unlock(&fs_info->subvol_srcu, index);
2567 srcu_read_unlock(&fs_info->subvol_srcu, index);
2569 /* step 3: relink backref */
2570 lock_start = backref->file_pos;
2571 lock_end = backref->file_pos + backref->num_bytes - 1;
2572 lock_extent_bits(&BTRFS_I(inode)->io_tree, lock_start, lock_end,
2575 ordered = btrfs_lookup_first_ordered_extent(inode, lock_end);
2577 btrfs_put_ordered_extent(ordered);
2581 trans = btrfs_join_transaction(root);
2582 if (IS_ERR(trans)) {
2583 ret = PTR_ERR(trans);
2587 key.objectid = backref->inum;
2588 key.type = BTRFS_EXTENT_DATA_KEY;
2589 key.offset = backref->file_pos;
2591 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2594 } else if (ret > 0) {
2599 extent = btrfs_item_ptr(path->nodes[0], path->slots[0],
2600 struct btrfs_file_extent_item);
2602 if (btrfs_file_extent_generation(path->nodes[0], extent) !=
2603 backref->generation)
2606 btrfs_release_path(path);
2608 start = backref->file_pos;
2609 if (backref->extent_offset < old->extent_offset + old->offset)
2610 start += old->extent_offset + old->offset -
2611 backref->extent_offset;
2613 len = min(backref->extent_offset + backref->num_bytes,
2614 old->extent_offset + old->offset + old->len);
2615 len -= max(backref->extent_offset, old->extent_offset + old->offset);
2617 ret = btrfs_drop_extents(trans, root, inode, start,
2622 key.objectid = btrfs_ino(BTRFS_I(inode));
2623 key.type = BTRFS_EXTENT_DATA_KEY;
2626 path->leave_spinning = 1;
2628 struct btrfs_file_extent_item *fi;
2630 struct btrfs_key found_key;
2632 ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
2637 leaf = path->nodes[0];
2638 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
2640 fi = btrfs_item_ptr(leaf, path->slots[0],
2641 struct btrfs_file_extent_item);
2642 extent_len = btrfs_file_extent_num_bytes(leaf, fi);
2644 if (extent_len + found_key.offset == start &&
2645 relink_is_mergable(leaf, fi, new)) {
2646 btrfs_set_file_extent_num_bytes(leaf, fi,
2648 btrfs_mark_buffer_dirty(leaf);
2649 inode_add_bytes(inode, len);
2655 btrfs_release_path(path);
2660 ret = btrfs_insert_empty_item(trans, root, path, &key,
2663 btrfs_abort_transaction(trans, ret);
2667 leaf = path->nodes[0];
2668 item = btrfs_item_ptr(leaf, path->slots[0],
2669 struct btrfs_file_extent_item);
2670 btrfs_set_file_extent_disk_bytenr(leaf, item, new->bytenr);
2671 btrfs_set_file_extent_disk_num_bytes(leaf, item, new->disk_len);
2672 btrfs_set_file_extent_offset(leaf, item, start - new->file_pos);
2673 btrfs_set_file_extent_num_bytes(leaf, item, len);
2674 btrfs_set_file_extent_ram_bytes(leaf, item, new->len);
2675 btrfs_set_file_extent_generation(leaf, item, trans->transid);
2676 btrfs_set_file_extent_type(leaf, item, BTRFS_FILE_EXTENT_REG);
2677 btrfs_set_file_extent_compression(leaf, item, new->compress_type);
2678 btrfs_set_file_extent_encryption(leaf, item, 0);
2679 btrfs_set_file_extent_other_encoding(leaf, item, 0);
2681 btrfs_mark_buffer_dirty(leaf);
2682 inode_add_bytes(inode, len);
2683 btrfs_release_path(path);
2685 ret = btrfs_inc_extent_ref(trans, fs_info, new->bytenr,
2687 backref->root_id, backref->inum,
2688 new->file_pos); /* start - extent_offset */
2690 btrfs_abort_transaction(trans, ret);
2696 btrfs_release_path(path);
2697 path->leave_spinning = 0;
2698 btrfs_end_transaction(trans);
2700 unlock_extent_cached(&BTRFS_I(inode)->io_tree, lock_start, lock_end,
2706 static void free_sa_defrag_extent(struct new_sa_defrag_extent *new)
2708 struct old_sa_defrag_extent *old, *tmp;
2713 list_for_each_entry_safe(old, tmp, &new->head, list) {
2719 static void relink_file_extents(struct new_sa_defrag_extent *new)
2721 struct btrfs_fs_info *fs_info = btrfs_sb(new->inode->i_sb);
2722 struct btrfs_path *path;
2723 struct sa_defrag_extent_backref *backref;
2724 struct sa_defrag_extent_backref *prev = NULL;
2725 struct inode *inode;
2726 struct btrfs_root *root;
2727 struct rb_node *node;
2731 root = BTRFS_I(inode)->root;
2733 path = btrfs_alloc_path();
2737 if (!record_extent_backrefs(path, new)) {
2738 btrfs_free_path(path);
2741 btrfs_release_path(path);
2744 node = rb_first(&new->root);
2747 rb_erase(node, &new->root);
2749 backref = rb_entry(node, struct sa_defrag_extent_backref, node);
2751 ret = relink_extent_backref(path, prev, backref);
2764 btrfs_free_path(path);
2766 free_sa_defrag_extent(new);
2768 atomic_dec(&fs_info->defrag_running);
2769 wake_up(&fs_info->transaction_wait);
2772 static struct new_sa_defrag_extent *
2773 record_old_file_extents(struct inode *inode,
2774 struct btrfs_ordered_extent *ordered)
2776 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2777 struct btrfs_root *root = BTRFS_I(inode)->root;
2778 struct btrfs_path *path;
2779 struct btrfs_key key;
2780 struct old_sa_defrag_extent *old;
2781 struct new_sa_defrag_extent *new;
2784 new = kmalloc(sizeof(*new), GFP_NOFS);
2789 new->file_pos = ordered->file_offset;
2790 new->len = ordered->len;
2791 new->bytenr = ordered->start;
2792 new->disk_len = ordered->disk_len;
2793 new->compress_type = ordered->compress_type;
2794 new->root = RB_ROOT;
2795 INIT_LIST_HEAD(&new->head);
2797 path = btrfs_alloc_path();
2801 key.objectid = btrfs_ino(BTRFS_I(inode));
2802 key.type = BTRFS_EXTENT_DATA_KEY;
2803 key.offset = new->file_pos;
2805 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2808 if (ret > 0 && path->slots[0] > 0)
2811 /* find out all the old extents for the file range */
2813 struct btrfs_file_extent_item *extent;
2814 struct extent_buffer *l;
2823 slot = path->slots[0];
2825 if (slot >= btrfs_header_nritems(l)) {
2826 ret = btrfs_next_leaf(root, path);
2834 btrfs_item_key_to_cpu(l, &key, slot);
2836 if (key.objectid != btrfs_ino(BTRFS_I(inode)))
2838 if (key.type != BTRFS_EXTENT_DATA_KEY)
2840 if (key.offset >= new->file_pos + new->len)
2843 extent = btrfs_item_ptr(l, slot, struct btrfs_file_extent_item);
2845 num_bytes = btrfs_file_extent_num_bytes(l, extent);
2846 if (key.offset + num_bytes < new->file_pos)
2849 disk_bytenr = btrfs_file_extent_disk_bytenr(l, extent);
2853 extent_offset = btrfs_file_extent_offset(l, extent);
2855 old = kmalloc(sizeof(*old), GFP_NOFS);
2859 offset = max(new->file_pos, key.offset);
2860 end = min(new->file_pos + new->len, key.offset + num_bytes);
2862 old->bytenr = disk_bytenr;
2863 old->extent_offset = extent_offset;
2864 old->offset = offset - key.offset;
2865 old->len = end - offset;
2868 list_add_tail(&old->list, &new->head);
2874 btrfs_free_path(path);
2875 atomic_inc(&fs_info->defrag_running);
2880 btrfs_free_path(path);
2882 free_sa_defrag_extent(new);
2886 static void btrfs_release_delalloc_bytes(struct btrfs_fs_info *fs_info,
2889 struct btrfs_block_group_cache *cache;
2891 cache = btrfs_lookup_block_group(fs_info, start);
2894 spin_lock(&cache->lock);
2895 cache->delalloc_bytes -= len;
2896 spin_unlock(&cache->lock);
2898 btrfs_put_block_group(cache);
2901 /* as ordered data IO finishes, this gets called so we can finish
2902 * an ordered extent if the range of bytes in the file it covers are
2905 static int btrfs_finish_ordered_io(struct btrfs_ordered_extent *ordered_extent)
2907 struct inode *inode = ordered_extent->inode;
2908 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2909 struct btrfs_root *root = BTRFS_I(inode)->root;
2910 struct btrfs_trans_handle *trans = NULL;
2911 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
2912 struct extent_state *cached_state = NULL;
2913 struct new_sa_defrag_extent *new = NULL;
2914 int compress_type = 0;
2916 u64 logical_len = ordered_extent->len;
2918 bool truncated = false;
2919 bool range_locked = false;
2920 bool clear_new_delalloc_bytes = false;
2922 if (!test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags) &&
2923 !test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags) &&
2924 !test_bit(BTRFS_ORDERED_DIRECT, &ordered_extent->flags))
2925 clear_new_delalloc_bytes = true;
2927 nolock = btrfs_is_free_space_inode(BTRFS_I(inode));
2929 if (test_bit(BTRFS_ORDERED_IOERR, &ordered_extent->flags)) {
2934 btrfs_free_io_failure_record(BTRFS_I(inode),
2935 ordered_extent->file_offset,
2936 ordered_extent->file_offset +
2937 ordered_extent->len - 1);
2939 if (test_bit(BTRFS_ORDERED_TRUNCATED, &ordered_extent->flags)) {
2941 logical_len = ordered_extent->truncated_len;
2942 /* Truncated the entire extent, don't bother adding */
2947 if (test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags)) {
2948 BUG_ON(!list_empty(&ordered_extent->list)); /* Logic error */
2951 * For mwrite(mmap + memset to write) case, we still reserve
2952 * space for NOCOW range.
2953 * As NOCOW won't cause a new delayed ref, just free the space
2955 btrfs_qgroup_free_data(inode, NULL, ordered_extent->file_offset,
2956 ordered_extent->len);
2957 btrfs_ordered_update_i_size(inode, 0, ordered_extent);
2959 trans = btrfs_join_transaction_nolock(root);
2961 trans = btrfs_join_transaction(root);
2962 if (IS_ERR(trans)) {
2963 ret = PTR_ERR(trans);
2967 trans->block_rsv = &fs_info->delalloc_block_rsv;
2968 ret = btrfs_update_inode_fallback(trans, root, inode);
2969 if (ret) /* -ENOMEM or corruption */
2970 btrfs_abort_transaction(trans, ret);
2974 range_locked = true;
2975 lock_extent_bits(io_tree, ordered_extent->file_offset,
2976 ordered_extent->file_offset + ordered_extent->len - 1,
2979 ret = test_range_bit(io_tree, ordered_extent->file_offset,
2980 ordered_extent->file_offset + ordered_extent->len - 1,
2981 EXTENT_DEFRAG, 0, cached_state);
2983 u64 last_snapshot = btrfs_root_last_snapshot(&root->root_item);
2984 if (0 && last_snapshot >= BTRFS_I(inode)->generation)
2985 /* the inode is shared */
2986 new = record_old_file_extents(inode, ordered_extent);
2988 clear_extent_bit(io_tree, ordered_extent->file_offset,
2989 ordered_extent->file_offset + ordered_extent->len - 1,
2990 EXTENT_DEFRAG, 0, 0, &cached_state, GFP_NOFS);
2994 trans = btrfs_join_transaction_nolock(root);
2996 trans = btrfs_join_transaction(root);
2997 if (IS_ERR(trans)) {
2998 ret = PTR_ERR(trans);
3003 trans->block_rsv = &fs_info->delalloc_block_rsv;
3005 if (test_bit(BTRFS_ORDERED_COMPRESSED, &ordered_extent->flags))
3006 compress_type = ordered_extent->compress_type;
3007 if (test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags)) {
3008 BUG_ON(compress_type);
3009 ret = btrfs_mark_extent_written(trans, BTRFS_I(inode),
3010 ordered_extent->file_offset,
3011 ordered_extent->file_offset +
3014 BUG_ON(root == fs_info->tree_root);
3015 ret = insert_reserved_file_extent(trans, inode,
3016 ordered_extent->file_offset,
3017 ordered_extent->start,
3018 ordered_extent->disk_len,
3019 logical_len, logical_len,
3020 compress_type, 0, 0,
3021 BTRFS_FILE_EXTENT_REG);
3023 btrfs_release_delalloc_bytes(fs_info,
3024 ordered_extent->start,
3025 ordered_extent->disk_len);
3027 unpin_extent_cache(&BTRFS_I(inode)->extent_tree,
3028 ordered_extent->file_offset, ordered_extent->len,
3031 btrfs_abort_transaction(trans, ret);
3035 add_pending_csums(trans, inode, &ordered_extent->list);
3037 btrfs_ordered_update_i_size(inode, 0, ordered_extent);
3038 ret = btrfs_update_inode_fallback(trans, root, inode);
3039 if (ret) { /* -ENOMEM or corruption */
3040 btrfs_abort_transaction(trans, ret);
3045 if (range_locked || clear_new_delalloc_bytes) {
3046 unsigned int clear_bits = 0;
3049 clear_bits |= EXTENT_LOCKED;
3050 if (clear_new_delalloc_bytes)
3051 clear_bits |= EXTENT_DELALLOC_NEW;
3052 clear_extent_bit(&BTRFS_I(inode)->io_tree,
3053 ordered_extent->file_offset,
3054 ordered_extent->file_offset +
3055 ordered_extent->len - 1,
3057 (clear_bits & EXTENT_LOCKED) ? 1 : 0,
3058 0, &cached_state, GFP_NOFS);
3061 if (root != fs_info->tree_root)
3062 btrfs_delalloc_release_metadata(BTRFS_I(inode),
3063 ordered_extent->len);
3065 btrfs_end_transaction(trans);
3067 if (ret || truncated) {
3071 start = ordered_extent->file_offset + logical_len;
3073 start = ordered_extent->file_offset;
3074 end = ordered_extent->file_offset + ordered_extent->len - 1;
3075 clear_extent_uptodate(io_tree, start, end, NULL, GFP_NOFS);
3077 /* Drop the cache for the part of the extent we didn't write. */
3078 btrfs_drop_extent_cache(BTRFS_I(inode), start, end, 0);
3081 * If the ordered extent had an IOERR or something else went
3082 * wrong we need to return the space for this ordered extent
3083 * back to the allocator. We only free the extent in the
3084 * truncated case if we didn't write out the extent at all.
3086 if ((ret || !logical_len) &&
3087 !test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags) &&
3088 !test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags))
3089 btrfs_free_reserved_extent(fs_info,
3090 ordered_extent->start,
3091 ordered_extent->disk_len, 1);
3096 * This needs to be done to make sure anybody waiting knows we are done
3097 * updating everything for this ordered extent.
3099 btrfs_remove_ordered_extent(inode, ordered_extent);
3101 /* for snapshot-aware defrag */
3104 free_sa_defrag_extent(new);
3105 atomic_dec(&fs_info->defrag_running);
3107 relink_file_extents(new);
3112 btrfs_put_ordered_extent(ordered_extent);
3113 /* once for the tree */
3114 btrfs_put_ordered_extent(ordered_extent);
3119 static void finish_ordered_fn(struct btrfs_work *work)
3121 struct btrfs_ordered_extent *ordered_extent;
3122 ordered_extent = container_of(work, struct btrfs_ordered_extent, work);
3123 btrfs_finish_ordered_io(ordered_extent);
3126 static void btrfs_writepage_end_io_hook(struct page *page, u64 start, u64 end,
3127 struct extent_state *state, int uptodate)
3129 struct inode *inode = page->mapping->host;
3130 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
3131 struct btrfs_ordered_extent *ordered_extent = NULL;
3132 struct btrfs_workqueue *wq;
3133 btrfs_work_func_t func;
3135 trace_btrfs_writepage_end_io_hook(page, start, end, uptodate);
3137 ClearPagePrivate2(page);
3138 if (!btrfs_dec_test_ordered_pending(inode, &ordered_extent, start,
3139 end - start + 1, uptodate))
3142 if (btrfs_is_free_space_inode(BTRFS_I(inode))) {
3143 wq = fs_info->endio_freespace_worker;
3144 func = btrfs_freespace_write_helper;
3146 wq = fs_info->endio_write_workers;
3147 func = btrfs_endio_write_helper;
3150 btrfs_init_work(&ordered_extent->work, func, finish_ordered_fn, NULL,
3152 btrfs_queue_work(wq, &ordered_extent->work);
3155 static int __readpage_endio_check(struct inode *inode,
3156 struct btrfs_io_bio *io_bio,
3157 int icsum, struct page *page,
3158 int pgoff, u64 start, size_t len)
3164 csum_expected = *(((u32 *)io_bio->csum) + icsum);
3166 kaddr = kmap_atomic(page);
3167 csum = btrfs_csum_data(kaddr + pgoff, csum, len);
3168 btrfs_csum_final(csum, (u8 *)&csum);
3169 if (csum != csum_expected)
3172 kunmap_atomic(kaddr);
3175 btrfs_print_data_csum_error(BTRFS_I(inode), start, csum, csum_expected,
3176 io_bio->mirror_num);
3177 memset(kaddr + pgoff, 1, len);
3178 flush_dcache_page(page);
3179 kunmap_atomic(kaddr);
3184 * when reads are done, we need to check csums to verify the data is correct
3185 * if there's a match, we allow the bio to finish. If not, the code in
3186 * extent_io.c will try to find good copies for us.
3188 static int btrfs_readpage_end_io_hook(struct btrfs_io_bio *io_bio,
3189 u64 phy_offset, struct page *page,
3190 u64 start, u64 end, int mirror)
3192 size_t offset = start - page_offset(page);
3193 struct inode *inode = page->mapping->host;
3194 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
3195 struct btrfs_root *root = BTRFS_I(inode)->root;
3197 if (PageChecked(page)) {
3198 ClearPageChecked(page);
3202 if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)
3205 if (root->root_key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID &&
3206 test_range_bit(io_tree, start, end, EXTENT_NODATASUM, 1, NULL)) {
3207 clear_extent_bits(io_tree, start, end, EXTENT_NODATASUM);
3211 phy_offset >>= inode->i_sb->s_blocksize_bits;
3212 return __readpage_endio_check(inode, io_bio, phy_offset, page, offset,
3213 start, (size_t)(end - start + 1));
3216 void btrfs_add_delayed_iput(struct inode *inode)
3218 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
3219 struct btrfs_inode *binode = BTRFS_I(inode);
3221 if (atomic_add_unless(&inode->i_count, -1, 1))
3224 spin_lock(&fs_info->delayed_iput_lock);
3225 if (binode->delayed_iput_count == 0) {
3226 ASSERT(list_empty(&binode->delayed_iput));
3227 list_add_tail(&binode->delayed_iput, &fs_info->delayed_iputs);
3229 binode->delayed_iput_count++;
3231 spin_unlock(&fs_info->delayed_iput_lock);
3234 void btrfs_run_delayed_iputs(struct btrfs_fs_info *fs_info)
3237 spin_lock(&fs_info->delayed_iput_lock);
3238 while (!list_empty(&fs_info->delayed_iputs)) {
3239 struct btrfs_inode *inode;
3241 inode = list_first_entry(&fs_info->delayed_iputs,
3242 struct btrfs_inode, delayed_iput);
3243 if (inode->delayed_iput_count) {
3244 inode->delayed_iput_count--;
3245 list_move_tail(&inode->delayed_iput,
3246 &fs_info->delayed_iputs);
3248 list_del_init(&inode->delayed_iput);
3250 spin_unlock(&fs_info->delayed_iput_lock);
3251 iput(&inode->vfs_inode);
3252 spin_lock(&fs_info->delayed_iput_lock);
3254 spin_unlock(&fs_info->delayed_iput_lock);
3258 * This is called in transaction commit time. If there are no orphan
3259 * files in the subvolume, it removes orphan item and frees block_rsv
3262 void btrfs_orphan_commit_root(struct btrfs_trans_handle *trans,
3263 struct btrfs_root *root)
3265 struct btrfs_fs_info *fs_info = root->fs_info;
3266 struct btrfs_block_rsv *block_rsv;
3269 if (atomic_read(&root->orphan_inodes) ||
3270 root->orphan_cleanup_state != ORPHAN_CLEANUP_DONE)
3273 spin_lock(&root->orphan_lock);
3274 if (atomic_read(&root->orphan_inodes)) {
3275 spin_unlock(&root->orphan_lock);
3279 if (root->orphan_cleanup_state != ORPHAN_CLEANUP_DONE) {
3280 spin_unlock(&root->orphan_lock);
3284 block_rsv = root->orphan_block_rsv;
3285 root->orphan_block_rsv = NULL;
3286 spin_unlock(&root->orphan_lock);
3288 if (test_bit(BTRFS_ROOT_ORPHAN_ITEM_INSERTED, &root->state) &&
3289 btrfs_root_refs(&root->root_item) > 0) {
3290 ret = btrfs_del_orphan_item(trans, fs_info->tree_root,
3291 root->root_key.objectid);
3293 btrfs_abort_transaction(trans, ret);
3295 clear_bit(BTRFS_ROOT_ORPHAN_ITEM_INSERTED,
3300 WARN_ON(block_rsv->size > 0);
3301 btrfs_free_block_rsv(fs_info, block_rsv);
3306 * This creates an orphan entry for the given inode in case something goes
3307 * wrong in the middle of an unlink/truncate.
3309 * NOTE: caller of this function should reserve 5 units of metadata for
3312 int btrfs_orphan_add(struct btrfs_trans_handle *trans,
3313 struct btrfs_inode *inode)
3315 struct btrfs_fs_info *fs_info = btrfs_sb(inode->vfs_inode.i_sb);
3316 struct btrfs_root *root = inode->root;
3317 struct btrfs_block_rsv *block_rsv = NULL;
3322 if (!root->orphan_block_rsv) {
3323 block_rsv = btrfs_alloc_block_rsv(fs_info,
3324 BTRFS_BLOCK_RSV_TEMP);
3329 spin_lock(&root->orphan_lock);
3330 if (!root->orphan_block_rsv) {
3331 root->orphan_block_rsv = block_rsv;
3332 } else if (block_rsv) {
3333 btrfs_free_block_rsv(fs_info, block_rsv);
3337 if (!test_and_set_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
3338 &inode->runtime_flags)) {
3341 * For proper ENOSPC handling, we should do orphan
3342 * cleanup when mounting. But this introduces backward
3343 * compatibility issue.
3345 if (!xchg(&root->orphan_item_inserted, 1))
3351 atomic_inc(&root->orphan_inodes);
3354 if (!test_and_set_bit(BTRFS_INODE_ORPHAN_META_RESERVED,
3355 &inode->runtime_flags))
3357 spin_unlock(&root->orphan_lock);
3359 /* grab metadata reservation from transaction handle */
3361 ret = btrfs_orphan_reserve_metadata(trans, inode);
3364 atomic_dec(&root->orphan_inodes);
3365 clear_bit(BTRFS_INODE_ORPHAN_META_RESERVED,
3366 &inode->runtime_flags);
3368 clear_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
3369 &inode->runtime_flags);
3374 /* insert an orphan item to track this unlinked/truncated file */
3376 ret = btrfs_insert_orphan_item(trans, root, btrfs_ino(inode));
3378 atomic_dec(&root->orphan_inodes);
3380 clear_bit(BTRFS_INODE_ORPHAN_META_RESERVED,
3381 &inode->runtime_flags);
3382 btrfs_orphan_release_metadata(inode);
3384 if (ret != -EEXIST) {
3385 clear_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
3386 &inode->runtime_flags);
3387 btrfs_abort_transaction(trans, ret);
3394 /* insert an orphan item to track subvolume contains orphan files */
3396 ret = btrfs_insert_orphan_item(trans, fs_info->tree_root,
3397 root->root_key.objectid);
3398 if (ret && ret != -EEXIST) {
3399 btrfs_abort_transaction(trans, ret);
3407 * We have done the truncate/delete so we can go ahead and remove the orphan
3408 * item for this particular inode.
3410 static int btrfs_orphan_del(struct btrfs_trans_handle *trans,
3411 struct btrfs_inode *inode)
3413 struct btrfs_root *root = inode->root;
3414 int delete_item = 0;
3415 int release_rsv = 0;
3418 spin_lock(&root->orphan_lock);
3419 if (test_and_clear_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
3420 &inode->runtime_flags))
3423 if (test_and_clear_bit(BTRFS_INODE_ORPHAN_META_RESERVED,
3424 &inode->runtime_flags))
3426 spin_unlock(&root->orphan_lock);
3429 atomic_dec(&root->orphan_inodes);
3431 ret = btrfs_del_orphan_item(trans, root,
3436 btrfs_orphan_release_metadata(inode);
3442 * this cleans up any orphans that may be left on the list from the last use
3445 int btrfs_orphan_cleanup(struct btrfs_root *root)
3447 struct btrfs_fs_info *fs_info = root->fs_info;
3448 struct btrfs_path *path;
3449 struct extent_buffer *leaf;
3450 struct btrfs_key key, found_key;
3451 struct btrfs_trans_handle *trans;
3452 struct inode *inode;
3453 u64 last_objectid = 0;
3454 int ret = 0, nr_unlink = 0, nr_truncate = 0;
3456 if (cmpxchg(&root->orphan_cleanup_state, 0, ORPHAN_CLEANUP_STARTED))
3459 path = btrfs_alloc_path();
3464 path->reada = READA_BACK;
3466 key.objectid = BTRFS_ORPHAN_OBJECTID;
3467 key.type = BTRFS_ORPHAN_ITEM_KEY;
3468 key.offset = (u64)-1;
3471 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
3476 * if ret == 0 means we found what we were searching for, which
3477 * is weird, but possible, so only screw with path if we didn't
3478 * find the key and see if we have stuff that matches
3482 if (path->slots[0] == 0)
3487 /* pull out the item */
3488 leaf = path->nodes[0];
3489 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
3491 /* make sure the item matches what we want */
3492 if (found_key.objectid != BTRFS_ORPHAN_OBJECTID)
3494 if (found_key.type != BTRFS_ORPHAN_ITEM_KEY)
3497 /* release the path since we're done with it */
3498 btrfs_release_path(path);
3501 * this is where we are basically btrfs_lookup, without the
3502 * crossing root thing. we store the inode number in the
3503 * offset of the orphan item.
3506 if (found_key.offset == last_objectid) {
3508 "Error removing orphan entry, stopping orphan cleanup");
3513 last_objectid = found_key.offset;
3515 found_key.objectid = found_key.offset;
3516 found_key.type = BTRFS_INODE_ITEM_KEY;
3517 found_key.offset = 0;
3518 inode = btrfs_iget(fs_info->sb, &found_key, root, NULL);
3519 ret = PTR_ERR_OR_ZERO(inode);
3520 if (ret && ret != -ENOENT)
3523 if (ret == -ENOENT && root == fs_info->tree_root) {
3524 struct btrfs_root *dead_root;
3525 struct btrfs_fs_info *fs_info = root->fs_info;
3526 int is_dead_root = 0;
3529 * this is an orphan in the tree root. Currently these
3530 * could come from 2 sources:
3531 * a) a snapshot deletion in progress
3532 * b) a free space cache inode
3533 * We need to distinguish those two, as the snapshot
3534 * orphan must not get deleted.
3535 * find_dead_roots already ran before us, so if this
3536 * is a snapshot deletion, we should find the root
3537 * in the dead_roots list
3539 spin_lock(&fs_info->trans_lock);
3540 list_for_each_entry(dead_root, &fs_info->dead_roots,
3542 if (dead_root->root_key.objectid ==
3543 found_key.objectid) {
3548 spin_unlock(&fs_info->trans_lock);
3550 /* prevent this orphan from being found again */
3551 key.offset = found_key.objectid - 1;
3556 * Inode is already gone but the orphan item is still there,
3557 * kill the orphan item.
3559 if (ret == -ENOENT) {
3560 trans = btrfs_start_transaction(root, 1);
3561 if (IS_ERR(trans)) {
3562 ret = PTR_ERR(trans);
3565 btrfs_debug(fs_info, "auto deleting %Lu",
3566 found_key.objectid);
3567 ret = btrfs_del_orphan_item(trans, root,
3568 found_key.objectid);
3569 btrfs_end_transaction(trans);
3576 * add this inode to the orphan list so btrfs_orphan_del does
3577 * the proper thing when we hit it
3579 set_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
3580 &BTRFS_I(inode)->runtime_flags);
3581 atomic_inc(&root->orphan_inodes);
3583 /* if we have links, this was a truncate, lets do that */
3584 if (inode->i_nlink) {
3585 if (WARN_ON(!S_ISREG(inode->i_mode))) {
3591 /* 1 for the orphan item deletion. */
3592 trans = btrfs_start_transaction(root, 1);
3593 if (IS_ERR(trans)) {
3595 ret = PTR_ERR(trans);
3598 ret = btrfs_orphan_add(trans, BTRFS_I(inode));
3599 btrfs_end_transaction(trans);
3605 ret = btrfs_truncate(inode);
3607 btrfs_orphan_del(NULL, BTRFS_I(inode));
3612 /* this will do delete_inode and everything for us */
3617 /* release the path since we're done with it */
3618 btrfs_release_path(path);
3620 root->orphan_cleanup_state = ORPHAN_CLEANUP_DONE;
3622 if (root->orphan_block_rsv)
3623 btrfs_block_rsv_release(fs_info, root->orphan_block_rsv,
3626 if (root->orphan_block_rsv ||
3627 test_bit(BTRFS_ROOT_ORPHAN_ITEM_INSERTED, &root->state)) {
3628 trans = btrfs_join_transaction(root);
3630 btrfs_end_transaction(trans);
3634 btrfs_debug(fs_info, "unlinked %d orphans", nr_unlink);
3636 btrfs_debug(fs_info, "truncated %d orphans", nr_truncate);
3640 btrfs_err(fs_info, "could not do orphan cleanup %d", ret);
3641 btrfs_free_path(path);
3646 * very simple check to peek ahead in the leaf looking for xattrs. If we
3647 * don't find any xattrs, we know there can't be any acls.
3649 * slot is the slot the inode is in, objectid is the objectid of the inode
3651 static noinline int acls_after_inode_item(struct extent_buffer *leaf,
3652 int slot, u64 objectid,
3653 int *first_xattr_slot)
3655 u32 nritems = btrfs_header_nritems(leaf);
3656 struct btrfs_key found_key;
3657 static u64 xattr_access = 0;
3658 static u64 xattr_default = 0;
3661 if (!xattr_access) {
3662 xattr_access = btrfs_name_hash(XATTR_NAME_POSIX_ACL_ACCESS,
3663 strlen(XATTR_NAME_POSIX_ACL_ACCESS));
3664 xattr_default = btrfs_name_hash(XATTR_NAME_POSIX_ACL_DEFAULT,
3665 strlen(XATTR_NAME_POSIX_ACL_DEFAULT));
3669 *first_xattr_slot = -1;
3670 while (slot < nritems) {
3671 btrfs_item_key_to_cpu(leaf, &found_key, slot);
3673 /* we found a different objectid, there must not be acls */
3674 if (found_key.objectid != objectid)
3677 /* we found an xattr, assume we've got an acl */
3678 if (found_key.type == BTRFS_XATTR_ITEM_KEY) {
3679 if (*first_xattr_slot == -1)
3680 *first_xattr_slot = slot;
3681 if (found_key.offset == xattr_access ||
3682 found_key.offset == xattr_default)
3687 * we found a key greater than an xattr key, there can't
3688 * be any acls later on
3690 if (found_key.type > BTRFS_XATTR_ITEM_KEY)
3697 * it goes inode, inode backrefs, xattrs, extents,
3698 * so if there are a ton of hard links to an inode there can
3699 * be a lot of backrefs. Don't waste time searching too hard,
3700 * this is just an optimization
3705 /* we hit the end of the leaf before we found an xattr or
3706 * something larger than an xattr. We have to assume the inode
3709 if (*first_xattr_slot == -1)
3710 *first_xattr_slot = slot;
3715 * read an inode from the btree into the in-memory inode
3717 static int btrfs_read_locked_inode(struct inode *inode)
3719 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
3720 struct btrfs_path *path;
3721 struct extent_buffer *leaf;
3722 struct btrfs_inode_item *inode_item;
3723 struct btrfs_root *root = BTRFS_I(inode)->root;
3724 struct btrfs_key location;
3729 bool filled = false;
3730 int first_xattr_slot;
3732 ret = btrfs_fill_inode(inode, &rdev);
3736 path = btrfs_alloc_path();
3742 memcpy(&location, &BTRFS_I(inode)->location, sizeof(location));
3744 ret = btrfs_lookup_inode(NULL, root, path, &location, 0);
3751 leaf = path->nodes[0];
3756 inode_item = btrfs_item_ptr(leaf, path->slots[0],
3757 struct btrfs_inode_item);
3758 inode->i_mode = btrfs_inode_mode(leaf, inode_item);
3759 set_nlink(inode, btrfs_inode_nlink(leaf, inode_item));
3760 i_uid_write(inode, btrfs_inode_uid(leaf, inode_item));
3761 i_gid_write(inode, btrfs_inode_gid(leaf, inode_item));
3762 btrfs_i_size_write(BTRFS_I(inode), btrfs_inode_size(leaf, inode_item));
3764 inode->i_atime.tv_sec = btrfs_timespec_sec(leaf, &inode_item->atime);
3765 inode->i_atime.tv_nsec = btrfs_timespec_nsec(leaf, &inode_item->atime);
3767 inode->i_mtime.tv_sec = btrfs_timespec_sec(leaf, &inode_item->mtime);
3768 inode->i_mtime.tv_nsec = btrfs_timespec_nsec(leaf, &inode_item->mtime);
3770 inode->i_ctime.tv_sec = btrfs_timespec_sec(leaf, &inode_item->ctime);
3771 inode->i_ctime.tv_nsec = btrfs_timespec_nsec(leaf, &inode_item->ctime);
3773 BTRFS_I(inode)->i_otime.tv_sec =
3774 btrfs_timespec_sec(leaf, &inode_item->otime);
3775 BTRFS_I(inode)->i_otime.tv_nsec =
3776 btrfs_timespec_nsec(leaf, &inode_item->otime);
3778 inode_set_bytes(inode, btrfs_inode_nbytes(leaf, inode_item));
3779 BTRFS_I(inode)->generation = btrfs_inode_generation(leaf, inode_item);
3780 BTRFS_I(inode)->last_trans = btrfs_inode_transid(leaf, inode_item);
3782 inode->i_version = btrfs_inode_sequence(leaf, inode_item);
3783 inode->i_generation = BTRFS_I(inode)->generation;
3785 rdev = btrfs_inode_rdev(leaf, inode_item);
3787 BTRFS_I(inode)->index_cnt = (u64)-1;
3788 BTRFS_I(inode)->flags = btrfs_inode_flags(leaf, inode_item);
3792 * If we were modified in the current generation and evicted from memory
3793 * and then re-read we need to do a full sync since we don't have any
3794 * idea about which extents were modified before we were evicted from
3797 * This is required for both inode re-read from disk and delayed inode
3798 * in delayed_nodes_tree.
3800 if (BTRFS_I(inode)->last_trans == fs_info->generation)
3801 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
3802 &BTRFS_I(inode)->runtime_flags);
3805 * We don't persist the id of the transaction where an unlink operation
3806 * against the inode was last made. So here we assume the inode might
3807 * have been evicted, and therefore the exact value of last_unlink_trans
3808 * lost, and set it to last_trans to avoid metadata inconsistencies
3809 * between the inode and its parent if the inode is fsync'ed and the log
3810 * replayed. For example, in the scenario:
3813 * ln mydir/foo mydir/bar
3816 * echo 2 > /proc/sys/vm/drop_caches # evicts inode
3817 * xfs_io -c fsync mydir/foo
3819 * mount fs, triggers fsync log replay
3821 * We must make sure that when we fsync our inode foo we also log its
3822 * parent inode, otherwise after log replay the parent still has the
3823 * dentry with the "bar" name but our inode foo has a link count of 1
3824 * and doesn't have an inode ref with the name "bar" anymore.
3826 * Setting last_unlink_trans to last_trans is a pessimistic approach,
3827 * but it guarantees correctness at the expense of occasional full
3828 * transaction commits on fsync if our inode is a directory, or if our
3829 * inode is not a directory, logging its parent unnecessarily.
3831 BTRFS_I(inode)->last_unlink_trans = BTRFS_I(inode)->last_trans;
3834 if (inode->i_nlink != 1 ||
3835 path->slots[0] >= btrfs_header_nritems(leaf))
3838 btrfs_item_key_to_cpu(leaf, &location, path->slots[0]);
3839 if (location.objectid != btrfs_ino(BTRFS_I(inode)))
3842 ptr = btrfs_item_ptr_offset(leaf, path->slots[0]);
3843 if (location.type == BTRFS_INODE_REF_KEY) {
3844 struct btrfs_inode_ref *ref;
3846 ref = (struct btrfs_inode_ref *)ptr;
3847 BTRFS_I(inode)->dir_index = btrfs_inode_ref_index(leaf, ref);
3848 } else if (location.type == BTRFS_INODE_EXTREF_KEY) {
3849 struct btrfs_inode_extref *extref;
3851 extref = (struct btrfs_inode_extref *)ptr;
3852 BTRFS_I(inode)->dir_index = btrfs_inode_extref_index(leaf,
3857 * try to precache a NULL acl entry for files that don't have
3858 * any xattrs or acls
3860 maybe_acls = acls_after_inode_item(leaf, path->slots[0],
3861 btrfs_ino(BTRFS_I(inode)), &first_xattr_slot);
3862 if (first_xattr_slot != -1) {
3863 path->slots[0] = first_xattr_slot;
3864 ret = btrfs_load_inode_props(inode, path);
3867 "error loading props for ino %llu (root %llu): %d",
3868 btrfs_ino(BTRFS_I(inode)),
3869 root->root_key.objectid, ret);
3871 btrfs_free_path(path);
3874 cache_no_acl(inode);
3876 switch (inode->i_mode & S_IFMT) {
3878 inode->i_mapping->a_ops = &btrfs_aops;
3879 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
3880 inode->i_fop = &btrfs_file_operations;
3881 inode->i_op = &btrfs_file_inode_operations;
3884 inode->i_fop = &btrfs_dir_file_operations;
3885 inode->i_op = &btrfs_dir_inode_operations;
3888 inode->i_op = &btrfs_symlink_inode_operations;
3889 inode_nohighmem(inode);
3890 inode->i_mapping->a_ops = &btrfs_symlink_aops;
3893 inode->i_op = &btrfs_special_inode_operations;
3894 init_special_inode(inode, inode->i_mode, rdev);
3898 btrfs_update_iflags(inode);
3902 btrfs_free_path(path);
3903 make_bad_inode(inode);
3908 * given a leaf and an inode, copy the inode fields into the leaf
3910 static void fill_inode_item(struct btrfs_trans_handle *trans,
3911 struct extent_buffer *leaf,
3912 struct btrfs_inode_item *item,
3913 struct inode *inode)
3915 struct btrfs_map_token token;
3917 btrfs_init_map_token(&token);
3919 btrfs_set_token_inode_uid(leaf, item, i_uid_read(inode), &token);
3920 btrfs_set_token_inode_gid(leaf, item, i_gid_read(inode), &token);
3921 btrfs_set_token_inode_size(leaf, item, BTRFS_I(inode)->disk_i_size,
3923 btrfs_set_token_inode_mode(leaf, item, inode->i_mode, &token);
3924 btrfs_set_token_inode_nlink(leaf, item, inode->i_nlink, &token);
3926 btrfs_set_token_timespec_sec(leaf, &item->atime,
3927 inode->i_atime.tv_sec, &token);
3928 btrfs_set_token_timespec_nsec(leaf, &item->atime,
3929 inode->i_atime.tv_nsec, &token);
3931 btrfs_set_token_timespec_sec(leaf, &item->mtime,
3932 inode->i_mtime.tv_sec, &token);
3933 btrfs_set_token_timespec_nsec(leaf, &item->mtime,
3934 inode->i_mtime.tv_nsec, &token);
3936 btrfs_set_token_timespec_sec(leaf, &item->ctime,
3937 inode->i_ctime.tv_sec, &token);
3938 btrfs_set_token_timespec_nsec(leaf, &item->ctime,
3939 inode->i_ctime.tv_nsec, &token);
3941 btrfs_set_token_timespec_sec(leaf, &item->otime,
3942 BTRFS_I(inode)->i_otime.tv_sec, &token);
3943 btrfs_set_token_timespec_nsec(leaf, &item->otime,
3944 BTRFS_I(inode)->i_otime.tv_nsec, &token);
3946 btrfs_set_token_inode_nbytes(leaf, item, inode_get_bytes(inode),
3948 btrfs_set_token_inode_generation(leaf, item, BTRFS_I(inode)->generation,
3950 btrfs_set_token_inode_sequence(leaf, item, inode->i_version, &token);
3951 btrfs_set_token_inode_transid(leaf, item, trans->transid, &token);
3952 btrfs_set_token_inode_rdev(leaf, item, inode->i_rdev, &token);
3953 btrfs_set_token_inode_flags(leaf, item, BTRFS_I(inode)->flags, &token);
3954 btrfs_set_token_inode_block_group(leaf, item, 0, &token);
3958 * copy everything in the in-memory inode into the btree.
3960 static noinline int btrfs_update_inode_item(struct btrfs_trans_handle *trans,
3961 struct btrfs_root *root, struct inode *inode)
3963 struct btrfs_inode_item *inode_item;
3964 struct btrfs_path *path;
3965 struct extent_buffer *leaf;
3968 path = btrfs_alloc_path();
3972 path->leave_spinning = 1;
3973 ret = btrfs_lookup_inode(trans, root, path, &BTRFS_I(inode)->location,
3981 leaf = path->nodes[0];
3982 inode_item = btrfs_item_ptr(leaf, path->slots[0],
3983 struct btrfs_inode_item);
3985 fill_inode_item(trans, leaf, inode_item, inode);
3986 btrfs_mark_buffer_dirty(leaf);
3987 btrfs_set_inode_last_trans(trans, inode);
3990 btrfs_free_path(path);
3995 * copy everything in the in-memory inode into the btree.
3997 noinline int btrfs_update_inode(struct btrfs_trans_handle *trans,
3998 struct btrfs_root *root, struct inode *inode)
4000 struct btrfs_fs_info *fs_info = root->fs_info;
4004 * If the inode is a free space inode, we can deadlock during commit
4005 * if we put it into the delayed code.
4007 * The data relocation inode should also be directly updated
4010 if (!btrfs_is_free_space_inode(BTRFS_I(inode))
4011 && root->root_key.objectid != BTRFS_DATA_RELOC_TREE_OBJECTID
4012 && !test_bit(BTRFS_FS_LOG_RECOVERING, &fs_info->flags)) {
4013 btrfs_update_root_times(trans, root);
4015 ret = btrfs_delayed_update_inode(trans, root, inode);
4017 btrfs_set_inode_last_trans(trans, inode);
4021 return btrfs_update_inode_item(trans, root, inode);
4024 noinline int btrfs_update_inode_fallback(struct btrfs_trans_handle *trans,
4025 struct btrfs_root *root,
4026 struct inode *inode)
4030 ret = btrfs_update_inode(trans, root, inode);
4032 return btrfs_update_inode_item(trans, root, inode);
4037 * unlink helper that gets used here in inode.c and in the tree logging
4038 * recovery code. It remove a link in a directory with a given name, and
4039 * also drops the back refs in the inode to the directory
4041 static int __btrfs_unlink_inode(struct btrfs_trans_handle *trans,
4042 struct btrfs_root *root,
4043 struct btrfs_inode *dir,
4044 struct btrfs_inode *inode,
4045 const char *name, int name_len)
4047 struct btrfs_fs_info *fs_info = root->fs_info;
4048 struct btrfs_path *path;
4050 struct extent_buffer *leaf;
4051 struct btrfs_dir_item *di;
4052 struct btrfs_key key;
4054 u64 ino = btrfs_ino(inode);
4055 u64 dir_ino = btrfs_ino(dir);
4057 path = btrfs_alloc_path();
4063 path->leave_spinning = 1;
4064 di = btrfs_lookup_dir_item(trans, root, path, dir_ino,
4065 name, name_len, -1);
4074 leaf = path->nodes[0];
4075 btrfs_dir_item_key_to_cpu(leaf, di, &key);
4076 ret = btrfs_delete_one_dir_name(trans, root, path, di);
4079 btrfs_release_path(path);
4082 * If we don't have dir index, we have to get it by looking up
4083 * the inode ref, since we get the inode ref, remove it directly,
4084 * it is unnecessary to do delayed deletion.
4086 * But if we have dir index, needn't search inode ref to get it.
4087 * Since the inode ref is close to the inode item, it is better
4088 * that we delay to delete it, and just do this deletion when
4089 * we update the inode item.
4091 if (inode->dir_index) {
4092 ret = btrfs_delayed_delete_inode_ref(inode);
4094 index = inode->dir_index;
4099 ret = btrfs_del_inode_ref(trans, root, name, name_len, ino,
4103 "failed to delete reference to %.*s, inode %llu parent %llu",
4104 name_len, name, ino, dir_ino);
4105 btrfs_abort_transaction(trans, ret);
4109 ret = btrfs_delete_delayed_dir_index(trans, fs_info, dir, index);
4111 btrfs_abort_transaction(trans, ret);
4115 ret = btrfs_del_inode_ref_in_log(trans, root, name, name_len, inode,
4117 if (ret != 0 && ret != -ENOENT) {
4118 btrfs_abort_transaction(trans, ret);
4122 ret = btrfs_del_dir_entries_in_log(trans, root, name, name_len, dir,
4127 btrfs_abort_transaction(trans, ret);
4129 btrfs_free_path(path);
4133 btrfs_i_size_write(dir, dir->vfs_inode.i_size - name_len * 2);
4134 inode_inc_iversion(&inode->vfs_inode);
4135 inode_inc_iversion(&dir->vfs_inode);
4136 inode->vfs_inode.i_ctime = dir->vfs_inode.i_mtime =
4137 dir->vfs_inode.i_ctime = current_time(&inode->vfs_inode);
4138 ret = btrfs_update_inode(trans, root, &dir->vfs_inode);
4143 int btrfs_unlink_inode(struct btrfs_trans_handle *trans,
4144 struct btrfs_root *root,
4145 struct btrfs_inode *dir, struct btrfs_inode *inode,
4146 const char *name, int name_len)
4149 ret = __btrfs_unlink_inode(trans, root, dir, inode, name, name_len);
4151 drop_nlink(&inode->vfs_inode);
4152 ret = btrfs_update_inode(trans, root, &inode->vfs_inode);
4158 * helper to start transaction for unlink and rmdir.
4160 * unlink and rmdir are special in btrfs, they do not always free space, so
4161 * if we cannot make our reservations the normal way try and see if there is
4162 * plenty of slack room in the global reserve to migrate, otherwise we cannot
4163 * allow the unlink to occur.
4165 static struct btrfs_trans_handle *__unlink_start_trans(struct inode *dir)
4167 struct btrfs_root *root = BTRFS_I(dir)->root;
4170 * 1 for the possible orphan item
4171 * 1 for the dir item
4172 * 1 for the dir index
4173 * 1 for the inode ref
4176 return btrfs_start_transaction_fallback_global_rsv(root, 5, 5);
4179 static int btrfs_unlink(struct inode *dir, struct dentry *dentry)
4181 struct btrfs_root *root = BTRFS_I(dir)->root;
4182 struct btrfs_trans_handle *trans;
4183 struct inode *inode = d_inode(dentry);
4186 trans = __unlink_start_trans(dir);
4188 return PTR_ERR(trans);
4190 btrfs_record_unlink_dir(trans, BTRFS_I(dir), BTRFS_I(d_inode(dentry)),
4193 ret = btrfs_unlink_inode(trans, root, BTRFS_I(dir),
4194 BTRFS_I(d_inode(dentry)), dentry->d_name.name,
4195 dentry->d_name.len);
4199 if (inode->i_nlink == 0) {
4200 ret = btrfs_orphan_add(trans, BTRFS_I(inode));
4206 btrfs_end_transaction(trans);
4207 btrfs_btree_balance_dirty(root->fs_info);
4211 int btrfs_unlink_subvol(struct btrfs_trans_handle *trans,
4212 struct btrfs_root *root,
4213 struct inode *dir, u64 objectid,
4214 const char *name, int name_len)
4216 struct btrfs_fs_info *fs_info = root->fs_info;
4217 struct btrfs_path *path;
4218 struct extent_buffer *leaf;
4219 struct btrfs_dir_item *di;
4220 struct btrfs_key key;
4223 u64 dir_ino = btrfs_ino(BTRFS_I(dir));
4225 path = btrfs_alloc_path();
4229 di = btrfs_lookup_dir_item(trans, root, path, dir_ino,
4230 name, name_len, -1);
4231 if (IS_ERR_OR_NULL(di)) {
4239 leaf = path->nodes[0];
4240 btrfs_dir_item_key_to_cpu(leaf, di, &key);
4241 WARN_ON(key.type != BTRFS_ROOT_ITEM_KEY || key.objectid != objectid);
4242 ret = btrfs_delete_one_dir_name(trans, root, path, di);
4244 btrfs_abort_transaction(trans, ret);
4247 btrfs_release_path(path);
4249 ret = btrfs_del_root_ref(trans, fs_info, objectid,
4250 root->root_key.objectid, dir_ino,
4251 &index, name, name_len);
4253 if (ret != -ENOENT) {
4254 btrfs_abort_transaction(trans, ret);
4257 di = btrfs_search_dir_index_item(root, path, dir_ino,
4259 if (IS_ERR_OR_NULL(di)) {
4264 btrfs_abort_transaction(trans, ret);
4268 leaf = path->nodes[0];
4269 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
4270 btrfs_release_path(path);
4273 btrfs_release_path(path);
4275 ret = btrfs_delete_delayed_dir_index(trans, fs_info, BTRFS_I(dir), index);
4277 btrfs_abort_transaction(trans, ret);
4281 btrfs_i_size_write(BTRFS_I(dir), dir->i_size - name_len * 2);
4282 inode_inc_iversion(dir);
4283 dir->i_mtime = dir->i_ctime = current_time(dir);
4284 ret = btrfs_update_inode_fallback(trans, root, dir);
4286 btrfs_abort_transaction(trans, ret);
4288 btrfs_free_path(path);
4292 static int btrfs_rmdir(struct inode *dir, struct dentry *dentry)
4294 struct inode *inode = d_inode(dentry);
4296 struct btrfs_root *root = BTRFS_I(dir)->root;
4297 struct btrfs_trans_handle *trans;
4298 u64 last_unlink_trans;
4300 if (inode->i_size > BTRFS_EMPTY_DIR_SIZE)
4302 if (btrfs_ino(BTRFS_I(inode)) == BTRFS_FIRST_FREE_OBJECTID)
4305 trans = __unlink_start_trans(dir);
4307 return PTR_ERR(trans);
4309 if (unlikely(btrfs_ino(BTRFS_I(inode)) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)) {
4310 err = btrfs_unlink_subvol(trans, root, dir,
4311 BTRFS_I(inode)->location.objectid,
4312 dentry->d_name.name,
4313 dentry->d_name.len);
4317 err = btrfs_orphan_add(trans, BTRFS_I(inode));
4321 last_unlink_trans = BTRFS_I(inode)->last_unlink_trans;
4323 /* now the directory is empty */
4324 err = btrfs_unlink_inode(trans, root, BTRFS_I(dir),
4325 BTRFS_I(d_inode(dentry)), dentry->d_name.name,
4326 dentry->d_name.len);
4328 btrfs_i_size_write(BTRFS_I(inode), 0);
4330 * Propagate the last_unlink_trans value of the deleted dir to
4331 * its parent directory. This is to prevent an unrecoverable
4332 * log tree in the case we do something like this:
4334 * 2) create snapshot under dir foo
4335 * 3) delete the snapshot
4338 * 6) fsync foo or some file inside foo
4340 if (last_unlink_trans >= trans->transid)
4341 BTRFS_I(dir)->last_unlink_trans = last_unlink_trans;
4344 btrfs_end_transaction(trans);
4345 btrfs_btree_balance_dirty(root->fs_info);
4350 static int truncate_space_check(struct btrfs_trans_handle *trans,
4351 struct btrfs_root *root,
4354 struct btrfs_fs_info *fs_info = root->fs_info;
4358 * This is only used to apply pressure to the enospc system, we don't
4359 * intend to use this reservation at all.
4361 bytes_deleted = btrfs_csum_bytes_to_leaves(fs_info, bytes_deleted);
4362 bytes_deleted *= fs_info->nodesize;
4363 ret = btrfs_block_rsv_add(root, &fs_info->trans_block_rsv,
4364 bytes_deleted, BTRFS_RESERVE_NO_FLUSH);
4366 trace_btrfs_space_reservation(fs_info, "transaction",
4369 trans->bytes_reserved += bytes_deleted;
4375 static int truncate_inline_extent(struct inode *inode,
4376 struct btrfs_path *path,
4377 struct btrfs_key *found_key,
4381 struct extent_buffer *leaf = path->nodes[0];
4382 int slot = path->slots[0];
4383 struct btrfs_file_extent_item *fi;
4384 u32 size = (u32)(new_size - found_key->offset);
4385 struct btrfs_root *root = BTRFS_I(inode)->root;
4387 fi = btrfs_item_ptr(leaf, slot, struct btrfs_file_extent_item);
4389 if (btrfs_file_extent_compression(leaf, fi) != BTRFS_COMPRESS_NONE) {
4390 loff_t offset = new_size;
4391 loff_t page_end = ALIGN(offset, PAGE_SIZE);
4394 * Zero out the remaining of the last page of our inline extent,
4395 * instead of directly truncating our inline extent here - that
4396 * would be much more complex (decompressing all the data, then
4397 * compressing the truncated data, which might be bigger than
4398 * the size of the inline extent, resize the extent, etc).
4399 * We release the path because to get the page we might need to
4400 * read the extent item from disk (data not in the page cache).
4402 btrfs_release_path(path);
4403 return btrfs_truncate_block(inode, offset, page_end - offset,
4407 btrfs_set_file_extent_ram_bytes(leaf, fi, size);
4408 size = btrfs_file_extent_calc_inline_size(size);
4409 btrfs_truncate_item(root->fs_info, path, size, 1);
4411 if (test_bit(BTRFS_ROOT_REF_COWS, &root->state))
4412 inode_sub_bytes(inode, item_end + 1 - new_size);
4418 * this can truncate away extent items, csum items and directory items.
4419 * It starts at a high offset and removes keys until it can't find
4420 * any higher than new_size
4422 * csum items that cross the new i_size are truncated to the new size
4425 * min_type is the minimum key type to truncate down to. If set to 0, this
4426 * will kill all the items on this inode, including the INODE_ITEM_KEY.
4428 int btrfs_truncate_inode_items(struct btrfs_trans_handle *trans,
4429 struct btrfs_root *root,
4430 struct inode *inode,
4431 u64 new_size, u32 min_type)
4433 struct btrfs_fs_info *fs_info = root->fs_info;
4434 struct btrfs_path *path;
4435 struct extent_buffer *leaf;
4436 struct btrfs_file_extent_item *fi;
4437 struct btrfs_key key;
4438 struct btrfs_key found_key;
4439 u64 extent_start = 0;
4440 u64 extent_num_bytes = 0;
4441 u64 extent_offset = 0;
4443 u64 last_size = new_size;
4444 u32 found_type = (u8)-1;
4447 int pending_del_nr = 0;
4448 int pending_del_slot = 0;
4449 int extent_type = -1;
4452 u64 ino = btrfs_ino(BTRFS_I(inode));
4453 u64 bytes_deleted = 0;
4455 bool should_throttle = 0;
4456 bool should_end = 0;
4458 BUG_ON(new_size > 0 && min_type != BTRFS_EXTENT_DATA_KEY);
4461 * for non-free space inodes and ref cows, we want to back off from
4464 if (!btrfs_is_free_space_inode(BTRFS_I(inode)) &&
4465 test_bit(BTRFS_ROOT_REF_COWS, &root->state))
4468 path = btrfs_alloc_path();
4471 path->reada = READA_BACK;
4474 * We want to drop from the next block forward in case this new size is
4475 * not block aligned since we will be keeping the last block of the
4476 * extent just the way it is.
4478 if (test_bit(BTRFS_ROOT_REF_COWS, &root->state) ||
4479 root == fs_info->tree_root)
4480 btrfs_drop_extent_cache(BTRFS_I(inode), ALIGN(new_size,
4481 fs_info->sectorsize),
4485 * This function is also used to drop the items in the log tree before
4486 * we relog the inode, so if root != BTRFS_I(inode)->root, it means
4487 * it is used to drop the loged items. So we shouldn't kill the delayed
4490 if (min_type == 0 && root == BTRFS_I(inode)->root)
4491 btrfs_kill_delayed_inode_items(BTRFS_I(inode));
4494 key.offset = (u64)-1;
4499 * with a 16K leaf size and 128MB extents, you can actually queue
4500 * up a huge file in a single leaf. Most of the time that
4501 * bytes_deleted is > 0, it will be huge by the time we get here
4503 if (be_nice && bytes_deleted > SZ_32M) {
4504 if (btrfs_should_end_transaction(trans)) {
4511 path->leave_spinning = 1;
4512 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
4519 /* there are no items in the tree for us to truncate, we're
4522 if (path->slots[0] == 0)
4529 leaf = path->nodes[0];
4530 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
4531 found_type = found_key.type;
4533 if (found_key.objectid != ino)
4536 if (found_type < min_type)
4539 item_end = found_key.offset;
4540 if (found_type == BTRFS_EXTENT_DATA_KEY) {
4541 fi = btrfs_item_ptr(leaf, path->slots[0],
4542 struct btrfs_file_extent_item);
4543 extent_type = btrfs_file_extent_type(leaf, fi);
4544 if (extent_type != BTRFS_FILE_EXTENT_INLINE) {
4546 btrfs_file_extent_num_bytes(leaf, fi);
4548 trace_btrfs_truncate_show_fi_regular(
4549 BTRFS_I(inode), leaf, fi,
4551 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
4552 item_end += btrfs_file_extent_inline_len(leaf,
4553 path->slots[0], fi);
4555 trace_btrfs_truncate_show_fi_inline(
4556 BTRFS_I(inode), leaf, fi, path->slots[0],
4561 if (found_type > min_type) {
4564 if (item_end < new_size)
4566 if (found_key.offset >= new_size)
4572 /* FIXME, shrink the extent if the ref count is only 1 */
4573 if (found_type != BTRFS_EXTENT_DATA_KEY)
4577 last_size = found_key.offset;
4579 last_size = new_size;
4581 if (extent_type != BTRFS_FILE_EXTENT_INLINE) {
4583 extent_start = btrfs_file_extent_disk_bytenr(leaf, fi);
4585 u64 orig_num_bytes =
4586 btrfs_file_extent_num_bytes(leaf, fi);
4587 extent_num_bytes = ALIGN(new_size -
4589 fs_info->sectorsize);
4590 btrfs_set_file_extent_num_bytes(leaf, fi,
4592 num_dec = (orig_num_bytes -
4594 if (test_bit(BTRFS_ROOT_REF_COWS,
4597 inode_sub_bytes(inode, num_dec);
4598 btrfs_mark_buffer_dirty(leaf);
4601 btrfs_file_extent_disk_num_bytes(leaf,
4603 extent_offset = found_key.offset -
4604 btrfs_file_extent_offset(leaf, fi);
4606 /* FIXME blocksize != 4096 */
4607 num_dec = btrfs_file_extent_num_bytes(leaf, fi);
4608 if (extent_start != 0) {
4610 if (test_bit(BTRFS_ROOT_REF_COWS,
4612 inode_sub_bytes(inode, num_dec);
4615 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
4617 * we can't truncate inline items that have had
4621 btrfs_file_extent_encryption(leaf, fi) == 0 &&
4622 btrfs_file_extent_other_encoding(leaf, fi) == 0) {
4625 * Need to release path in order to truncate a
4626 * compressed extent. So delete any accumulated
4627 * extent items so far.
4629 if (btrfs_file_extent_compression(leaf, fi) !=
4630 BTRFS_COMPRESS_NONE && pending_del_nr) {
4631 err = btrfs_del_items(trans, root, path,
4635 btrfs_abort_transaction(trans,
4642 err = truncate_inline_extent(inode, path,
4647 btrfs_abort_transaction(trans, err);
4650 } else if (test_bit(BTRFS_ROOT_REF_COWS,
4652 inode_sub_bytes(inode, item_end + 1 - new_size);
4657 if (!pending_del_nr) {
4658 /* no pending yet, add ourselves */
4659 pending_del_slot = path->slots[0];
4661 } else if (pending_del_nr &&
4662 path->slots[0] + 1 == pending_del_slot) {
4663 /* hop on the pending chunk */
4665 pending_del_slot = path->slots[0];
4672 should_throttle = 0;
4675 (test_bit(BTRFS_ROOT_REF_COWS, &root->state) ||
4676 root == fs_info->tree_root)) {
4677 btrfs_set_path_blocking(path);
4678 bytes_deleted += extent_num_bytes;
4679 ret = btrfs_free_extent(trans, fs_info, extent_start,
4680 extent_num_bytes, 0,
4681 btrfs_header_owner(leaf),
4682 ino, extent_offset);
4684 if (btrfs_should_throttle_delayed_refs(trans, fs_info))
4685 btrfs_async_run_delayed_refs(fs_info,
4686 trans->delayed_ref_updates * 2,
4689 if (truncate_space_check(trans, root,
4690 extent_num_bytes)) {
4693 if (btrfs_should_throttle_delayed_refs(trans,
4695 should_throttle = 1;
4699 if (found_type == BTRFS_INODE_ITEM_KEY)
4702 if (path->slots[0] == 0 ||
4703 path->slots[0] != pending_del_slot ||
4704 should_throttle || should_end) {
4705 if (pending_del_nr) {
4706 ret = btrfs_del_items(trans, root, path,
4710 btrfs_abort_transaction(trans, ret);
4715 btrfs_release_path(path);
4716 if (should_throttle) {
4717 unsigned long updates = trans->delayed_ref_updates;
4719 trans->delayed_ref_updates = 0;
4720 ret = btrfs_run_delayed_refs(trans,
4728 * if we failed to refill our space rsv, bail out
4729 * and let the transaction restart
4741 if (pending_del_nr) {
4742 ret = btrfs_del_items(trans, root, path, pending_del_slot,
4745 btrfs_abort_transaction(trans, ret);
4748 if (root->root_key.objectid != BTRFS_TREE_LOG_OBJECTID) {
4749 ASSERT(last_size >= new_size);
4750 if (!err && last_size > new_size)
4751 last_size = new_size;
4752 btrfs_ordered_update_i_size(inode, last_size, NULL);
4755 btrfs_free_path(path);
4757 if (be_nice && bytes_deleted > SZ_32M) {
4758 unsigned long updates = trans->delayed_ref_updates;
4760 trans->delayed_ref_updates = 0;
4761 ret = btrfs_run_delayed_refs(trans, fs_info,
4771 * btrfs_truncate_block - read, zero a chunk and write a block
4772 * @inode - inode that we're zeroing
4773 * @from - the offset to start zeroing
4774 * @len - the length to zero, 0 to zero the entire range respective to the
4776 * @front - zero up to the offset instead of from the offset on
4778 * This will find the block for the "from" offset and cow the block and zero the
4779 * part we want to zero. This is used with truncate and hole punching.
4781 int btrfs_truncate_block(struct inode *inode, loff_t from, loff_t len,
4784 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
4785 struct address_space *mapping = inode->i_mapping;
4786 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
4787 struct btrfs_ordered_extent *ordered;
4788 struct extent_state *cached_state = NULL;
4789 struct extent_changeset *data_reserved = NULL;
4791 u32 blocksize = fs_info->sectorsize;
4792 pgoff_t index = from >> PAGE_SHIFT;
4793 unsigned offset = from & (blocksize - 1);
4795 gfp_t mask = btrfs_alloc_write_mask(mapping);
4800 if ((offset & (blocksize - 1)) == 0 &&
4801 (!len || ((len & (blocksize - 1)) == 0)))
4804 ret = btrfs_delalloc_reserve_space(inode, &data_reserved,
4805 round_down(from, blocksize), blocksize);
4810 page = find_or_create_page(mapping, index, mask);
4812 btrfs_delalloc_release_space(inode, data_reserved,
4813 round_down(from, blocksize),
4819 block_start = round_down(from, blocksize);
4820 block_end = block_start + blocksize - 1;
4822 if (!PageUptodate(page)) {
4823 ret = btrfs_readpage(NULL, page);
4825 if (page->mapping != mapping) {
4830 if (!PageUptodate(page)) {
4835 wait_on_page_writeback(page);
4837 lock_extent_bits(io_tree, block_start, block_end, &cached_state);
4838 set_page_extent_mapped(page);
4840 ordered = btrfs_lookup_ordered_extent(inode, block_start);
4842 unlock_extent_cached(io_tree, block_start, block_end,
4843 &cached_state, GFP_NOFS);
4846 btrfs_start_ordered_extent(inode, ordered, 1);
4847 btrfs_put_ordered_extent(ordered);
4851 clear_extent_bit(&BTRFS_I(inode)->io_tree, block_start, block_end,
4852 EXTENT_DIRTY | EXTENT_DELALLOC |
4853 EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG,
4854 0, 0, &cached_state, GFP_NOFS);
4856 ret = btrfs_set_extent_delalloc(inode, block_start, block_end,
4859 unlock_extent_cached(io_tree, block_start, block_end,
4860 &cached_state, GFP_NOFS);
4864 if (offset != blocksize) {
4866 len = blocksize - offset;
4869 memset(kaddr + (block_start - page_offset(page)),
4872 memset(kaddr + (block_start - page_offset(page)) + offset,
4874 flush_dcache_page(page);
4877 ClearPageChecked(page);
4878 set_page_dirty(page);
4879 unlock_extent_cached(io_tree, block_start, block_end, &cached_state,
4884 btrfs_delalloc_release_space(inode, data_reserved, block_start,
4889 extent_changeset_free(data_reserved);
4893 static int maybe_insert_hole(struct btrfs_root *root, struct inode *inode,
4894 u64 offset, u64 len)
4896 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
4897 struct btrfs_trans_handle *trans;
4901 * Still need to make sure the inode looks like it's been updated so
4902 * that any holes get logged if we fsync.
4904 if (btrfs_fs_incompat(fs_info, NO_HOLES)) {
4905 BTRFS_I(inode)->last_trans = fs_info->generation;
4906 BTRFS_I(inode)->last_sub_trans = root->log_transid;
4907 BTRFS_I(inode)->last_log_commit = root->last_log_commit;
4912 * 1 - for the one we're dropping
4913 * 1 - for the one we're adding
4914 * 1 - for updating the inode.
4916 trans = btrfs_start_transaction(root, 3);
4918 return PTR_ERR(trans);
4920 ret = btrfs_drop_extents(trans, root, inode, offset, offset + len, 1);
4922 btrfs_abort_transaction(trans, ret);
4923 btrfs_end_transaction(trans);
4927 ret = btrfs_insert_file_extent(trans, root, btrfs_ino(BTRFS_I(inode)),
4928 offset, 0, 0, len, 0, len, 0, 0, 0);
4930 btrfs_abort_transaction(trans, ret);
4932 btrfs_update_inode(trans, root, inode);
4933 btrfs_end_transaction(trans);
4938 * This function puts in dummy file extents for the area we're creating a hole
4939 * for. So if we are truncating this file to a larger size we need to insert
4940 * these file extents so that btrfs_get_extent will return a EXTENT_MAP_HOLE for
4941 * the range between oldsize and size
4943 int btrfs_cont_expand(struct inode *inode, loff_t oldsize, loff_t size)
4945 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
4946 struct btrfs_root *root = BTRFS_I(inode)->root;
4947 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
4948 struct extent_map *em = NULL;
4949 struct extent_state *cached_state = NULL;
4950 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
4951 u64 hole_start = ALIGN(oldsize, fs_info->sectorsize);
4952 u64 block_end = ALIGN(size, fs_info->sectorsize);
4959 * If our size started in the middle of a block we need to zero out the
4960 * rest of the block before we expand the i_size, otherwise we could
4961 * expose stale data.
4963 err = btrfs_truncate_block(inode, oldsize, 0, 0);
4967 if (size <= hole_start)
4971 struct btrfs_ordered_extent *ordered;
4973 lock_extent_bits(io_tree, hole_start, block_end - 1,
4975 ordered = btrfs_lookup_ordered_range(BTRFS_I(inode), hole_start,
4976 block_end - hole_start);
4979 unlock_extent_cached(io_tree, hole_start, block_end - 1,
4980 &cached_state, GFP_NOFS);
4981 btrfs_start_ordered_extent(inode, ordered, 1);
4982 btrfs_put_ordered_extent(ordered);
4985 cur_offset = hole_start;
4987 em = btrfs_get_extent(BTRFS_I(inode), NULL, 0, cur_offset,
4988 block_end - cur_offset, 0);
4994 last_byte = min(extent_map_end(em), block_end);
4995 last_byte = ALIGN(last_byte, fs_info->sectorsize);
4996 if (!test_bit(EXTENT_FLAG_PREALLOC, &em->flags)) {
4997 struct extent_map *hole_em;
4998 hole_size = last_byte - cur_offset;
5000 err = maybe_insert_hole(root, inode, cur_offset,
5004 btrfs_drop_extent_cache(BTRFS_I(inode), cur_offset,
5005 cur_offset + hole_size - 1, 0);
5006 hole_em = alloc_extent_map();
5008 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
5009 &BTRFS_I(inode)->runtime_flags);
5012 hole_em->start = cur_offset;
5013 hole_em->len = hole_size;
5014 hole_em->orig_start = cur_offset;
5016 hole_em->block_start = EXTENT_MAP_HOLE;
5017 hole_em->block_len = 0;
5018 hole_em->orig_block_len = 0;
5019 hole_em->ram_bytes = hole_size;
5020 hole_em->bdev = fs_info->fs_devices->latest_bdev;
5021 hole_em->compress_type = BTRFS_COMPRESS_NONE;
5022 hole_em->generation = fs_info->generation;
5025 write_lock(&em_tree->lock);
5026 err = add_extent_mapping(em_tree, hole_em, 1);
5027 write_unlock(&em_tree->lock);
5030 btrfs_drop_extent_cache(BTRFS_I(inode),
5035 free_extent_map(hole_em);
5038 free_extent_map(em);
5040 cur_offset = last_byte;
5041 if (cur_offset >= block_end)
5044 free_extent_map(em);
5045 unlock_extent_cached(io_tree, hole_start, block_end - 1, &cached_state,
5050 static int btrfs_setsize(struct inode *inode, struct iattr *attr)
5052 struct btrfs_root *root = BTRFS_I(inode)->root;
5053 struct btrfs_trans_handle *trans;
5054 loff_t oldsize = i_size_read(inode);
5055 loff_t newsize = attr->ia_size;
5056 int mask = attr->ia_valid;
5060 * The regular truncate() case without ATTR_CTIME and ATTR_MTIME is a
5061 * special case where we need to update the times despite not having
5062 * these flags set. For all other operations the VFS set these flags
5063 * explicitly if it wants a timestamp update.
5065 if (newsize != oldsize) {
5066 inode_inc_iversion(inode);
5067 if (!(mask & (ATTR_CTIME | ATTR_MTIME)))
5068 inode->i_ctime = inode->i_mtime =
5069 current_time(inode);
5072 if (newsize > oldsize) {
5074 * Don't do an expanding truncate while snapshotting is ongoing.
5075 * This is to ensure the snapshot captures a fully consistent
5076 * state of this file - if the snapshot captures this expanding
5077 * truncation, it must capture all writes that happened before
5080 btrfs_wait_for_snapshot_creation(root);
5081 ret = btrfs_cont_expand(inode, oldsize, newsize);
5083 btrfs_end_write_no_snapshotting(root);
5087 trans = btrfs_start_transaction(root, 1);
5088 if (IS_ERR(trans)) {
5089 btrfs_end_write_no_snapshotting(root);
5090 return PTR_ERR(trans);
5093 i_size_write(inode, newsize);
5094 btrfs_ordered_update_i_size(inode, i_size_read(inode), NULL);
5095 pagecache_isize_extended(inode, oldsize, newsize);
5096 ret = btrfs_update_inode(trans, root, inode);
5097 btrfs_end_write_no_snapshotting(root);
5098 btrfs_end_transaction(trans);
5102 * We're truncating a file that used to have good data down to
5103 * zero. Make sure it gets into the ordered flush list so that
5104 * any new writes get down to disk quickly.
5107 set_bit(BTRFS_INODE_ORDERED_DATA_CLOSE,
5108 &BTRFS_I(inode)->runtime_flags);
5111 * 1 for the orphan item we're going to add
5112 * 1 for the orphan item deletion.
5114 trans = btrfs_start_transaction(root, 2);
5116 return PTR_ERR(trans);
5119 * We need to do this in case we fail at _any_ point during the
5120 * actual truncate. Once we do the truncate_setsize we could
5121 * invalidate pages which forces any outstanding ordered io to
5122 * be instantly completed which will give us extents that need
5123 * to be truncated. If we fail to get an orphan inode down we
5124 * could have left over extents that were never meant to live,
5125 * so we need to guarantee from this point on that everything
5126 * will be consistent.
5128 ret = btrfs_orphan_add(trans, BTRFS_I(inode));
5129 btrfs_end_transaction(trans);
5133 /* we don't support swapfiles, so vmtruncate shouldn't fail */
5134 truncate_setsize(inode, newsize);
5136 /* Disable nonlocked read DIO to avoid the end less truncate */
5137 btrfs_inode_block_unlocked_dio(BTRFS_I(inode));
5138 inode_dio_wait(inode);
5139 btrfs_inode_resume_unlocked_dio(BTRFS_I(inode));
5141 ret = btrfs_truncate(inode);
5142 if (ret && inode->i_nlink) {
5145 /* To get a stable disk_i_size */
5146 err = btrfs_wait_ordered_range(inode, 0, (u64)-1);
5148 btrfs_orphan_del(NULL, BTRFS_I(inode));
5153 * failed to truncate, disk_i_size is only adjusted down
5154 * as we remove extents, so it should represent the true
5155 * size of the inode, so reset the in memory size and
5156 * delete our orphan entry.
5158 trans = btrfs_join_transaction(root);
5159 if (IS_ERR(trans)) {
5160 btrfs_orphan_del(NULL, BTRFS_I(inode));
5163 i_size_write(inode, BTRFS_I(inode)->disk_i_size);
5164 err = btrfs_orphan_del(trans, BTRFS_I(inode));
5166 btrfs_abort_transaction(trans, err);
5167 btrfs_end_transaction(trans);
5174 static int btrfs_setattr(struct dentry *dentry, struct iattr *attr)
5176 struct inode *inode = d_inode(dentry);
5177 struct btrfs_root *root = BTRFS_I(inode)->root;
5180 if (btrfs_root_readonly(root))
5183 err = setattr_prepare(dentry, attr);
5187 if (S_ISREG(inode->i_mode) && (attr->ia_valid & ATTR_SIZE)) {
5188 err = btrfs_setsize(inode, attr);
5193 if (attr->ia_valid) {
5194 setattr_copy(inode, attr);
5195 inode_inc_iversion(inode);
5196 err = btrfs_dirty_inode(inode);
5198 if (!err && attr->ia_valid & ATTR_MODE)
5199 err = posix_acl_chmod(inode, inode->i_mode);
5206 * While truncating the inode pages during eviction, we get the VFS calling
5207 * btrfs_invalidatepage() against each page of the inode. This is slow because
5208 * the calls to btrfs_invalidatepage() result in a huge amount of calls to
5209 * lock_extent_bits() and clear_extent_bit(), which keep merging and splitting
5210 * extent_state structures over and over, wasting lots of time.
5212 * Therefore if the inode is being evicted, let btrfs_invalidatepage() skip all
5213 * those expensive operations on a per page basis and do only the ordered io
5214 * finishing, while we release here the extent_map and extent_state structures,
5215 * without the excessive merging and splitting.
5217 static void evict_inode_truncate_pages(struct inode *inode)
5219 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
5220 struct extent_map_tree *map_tree = &BTRFS_I(inode)->extent_tree;
5221 struct rb_node *node;
5223 ASSERT(inode->i_state & I_FREEING);
5224 truncate_inode_pages_final(&inode->i_data);
5226 write_lock(&map_tree->lock);
5227 while (!RB_EMPTY_ROOT(&map_tree->map)) {
5228 struct extent_map *em;
5230 node = rb_first(&map_tree->map);
5231 em = rb_entry(node, struct extent_map, rb_node);
5232 clear_bit(EXTENT_FLAG_PINNED, &em->flags);
5233 clear_bit(EXTENT_FLAG_LOGGING, &em->flags);
5234 remove_extent_mapping(map_tree, em);
5235 free_extent_map(em);
5236 if (need_resched()) {
5237 write_unlock(&map_tree->lock);
5239 write_lock(&map_tree->lock);
5242 write_unlock(&map_tree->lock);
5245 * Keep looping until we have no more ranges in the io tree.
5246 * We can have ongoing bios started by readpages (called from readahead)
5247 * that have their endio callback (extent_io.c:end_bio_extent_readpage)
5248 * still in progress (unlocked the pages in the bio but did not yet
5249 * unlocked the ranges in the io tree). Therefore this means some
5250 * ranges can still be locked and eviction started because before
5251 * submitting those bios, which are executed by a separate task (work
5252 * queue kthread), inode references (inode->i_count) were not taken
5253 * (which would be dropped in the end io callback of each bio).
5254 * Therefore here we effectively end up waiting for those bios and
5255 * anyone else holding locked ranges without having bumped the inode's
5256 * reference count - if we don't do it, when they access the inode's
5257 * io_tree to unlock a range it may be too late, leading to an
5258 * use-after-free issue.
5260 spin_lock(&io_tree->lock);
5261 while (!RB_EMPTY_ROOT(&io_tree->state)) {
5262 struct extent_state *state;
5263 struct extent_state *cached_state = NULL;
5267 node = rb_first(&io_tree->state);
5268 state = rb_entry(node, struct extent_state, rb_node);
5269 start = state->start;
5271 spin_unlock(&io_tree->lock);
5273 lock_extent_bits(io_tree, start, end, &cached_state);
5276 * If still has DELALLOC flag, the extent didn't reach disk,
5277 * and its reserved space won't be freed by delayed_ref.
5278 * So we need to free its reserved space here.
5279 * (Refer to comment in btrfs_invalidatepage, case 2)
5281 * Note, end is the bytenr of last byte, so we need + 1 here.
5283 if (state->state & EXTENT_DELALLOC)
5284 btrfs_qgroup_free_data(inode, NULL, start, end - start + 1);
5286 clear_extent_bit(io_tree, start, end,
5287 EXTENT_LOCKED | EXTENT_DIRTY |
5288 EXTENT_DELALLOC | EXTENT_DO_ACCOUNTING |
5289 EXTENT_DEFRAG, 1, 1,
5290 &cached_state, GFP_NOFS);
5293 spin_lock(&io_tree->lock);
5295 spin_unlock(&io_tree->lock);
5298 void btrfs_evict_inode(struct inode *inode)
5300 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
5301 struct btrfs_trans_handle *trans;
5302 struct btrfs_root *root = BTRFS_I(inode)->root;
5303 struct btrfs_block_rsv *rsv, *global_rsv;
5304 int steal_from_global = 0;
5308 trace_btrfs_inode_evict(inode);
5311 kmem_cache_free(btrfs_inode_cachep, BTRFS_I(inode));
5315 min_size = btrfs_calc_trunc_metadata_size(fs_info, 1);
5317 evict_inode_truncate_pages(inode);
5319 if (inode->i_nlink &&
5320 ((btrfs_root_refs(&root->root_item) != 0 &&
5321 root->root_key.objectid != BTRFS_ROOT_TREE_OBJECTID) ||
5322 btrfs_is_free_space_inode(BTRFS_I(inode))))
5325 if (is_bad_inode(inode)) {
5326 btrfs_orphan_del(NULL, BTRFS_I(inode));
5329 /* do we really want it for ->i_nlink > 0 and zero btrfs_root_refs? */
5330 if (!special_file(inode->i_mode))
5331 btrfs_wait_ordered_range(inode, 0, (u64)-1);
5333 btrfs_free_io_failure_record(BTRFS_I(inode), 0, (u64)-1);
5335 if (test_bit(BTRFS_FS_LOG_RECOVERING, &fs_info->flags)) {
5336 BUG_ON(test_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
5337 &BTRFS_I(inode)->runtime_flags));
5341 if (inode->i_nlink > 0) {
5342 BUG_ON(btrfs_root_refs(&root->root_item) != 0 &&
5343 root->root_key.objectid != BTRFS_ROOT_TREE_OBJECTID);
5347 ret = btrfs_commit_inode_delayed_inode(BTRFS_I(inode));
5349 btrfs_orphan_del(NULL, BTRFS_I(inode));
5353 rsv = btrfs_alloc_block_rsv(fs_info, BTRFS_BLOCK_RSV_TEMP);
5355 btrfs_orphan_del(NULL, BTRFS_I(inode));
5358 rsv->size = min_size;
5360 global_rsv = &fs_info->global_block_rsv;
5362 btrfs_i_size_write(BTRFS_I(inode), 0);
5365 * This is a bit simpler than btrfs_truncate since we've already
5366 * reserved our space for our orphan item in the unlink, so we just
5367 * need to reserve some slack space in case we add bytes and update
5368 * inode item when doing the truncate.
5371 ret = btrfs_block_rsv_refill(root, rsv, min_size,
5372 BTRFS_RESERVE_FLUSH_LIMIT);
5375 * Try and steal from the global reserve since we will
5376 * likely not use this space anyway, we want to try as
5377 * hard as possible to get this to work.
5380 steal_from_global++;
5382 steal_from_global = 0;
5386 * steal_from_global == 0: we reserved stuff, hooray!
5387 * steal_from_global == 1: we didn't reserve stuff, boo!
5388 * steal_from_global == 2: we've committed, still not a lot of
5389 * room but maybe we'll have room in the global reserve this
5391 * steal_from_global == 3: abandon all hope!
5393 if (steal_from_global > 2) {
5395 "Could not get space for a delete, will truncate on mount %d",
5397 btrfs_orphan_del(NULL, BTRFS_I(inode));
5398 btrfs_free_block_rsv(fs_info, rsv);
5402 trans = btrfs_join_transaction(root);
5403 if (IS_ERR(trans)) {
5404 btrfs_orphan_del(NULL, BTRFS_I(inode));
5405 btrfs_free_block_rsv(fs_info, rsv);
5410 * We can't just steal from the global reserve, we need to make
5411 * sure there is room to do it, if not we need to commit and try
5414 if (steal_from_global) {
5415 if (!btrfs_check_space_for_delayed_refs(trans, fs_info))
5416 ret = btrfs_block_rsv_migrate(global_rsv, rsv,
5423 * Couldn't steal from the global reserve, we have too much
5424 * pending stuff built up, commit the transaction and try it
5428 ret = btrfs_commit_transaction(trans);
5430 btrfs_orphan_del(NULL, BTRFS_I(inode));
5431 btrfs_free_block_rsv(fs_info, rsv);
5436 steal_from_global = 0;
5439 trans->block_rsv = rsv;
5441 ret = btrfs_truncate_inode_items(trans, root, inode, 0, 0);
5442 if (ret != -ENOSPC && ret != -EAGAIN)
5445 trans->block_rsv = &fs_info->trans_block_rsv;
5446 btrfs_end_transaction(trans);
5448 btrfs_btree_balance_dirty(fs_info);
5451 btrfs_free_block_rsv(fs_info, rsv);
5454 * Errors here aren't a big deal, it just means we leave orphan items
5455 * in the tree. They will be cleaned up on the next mount.
5458 trans->block_rsv = root->orphan_block_rsv;
5459 btrfs_orphan_del(trans, BTRFS_I(inode));
5461 btrfs_orphan_del(NULL, BTRFS_I(inode));
5464 trans->block_rsv = &fs_info->trans_block_rsv;
5465 if (!(root == fs_info->tree_root ||
5466 root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID))
5467 btrfs_return_ino(root, btrfs_ino(BTRFS_I(inode)));
5469 btrfs_end_transaction(trans);
5470 btrfs_btree_balance_dirty(fs_info);
5472 btrfs_remove_delayed_node(BTRFS_I(inode));
5477 * this returns the key found in the dir entry in the location pointer.
5478 * If no dir entries were found, location->objectid is 0.
5480 static int btrfs_inode_by_name(struct inode *dir, struct dentry *dentry,
5481 struct btrfs_key *location)
5483 const char *name = dentry->d_name.name;
5484 int namelen = dentry->d_name.len;
5485 struct btrfs_dir_item *di;
5486 struct btrfs_path *path;
5487 struct btrfs_root *root = BTRFS_I(dir)->root;
5490 path = btrfs_alloc_path();
5494 di = btrfs_lookup_dir_item(NULL, root, path, btrfs_ino(BTRFS_I(dir)),
5499 if (IS_ERR_OR_NULL(di))
5502 btrfs_dir_item_key_to_cpu(path->nodes[0], di, location);
5504 btrfs_free_path(path);
5507 location->objectid = 0;
5512 * when we hit a tree root in a directory, the btrfs part of the inode
5513 * needs to be changed to reflect the root directory of the tree root. This
5514 * is kind of like crossing a mount point.
5516 static int fixup_tree_root_location(struct btrfs_fs_info *fs_info,
5518 struct dentry *dentry,
5519 struct btrfs_key *location,
5520 struct btrfs_root **sub_root)
5522 struct btrfs_path *path;
5523 struct btrfs_root *new_root;
5524 struct btrfs_root_ref *ref;
5525 struct extent_buffer *leaf;
5526 struct btrfs_key key;
5530 path = btrfs_alloc_path();
5537 key.objectid = BTRFS_I(dir)->root->root_key.objectid;
5538 key.type = BTRFS_ROOT_REF_KEY;
5539 key.offset = location->objectid;
5541 ret = btrfs_search_slot(NULL, fs_info->tree_root, &key, path, 0, 0);
5548 leaf = path->nodes[0];
5549 ref = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_root_ref);
5550 if (btrfs_root_ref_dirid(leaf, ref) != btrfs_ino(BTRFS_I(dir)) ||
5551 btrfs_root_ref_name_len(leaf, ref) != dentry->d_name.len)
5554 ret = memcmp_extent_buffer(leaf, dentry->d_name.name,
5555 (unsigned long)(ref + 1),
5556 dentry->d_name.len);
5560 btrfs_release_path(path);
5562 new_root = btrfs_read_fs_root_no_name(fs_info, location);
5563 if (IS_ERR(new_root)) {
5564 err = PTR_ERR(new_root);
5568 *sub_root = new_root;
5569 location->objectid = btrfs_root_dirid(&new_root->root_item);
5570 location->type = BTRFS_INODE_ITEM_KEY;
5571 location->offset = 0;
5574 btrfs_free_path(path);
5578 static void inode_tree_add(struct inode *inode)
5580 struct btrfs_root *root = BTRFS_I(inode)->root;
5581 struct btrfs_inode *entry;
5583 struct rb_node *parent;
5584 struct rb_node *new = &BTRFS_I(inode)->rb_node;
5585 u64 ino = btrfs_ino(BTRFS_I(inode));
5587 if (inode_unhashed(inode))
5590 spin_lock(&root->inode_lock);
5591 p = &root->inode_tree.rb_node;
5594 entry = rb_entry(parent, struct btrfs_inode, rb_node);
5596 if (ino < btrfs_ino(BTRFS_I(&entry->vfs_inode)))
5597 p = &parent->rb_left;
5598 else if (ino > btrfs_ino(BTRFS_I(&entry->vfs_inode)))
5599 p = &parent->rb_right;
5601 WARN_ON(!(entry->vfs_inode.i_state &
5602 (I_WILL_FREE | I_FREEING)));
5603 rb_replace_node(parent, new, &root->inode_tree);
5604 RB_CLEAR_NODE(parent);
5605 spin_unlock(&root->inode_lock);
5609 rb_link_node(new, parent, p);
5610 rb_insert_color(new, &root->inode_tree);
5611 spin_unlock(&root->inode_lock);
5614 static void inode_tree_del(struct inode *inode)
5616 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
5617 struct btrfs_root *root = BTRFS_I(inode)->root;
5620 spin_lock(&root->inode_lock);
5621 if (!RB_EMPTY_NODE(&BTRFS_I(inode)->rb_node)) {
5622 rb_erase(&BTRFS_I(inode)->rb_node, &root->inode_tree);
5623 RB_CLEAR_NODE(&BTRFS_I(inode)->rb_node);
5624 empty = RB_EMPTY_ROOT(&root->inode_tree);
5626 spin_unlock(&root->inode_lock);
5628 if (empty && btrfs_root_refs(&root->root_item) == 0) {
5629 synchronize_srcu(&fs_info->subvol_srcu);
5630 spin_lock(&root->inode_lock);
5631 empty = RB_EMPTY_ROOT(&root->inode_tree);
5632 spin_unlock(&root->inode_lock);
5634 btrfs_add_dead_root(root);
5638 void btrfs_invalidate_inodes(struct btrfs_root *root)
5640 struct btrfs_fs_info *fs_info = root->fs_info;
5641 struct rb_node *node;
5642 struct rb_node *prev;
5643 struct btrfs_inode *entry;
5644 struct inode *inode;
5647 if (!test_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state))
5648 WARN_ON(btrfs_root_refs(&root->root_item) != 0);
5650 spin_lock(&root->inode_lock);
5652 node = root->inode_tree.rb_node;
5656 entry = rb_entry(node, struct btrfs_inode, rb_node);
5658 if (objectid < btrfs_ino(BTRFS_I(&entry->vfs_inode)))
5659 node = node->rb_left;
5660 else if (objectid > btrfs_ino(BTRFS_I(&entry->vfs_inode)))
5661 node = node->rb_right;
5667 entry = rb_entry(prev, struct btrfs_inode, rb_node);
5668 if (objectid <= btrfs_ino(BTRFS_I(&entry->vfs_inode))) {
5672 prev = rb_next(prev);
5676 entry = rb_entry(node, struct btrfs_inode, rb_node);
5677 objectid = btrfs_ino(BTRFS_I(&entry->vfs_inode)) + 1;
5678 inode = igrab(&entry->vfs_inode);
5680 spin_unlock(&root->inode_lock);
5681 if (atomic_read(&inode->i_count) > 1)
5682 d_prune_aliases(inode);
5684 * btrfs_drop_inode will have it removed from
5685 * the inode cache when its usage count
5690 spin_lock(&root->inode_lock);
5694 if (cond_resched_lock(&root->inode_lock))
5697 node = rb_next(node);
5699 spin_unlock(&root->inode_lock);
5702 static int btrfs_init_locked_inode(struct inode *inode, void *p)
5704 struct btrfs_iget_args *args = p;
5705 inode->i_ino = args->location->objectid;
5706 memcpy(&BTRFS_I(inode)->location, args->location,
5707 sizeof(*args->location));
5708 BTRFS_I(inode)->root = args->root;
5712 static int btrfs_find_actor(struct inode *inode, void *opaque)
5714 struct btrfs_iget_args *args = opaque;
5715 return args->location->objectid == BTRFS_I(inode)->location.objectid &&
5716 args->root == BTRFS_I(inode)->root;
5719 static struct inode *btrfs_iget_locked(struct super_block *s,
5720 struct btrfs_key *location,
5721 struct btrfs_root *root)
5723 struct inode *inode;
5724 struct btrfs_iget_args args;
5725 unsigned long hashval = btrfs_inode_hash(location->objectid, root);
5727 args.location = location;
5730 inode = iget5_locked(s, hashval, btrfs_find_actor,
5731 btrfs_init_locked_inode,
5736 /* Get an inode object given its location and corresponding root.
5737 * Returns in *is_new if the inode was read from disk
5739 struct inode *btrfs_iget(struct super_block *s, struct btrfs_key *location,
5740 struct btrfs_root *root, int *new)
5742 struct inode *inode;
5744 inode = btrfs_iget_locked(s, location, root);
5746 return ERR_PTR(-ENOMEM);
5748 if (inode->i_state & I_NEW) {
5751 ret = btrfs_read_locked_inode(inode);
5752 if (!is_bad_inode(inode)) {
5753 inode_tree_add(inode);
5754 unlock_new_inode(inode);
5758 unlock_new_inode(inode);
5761 inode = ERR_PTR(ret < 0 ? ret : -ESTALE);
5768 static struct inode *new_simple_dir(struct super_block *s,
5769 struct btrfs_key *key,
5770 struct btrfs_root *root)
5772 struct inode *inode = new_inode(s);
5775 return ERR_PTR(-ENOMEM);
5777 BTRFS_I(inode)->root = root;
5778 memcpy(&BTRFS_I(inode)->location, key, sizeof(*key));
5779 set_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags);
5781 inode->i_ino = BTRFS_EMPTY_SUBVOL_DIR_OBJECTID;
5782 inode->i_op = &btrfs_dir_ro_inode_operations;
5783 inode->i_opflags &= ~IOP_XATTR;
5784 inode->i_fop = &simple_dir_operations;
5785 inode->i_mode = S_IFDIR | S_IRUGO | S_IWUSR | S_IXUGO;
5786 inode->i_mtime = current_time(inode);
5787 inode->i_atime = inode->i_mtime;
5788 inode->i_ctime = inode->i_mtime;
5789 BTRFS_I(inode)->i_otime = inode->i_mtime;
5794 struct inode *btrfs_lookup_dentry(struct inode *dir, struct dentry *dentry)
5796 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
5797 struct inode *inode;
5798 struct btrfs_root *root = BTRFS_I(dir)->root;
5799 struct btrfs_root *sub_root = root;
5800 struct btrfs_key location;
5804 if (dentry->d_name.len > BTRFS_NAME_LEN)
5805 return ERR_PTR(-ENAMETOOLONG);
5807 ret = btrfs_inode_by_name(dir, dentry, &location);
5809 return ERR_PTR(ret);
5811 if (location.objectid == 0)
5812 return ERR_PTR(-ENOENT);
5814 if (location.type == BTRFS_INODE_ITEM_KEY) {
5815 inode = btrfs_iget(dir->i_sb, &location, root, NULL);
5819 BUG_ON(location.type != BTRFS_ROOT_ITEM_KEY);
5821 index = srcu_read_lock(&fs_info->subvol_srcu);
5822 ret = fixup_tree_root_location(fs_info, dir, dentry,
5823 &location, &sub_root);
5826 inode = ERR_PTR(ret);
5828 inode = new_simple_dir(dir->i_sb, &location, sub_root);
5830 inode = btrfs_iget(dir->i_sb, &location, sub_root, NULL);
5832 srcu_read_unlock(&fs_info->subvol_srcu, index);
5834 if (!IS_ERR(inode) && root != sub_root) {
5835 down_read(&fs_info->cleanup_work_sem);
5836 if (!(inode->i_sb->s_flags & MS_RDONLY))
5837 ret = btrfs_orphan_cleanup(sub_root);
5838 up_read(&fs_info->cleanup_work_sem);
5841 inode = ERR_PTR(ret);
5848 static int btrfs_dentry_delete(const struct dentry *dentry)
5850 struct btrfs_root *root;
5851 struct inode *inode = d_inode(dentry);
5853 if (!inode && !IS_ROOT(dentry))
5854 inode = d_inode(dentry->d_parent);
5857 root = BTRFS_I(inode)->root;
5858 if (btrfs_root_refs(&root->root_item) == 0)
5861 if (btrfs_ino(BTRFS_I(inode)) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)
5867 static void btrfs_dentry_release(struct dentry *dentry)
5869 kfree(dentry->d_fsdata);
5872 static struct dentry *btrfs_lookup(struct inode *dir, struct dentry *dentry,
5875 struct inode *inode;
5877 inode = btrfs_lookup_dentry(dir, dentry);
5878 if (IS_ERR(inode)) {
5879 if (PTR_ERR(inode) == -ENOENT)
5882 return ERR_CAST(inode);
5885 return d_splice_alias(inode, dentry);
5888 unsigned char btrfs_filetype_table[] = {
5889 DT_UNKNOWN, DT_REG, DT_DIR, DT_CHR, DT_BLK, DT_FIFO, DT_SOCK, DT_LNK
5893 * All this infrastructure exists because dir_emit can fault, and we are holding
5894 * the tree lock when doing readdir. For now just allocate a buffer and copy
5895 * our information into that, and then dir_emit from the buffer. This is
5896 * similar to what NFS does, only we don't keep the buffer around in pagecache
5897 * because I'm afraid I'll mess that up. Long term we need to make filldir do
5898 * copy_to_user_inatomic so we don't have to worry about page faulting under the
5901 static int btrfs_opendir(struct inode *inode, struct file *file)
5903 struct btrfs_file_private *private;
5905 private = kzalloc(sizeof(struct btrfs_file_private), GFP_KERNEL);
5908 private->filldir_buf = kzalloc(PAGE_SIZE, GFP_KERNEL);
5909 if (!private->filldir_buf) {
5913 file->private_data = private;
5924 static int btrfs_filldir(void *addr, int entries, struct dir_context *ctx)
5927 struct dir_entry *entry = addr;
5928 char *name = (char *)(entry + 1);
5930 ctx->pos = entry->offset;
5931 if (!dir_emit(ctx, name, entry->name_len, entry->ino,
5934 addr += sizeof(struct dir_entry) + entry->name_len;
5940 static int btrfs_real_readdir(struct file *file, struct dir_context *ctx)
5942 struct inode *inode = file_inode(file);
5943 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
5944 struct btrfs_root *root = BTRFS_I(inode)->root;
5945 struct btrfs_file_private *private = file->private_data;
5946 struct btrfs_dir_item *di;
5947 struct btrfs_key key;
5948 struct btrfs_key found_key;
5949 struct btrfs_path *path;
5951 struct list_head ins_list;
5952 struct list_head del_list;
5954 struct extent_buffer *leaf;
5961 struct btrfs_key location;
5963 if (!dir_emit_dots(file, ctx))
5966 path = btrfs_alloc_path();
5970 addr = private->filldir_buf;
5971 path->reada = READA_FORWARD;
5973 INIT_LIST_HEAD(&ins_list);
5974 INIT_LIST_HEAD(&del_list);
5975 put = btrfs_readdir_get_delayed_items(inode, &ins_list, &del_list);
5978 key.type = BTRFS_DIR_INDEX_KEY;
5979 key.offset = ctx->pos;
5980 key.objectid = btrfs_ino(BTRFS_I(inode));
5982 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
5987 struct dir_entry *entry;
5989 leaf = path->nodes[0];
5990 slot = path->slots[0];
5991 if (slot >= btrfs_header_nritems(leaf)) {
5992 ret = btrfs_next_leaf(root, path);
6000 btrfs_item_key_to_cpu(leaf, &found_key, slot);
6002 if (found_key.objectid != key.objectid)
6004 if (found_key.type != BTRFS_DIR_INDEX_KEY)
6006 if (found_key.offset < ctx->pos)
6008 if (btrfs_should_delete_dir_index(&del_list, found_key.offset))
6010 di = btrfs_item_ptr(leaf, slot, struct btrfs_dir_item);
6011 if (verify_dir_item(fs_info, leaf, slot, di))
6014 name_len = btrfs_dir_name_len(leaf, di);
6015 if ((total_len + sizeof(struct dir_entry) + name_len) >=
6017 btrfs_release_path(path);
6018 ret = btrfs_filldir(private->filldir_buf, entries, ctx);
6021 addr = private->filldir_buf;
6028 entry->name_len = name_len;
6029 name_ptr = (char *)(entry + 1);
6030 read_extent_buffer(leaf, name_ptr, (unsigned long)(di + 1),
6032 entry->type = btrfs_filetype_table[btrfs_dir_type(leaf, di)];
6033 btrfs_dir_item_key_to_cpu(leaf, di, &location);
6034 entry->ino = location.objectid;
6035 entry->offset = found_key.offset;
6037 addr += sizeof(struct dir_entry) + name_len;
6038 total_len += sizeof(struct dir_entry) + name_len;
6042 btrfs_release_path(path);
6044 ret = btrfs_filldir(private->filldir_buf, entries, ctx);
6048 ret = btrfs_readdir_delayed_dir_index(ctx, &ins_list);
6053 * Stop new entries from being returned after we return the last
6056 * New directory entries are assigned a strictly increasing
6057 * offset. This means that new entries created during readdir
6058 * are *guaranteed* to be seen in the future by that readdir.
6059 * This has broken buggy programs which operate on names as
6060 * they're returned by readdir. Until we re-use freed offsets
6061 * we have this hack to stop new entries from being returned
6062 * under the assumption that they'll never reach this huge
6065 * This is being careful not to overflow 32bit loff_t unless the
6066 * last entry requires it because doing so has broken 32bit apps
6069 if (ctx->pos >= INT_MAX)
6070 ctx->pos = LLONG_MAX;
6077 btrfs_readdir_put_delayed_items(inode, &ins_list, &del_list);
6078 btrfs_free_path(path);
6082 int btrfs_write_inode(struct inode *inode, struct writeback_control *wbc)
6084 struct btrfs_root *root = BTRFS_I(inode)->root;
6085 struct btrfs_trans_handle *trans;
6087 bool nolock = false;
6089 if (test_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags))
6092 if (btrfs_fs_closing(root->fs_info) &&
6093 btrfs_is_free_space_inode(BTRFS_I(inode)))
6096 if (wbc->sync_mode == WB_SYNC_ALL) {
6098 trans = btrfs_join_transaction_nolock(root);
6100 trans = btrfs_join_transaction(root);
6102 return PTR_ERR(trans);
6103 ret = btrfs_commit_transaction(trans);
6109 * This is somewhat expensive, updating the tree every time the
6110 * inode changes. But, it is most likely to find the inode in cache.
6111 * FIXME, needs more benchmarking...there are no reasons other than performance
6112 * to keep or drop this code.
6114 static int btrfs_dirty_inode(struct inode *inode)
6116 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
6117 struct btrfs_root *root = BTRFS_I(inode)->root;
6118 struct btrfs_trans_handle *trans;
6121 if (test_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags))
6124 trans = btrfs_join_transaction(root);
6126 return PTR_ERR(trans);
6128 ret = btrfs_update_inode(trans, root, inode);
6129 if (ret && ret == -ENOSPC) {
6130 /* whoops, lets try again with the full transaction */
6131 btrfs_end_transaction(trans);
6132 trans = btrfs_start_transaction(root, 1);
6134 return PTR_ERR(trans);
6136 ret = btrfs_update_inode(trans, root, inode);
6138 btrfs_end_transaction(trans);
6139 if (BTRFS_I(inode)->delayed_node)
6140 btrfs_balance_delayed_items(fs_info);
6146 * This is a copy of file_update_time. We need this so we can return error on
6147 * ENOSPC for updating the inode in the case of file write and mmap writes.
6149 static int btrfs_update_time(struct inode *inode, struct timespec *now,
6152 struct btrfs_root *root = BTRFS_I(inode)->root;
6154 if (btrfs_root_readonly(root))
6157 if (flags & S_VERSION)
6158 inode_inc_iversion(inode);
6159 if (flags & S_CTIME)
6160 inode->i_ctime = *now;
6161 if (flags & S_MTIME)
6162 inode->i_mtime = *now;
6163 if (flags & S_ATIME)
6164 inode->i_atime = *now;
6165 return btrfs_dirty_inode(inode);
6169 * find the highest existing sequence number in a directory
6170 * and then set the in-memory index_cnt variable to reflect
6171 * free sequence numbers
6173 static int btrfs_set_inode_index_count(struct btrfs_inode *inode)
6175 struct btrfs_root *root = inode->root;
6176 struct btrfs_key key, found_key;
6177 struct btrfs_path *path;
6178 struct extent_buffer *leaf;
6181 key.objectid = btrfs_ino(inode);
6182 key.type = BTRFS_DIR_INDEX_KEY;
6183 key.offset = (u64)-1;
6185 path = btrfs_alloc_path();
6189 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
6192 /* FIXME: we should be able to handle this */
6198 * MAGIC NUMBER EXPLANATION:
6199 * since we search a directory based on f_pos we have to start at 2
6200 * since '.' and '..' have f_pos of 0 and 1 respectively, so everybody
6201 * else has to start at 2
6203 if (path->slots[0] == 0) {
6204 inode->index_cnt = 2;
6210 leaf = path->nodes[0];
6211 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
6213 if (found_key.objectid != btrfs_ino(inode) ||
6214 found_key.type != BTRFS_DIR_INDEX_KEY) {
6215 inode->index_cnt = 2;
6219 inode->index_cnt = found_key.offset + 1;
6221 btrfs_free_path(path);
6226 * helper to find a free sequence number in a given directory. This current
6227 * code is very simple, later versions will do smarter things in the btree
6229 int btrfs_set_inode_index(struct btrfs_inode *dir, u64 *index)
6233 if (dir->index_cnt == (u64)-1) {
6234 ret = btrfs_inode_delayed_dir_index_count(dir);
6236 ret = btrfs_set_inode_index_count(dir);
6242 *index = dir->index_cnt;
6248 static int btrfs_insert_inode_locked(struct inode *inode)
6250 struct btrfs_iget_args args;
6251 args.location = &BTRFS_I(inode)->location;
6252 args.root = BTRFS_I(inode)->root;
6254 return insert_inode_locked4(inode,
6255 btrfs_inode_hash(inode->i_ino, BTRFS_I(inode)->root),
6256 btrfs_find_actor, &args);
6260 * Inherit flags from the parent inode.
6262 * Currently only the compression flags and the cow flags are inherited.
6264 static void btrfs_inherit_iflags(struct inode *inode, struct inode *dir)
6271 flags = BTRFS_I(dir)->flags;
6273 if (flags & BTRFS_INODE_NOCOMPRESS) {
6274 BTRFS_I(inode)->flags &= ~BTRFS_INODE_COMPRESS;
6275 BTRFS_I(inode)->flags |= BTRFS_INODE_NOCOMPRESS;
6276 } else if (flags & BTRFS_INODE_COMPRESS) {
6277 BTRFS_I(inode)->flags &= ~BTRFS_INODE_NOCOMPRESS;
6278 BTRFS_I(inode)->flags |= BTRFS_INODE_COMPRESS;
6281 if (flags & BTRFS_INODE_NODATACOW) {
6282 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATACOW;
6283 if (S_ISREG(inode->i_mode))
6284 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATASUM;
6287 btrfs_update_iflags(inode);
6290 static struct inode *btrfs_new_inode(struct btrfs_trans_handle *trans,
6291 struct btrfs_root *root,
6293 const char *name, int name_len,
6294 u64 ref_objectid, u64 objectid,
6295 umode_t mode, u64 *index)
6297 struct btrfs_fs_info *fs_info = root->fs_info;
6298 struct inode *inode;
6299 struct btrfs_inode_item *inode_item;
6300 struct btrfs_key *location;
6301 struct btrfs_path *path;
6302 struct btrfs_inode_ref *ref;
6303 struct btrfs_key key[2];
6305 int nitems = name ? 2 : 1;
6309 path = btrfs_alloc_path();
6311 return ERR_PTR(-ENOMEM);
6313 inode = new_inode(fs_info->sb);
6315 btrfs_free_path(path);
6316 return ERR_PTR(-ENOMEM);
6320 * O_TMPFILE, set link count to 0, so that after this point,
6321 * we fill in an inode item with the correct link count.
6324 set_nlink(inode, 0);
6327 * we have to initialize this early, so we can reclaim the inode
6328 * number if we fail afterwards in this function.
6330 inode->i_ino = objectid;
6333 trace_btrfs_inode_request(dir);
6335 ret = btrfs_set_inode_index(BTRFS_I(dir), index);
6337 btrfs_free_path(path);
6339 return ERR_PTR(ret);
6345 * index_cnt is ignored for everything but a dir,
6346 * btrfs_get_inode_index_count has an explanation for the magic
6349 BTRFS_I(inode)->index_cnt = 2;
6350 BTRFS_I(inode)->dir_index = *index;
6351 BTRFS_I(inode)->root = root;
6352 BTRFS_I(inode)->generation = trans->transid;
6353 inode->i_generation = BTRFS_I(inode)->generation;
6356 * We could have gotten an inode number from somebody who was fsynced
6357 * and then removed in this same transaction, so let's just set full
6358 * sync since it will be a full sync anyway and this will blow away the
6359 * old info in the log.
6361 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &BTRFS_I(inode)->runtime_flags);
6363 key[0].objectid = objectid;
6364 key[0].type = BTRFS_INODE_ITEM_KEY;
6367 sizes[0] = sizeof(struct btrfs_inode_item);
6371 * Start new inodes with an inode_ref. This is slightly more
6372 * efficient for small numbers of hard links since they will
6373 * be packed into one item. Extended refs will kick in if we
6374 * add more hard links than can fit in the ref item.
6376 key[1].objectid = objectid;
6377 key[1].type = BTRFS_INODE_REF_KEY;
6378 key[1].offset = ref_objectid;
6380 sizes[1] = name_len + sizeof(*ref);
6383 location = &BTRFS_I(inode)->location;
6384 location->objectid = objectid;
6385 location->offset = 0;
6386 location->type = BTRFS_INODE_ITEM_KEY;
6388 ret = btrfs_insert_inode_locked(inode);
6392 path->leave_spinning = 1;
6393 ret = btrfs_insert_empty_items(trans, root, path, key, sizes, nitems);
6397 inode_init_owner(inode, dir, mode);
6398 inode_set_bytes(inode, 0);
6400 inode->i_mtime = current_time(inode);
6401 inode->i_atime = inode->i_mtime;
6402 inode->i_ctime = inode->i_mtime;
6403 BTRFS_I(inode)->i_otime = inode->i_mtime;
6405 inode_item = btrfs_item_ptr(path->nodes[0], path->slots[0],
6406 struct btrfs_inode_item);
6407 memzero_extent_buffer(path->nodes[0], (unsigned long)inode_item,
6408 sizeof(*inode_item));
6409 fill_inode_item(trans, path->nodes[0], inode_item, inode);
6412 ref = btrfs_item_ptr(path->nodes[0], path->slots[0] + 1,
6413 struct btrfs_inode_ref);
6414 btrfs_set_inode_ref_name_len(path->nodes[0], ref, name_len);
6415 btrfs_set_inode_ref_index(path->nodes[0], ref, *index);
6416 ptr = (unsigned long)(ref + 1);
6417 write_extent_buffer(path->nodes[0], name, ptr, name_len);
6420 btrfs_mark_buffer_dirty(path->nodes[0]);
6421 btrfs_free_path(path);
6423 btrfs_inherit_iflags(inode, dir);
6425 if (S_ISREG(mode)) {
6426 if (btrfs_test_opt(fs_info, NODATASUM))
6427 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATASUM;
6428 if (btrfs_test_opt(fs_info, NODATACOW))
6429 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATACOW |
6430 BTRFS_INODE_NODATASUM;
6433 inode_tree_add(inode);
6435 trace_btrfs_inode_new(inode);
6436 btrfs_set_inode_last_trans(trans, inode);
6438 btrfs_update_root_times(trans, root);
6440 ret = btrfs_inode_inherit_props(trans, inode, dir);
6443 "error inheriting props for ino %llu (root %llu): %d",
6444 btrfs_ino(BTRFS_I(inode)), root->root_key.objectid, ret);
6449 unlock_new_inode(inode);
6452 BTRFS_I(dir)->index_cnt--;
6453 btrfs_free_path(path);
6455 return ERR_PTR(ret);
6458 static inline u8 btrfs_inode_type(struct inode *inode)
6460 return btrfs_type_by_mode[(inode->i_mode & S_IFMT) >> S_SHIFT];
6464 * utility function to add 'inode' into 'parent_inode' with
6465 * a give name and a given sequence number.
6466 * if 'add_backref' is true, also insert a backref from the
6467 * inode to the parent directory.
6469 int btrfs_add_link(struct btrfs_trans_handle *trans,
6470 struct btrfs_inode *parent_inode, struct btrfs_inode *inode,
6471 const char *name, int name_len, int add_backref, u64 index)
6473 struct btrfs_fs_info *fs_info = btrfs_sb(inode->vfs_inode.i_sb);
6475 struct btrfs_key key;
6476 struct btrfs_root *root = parent_inode->root;
6477 u64 ino = btrfs_ino(inode);
6478 u64 parent_ino = btrfs_ino(parent_inode);
6480 if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
6481 memcpy(&key, &inode->root->root_key, sizeof(key));
6484 key.type = BTRFS_INODE_ITEM_KEY;
6488 if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
6489 ret = btrfs_add_root_ref(trans, fs_info, key.objectid,
6490 root->root_key.objectid, parent_ino,
6491 index, name, name_len);
6492 } else if (add_backref) {
6493 ret = btrfs_insert_inode_ref(trans, root, name, name_len, ino,
6497 /* Nothing to clean up yet */
6501 ret = btrfs_insert_dir_item(trans, root, name, name_len,
6503 btrfs_inode_type(&inode->vfs_inode), index);
6504 if (ret == -EEXIST || ret == -EOVERFLOW)
6507 btrfs_abort_transaction(trans, ret);
6511 btrfs_i_size_write(parent_inode, parent_inode->vfs_inode.i_size +
6513 inode_inc_iversion(&parent_inode->vfs_inode);
6514 parent_inode->vfs_inode.i_mtime = parent_inode->vfs_inode.i_ctime =
6515 current_time(&parent_inode->vfs_inode);
6516 ret = btrfs_update_inode(trans, root, &parent_inode->vfs_inode);
6518 btrfs_abort_transaction(trans, ret);
6522 if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
6525 err = btrfs_del_root_ref(trans, fs_info, key.objectid,
6526 root->root_key.objectid, parent_ino,
6527 &local_index, name, name_len);
6529 } else if (add_backref) {
6533 err = btrfs_del_inode_ref(trans, root, name, name_len,
6534 ino, parent_ino, &local_index);
6539 static int btrfs_add_nondir(struct btrfs_trans_handle *trans,
6540 struct btrfs_inode *dir, struct dentry *dentry,
6541 struct btrfs_inode *inode, int backref, u64 index)
6543 int err = btrfs_add_link(trans, dir, inode,
6544 dentry->d_name.name, dentry->d_name.len,
6551 static int btrfs_mknod(struct inode *dir, struct dentry *dentry,
6552 umode_t mode, dev_t rdev)
6554 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
6555 struct btrfs_trans_handle *trans;
6556 struct btrfs_root *root = BTRFS_I(dir)->root;
6557 struct inode *inode = NULL;
6564 * 2 for inode item and ref
6566 * 1 for xattr if selinux is on
6568 trans = btrfs_start_transaction(root, 5);
6570 return PTR_ERR(trans);
6572 err = btrfs_find_free_ino(root, &objectid);
6576 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
6577 dentry->d_name.len, btrfs_ino(BTRFS_I(dir)), objectid,
6579 if (IS_ERR(inode)) {
6580 err = PTR_ERR(inode);
6585 * If the active LSM wants to access the inode during
6586 * d_instantiate it needs these. Smack checks to see
6587 * if the filesystem supports xattrs by looking at the
6590 inode->i_op = &btrfs_special_inode_operations;
6591 init_special_inode(inode, inode->i_mode, rdev);
6593 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
6595 goto out_unlock_inode;
6597 err = btrfs_add_nondir(trans, BTRFS_I(dir), dentry, BTRFS_I(inode),
6600 goto out_unlock_inode;
6602 btrfs_update_inode(trans, root, inode);
6603 unlock_new_inode(inode);
6604 d_instantiate(dentry, inode);
6608 btrfs_end_transaction(trans);
6609 btrfs_balance_delayed_items(fs_info);
6610 btrfs_btree_balance_dirty(fs_info);
6612 inode_dec_link_count(inode);
6619 unlock_new_inode(inode);
6624 static int btrfs_create(struct inode *dir, struct dentry *dentry,
6625 umode_t mode, bool excl)
6627 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
6628 struct btrfs_trans_handle *trans;
6629 struct btrfs_root *root = BTRFS_I(dir)->root;
6630 struct inode *inode = NULL;
6631 int drop_inode_on_err = 0;
6637 * 2 for inode item and ref
6639 * 1 for xattr if selinux is on
6641 trans = btrfs_start_transaction(root, 5);
6643 return PTR_ERR(trans);
6645 err = btrfs_find_free_ino(root, &objectid);
6649 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
6650 dentry->d_name.len, btrfs_ino(BTRFS_I(dir)), objectid,
6652 if (IS_ERR(inode)) {
6653 err = PTR_ERR(inode);
6656 drop_inode_on_err = 1;
6658 * If the active LSM wants to access the inode during
6659 * d_instantiate it needs these. Smack checks to see
6660 * if the filesystem supports xattrs by looking at the
6663 inode->i_fop = &btrfs_file_operations;
6664 inode->i_op = &btrfs_file_inode_operations;
6665 inode->i_mapping->a_ops = &btrfs_aops;
6667 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
6669 goto out_unlock_inode;
6671 err = btrfs_update_inode(trans, root, inode);
6673 goto out_unlock_inode;
6675 err = btrfs_add_nondir(trans, BTRFS_I(dir), dentry, BTRFS_I(inode),
6678 goto out_unlock_inode;
6680 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
6681 unlock_new_inode(inode);
6682 d_instantiate(dentry, inode);
6685 btrfs_end_transaction(trans);
6686 if (err && drop_inode_on_err) {
6687 inode_dec_link_count(inode);
6690 btrfs_balance_delayed_items(fs_info);
6691 btrfs_btree_balance_dirty(fs_info);
6695 unlock_new_inode(inode);
6700 static int btrfs_link(struct dentry *old_dentry, struct inode *dir,
6701 struct dentry *dentry)
6703 struct btrfs_trans_handle *trans = NULL;
6704 struct btrfs_root *root = BTRFS_I(dir)->root;
6705 struct inode *inode = d_inode(old_dentry);
6706 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
6711 /* do not allow sys_link's with other subvols of the same device */
6712 if (root->objectid != BTRFS_I(inode)->root->objectid)
6715 if (inode->i_nlink >= BTRFS_LINK_MAX)
6718 err = btrfs_set_inode_index(BTRFS_I(dir), &index);
6723 * 2 items for inode and inode ref
6724 * 2 items for dir items
6725 * 1 item for parent inode
6727 trans = btrfs_start_transaction(root, 5);
6728 if (IS_ERR(trans)) {
6729 err = PTR_ERR(trans);
6734 /* There are several dir indexes for this inode, clear the cache. */
6735 BTRFS_I(inode)->dir_index = 0ULL;
6737 inode_inc_iversion(inode);
6738 inode->i_ctime = current_time(inode);
6740 set_bit(BTRFS_INODE_COPY_EVERYTHING, &BTRFS_I(inode)->runtime_flags);
6742 err = btrfs_add_nondir(trans, BTRFS_I(dir), dentry, BTRFS_I(inode),
6748 struct dentry *parent = dentry->d_parent;
6749 err = btrfs_update_inode(trans, root, inode);
6752 if (inode->i_nlink == 1) {
6754 * If new hard link count is 1, it's a file created
6755 * with open(2) O_TMPFILE flag.
6757 err = btrfs_orphan_del(trans, BTRFS_I(inode));
6761 d_instantiate(dentry, inode);
6762 btrfs_log_new_name(trans, BTRFS_I(inode), NULL, parent);
6765 btrfs_balance_delayed_items(fs_info);
6768 btrfs_end_transaction(trans);
6770 inode_dec_link_count(inode);
6773 btrfs_btree_balance_dirty(fs_info);
6777 static int btrfs_mkdir(struct inode *dir, struct dentry *dentry, umode_t mode)
6779 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
6780 struct inode *inode = NULL;
6781 struct btrfs_trans_handle *trans;
6782 struct btrfs_root *root = BTRFS_I(dir)->root;
6784 int drop_on_err = 0;
6789 * 2 items for inode and ref
6790 * 2 items for dir items
6791 * 1 for xattr if selinux is on
6793 trans = btrfs_start_transaction(root, 5);
6795 return PTR_ERR(trans);
6797 err = btrfs_find_free_ino(root, &objectid);
6801 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
6802 dentry->d_name.len, btrfs_ino(BTRFS_I(dir)), objectid,
6803 S_IFDIR | mode, &index);
6804 if (IS_ERR(inode)) {
6805 err = PTR_ERR(inode);
6810 /* these must be set before we unlock the inode */
6811 inode->i_op = &btrfs_dir_inode_operations;
6812 inode->i_fop = &btrfs_dir_file_operations;
6814 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
6816 goto out_fail_inode;
6818 btrfs_i_size_write(BTRFS_I(inode), 0);
6819 err = btrfs_update_inode(trans, root, inode);
6821 goto out_fail_inode;
6823 err = btrfs_add_link(trans, BTRFS_I(dir), BTRFS_I(inode),
6824 dentry->d_name.name,
6825 dentry->d_name.len, 0, index);
6827 goto out_fail_inode;
6829 d_instantiate(dentry, inode);
6831 * mkdir is special. We're unlocking after we call d_instantiate
6832 * to avoid a race with nfsd calling d_instantiate.
6834 unlock_new_inode(inode);
6838 btrfs_end_transaction(trans);
6840 inode_dec_link_count(inode);
6843 btrfs_balance_delayed_items(fs_info);
6844 btrfs_btree_balance_dirty(fs_info);
6848 unlock_new_inode(inode);
6852 /* Find next extent map of a given extent map, caller needs to ensure locks */
6853 static struct extent_map *next_extent_map(struct extent_map *em)
6855 struct rb_node *next;
6857 next = rb_next(&em->rb_node);
6860 return container_of(next, struct extent_map, rb_node);
6863 static struct extent_map *prev_extent_map(struct extent_map *em)
6865 struct rb_node *prev;
6867 prev = rb_prev(&em->rb_node);
6870 return container_of(prev, struct extent_map, rb_node);
6873 /* helper for btfs_get_extent. Given an existing extent in the tree,
6874 * the existing extent is the nearest extent to map_start,
6875 * and an extent that you want to insert, deal with overlap and insert
6876 * the best fitted new extent into the tree.
6878 static int merge_extent_mapping(struct extent_map_tree *em_tree,
6879 struct extent_map *existing,
6880 struct extent_map *em,
6883 struct extent_map *prev;
6884 struct extent_map *next;
6889 BUG_ON(map_start < em->start || map_start >= extent_map_end(em));
6891 if (existing->start > map_start) {
6893 prev = prev_extent_map(next);
6896 next = next_extent_map(prev);
6899 start = prev ? extent_map_end(prev) : em->start;
6900 start = max_t(u64, start, em->start);
6901 end = next ? next->start : extent_map_end(em);
6902 end = min_t(u64, end, extent_map_end(em));
6903 start_diff = start - em->start;
6905 em->len = end - start;
6906 if (em->block_start < EXTENT_MAP_LAST_BYTE &&
6907 !test_bit(EXTENT_FLAG_COMPRESSED, &em->flags)) {
6908 em->block_start += start_diff;
6909 em->block_len -= start_diff;
6911 return add_extent_mapping(em_tree, em, 0);
6914 static noinline int uncompress_inline(struct btrfs_path *path,
6916 size_t pg_offset, u64 extent_offset,
6917 struct btrfs_file_extent_item *item)
6920 struct extent_buffer *leaf = path->nodes[0];
6923 unsigned long inline_size;
6927 WARN_ON(pg_offset != 0);
6928 compress_type = btrfs_file_extent_compression(leaf, item);
6929 max_size = btrfs_file_extent_ram_bytes(leaf, item);
6930 inline_size = btrfs_file_extent_inline_item_len(leaf,
6931 btrfs_item_nr(path->slots[0]));
6932 tmp = kmalloc(inline_size, GFP_NOFS);
6935 ptr = btrfs_file_extent_inline_start(item);
6937 read_extent_buffer(leaf, tmp, ptr, inline_size);
6939 max_size = min_t(unsigned long, PAGE_SIZE, max_size);
6940 ret = btrfs_decompress(compress_type, tmp, page,
6941 extent_offset, inline_size, max_size);
6944 * decompression code contains a memset to fill in any space between the end
6945 * of the uncompressed data and the end of max_size in case the decompressed
6946 * data ends up shorter than ram_bytes. That doesn't cover the hole between
6947 * the end of an inline extent and the beginning of the next block, so we
6948 * cover that region here.
6951 if (max_size + pg_offset < PAGE_SIZE) {
6952 char *map = kmap(page);
6953 memset(map + pg_offset + max_size, 0, PAGE_SIZE - max_size - pg_offset);
6961 * a bit scary, this does extent mapping from logical file offset to the disk.
6962 * the ugly parts come from merging extents from the disk with the in-ram
6963 * representation. This gets more complex because of the data=ordered code,
6964 * where the in-ram extents might be locked pending data=ordered completion.
6966 * This also copies inline extents directly into the page.
6968 struct extent_map *btrfs_get_extent(struct btrfs_inode *inode,
6970 size_t pg_offset, u64 start, u64 len,
6973 struct btrfs_fs_info *fs_info = btrfs_sb(inode->vfs_inode.i_sb);
6976 u64 extent_start = 0;
6978 u64 objectid = btrfs_ino(inode);
6980 struct btrfs_path *path = NULL;
6981 struct btrfs_root *root = inode->root;
6982 struct btrfs_file_extent_item *item;
6983 struct extent_buffer *leaf;
6984 struct btrfs_key found_key;
6985 struct extent_map *em = NULL;
6986 struct extent_map_tree *em_tree = &inode->extent_tree;
6987 struct extent_io_tree *io_tree = &inode->io_tree;
6988 struct btrfs_trans_handle *trans = NULL;
6989 const bool new_inline = !page || create;
6992 read_lock(&em_tree->lock);
6993 em = lookup_extent_mapping(em_tree, start, len);
6995 em->bdev = fs_info->fs_devices->latest_bdev;
6996 read_unlock(&em_tree->lock);
6999 if (em->start > start || em->start + em->len <= start)
7000 free_extent_map(em);
7001 else if (em->block_start == EXTENT_MAP_INLINE && page)
7002 free_extent_map(em);
7006 em = alloc_extent_map();
7011 em->bdev = fs_info->fs_devices->latest_bdev;
7012 em->start = EXTENT_MAP_HOLE;
7013 em->orig_start = EXTENT_MAP_HOLE;
7015 em->block_len = (u64)-1;
7018 path = btrfs_alloc_path();
7024 * Chances are we'll be called again, so go ahead and do
7027 path->reada = READA_FORWARD;
7030 ret = btrfs_lookup_file_extent(trans, root, path,
7031 objectid, start, trans != NULL);
7038 if (path->slots[0] == 0)
7043 leaf = path->nodes[0];
7044 item = btrfs_item_ptr(leaf, path->slots[0],
7045 struct btrfs_file_extent_item);
7046 /* are we inside the extent that was found? */
7047 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
7048 found_type = found_key.type;
7049 if (found_key.objectid != objectid ||
7050 found_type != BTRFS_EXTENT_DATA_KEY) {
7052 * If we backup past the first extent we want to move forward
7053 * and see if there is an extent in front of us, otherwise we'll
7054 * say there is a hole for our whole search range which can
7061 found_type = btrfs_file_extent_type(leaf, item);
7062 extent_start = found_key.offset;
7063 if (found_type == BTRFS_FILE_EXTENT_REG ||
7064 found_type == BTRFS_FILE_EXTENT_PREALLOC) {
7065 extent_end = extent_start +
7066 btrfs_file_extent_num_bytes(leaf, item);
7068 trace_btrfs_get_extent_show_fi_regular(inode, leaf, item,
7070 } else if (found_type == BTRFS_FILE_EXTENT_INLINE) {
7072 size = btrfs_file_extent_inline_len(leaf, path->slots[0], item);
7073 extent_end = ALIGN(extent_start + size,
7074 fs_info->sectorsize);
7076 trace_btrfs_get_extent_show_fi_inline(inode, leaf, item,
7081 if (start >= extent_end) {
7083 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
7084 ret = btrfs_next_leaf(root, path);
7091 leaf = path->nodes[0];
7093 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
7094 if (found_key.objectid != objectid ||
7095 found_key.type != BTRFS_EXTENT_DATA_KEY)
7097 if (start + len <= found_key.offset)
7099 if (start > found_key.offset)
7102 em->orig_start = start;
7103 em->len = found_key.offset - start;
7107 btrfs_extent_item_to_extent_map(inode, path, item,
7110 if (found_type == BTRFS_FILE_EXTENT_REG ||
7111 found_type == BTRFS_FILE_EXTENT_PREALLOC) {
7113 } else if (found_type == BTRFS_FILE_EXTENT_INLINE) {
7117 size_t extent_offset;
7123 size = btrfs_file_extent_inline_len(leaf, path->slots[0], item);
7124 extent_offset = page_offset(page) + pg_offset - extent_start;
7125 copy_size = min_t(u64, PAGE_SIZE - pg_offset,
7126 size - extent_offset);
7127 em->start = extent_start + extent_offset;
7128 em->len = ALIGN(copy_size, fs_info->sectorsize);
7129 em->orig_block_len = em->len;
7130 em->orig_start = em->start;
7131 ptr = btrfs_file_extent_inline_start(item) + extent_offset;
7132 if (create == 0 && !PageUptodate(page)) {
7133 if (btrfs_file_extent_compression(leaf, item) !=
7134 BTRFS_COMPRESS_NONE) {
7135 ret = uncompress_inline(path, page, pg_offset,
7136 extent_offset, item);
7143 read_extent_buffer(leaf, map + pg_offset, ptr,
7145 if (pg_offset + copy_size < PAGE_SIZE) {
7146 memset(map + pg_offset + copy_size, 0,
7147 PAGE_SIZE - pg_offset -
7152 flush_dcache_page(page);
7153 } else if (create && PageUptodate(page)) {
7157 free_extent_map(em);
7160 btrfs_release_path(path);
7161 trans = btrfs_join_transaction(root);
7164 return ERR_CAST(trans);
7168 write_extent_buffer(leaf, map + pg_offset, ptr,
7171 btrfs_mark_buffer_dirty(leaf);
7173 set_extent_uptodate(io_tree, em->start,
7174 extent_map_end(em) - 1, NULL, GFP_NOFS);
7179 em->orig_start = start;
7182 em->block_start = EXTENT_MAP_HOLE;
7183 set_bit(EXTENT_FLAG_VACANCY, &em->flags);
7185 btrfs_release_path(path);
7186 if (em->start > start || extent_map_end(em) <= start) {
7188 "bad extent! em: [%llu %llu] passed [%llu %llu]",
7189 em->start, em->len, start, len);
7195 write_lock(&em_tree->lock);
7196 ret = add_extent_mapping(em_tree, em, 0);
7197 /* it is possible that someone inserted the extent into the tree
7198 * while we had the lock dropped. It is also possible that
7199 * an overlapping map exists in the tree
7201 if (ret == -EEXIST) {
7202 struct extent_map *existing;
7206 existing = search_extent_mapping(em_tree, start, len);
7208 * existing will always be non-NULL, since there must be
7209 * extent causing the -EEXIST.
7211 if (existing->start == em->start &&
7212 extent_map_end(existing) >= extent_map_end(em) &&
7213 em->block_start == existing->block_start) {
7215 * The existing extent map already encompasses the
7216 * entire extent map we tried to add.
7218 free_extent_map(em);
7222 } else if (start >= extent_map_end(existing) ||
7223 start <= existing->start) {
7225 * The existing extent map is the one nearest to
7226 * the [start, start + len) range which overlaps
7228 err = merge_extent_mapping(em_tree, existing,
7230 free_extent_map(existing);
7232 free_extent_map(em);
7236 free_extent_map(em);
7241 write_unlock(&em_tree->lock);
7244 trace_btrfs_get_extent(root, inode, em);
7246 btrfs_free_path(path);
7248 ret = btrfs_end_transaction(trans);
7253 free_extent_map(em);
7254 return ERR_PTR(err);
7256 BUG_ON(!em); /* Error is always set */
7260 struct extent_map *btrfs_get_extent_fiemap(struct btrfs_inode *inode,
7262 size_t pg_offset, u64 start, u64 len,
7265 struct extent_map *em;
7266 struct extent_map *hole_em = NULL;
7267 u64 range_start = start;
7273 em = btrfs_get_extent(inode, page, pg_offset, start, len, create);
7277 * If our em maps to:
7279 * - a pre-alloc extent,
7280 * there might actually be delalloc bytes behind it.
7282 if (em->block_start != EXTENT_MAP_HOLE &&
7283 !test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
7288 /* check to see if we've wrapped (len == -1 or similar) */
7297 /* ok, we didn't find anything, lets look for delalloc */
7298 found = count_range_bits(&inode->io_tree, &range_start,
7299 end, len, EXTENT_DELALLOC, 1);
7300 found_end = range_start + found;
7301 if (found_end < range_start)
7302 found_end = (u64)-1;
7305 * we didn't find anything useful, return
7306 * the original results from get_extent()
7308 if (range_start > end || found_end <= start) {
7314 /* adjust the range_start to make sure it doesn't
7315 * go backwards from the start they passed in
7317 range_start = max(start, range_start);
7318 found = found_end - range_start;
7321 u64 hole_start = start;
7324 em = alloc_extent_map();
7330 * when btrfs_get_extent can't find anything it
7331 * returns one huge hole
7333 * make sure what it found really fits our range, and
7334 * adjust to make sure it is based on the start from
7338 u64 calc_end = extent_map_end(hole_em);
7340 if (calc_end <= start || (hole_em->start > end)) {
7341 free_extent_map(hole_em);
7344 hole_start = max(hole_em->start, start);
7345 hole_len = calc_end - hole_start;
7349 if (hole_em && range_start > hole_start) {
7350 /* our hole starts before our delalloc, so we
7351 * have to return just the parts of the hole
7352 * that go until the delalloc starts
7354 em->len = min(hole_len,
7355 range_start - hole_start);
7356 em->start = hole_start;
7357 em->orig_start = hole_start;
7359 * don't adjust block start at all,
7360 * it is fixed at EXTENT_MAP_HOLE
7362 em->block_start = hole_em->block_start;
7363 em->block_len = hole_len;
7364 if (test_bit(EXTENT_FLAG_PREALLOC, &hole_em->flags))
7365 set_bit(EXTENT_FLAG_PREALLOC, &em->flags);
7367 em->start = range_start;
7369 em->orig_start = range_start;
7370 em->block_start = EXTENT_MAP_DELALLOC;
7371 em->block_len = found;
7373 } else if (hole_em) {
7378 free_extent_map(hole_em);
7380 free_extent_map(em);
7381 return ERR_PTR(err);
7386 static struct extent_map *btrfs_create_dio_extent(struct inode *inode,
7389 const u64 orig_start,
7390 const u64 block_start,
7391 const u64 block_len,
7392 const u64 orig_block_len,
7393 const u64 ram_bytes,
7396 struct extent_map *em = NULL;
7399 if (type != BTRFS_ORDERED_NOCOW) {
7400 em = create_io_em(inode, start, len, orig_start,
7401 block_start, block_len, orig_block_len,
7403 BTRFS_COMPRESS_NONE, /* compress_type */
7408 ret = btrfs_add_ordered_extent_dio(inode, start, block_start,
7409 len, block_len, type);
7412 free_extent_map(em);
7413 btrfs_drop_extent_cache(BTRFS_I(inode), start,
7414 start + len - 1, 0);
7423 static struct extent_map *btrfs_new_extent_direct(struct inode *inode,
7426 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7427 struct btrfs_root *root = BTRFS_I(inode)->root;
7428 struct extent_map *em;
7429 struct btrfs_key ins;
7433 alloc_hint = get_extent_allocation_hint(inode, start, len);
7434 ret = btrfs_reserve_extent(root, len, len, fs_info->sectorsize,
7435 0, alloc_hint, &ins, 1, 1);
7437 return ERR_PTR(ret);
7439 em = btrfs_create_dio_extent(inode, start, ins.offset, start,
7440 ins.objectid, ins.offset, ins.offset,
7441 ins.offset, BTRFS_ORDERED_REGULAR);
7442 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
7444 btrfs_free_reserved_extent(fs_info, ins.objectid,
7451 * returns 1 when the nocow is safe, < 1 on error, 0 if the
7452 * block must be cow'd
7454 noinline int can_nocow_extent(struct inode *inode, u64 offset, u64 *len,
7455 u64 *orig_start, u64 *orig_block_len,
7458 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7459 struct btrfs_path *path;
7461 struct extent_buffer *leaf;
7462 struct btrfs_root *root = BTRFS_I(inode)->root;
7463 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
7464 struct btrfs_file_extent_item *fi;
7465 struct btrfs_key key;
7472 bool nocow = (BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW);
7474 path = btrfs_alloc_path();
7478 ret = btrfs_lookup_file_extent(NULL, root, path,
7479 btrfs_ino(BTRFS_I(inode)), offset, 0);
7483 slot = path->slots[0];
7486 /* can't find the item, must cow */
7493 leaf = path->nodes[0];
7494 btrfs_item_key_to_cpu(leaf, &key, slot);
7495 if (key.objectid != btrfs_ino(BTRFS_I(inode)) ||
7496 key.type != BTRFS_EXTENT_DATA_KEY) {
7497 /* not our file or wrong item type, must cow */
7501 if (key.offset > offset) {
7502 /* Wrong offset, must cow */
7506 fi = btrfs_item_ptr(leaf, slot, struct btrfs_file_extent_item);
7507 found_type = btrfs_file_extent_type(leaf, fi);
7508 if (found_type != BTRFS_FILE_EXTENT_REG &&
7509 found_type != BTRFS_FILE_EXTENT_PREALLOC) {
7510 /* not a regular extent, must cow */
7514 if (!nocow && found_type == BTRFS_FILE_EXTENT_REG)
7517 extent_end = key.offset + btrfs_file_extent_num_bytes(leaf, fi);
7518 if (extent_end <= offset)
7521 disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
7522 if (disk_bytenr == 0)
7525 if (btrfs_file_extent_compression(leaf, fi) ||
7526 btrfs_file_extent_encryption(leaf, fi) ||
7527 btrfs_file_extent_other_encoding(leaf, fi))
7530 backref_offset = btrfs_file_extent_offset(leaf, fi);
7533 *orig_start = key.offset - backref_offset;
7534 *orig_block_len = btrfs_file_extent_disk_num_bytes(leaf, fi);
7535 *ram_bytes = btrfs_file_extent_ram_bytes(leaf, fi);
7538 if (btrfs_extent_readonly(fs_info, disk_bytenr))
7541 num_bytes = min(offset + *len, extent_end) - offset;
7542 if (!nocow && found_type == BTRFS_FILE_EXTENT_PREALLOC) {
7545 range_end = round_up(offset + num_bytes,
7546 root->fs_info->sectorsize) - 1;
7547 ret = test_range_bit(io_tree, offset, range_end,
7548 EXTENT_DELALLOC, 0, NULL);
7555 btrfs_release_path(path);
7558 * look for other files referencing this extent, if we
7559 * find any we must cow
7562 ret = btrfs_cross_ref_exist(root, btrfs_ino(BTRFS_I(inode)),
7563 key.offset - backref_offset, disk_bytenr);
7570 * adjust disk_bytenr and num_bytes to cover just the bytes
7571 * in this extent we are about to write. If there
7572 * are any csums in that range we have to cow in order
7573 * to keep the csums correct
7575 disk_bytenr += backref_offset;
7576 disk_bytenr += offset - key.offset;
7577 if (csum_exist_in_range(fs_info, disk_bytenr, num_bytes))
7580 * all of the above have passed, it is safe to overwrite this extent
7586 btrfs_free_path(path);
7590 bool btrfs_page_exists_in_range(struct inode *inode, loff_t start, loff_t end)
7592 struct radix_tree_root *root = &inode->i_mapping->page_tree;
7594 void **pagep = NULL;
7595 struct page *page = NULL;
7596 unsigned long start_idx;
7597 unsigned long end_idx;
7599 start_idx = start >> PAGE_SHIFT;
7602 * end is the last byte in the last page. end == start is legal
7604 end_idx = end >> PAGE_SHIFT;
7608 /* Most of the code in this while loop is lifted from
7609 * find_get_page. It's been modified to begin searching from a
7610 * page and return just the first page found in that range. If the
7611 * found idx is less than or equal to the end idx then we know that
7612 * a page exists. If no pages are found or if those pages are
7613 * outside of the range then we're fine (yay!) */
7614 while (page == NULL &&
7615 radix_tree_gang_lookup_slot(root, &pagep, NULL, start_idx, 1)) {
7616 page = radix_tree_deref_slot(pagep);
7617 if (unlikely(!page))
7620 if (radix_tree_exception(page)) {
7621 if (radix_tree_deref_retry(page)) {
7626 * Otherwise, shmem/tmpfs must be storing a swap entry
7627 * here as an exceptional entry: so return it without
7628 * attempting to raise page count.
7631 break; /* TODO: Is this relevant for this use case? */
7634 if (!page_cache_get_speculative(page)) {
7640 * Has the page moved?
7641 * This is part of the lockless pagecache protocol. See
7642 * include/linux/pagemap.h for details.
7644 if (unlikely(page != *pagep)) {
7651 if (page->index <= end_idx)
7660 static int lock_extent_direct(struct inode *inode, u64 lockstart, u64 lockend,
7661 struct extent_state **cached_state, int writing)
7663 struct btrfs_ordered_extent *ordered;
7667 lock_extent_bits(&BTRFS_I(inode)->io_tree, lockstart, lockend,
7670 * We're concerned with the entire range that we're going to be
7671 * doing DIO to, so we need to make sure there's no ordered
7672 * extents in this range.
7674 ordered = btrfs_lookup_ordered_range(BTRFS_I(inode), lockstart,
7675 lockend - lockstart + 1);
7678 * We need to make sure there are no buffered pages in this
7679 * range either, we could have raced between the invalidate in
7680 * generic_file_direct_write and locking the extent. The
7681 * invalidate needs to happen so that reads after a write do not
7686 !btrfs_page_exists_in_range(inode, lockstart, lockend)))
7689 unlock_extent_cached(&BTRFS_I(inode)->io_tree, lockstart, lockend,
7690 cached_state, GFP_NOFS);
7694 * If we are doing a DIO read and the ordered extent we
7695 * found is for a buffered write, we can not wait for it
7696 * to complete and retry, because if we do so we can
7697 * deadlock with concurrent buffered writes on page
7698 * locks. This happens only if our DIO read covers more
7699 * than one extent map, if at this point has already
7700 * created an ordered extent for a previous extent map
7701 * and locked its range in the inode's io tree, and a
7702 * concurrent write against that previous extent map's
7703 * range and this range started (we unlock the ranges
7704 * in the io tree only when the bios complete and
7705 * buffered writes always lock pages before attempting
7706 * to lock range in the io tree).
7709 test_bit(BTRFS_ORDERED_DIRECT, &ordered->flags))
7710 btrfs_start_ordered_extent(inode, ordered, 1);
7713 btrfs_put_ordered_extent(ordered);
7716 * We could trigger writeback for this range (and wait
7717 * for it to complete) and then invalidate the pages for
7718 * this range (through invalidate_inode_pages2_range()),
7719 * but that can lead us to a deadlock with a concurrent
7720 * call to readpages() (a buffered read or a defrag call
7721 * triggered a readahead) on a page lock due to an
7722 * ordered dio extent we created before but did not have
7723 * yet a corresponding bio submitted (whence it can not
7724 * complete), which makes readpages() wait for that
7725 * ordered extent to complete while holding a lock on
7740 /* The callers of this must take lock_extent() */
7741 static struct extent_map *create_io_em(struct inode *inode, u64 start, u64 len,
7742 u64 orig_start, u64 block_start,
7743 u64 block_len, u64 orig_block_len,
7744 u64 ram_bytes, int compress_type,
7747 struct extent_map_tree *em_tree;
7748 struct extent_map *em;
7749 struct btrfs_root *root = BTRFS_I(inode)->root;
7752 ASSERT(type == BTRFS_ORDERED_PREALLOC ||
7753 type == BTRFS_ORDERED_COMPRESSED ||
7754 type == BTRFS_ORDERED_NOCOW ||
7755 type == BTRFS_ORDERED_REGULAR);
7757 em_tree = &BTRFS_I(inode)->extent_tree;
7758 em = alloc_extent_map();
7760 return ERR_PTR(-ENOMEM);
7763 em->orig_start = orig_start;
7765 em->block_len = block_len;
7766 em->block_start = block_start;
7767 em->bdev = root->fs_info->fs_devices->latest_bdev;
7768 em->orig_block_len = orig_block_len;
7769 em->ram_bytes = ram_bytes;
7770 em->generation = -1;
7771 set_bit(EXTENT_FLAG_PINNED, &em->flags);
7772 if (type == BTRFS_ORDERED_PREALLOC) {
7773 set_bit(EXTENT_FLAG_FILLING, &em->flags);
7774 } else if (type == BTRFS_ORDERED_COMPRESSED) {
7775 set_bit(EXTENT_FLAG_COMPRESSED, &em->flags);
7776 em->compress_type = compress_type;
7780 btrfs_drop_extent_cache(BTRFS_I(inode), em->start,
7781 em->start + em->len - 1, 0);
7782 write_lock(&em_tree->lock);
7783 ret = add_extent_mapping(em_tree, em, 1);
7784 write_unlock(&em_tree->lock);
7786 * The caller has taken lock_extent(), who could race with us
7789 } while (ret == -EEXIST);
7792 free_extent_map(em);
7793 return ERR_PTR(ret);
7796 /* em got 2 refs now, callers needs to do free_extent_map once. */
7800 static void adjust_dio_outstanding_extents(struct inode *inode,
7801 struct btrfs_dio_data *dio_data,
7804 unsigned num_extents = count_max_extents(len);
7807 * If we have an outstanding_extents count still set then we're
7808 * within our reservation, otherwise we need to adjust our inode
7809 * counter appropriately.
7811 if (dio_data->outstanding_extents >= num_extents) {
7812 dio_data->outstanding_extents -= num_extents;
7815 * If dio write length has been split due to no large enough
7816 * contiguous space, we need to compensate our inode counter
7819 u64 num_needed = num_extents - dio_data->outstanding_extents;
7821 spin_lock(&BTRFS_I(inode)->lock);
7822 BTRFS_I(inode)->outstanding_extents += num_needed;
7823 spin_unlock(&BTRFS_I(inode)->lock);
7827 static int btrfs_get_blocks_direct(struct inode *inode, sector_t iblock,
7828 struct buffer_head *bh_result, int create)
7830 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7831 struct extent_map *em;
7832 struct extent_state *cached_state = NULL;
7833 struct btrfs_dio_data *dio_data = NULL;
7834 u64 start = iblock << inode->i_blkbits;
7835 u64 lockstart, lockend;
7836 u64 len = bh_result->b_size;
7837 int unlock_bits = EXTENT_LOCKED;
7841 unlock_bits |= EXTENT_DIRTY;
7843 len = min_t(u64, len, fs_info->sectorsize);
7846 lockend = start + len - 1;
7848 if (current->journal_info) {
7850 * Need to pull our outstanding extents and set journal_info to NULL so
7851 * that anything that needs to check if there's a transaction doesn't get
7854 dio_data = current->journal_info;
7855 current->journal_info = NULL;
7859 * If this errors out it's because we couldn't invalidate pagecache for
7860 * this range and we need to fallback to buffered.
7862 if (lock_extent_direct(inode, lockstart, lockend, &cached_state,
7868 em = btrfs_get_extent(BTRFS_I(inode), NULL, 0, start, len, 0);
7875 * Ok for INLINE and COMPRESSED extents we need to fallback on buffered
7876 * io. INLINE is special, and we could probably kludge it in here, but
7877 * it's still buffered so for safety lets just fall back to the generic
7880 * For COMPRESSED we _have_ to read the entire extent in so we can
7881 * decompress it, so there will be buffering required no matter what we
7882 * do, so go ahead and fallback to buffered.
7884 * We return -ENOTBLK because that's what makes DIO go ahead and go back
7885 * to buffered IO. Don't blame me, this is the price we pay for using
7888 if (test_bit(EXTENT_FLAG_COMPRESSED, &em->flags) ||
7889 em->block_start == EXTENT_MAP_INLINE) {
7890 free_extent_map(em);
7895 /* Just a good old fashioned hole, return */
7896 if (!create && (em->block_start == EXTENT_MAP_HOLE ||
7897 test_bit(EXTENT_FLAG_PREALLOC, &em->flags))) {
7898 free_extent_map(em);
7903 * We don't allocate a new extent in the following cases
7905 * 1) The inode is marked as NODATACOW. In this case we'll just use the
7907 * 2) The extent is marked as PREALLOC. We're good to go here and can
7908 * just use the extent.
7912 len = min(len, em->len - (start - em->start));
7913 lockstart = start + len;
7917 if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags) ||
7918 ((BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW) &&
7919 em->block_start != EXTENT_MAP_HOLE)) {
7921 u64 block_start, orig_start, orig_block_len, ram_bytes;
7923 if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
7924 type = BTRFS_ORDERED_PREALLOC;
7926 type = BTRFS_ORDERED_NOCOW;
7927 len = min(len, em->len - (start - em->start));
7928 block_start = em->block_start + (start - em->start);
7930 if (can_nocow_extent(inode, start, &len, &orig_start,
7931 &orig_block_len, &ram_bytes) == 1 &&
7932 btrfs_inc_nocow_writers(fs_info, block_start)) {
7933 struct extent_map *em2;
7935 em2 = btrfs_create_dio_extent(inode, start, len,
7936 orig_start, block_start,
7937 len, orig_block_len,
7939 btrfs_dec_nocow_writers(fs_info, block_start);
7940 if (type == BTRFS_ORDERED_PREALLOC) {
7941 free_extent_map(em);
7944 if (em2 && IS_ERR(em2)) {
7949 * For inode marked NODATACOW or extent marked PREALLOC,
7950 * use the existing or preallocated extent, so does not
7951 * need to adjust btrfs_space_info's bytes_may_use.
7953 btrfs_free_reserved_data_space_noquota(inode,
7960 * this will cow the extent, reset the len in case we changed
7963 len = bh_result->b_size;
7964 free_extent_map(em);
7965 em = btrfs_new_extent_direct(inode, start, len);
7970 len = min(len, em->len - (start - em->start));
7972 bh_result->b_blocknr = (em->block_start + (start - em->start)) >>
7974 bh_result->b_size = len;
7975 bh_result->b_bdev = em->bdev;
7976 set_buffer_mapped(bh_result);
7978 if (!test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
7979 set_buffer_new(bh_result);
7982 * Need to update the i_size under the extent lock so buffered
7983 * readers will get the updated i_size when we unlock.
7985 if (!dio_data->overwrite && start + len > i_size_read(inode))
7986 i_size_write(inode, start + len);
7988 adjust_dio_outstanding_extents(inode, dio_data, len);
7989 WARN_ON(dio_data->reserve < len);
7990 dio_data->reserve -= len;
7991 dio_data->unsubmitted_oe_range_end = start + len;
7992 current->journal_info = dio_data;
7996 * In the case of write we need to clear and unlock the entire range,
7997 * in the case of read we need to unlock only the end area that we
7998 * aren't using if there is any left over space.
8000 if (lockstart < lockend) {
8001 clear_extent_bit(&BTRFS_I(inode)->io_tree, lockstart,
8002 lockend, unlock_bits, 1, 0,
8003 &cached_state, GFP_NOFS);
8005 free_extent_state(cached_state);
8008 free_extent_map(em);
8013 clear_extent_bit(&BTRFS_I(inode)->io_tree, lockstart, lockend,
8014 unlock_bits, 1, 0, &cached_state, GFP_NOFS);
8017 current->journal_info = dio_data;
8019 * Compensate the delalloc release we do in btrfs_direct_IO() when we
8020 * write less data then expected, so that we don't underflow our inode's
8021 * outstanding extents counter.
8023 if (create && dio_data)
8024 adjust_dio_outstanding_extents(inode, dio_data, len);
8029 static inline int submit_dio_repair_bio(struct inode *inode, struct bio *bio,
8032 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
8035 BUG_ON(bio_op(bio) == REQ_OP_WRITE);
8039 ret = btrfs_bio_wq_end_io(fs_info, bio, BTRFS_WQ_ENDIO_DIO_REPAIR);
8043 ret = btrfs_map_bio(fs_info, bio, mirror_num, 0);
8049 static int btrfs_check_dio_repairable(struct inode *inode,
8050 struct bio *failed_bio,
8051 struct io_failure_record *failrec,
8054 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
8057 num_copies = btrfs_num_copies(fs_info, failrec->logical, failrec->len);
8058 if (num_copies == 1) {
8060 * we only have a single copy of the data, so don't bother with
8061 * all the retry and error correction code that follows. no
8062 * matter what the error is, it is very likely to persist.
8064 btrfs_debug(fs_info,
8065 "Check DIO Repairable: cannot repair, num_copies=%d, next_mirror %d, failed_mirror %d",
8066 num_copies, failrec->this_mirror, failed_mirror);
8070 failrec->failed_mirror = failed_mirror;
8071 failrec->this_mirror++;
8072 if (failrec->this_mirror == failed_mirror)
8073 failrec->this_mirror++;
8075 if (failrec->this_mirror > num_copies) {
8076 btrfs_debug(fs_info,
8077 "Check DIO Repairable: (fail) num_copies=%d, next_mirror %d, failed_mirror %d",
8078 num_copies, failrec->this_mirror, failed_mirror);
8085 static int dio_read_error(struct inode *inode, struct bio *failed_bio,
8086 struct page *page, unsigned int pgoff,
8087 u64 start, u64 end, int failed_mirror,
8088 bio_end_io_t *repair_endio, void *repair_arg)
8090 struct io_failure_record *failrec;
8091 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
8092 struct extent_io_tree *failure_tree = &BTRFS_I(inode)->io_failure_tree;
8095 unsigned int read_mode = 0;
8099 BUG_ON(bio_op(failed_bio) == REQ_OP_WRITE);
8101 ret = btrfs_get_io_failure_record(inode, start, end, &failrec);
8105 ret = btrfs_check_dio_repairable(inode, failed_bio, failrec,
8108 free_io_failure(failure_tree, io_tree, failrec);
8112 segs = bio_segments(failed_bio);
8114 (failed_bio->bi_io_vec->bv_len > btrfs_inode_sectorsize(inode)))
8115 read_mode |= REQ_FAILFAST_DEV;
8117 isector = start - btrfs_io_bio(failed_bio)->logical;
8118 isector >>= inode->i_sb->s_blocksize_bits;
8119 bio = btrfs_create_repair_bio(inode, failed_bio, failrec, page,
8120 pgoff, isector, repair_endio, repair_arg);
8121 bio_set_op_attrs(bio, REQ_OP_READ, read_mode);
8123 btrfs_debug(BTRFS_I(inode)->root->fs_info,
8124 "repair DIO read error: submitting new dio read[%#x] to this_mirror=%d, in_validation=%d",
8125 read_mode, failrec->this_mirror, failrec->in_validation);
8127 ret = submit_dio_repair_bio(inode, bio, failrec->this_mirror);
8129 free_io_failure(failure_tree, io_tree, failrec);
8136 struct btrfs_retry_complete {
8137 struct completion done;
8138 struct inode *inode;
8143 static void btrfs_retry_endio_nocsum(struct bio *bio)
8145 struct btrfs_retry_complete *done = bio->bi_private;
8146 struct inode *inode = done->inode;
8147 struct bio_vec *bvec;
8148 struct extent_io_tree *io_tree, *failure_tree;
8154 ASSERT(bio->bi_vcnt == 1);
8155 io_tree = &BTRFS_I(inode)->io_tree;
8156 failure_tree = &BTRFS_I(inode)->io_failure_tree;
8157 ASSERT(bio->bi_io_vec->bv_len == btrfs_inode_sectorsize(inode));
8160 ASSERT(!bio_flagged(bio, BIO_CLONED));
8161 bio_for_each_segment_all(bvec, bio, i)
8162 clean_io_failure(BTRFS_I(inode)->root->fs_info, failure_tree,
8163 io_tree, done->start, bvec->bv_page,
8164 btrfs_ino(BTRFS_I(inode)), 0);
8166 complete(&done->done);
8170 static int __btrfs_correct_data_nocsum(struct inode *inode,
8171 struct btrfs_io_bio *io_bio)
8173 struct btrfs_fs_info *fs_info;
8174 struct bio_vec bvec;
8175 struct bvec_iter iter;
8176 struct btrfs_retry_complete done;
8184 fs_info = BTRFS_I(inode)->root->fs_info;
8185 sectorsize = fs_info->sectorsize;
8187 start = io_bio->logical;
8189 io_bio->bio.bi_iter = io_bio->iter;
8191 bio_for_each_segment(bvec, &io_bio->bio, iter) {
8192 nr_sectors = BTRFS_BYTES_TO_BLKS(fs_info, bvec.bv_len);
8193 pgoff = bvec.bv_offset;
8195 next_block_or_try_again:
8198 init_completion(&done.done);
8200 ret = dio_read_error(inode, &io_bio->bio, bvec.bv_page,
8201 pgoff, start, start + sectorsize - 1,
8203 btrfs_retry_endio_nocsum, &done);
8209 wait_for_completion_io(&done.done);
8211 if (!done.uptodate) {
8212 /* We might have another mirror, so try again */
8213 goto next_block_or_try_again;
8217 start += sectorsize;
8221 pgoff += sectorsize;
8222 ASSERT(pgoff < PAGE_SIZE);
8223 goto next_block_or_try_again;
8230 static void btrfs_retry_endio(struct bio *bio)
8232 struct btrfs_retry_complete *done = bio->bi_private;
8233 struct btrfs_io_bio *io_bio = btrfs_io_bio(bio);
8234 struct extent_io_tree *io_tree, *failure_tree;
8235 struct inode *inode = done->inode;
8236 struct bio_vec *bvec;
8246 ASSERT(bio->bi_vcnt == 1);
8247 ASSERT(bio->bi_io_vec->bv_len == btrfs_inode_sectorsize(done->inode));
8249 io_tree = &BTRFS_I(inode)->io_tree;
8250 failure_tree = &BTRFS_I(inode)->io_failure_tree;
8252 ASSERT(!bio_flagged(bio, BIO_CLONED));
8253 bio_for_each_segment_all(bvec, bio, i) {
8254 ret = __readpage_endio_check(inode, io_bio, i, bvec->bv_page,
8255 bvec->bv_offset, done->start,
8258 clean_io_failure(BTRFS_I(inode)->root->fs_info,
8259 failure_tree, io_tree, done->start,
8261 btrfs_ino(BTRFS_I(inode)),
8267 done->uptodate = uptodate;
8269 complete(&done->done);
8273 static blk_status_t __btrfs_subio_endio_read(struct inode *inode,
8274 struct btrfs_io_bio *io_bio, blk_status_t err)
8276 struct btrfs_fs_info *fs_info;
8277 struct bio_vec bvec;
8278 struct bvec_iter iter;
8279 struct btrfs_retry_complete done;
8286 bool uptodate = (err == 0);
8289 fs_info = BTRFS_I(inode)->root->fs_info;
8290 sectorsize = fs_info->sectorsize;
8293 start = io_bio->logical;
8295 io_bio->bio.bi_iter = io_bio->iter;
8297 bio_for_each_segment(bvec, &io_bio->bio, iter) {
8298 nr_sectors = BTRFS_BYTES_TO_BLKS(fs_info, bvec.bv_len);
8300 pgoff = bvec.bv_offset;
8303 csum_pos = BTRFS_BYTES_TO_BLKS(fs_info, offset);
8304 ret = __readpage_endio_check(inode, io_bio, csum_pos,
8305 bvec.bv_page, pgoff, start, sectorsize);
8312 init_completion(&done.done);
8314 ret = dio_read_error(inode, &io_bio->bio, bvec.bv_page,
8315 pgoff, start, start + sectorsize - 1,
8317 btrfs_retry_endio, &done);
8319 err = errno_to_blk_status(ret);
8323 wait_for_completion_io(&done.done);
8325 if (!done.uptodate) {
8326 /* We might have another mirror, so try again */
8330 offset += sectorsize;
8331 start += sectorsize;
8337 pgoff += sectorsize;
8338 ASSERT(pgoff < PAGE_SIZE);
8346 static blk_status_t btrfs_subio_endio_read(struct inode *inode,
8347 struct btrfs_io_bio *io_bio, blk_status_t err)
8349 bool skip_csum = BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM;
8353 return __btrfs_correct_data_nocsum(inode, io_bio);
8357 return __btrfs_subio_endio_read(inode, io_bio, err);
8361 static void btrfs_endio_direct_read(struct bio *bio)
8363 struct btrfs_dio_private *dip = bio->bi_private;
8364 struct inode *inode = dip->inode;
8365 struct bio *dio_bio;
8366 struct btrfs_io_bio *io_bio = btrfs_io_bio(bio);
8367 blk_status_t err = bio->bi_status;
8369 if (dip->flags & BTRFS_DIO_ORIG_BIO_SUBMITTED)
8370 err = btrfs_subio_endio_read(inode, io_bio, err);
8372 unlock_extent(&BTRFS_I(inode)->io_tree, dip->logical_offset,
8373 dip->logical_offset + dip->bytes - 1);
8374 dio_bio = dip->dio_bio;
8378 dio_bio->bi_status = err;
8379 dio_end_io(dio_bio);
8382 io_bio->end_io(io_bio, blk_status_to_errno(err));
8386 static void __endio_write_update_ordered(struct inode *inode,
8387 const u64 offset, const u64 bytes,
8388 const bool uptodate)
8390 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
8391 struct btrfs_ordered_extent *ordered = NULL;
8392 struct btrfs_workqueue *wq;
8393 btrfs_work_func_t func;
8394 u64 ordered_offset = offset;
8395 u64 ordered_bytes = bytes;
8399 if (btrfs_is_free_space_inode(BTRFS_I(inode))) {
8400 wq = fs_info->endio_freespace_worker;
8401 func = btrfs_freespace_write_helper;
8403 wq = fs_info->endio_write_workers;
8404 func = btrfs_endio_write_helper;
8408 last_offset = ordered_offset;
8409 ret = btrfs_dec_test_first_ordered_pending(inode, &ordered,
8416 btrfs_init_work(&ordered->work, func, finish_ordered_fn, NULL, NULL);
8417 btrfs_queue_work(wq, &ordered->work);
8420 * If btrfs_dec_test_ordered_pending does not find any ordered extent
8421 * in the range, we can exit.
8423 if (ordered_offset == last_offset)
8426 * our bio might span multiple ordered extents. If we haven't
8427 * completed the accounting for the whole dio, go back and try again
8429 if (ordered_offset < offset + bytes) {
8430 ordered_bytes = offset + bytes - ordered_offset;
8436 static void btrfs_endio_direct_write(struct bio *bio)
8438 struct btrfs_dio_private *dip = bio->bi_private;
8439 struct bio *dio_bio = dip->dio_bio;
8441 __endio_write_update_ordered(dip->inode, dip->logical_offset,
8442 dip->bytes, !bio->bi_status);
8446 dio_bio->bi_status = bio->bi_status;
8447 dio_end_io(dio_bio);
8451 static blk_status_t __btrfs_submit_bio_start_direct_io(void *private_data,
8452 struct bio *bio, int mirror_num,
8453 unsigned long bio_flags, u64 offset)
8455 struct inode *inode = private_data;
8457 ret = btrfs_csum_one_bio(inode, bio, offset, 1);
8458 BUG_ON(ret); /* -ENOMEM */
8462 static void btrfs_end_dio_bio(struct bio *bio)
8464 struct btrfs_dio_private *dip = bio->bi_private;
8465 blk_status_t err = bio->bi_status;
8468 btrfs_warn(BTRFS_I(dip->inode)->root->fs_info,
8469 "direct IO failed ino %llu rw %d,%u sector %#Lx len %u err no %d",
8470 btrfs_ino(BTRFS_I(dip->inode)), bio_op(bio),
8472 (unsigned long long)bio->bi_iter.bi_sector,
8473 bio->bi_iter.bi_size, err);
8475 if (dip->subio_endio)
8476 err = dip->subio_endio(dip->inode, btrfs_io_bio(bio), err);
8482 * before atomic variable goto zero, we must make sure
8483 * dip->errors is perceived to be set.
8485 smp_mb__before_atomic();
8488 /* if there are more bios still pending for this dio, just exit */
8489 if (!atomic_dec_and_test(&dip->pending_bios))
8493 bio_io_error(dip->orig_bio);
8495 dip->dio_bio->bi_status = 0;
8496 bio_endio(dip->orig_bio);
8502 static inline blk_status_t btrfs_lookup_and_bind_dio_csum(struct inode *inode,
8503 struct btrfs_dio_private *dip,
8507 struct btrfs_io_bio *io_bio = btrfs_io_bio(bio);
8508 struct btrfs_io_bio *orig_io_bio = btrfs_io_bio(dip->orig_bio);
8512 * We load all the csum data we need when we submit
8513 * the first bio to reduce the csum tree search and
8516 if (dip->logical_offset == file_offset) {
8517 ret = btrfs_lookup_bio_sums_dio(inode, dip->orig_bio,
8523 if (bio == dip->orig_bio)
8526 file_offset -= dip->logical_offset;
8527 file_offset >>= inode->i_sb->s_blocksize_bits;
8528 io_bio->csum = (u8 *)(((u32 *)orig_io_bio->csum) + file_offset);
8533 static inline int __btrfs_submit_dio_bio(struct bio *bio, struct inode *inode,
8534 u64 file_offset, int async_submit)
8536 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
8537 struct btrfs_dio_private *dip = bio->bi_private;
8538 bool write = bio_op(bio) == REQ_OP_WRITE;
8542 async_submit = !atomic_read(&BTRFS_I(inode)->sync_writers);
8547 ret = btrfs_bio_wq_end_io(fs_info, bio, BTRFS_WQ_ENDIO_DATA);
8552 if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)
8555 if (write && async_submit) {
8556 ret = btrfs_wq_submit_bio(fs_info, bio, 0, 0,
8558 __btrfs_submit_bio_start_direct_io,
8559 __btrfs_submit_bio_done);
8563 * If we aren't doing async submit, calculate the csum of the
8566 ret = btrfs_csum_one_bio(inode, bio, file_offset, 1);
8570 ret = btrfs_lookup_and_bind_dio_csum(inode, dip, bio,
8576 ret = btrfs_map_bio(fs_info, bio, 0, async_submit);
8582 static int btrfs_submit_direct_hook(struct btrfs_dio_private *dip)
8584 struct inode *inode = dip->inode;
8585 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
8587 struct bio *orig_bio = dip->orig_bio;
8588 u64 start_sector = orig_bio->bi_iter.bi_sector;
8589 u64 file_offset = dip->logical_offset;
8591 int async_submit = 0;
8593 int clone_offset = 0;
8597 map_length = orig_bio->bi_iter.bi_size;
8598 submit_len = map_length;
8599 ret = btrfs_map_block(fs_info, btrfs_op(orig_bio), start_sector << 9,
8600 &map_length, NULL, 0);
8604 if (map_length >= submit_len) {
8606 dip->flags |= BTRFS_DIO_ORIG_BIO_SUBMITTED;
8610 /* async crcs make it difficult to collect full stripe writes. */
8611 if (btrfs_data_alloc_profile(fs_info) & BTRFS_BLOCK_GROUP_RAID56_MASK)
8617 ASSERT(map_length <= INT_MAX);
8618 atomic_inc(&dip->pending_bios);
8620 clone_len = min_t(int, submit_len, map_length);
8623 * This will never fail as it's passing GPF_NOFS and
8624 * the allocation is backed by btrfs_bioset.
8626 bio = btrfs_bio_clone_partial(orig_bio, clone_offset,
8628 bio->bi_private = dip;
8629 bio->bi_end_io = btrfs_end_dio_bio;
8630 btrfs_io_bio(bio)->logical = file_offset;
8632 ASSERT(submit_len >= clone_len);
8633 submit_len -= clone_len;
8634 if (submit_len == 0)
8638 * Increase the count before we submit the bio so we know
8639 * the end IO handler won't happen before we increase the
8640 * count. Otherwise, the dip might get freed before we're
8641 * done setting it up.
8643 atomic_inc(&dip->pending_bios);
8645 ret = __btrfs_submit_dio_bio(bio, inode, file_offset,
8649 atomic_dec(&dip->pending_bios);
8653 clone_offset += clone_len;
8654 start_sector += clone_len >> 9;
8655 file_offset += clone_len;
8657 map_length = submit_len;
8658 ret = btrfs_map_block(fs_info, btrfs_op(orig_bio),
8659 start_sector << 9, &map_length, NULL, 0);
8662 } while (submit_len > 0);
8665 ret = __btrfs_submit_dio_bio(bio, inode, file_offset, async_submit);
8673 * before atomic variable goto zero, we must
8674 * make sure dip->errors is perceived to be set.
8676 smp_mb__before_atomic();
8677 if (atomic_dec_and_test(&dip->pending_bios))
8678 bio_io_error(dip->orig_bio);
8680 /* bio_end_io() will handle error, so we needn't return it */
8684 static void btrfs_submit_direct(struct bio *dio_bio, struct inode *inode,
8687 struct btrfs_dio_private *dip = NULL;
8688 struct bio *bio = NULL;
8689 struct btrfs_io_bio *io_bio;
8690 bool write = (bio_op(dio_bio) == REQ_OP_WRITE);
8693 bio = btrfs_bio_clone(dio_bio);
8695 dip = kzalloc(sizeof(*dip), GFP_NOFS);
8701 dip->private = dio_bio->bi_private;
8703 dip->logical_offset = file_offset;
8704 dip->bytes = dio_bio->bi_iter.bi_size;
8705 dip->disk_bytenr = (u64)dio_bio->bi_iter.bi_sector << 9;
8706 bio->bi_private = dip;
8707 dip->orig_bio = bio;
8708 dip->dio_bio = dio_bio;
8709 atomic_set(&dip->pending_bios, 0);
8710 io_bio = btrfs_io_bio(bio);
8711 io_bio->logical = file_offset;
8714 bio->bi_end_io = btrfs_endio_direct_write;
8716 bio->bi_end_io = btrfs_endio_direct_read;
8717 dip->subio_endio = btrfs_subio_endio_read;
8721 * Reset the range for unsubmitted ordered extents (to a 0 length range)
8722 * even if we fail to submit a bio, because in such case we do the
8723 * corresponding error handling below and it must not be done a second
8724 * time by btrfs_direct_IO().
8727 struct btrfs_dio_data *dio_data = current->journal_info;
8729 dio_data->unsubmitted_oe_range_end = dip->logical_offset +
8731 dio_data->unsubmitted_oe_range_start =
8732 dio_data->unsubmitted_oe_range_end;
8735 ret = btrfs_submit_direct_hook(dip);
8740 io_bio->end_io(io_bio, ret);
8744 * If we arrived here it means either we failed to submit the dip
8745 * or we either failed to clone the dio_bio or failed to allocate the
8746 * dip. If we cloned the dio_bio and allocated the dip, we can just
8747 * call bio_endio against our io_bio so that we get proper resource
8748 * cleanup if we fail to submit the dip, otherwise, we must do the
8749 * same as btrfs_endio_direct_[write|read] because we can't call these
8750 * callbacks - they require an allocated dip and a clone of dio_bio.
8755 * The end io callbacks free our dip, do the final put on bio
8756 * and all the cleanup and final put for dio_bio (through
8763 __endio_write_update_ordered(inode,
8765 dio_bio->bi_iter.bi_size,
8768 unlock_extent(&BTRFS_I(inode)->io_tree, file_offset,
8769 file_offset + dio_bio->bi_iter.bi_size - 1);
8771 dio_bio->bi_status = BLK_STS_IOERR;
8773 * Releases and cleans up our dio_bio, no need to bio_put()
8774 * nor bio_endio()/bio_io_error() against dio_bio.
8776 dio_end_io(dio_bio);
8783 static ssize_t check_direct_IO(struct btrfs_fs_info *fs_info,
8785 const struct iov_iter *iter, loff_t offset)
8789 unsigned int blocksize_mask = fs_info->sectorsize - 1;
8790 ssize_t retval = -EINVAL;
8792 if (offset & blocksize_mask)
8795 if (iov_iter_alignment(iter) & blocksize_mask)
8798 /* If this is a write we don't need to check anymore */
8799 if (iov_iter_rw(iter) != READ || !iter_is_iovec(iter))
8802 * Check to make sure we don't have duplicate iov_base's in this
8803 * iovec, if so return EINVAL, otherwise we'll get csum errors
8804 * when reading back.
8806 for (seg = 0; seg < iter->nr_segs; seg++) {
8807 for (i = seg + 1; i < iter->nr_segs; i++) {
8808 if (iter->iov[seg].iov_base == iter->iov[i].iov_base)
8817 static ssize_t btrfs_direct_IO(struct kiocb *iocb, struct iov_iter *iter)
8819 struct file *file = iocb->ki_filp;
8820 struct inode *inode = file->f_mapping->host;
8821 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
8822 struct btrfs_dio_data dio_data = { 0 };
8823 struct extent_changeset *data_reserved = NULL;
8824 loff_t offset = iocb->ki_pos;
8828 bool relock = false;
8831 if (check_direct_IO(fs_info, iocb, iter, offset))
8834 inode_dio_begin(inode);
8837 * The generic stuff only does filemap_write_and_wait_range, which
8838 * isn't enough if we've written compressed pages to this area, so
8839 * we need to flush the dirty pages again to make absolutely sure
8840 * that any outstanding dirty pages are on disk.
8842 count = iov_iter_count(iter);
8843 if (test_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
8844 &BTRFS_I(inode)->runtime_flags))
8845 filemap_fdatawrite_range(inode->i_mapping, offset,
8846 offset + count - 1);
8848 if (iov_iter_rw(iter) == WRITE) {
8850 * If the write DIO is beyond the EOF, we need update
8851 * the isize, but it is protected by i_mutex. So we can
8852 * not unlock the i_mutex at this case.
8854 if (offset + count <= inode->i_size) {
8855 dio_data.overwrite = 1;
8856 inode_unlock(inode);
8858 } else if (iocb->ki_flags & IOCB_NOWAIT) {
8862 ret = btrfs_delalloc_reserve_space(inode, &data_reserved,
8866 dio_data.outstanding_extents = count_max_extents(count);
8869 * We need to know how many extents we reserved so that we can
8870 * do the accounting properly if we go over the number we
8871 * originally calculated. Abuse current->journal_info for this.
8873 dio_data.reserve = round_up(count,
8874 fs_info->sectorsize);
8875 dio_data.unsubmitted_oe_range_start = (u64)offset;
8876 dio_data.unsubmitted_oe_range_end = (u64)offset;
8877 current->journal_info = &dio_data;
8878 down_read(&BTRFS_I(inode)->dio_sem);
8879 } else if (test_bit(BTRFS_INODE_READDIO_NEED_LOCK,
8880 &BTRFS_I(inode)->runtime_flags)) {
8881 inode_dio_end(inode);
8882 flags = DIO_LOCKING | DIO_SKIP_HOLES;
8886 ret = __blockdev_direct_IO(iocb, inode,
8887 fs_info->fs_devices->latest_bdev,
8888 iter, btrfs_get_blocks_direct, NULL,
8889 btrfs_submit_direct, flags);
8890 if (iov_iter_rw(iter) == WRITE) {
8891 up_read(&BTRFS_I(inode)->dio_sem);
8892 current->journal_info = NULL;
8893 if (ret < 0 && ret != -EIOCBQUEUED) {
8894 if (dio_data.reserve)
8895 btrfs_delalloc_release_space(inode, data_reserved,
8896 offset, dio_data.reserve);
8898 * On error we might have left some ordered extents
8899 * without submitting corresponding bios for them, so
8900 * cleanup them up to avoid other tasks getting them
8901 * and waiting for them to complete forever.
8903 if (dio_data.unsubmitted_oe_range_start <
8904 dio_data.unsubmitted_oe_range_end)
8905 __endio_write_update_ordered(inode,
8906 dio_data.unsubmitted_oe_range_start,
8907 dio_data.unsubmitted_oe_range_end -
8908 dio_data.unsubmitted_oe_range_start,
8910 } else if (ret >= 0 && (size_t)ret < count)
8911 btrfs_delalloc_release_space(inode, data_reserved,
8912 offset, count - (size_t)ret);
8916 inode_dio_end(inode);
8920 extent_changeset_free(data_reserved);
8924 #define BTRFS_FIEMAP_FLAGS (FIEMAP_FLAG_SYNC)
8926 static int btrfs_fiemap(struct inode *inode, struct fiemap_extent_info *fieinfo,
8927 __u64 start, __u64 len)
8931 ret = fiemap_check_flags(fieinfo, BTRFS_FIEMAP_FLAGS);
8935 return extent_fiemap(inode, fieinfo, start, len, btrfs_get_extent_fiemap);
8938 int btrfs_readpage(struct file *file, struct page *page)
8940 struct extent_io_tree *tree;
8941 tree = &BTRFS_I(page->mapping->host)->io_tree;
8942 return extent_read_full_page(tree, page, btrfs_get_extent, 0);
8945 static int btrfs_writepage(struct page *page, struct writeback_control *wbc)
8947 struct extent_io_tree *tree;
8948 struct inode *inode = page->mapping->host;
8951 if (current->flags & PF_MEMALLOC) {
8952 redirty_page_for_writepage(wbc, page);
8958 * If we are under memory pressure we will call this directly from the
8959 * VM, we need to make sure we have the inode referenced for the ordered
8960 * extent. If not just return like we didn't do anything.
8962 if (!igrab(inode)) {
8963 redirty_page_for_writepage(wbc, page);
8964 return AOP_WRITEPAGE_ACTIVATE;
8966 tree = &BTRFS_I(page->mapping->host)->io_tree;
8967 ret = extent_write_full_page(tree, page, btrfs_get_extent, wbc);
8968 btrfs_add_delayed_iput(inode);
8972 static int btrfs_writepages(struct address_space *mapping,
8973 struct writeback_control *wbc)
8975 struct extent_io_tree *tree;
8977 tree = &BTRFS_I(mapping->host)->io_tree;
8978 return extent_writepages(tree, mapping, btrfs_get_extent, wbc);
8982 btrfs_readpages(struct file *file, struct address_space *mapping,
8983 struct list_head *pages, unsigned nr_pages)
8985 struct extent_io_tree *tree;
8986 tree = &BTRFS_I(mapping->host)->io_tree;
8987 return extent_readpages(tree, mapping, pages, nr_pages,
8990 static int __btrfs_releasepage(struct page *page, gfp_t gfp_flags)
8992 struct extent_io_tree *tree;
8993 struct extent_map_tree *map;
8996 tree = &BTRFS_I(page->mapping->host)->io_tree;
8997 map = &BTRFS_I(page->mapping->host)->extent_tree;
8998 ret = try_release_extent_mapping(map, tree, page, gfp_flags);
9000 ClearPagePrivate(page);
9001 set_page_private(page, 0);
9007 static int btrfs_releasepage(struct page *page, gfp_t gfp_flags)
9009 if (PageWriteback(page) || PageDirty(page))
9011 return __btrfs_releasepage(page, gfp_flags);
9014 static void btrfs_invalidatepage(struct page *page, unsigned int offset,
9015 unsigned int length)
9017 struct inode *inode = page->mapping->host;
9018 struct extent_io_tree *tree;
9019 struct btrfs_ordered_extent *ordered;
9020 struct extent_state *cached_state = NULL;
9021 u64 page_start = page_offset(page);
9022 u64 page_end = page_start + PAGE_SIZE - 1;
9025 int inode_evicting = inode->i_state & I_FREEING;
9028 * we have the page locked, so new writeback can't start,
9029 * and the dirty bit won't be cleared while we are here.
9031 * Wait for IO on this page so that we can safely clear
9032 * the PagePrivate2 bit and do ordered accounting
9034 wait_on_page_writeback(page);
9036 tree = &BTRFS_I(inode)->io_tree;
9038 btrfs_releasepage(page, GFP_NOFS);
9042 if (!inode_evicting)
9043 lock_extent_bits(tree, page_start, page_end, &cached_state);
9046 ordered = btrfs_lookup_ordered_range(BTRFS_I(inode), start,
9047 page_end - start + 1);
9049 end = min(page_end, ordered->file_offset + ordered->len - 1);
9051 * IO on this page will never be started, so we need
9052 * to account for any ordered extents now
9054 if (!inode_evicting)
9055 clear_extent_bit(tree, start, end,
9056 EXTENT_DIRTY | EXTENT_DELALLOC |
9057 EXTENT_DELALLOC_NEW |
9058 EXTENT_LOCKED | EXTENT_DO_ACCOUNTING |
9059 EXTENT_DEFRAG, 1, 0, &cached_state,
9062 * whoever cleared the private bit is responsible
9063 * for the finish_ordered_io
9065 if (TestClearPagePrivate2(page)) {
9066 struct btrfs_ordered_inode_tree *tree;
9069 tree = &BTRFS_I(inode)->ordered_tree;
9071 spin_lock_irq(&tree->lock);
9072 set_bit(BTRFS_ORDERED_TRUNCATED, &ordered->flags);
9073 new_len = start - ordered->file_offset;
9074 if (new_len < ordered->truncated_len)
9075 ordered->truncated_len = new_len;
9076 spin_unlock_irq(&tree->lock);
9078 if (btrfs_dec_test_ordered_pending(inode, &ordered,
9080 end - start + 1, 1))
9081 btrfs_finish_ordered_io(ordered);
9083 btrfs_put_ordered_extent(ordered);
9084 if (!inode_evicting) {
9085 cached_state = NULL;
9086 lock_extent_bits(tree, start, end,
9091 if (start < page_end)
9096 * Qgroup reserved space handler
9097 * Page here will be either
9098 * 1) Already written to disk
9099 * In this case, its reserved space is released from data rsv map
9100 * and will be freed by delayed_ref handler finally.
9101 * So even we call qgroup_free_data(), it won't decrease reserved
9103 * 2) Not written to disk
9104 * This means the reserved space should be freed here. However,
9105 * if a truncate invalidates the page (by clearing PageDirty)
9106 * and the page is accounted for while allocating extent
9107 * in btrfs_check_data_free_space() we let delayed_ref to
9108 * free the entire extent.
9110 if (PageDirty(page))
9111 btrfs_qgroup_free_data(inode, NULL, page_start, PAGE_SIZE);
9112 if (!inode_evicting) {
9113 clear_extent_bit(tree, page_start, page_end,
9114 EXTENT_LOCKED | EXTENT_DIRTY |
9115 EXTENT_DELALLOC | EXTENT_DELALLOC_NEW |
9116 EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG, 1, 1,
9117 &cached_state, GFP_NOFS);
9119 __btrfs_releasepage(page, GFP_NOFS);
9122 ClearPageChecked(page);
9123 if (PagePrivate(page)) {
9124 ClearPagePrivate(page);
9125 set_page_private(page, 0);
9131 * btrfs_page_mkwrite() is not allowed to change the file size as it gets
9132 * called from a page fault handler when a page is first dirtied. Hence we must
9133 * be careful to check for EOF conditions here. We set the page up correctly
9134 * for a written page which means we get ENOSPC checking when writing into
9135 * holes and correct delalloc and unwritten extent mapping on filesystems that
9136 * support these features.
9138 * We are not allowed to take the i_mutex here so we have to play games to
9139 * protect against truncate races as the page could now be beyond EOF. Because
9140 * vmtruncate() writes the inode size before removing pages, once we have the
9141 * page lock we can determine safely if the page is beyond EOF. If it is not
9142 * beyond EOF, then the page is guaranteed safe against truncation until we
9145 int btrfs_page_mkwrite(struct vm_fault *vmf)
9147 struct page *page = vmf->page;
9148 struct inode *inode = file_inode(vmf->vma->vm_file);
9149 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
9150 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
9151 struct btrfs_ordered_extent *ordered;
9152 struct extent_state *cached_state = NULL;
9153 struct extent_changeset *data_reserved = NULL;
9155 unsigned long zero_start;
9164 reserved_space = PAGE_SIZE;
9166 sb_start_pagefault(inode->i_sb);
9167 page_start = page_offset(page);
9168 page_end = page_start + PAGE_SIZE - 1;
9172 * Reserving delalloc space after obtaining the page lock can lead to
9173 * deadlock. For example, if a dirty page is locked by this function
9174 * and the call to btrfs_delalloc_reserve_space() ends up triggering
9175 * dirty page write out, then the btrfs_writepage() function could
9176 * end up waiting indefinitely to get a lock on the page currently
9177 * being processed by btrfs_page_mkwrite() function.
9179 ret = btrfs_delalloc_reserve_space(inode, &data_reserved, page_start,
9182 ret = file_update_time(vmf->vma->vm_file);
9188 else /* -ENOSPC, -EIO, etc */
9189 ret = VM_FAULT_SIGBUS;
9195 ret = VM_FAULT_NOPAGE; /* make the VM retry the fault */
9198 size = i_size_read(inode);
9200 if ((page->mapping != inode->i_mapping) ||
9201 (page_start >= size)) {
9202 /* page got truncated out from underneath us */
9205 wait_on_page_writeback(page);
9207 lock_extent_bits(io_tree, page_start, page_end, &cached_state);
9208 set_page_extent_mapped(page);
9211 * we can't set the delalloc bits if there are pending ordered
9212 * extents. Drop our locks and wait for them to finish
9214 ordered = btrfs_lookup_ordered_range(BTRFS_I(inode), page_start,
9217 unlock_extent_cached(io_tree, page_start, page_end,
9218 &cached_state, GFP_NOFS);
9220 btrfs_start_ordered_extent(inode, ordered, 1);
9221 btrfs_put_ordered_extent(ordered);
9225 if (page->index == ((size - 1) >> PAGE_SHIFT)) {
9226 reserved_space = round_up(size - page_start,
9227 fs_info->sectorsize);
9228 if (reserved_space < PAGE_SIZE) {
9229 end = page_start + reserved_space - 1;
9230 spin_lock(&BTRFS_I(inode)->lock);
9231 BTRFS_I(inode)->outstanding_extents++;
9232 spin_unlock(&BTRFS_I(inode)->lock);
9233 btrfs_delalloc_release_space(inode, data_reserved,
9234 page_start, PAGE_SIZE - reserved_space);
9239 * page_mkwrite gets called when the page is firstly dirtied after it's
9240 * faulted in, but write(2) could also dirty a page and set delalloc
9241 * bits, thus in this case for space account reason, we still need to
9242 * clear any delalloc bits within this page range since we have to
9243 * reserve data&meta space before lock_page() (see above comments).
9245 clear_extent_bit(&BTRFS_I(inode)->io_tree, page_start, end,
9246 EXTENT_DIRTY | EXTENT_DELALLOC |
9247 EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG,
9248 0, 0, &cached_state, GFP_NOFS);
9250 ret = btrfs_set_extent_delalloc(inode, page_start, end,
9253 unlock_extent_cached(io_tree, page_start, page_end,
9254 &cached_state, GFP_NOFS);
9255 ret = VM_FAULT_SIGBUS;
9260 /* page is wholly or partially inside EOF */
9261 if (page_start + PAGE_SIZE > size)
9262 zero_start = size & ~PAGE_MASK;
9264 zero_start = PAGE_SIZE;
9266 if (zero_start != PAGE_SIZE) {
9268 memset(kaddr + zero_start, 0, PAGE_SIZE - zero_start);
9269 flush_dcache_page(page);
9272 ClearPageChecked(page);
9273 set_page_dirty(page);
9274 SetPageUptodate(page);
9276 BTRFS_I(inode)->last_trans = fs_info->generation;
9277 BTRFS_I(inode)->last_sub_trans = BTRFS_I(inode)->root->log_transid;
9278 BTRFS_I(inode)->last_log_commit = BTRFS_I(inode)->root->last_log_commit;
9280 unlock_extent_cached(io_tree, page_start, page_end, &cached_state, GFP_NOFS);
9284 sb_end_pagefault(inode->i_sb);
9285 extent_changeset_free(data_reserved);
9286 return VM_FAULT_LOCKED;
9290 btrfs_delalloc_release_space(inode, data_reserved, page_start,
9293 sb_end_pagefault(inode->i_sb);
9294 extent_changeset_free(data_reserved);
9298 static int btrfs_truncate(struct inode *inode)
9300 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
9301 struct btrfs_root *root = BTRFS_I(inode)->root;
9302 struct btrfs_block_rsv *rsv;
9305 struct btrfs_trans_handle *trans;
9306 u64 mask = fs_info->sectorsize - 1;
9307 u64 min_size = btrfs_calc_trunc_metadata_size(fs_info, 1);
9309 ret = btrfs_wait_ordered_range(inode, inode->i_size & (~mask),
9315 * Yes ladies and gentlemen, this is indeed ugly. The fact is we have
9316 * 3 things going on here
9318 * 1) We need to reserve space for our orphan item and the space to
9319 * delete our orphan item. Lord knows we don't want to have a dangling
9320 * orphan item because we didn't reserve space to remove it.
9322 * 2) We need to reserve space to update our inode.
9324 * 3) We need to have something to cache all the space that is going to
9325 * be free'd up by the truncate operation, but also have some slack
9326 * space reserved in case it uses space during the truncate (thank you
9327 * very much snapshotting).
9329 * And we need these to all be separate. The fact is we can use a lot of
9330 * space doing the truncate, and we have no earthly idea how much space
9331 * we will use, so we need the truncate reservation to be separate so it
9332 * doesn't end up using space reserved for updating the inode or
9333 * removing the orphan item. We also need to be able to stop the
9334 * transaction and start a new one, which means we need to be able to
9335 * update the inode several times, and we have no idea of knowing how
9336 * many times that will be, so we can't just reserve 1 item for the
9337 * entirety of the operation, so that has to be done separately as well.
9338 * Then there is the orphan item, which does indeed need to be held on
9339 * to for the whole operation, and we need nobody to touch this reserved
9340 * space except the orphan code.
9342 * So that leaves us with
9344 * 1) root->orphan_block_rsv - for the orphan deletion.
9345 * 2) rsv - for the truncate reservation, which we will steal from the
9346 * transaction reservation.
9347 * 3) fs_info->trans_block_rsv - this will have 1 items worth left for
9348 * updating the inode.
9350 rsv = btrfs_alloc_block_rsv(fs_info, BTRFS_BLOCK_RSV_TEMP);
9353 rsv->size = min_size;
9357 * 1 for the truncate slack space
9358 * 1 for updating the inode.
9360 trans = btrfs_start_transaction(root, 2);
9361 if (IS_ERR(trans)) {
9362 err = PTR_ERR(trans);
9366 /* Migrate the slack space for the truncate to our reserve */
9367 ret = btrfs_block_rsv_migrate(&fs_info->trans_block_rsv, rsv,
9372 * So if we truncate and then write and fsync we normally would just
9373 * write the extents that changed, which is a problem if we need to
9374 * first truncate that entire inode. So set this flag so we write out
9375 * all of the extents in the inode to the sync log so we're completely
9378 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &BTRFS_I(inode)->runtime_flags);
9379 trans->block_rsv = rsv;
9382 ret = btrfs_truncate_inode_items(trans, root, inode,
9384 BTRFS_EXTENT_DATA_KEY);
9385 if (ret != -ENOSPC && ret != -EAGAIN) {
9390 trans->block_rsv = &fs_info->trans_block_rsv;
9391 ret = btrfs_update_inode(trans, root, inode);
9397 btrfs_end_transaction(trans);
9398 btrfs_btree_balance_dirty(fs_info);
9400 trans = btrfs_start_transaction(root, 2);
9401 if (IS_ERR(trans)) {
9402 ret = err = PTR_ERR(trans);
9407 btrfs_block_rsv_release(fs_info, rsv, -1);
9408 ret = btrfs_block_rsv_migrate(&fs_info->trans_block_rsv,
9410 BUG_ON(ret); /* shouldn't happen */
9411 trans->block_rsv = rsv;
9414 if (ret == 0 && inode->i_nlink > 0) {
9415 trans->block_rsv = root->orphan_block_rsv;
9416 ret = btrfs_orphan_del(trans, BTRFS_I(inode));
9422 trans->block_rsv = &fs_info->trans_block_rsv;
9423 ret = btrfs_update_inode(trans, root, inode);
9427 ret = btrfs_end_transaction(trans);
9428 btrfs_btree_balance_dirty(fs_info);
9431 btrfs_free_block_rsv(fs_info, rsv);
9440 * create a new subvolume directory/inode (helper for the ioctl).
9442 int btrfs_create_subvol_root(struct btrfs_trans_handle *trans,
9443 struct btrfs_root *new_root,
9444 struct btrfs_root *parent_root,
9447 struct inode *inode;
9451 inode = btrfs_new_inode(trans, new_root, NULL, "..", 2,
9452 new_dirid, new_dirid,
9453 S_IFDIR | (~current_umask() & S_IRWXUGO),
9456 return PTR_ERR(inode);
9457 inode->i_op = &btrfs_dir_inode_operations;
9458 inode->i_fop = &btrfs_dir_file_operations;
9460 set_nlink(inode, 1);
9461 btrfs_i_size_write(BTRFS_I(inode), 0);
9462 unlock_new_inode(inode);
9464 err = btrfs_subvol_inherit_props(trans, new_root, parent_root);
9466 btrfs_err(new_root->fs_info,
9467 "error inheriting subvolume %llu properties: %d",
9468 new_root->root_key.objectid, err);
9470 err = btrfs_update_inode(trans, new_root, inode);
9476 struct inode *btrfs_alloc_inode(struct super_block *sb)
9478 struct btrfs_inode *ei;
9479 struct inode *inode;
9481 ei = kmem_cache_alloc(btrfs_inode_cachep, GFP_NOFS);
9488 ei->last_sub_trans = 0;
9489 ei->logged_trans = 0;
9490 ei->delalloc_bytes = 0;
9491 ei->new_delalloc_bytes = 0;
9492 ei->defrag_bytes = 0;
9493 ei->disk_i_size = 0;
9496 ei->index_cnt = (u64)-1;
9498 ei->last_unlink_trans = 0;
9499 ei->last_log_commit = 0;
9500 ei->delayed_iput_count = 0;
9502 spin_lock_init(&ei->lock);
9503 ei->outstanding_extents = 0;
9504 ei->reserved_extents = 0;
9506 ei->runtime_flags = 0;
9507 ei->prop_compress = BTRFS_COMPRESS_NONE;
9508 ei->defrag_compress = BTRFS_COMPRESS_NONE;
9510 ei->delayed_node = NULL;
9512 ei->i_otime.tv_sec = 0;
9513 ei->i_otime.tv_nsec = 0;
9515 inode = &ei->vfs_inode;
9516 extent_map_tree_init(&ei->extent_tree);
9517 extent_io_tree_init(&ei->io_tree, inode);
9518 extent_io_tree_init(&ei->io_failure_tree, inode);
9519 ei->io_tree.track_uptodate = 1;
9520 ei->io_failure_tree.track_uptodate = 1;
9521 atomic_set(&ei->sync_writers, 0);
9522 mutex_init(&ei->log_mutex);
9523 mutex_init(&ei->delalloc_mutex);
9524 btrfs_ordered_inode_tree_init(&ei->ordered_tree);
9525 INIT_LIST_HEAD(&ei->delalloc_inodes);
9526 INIT_LIST_HEAD(&ei->delayed_iput);
9527 RB_CLEAR_NODE(&ei->rb_node);
9528 init_rwsem(&ei->dio_sem);
9533 #ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
9534 void btrfs_test_destroy_inode(struct inode *inode)
9536 btrfs_drop_extent_cache(BTRFS_I(inode), 0, (u64)-1, 0);
9537 kmem_cache_free(btrfs_inode_cachep, BTRFS_I(inode));
9541 static void btrfs_i_callback(struct rcu_head *head)
9543 struct inode *inode = container_of(head, struct inode, i_rcu);
9544 kmem_cache_free(btrfs_inode_cachep, BTRFS_I(inode));
9547 void btrfs_destroy_inode(struct inode *inode)
9549 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
9550 struct btrfs_ordered_extent *ordered;
9551 struct btrfs_root *root = BTRFS_I(inode)->root;
9553 WARN_ON(!hlist_empty(&inode->i_dentry));
9554 WARN_ON(inode->i_data.nrpages);
9555 WARN_ON(BTRFS_I(inode)->outstanding_extents);
9556 WARN_ON(BTRFS_I(inode)->reserved_extents);
9557 WARN_ON(BTRFS_I(inode)->delalloc_bytes);
9558 WARN_ON(BTRFS_I(inode)->new_delalloc_bytes);
9559 WARN_ON(BTRFS_I(inode)->csum_bytes);
9560 WARN_ON(BTRFS_I(inode)->defrag_bytes);
9563 * This can happen where we create an inode, but somebody else also
9564 * created the same inode and we need to destroy the one we already
9570 if (test_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
9571 &BTRFS_I(inode)->runtime_flags)) {
9572 btrfs_info(fs_info, "inode %llu still on the orphan list",
9573 btrfs_ino(BTRFS_I(inode)));
9574 atomic_dec(&root->orphan_inodes);
9578 ordered = btrfs_lookup_first_ordered_extent(inode, (u64)-1);
9583 "found ordered extent %llu %llu on inode cleanup",
9584 ordered->file_offset, ordered->len);
9585 btrfs_remove_ordered_extent(inode, ordered);
9586 btrfs_put_ordered_extent(ordered);
9587 btrfs_put_ordered_extent(ordered);
9590 btrfs_qgroup_check_reserved_leak(inode);
9591 inode_tree_del(inode);
9592 btrfs_drop_extent_cache(BTRFS_I(inode), 0, (u64)-1, 0);
9594 call_rcu(&inode->i_rcu, btrfs_i_callback);
9597 int btrfs_drop_inode(struct inode *inode)
9599 struct btrfs_root *root = BTRFS_I(inode)->root;
9604 /* the snap/subvol tree is on deleting */
9605 if (btrfs_root_refs(&root->root_item) == 0)
9608 return generic_drop_inode(inode);
9611 static void init_once(void *foo)
9613 struct btrfs_inode *ei = (struct btrfs_inode *) foo;
9615 inode_init_once(&ei->vfs_inode);
9618 void btrfs_destroy_cachep(void)
9621 * Make sure all delayed rcu free inodes are flushed before we
9625 kmem_cache_destroy(btrfs_inode_cachep);
9626 kmem_cache_destroy(btrfs_trans_handle_cachep);
9627 kmem_cache_destroy(btrfs_path_cachep);
9628 kmem_cache_destroy(btrfs_free_space_cachep);
9631 int btrfs_init_cachep(void)
9633 btrfs_inode_cachep = kmem_cache_create("btrfs_inode",
9634 sizeof(struct btrfs_inode), 0,
9635 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD | SLAB_ACCOUNT,
9637 if (!btrfs_inode_cachep)
9640 btrfs_trans_handle_cachep = kmem_cache_create("btrfs_trans_handle",
9641 sizeof(struct btrfs_trans_handle), 0,
9642 SLAB_TEMPORARY | SLAB_MEM_SPREAD, NULL);
9643 if (!btrfs_trans_handle_cachep)
9646 btrfs_path_cachep = kmem_cache_create("btrfs_path",
9647 sizeof(struct btrfs_path), 0,
9648 SLAB_MEM_SPREAD, NULL);
9649 if (!btrfs_path_cachep)
9652 btrfs_free_space_cachep = kmem_cache_create("btrfs_free_space",
9653 sizeof(struct btrfs_free_space), 0,
9654 SLAB_MEM_SPREAD, NULL);
9655 if (!btrfs_free_space_cachep)
9660 btrfs_destroy_cachep();
9664 static int btrfs_getattr(const struct path *path, struct kstat *stat,
9665 u32 request_mask, unsigned int flags)
9668 struct inode *inode = d_inode(path->dentry);
9669 u32 blocksize = inode->i_sb->s_blocksize;
9670 u32 bi_flags = BTRFS_I(inode)->flags;
9672 stat->result_mask |= STATX_BTIME;
9673 stat->btime.tv_sec = BTRFS_I(inode)->i_otime.tv_sec;
9674 stat->btime.tv_nsec = BTRFS_I(inode)->i_otime.tv_nsec;
9675 if (bi_flags & BTRFS_INODE_APPEND)
9676 stat->attributes |= STATX_ATTR_APPEND;
9677 if (bi_flags & BTRFS_INODE_COMPRESS)
9678 stat->attributes |= STATX_ATTR_COMPRESSED;
9679 if (bi_flags & BTRFS_INODE_IMMUTABLE)
9680 stat->attributes |= STATX_ATTR_IMMUTABLE;
9681 if (bi_flags & BTRFS_INODE_NODUMP)
9682 stat->attributes |= STATX_ATTR_NODUMP;
9684 stat->attributes_mask |= (STATX_ATTR_APPEND |
9685 STATX_ATTR_COMPRESSED |
9686 STATX_ATTR_IMMUTABLE |
9689 generic_fillattr(inode, stat);
9690 stat->dev = BTRFS_I(inode)->root->anon_dev;
9692 spin_lock(&BTRFS_I(inode)->lock);
9693 delalloc_bytes = BTRFS_I(inode)->new_delalloc_bytes;
9694 spin_unlock(&BTRFS_I(inode)->lock);
9695 stat->blocks = (ALIGN(inode_get_bytes(inode), blocksize) +
9696 ALIGN(delalloc_bytes, blocksize)) >> 9;
9700 static int btrfs_rename_exchange(struct inode *old_dir,
9701 struct dentry *old_dentry,
9702 struct inode *new_dir,
9703 struct dentry *new_dentry)
9705 struct btrfs_fs_info *fs_info = btrfs_sb(old_dir->i_sb);
9706 struct btrfs_trans_handle *trans;
9707 struct btrfs_root *root = BTRFS_I(old_dir)->root;
9708 struct btrfs_root *dest = BTRFS_I(new_dir)->root;
9709 struct inode *new_inode = new_dentry->d_inode;
9710 struct inode *old_inode = old_dentry->d_inode;
9711 struct timespec ctime = current_time(old_inode);
9712 struct dentry *parent;
9713 u64 old_ino = btrfs_ino(BTRFS_I(old_inode));
9714 u64 new_ino = btrfs_ino(BTRFS_I(new_inode));
9719 bool root_log_pinned = false;
9720 bool dest_log_pinned = false;
9722 /* we only allow rename subvolume link between subvolumes */
9723 if (old_ino != BTRFS_FIRST_FREE_OBJECTID && root != dest)
9726 /* close the race window with snapshot create/destroy ioctl */
9727 if (old_ino == BTRFS_FIRST_FREE_OBJECTID)
9728 down_read(&fs_info->subvol_sem);
9729 if (new_ino == BTRFS_FIRST_FREE_OBJECTID)
9730 down_read(&fs_info->subvol_sem);
9733 * We want to reserve the absolute worst case amount of items. So if
9734 * both inodes are subvols and we need to unlink them then that would
9735 * require 4 item modifications, but if they are both normal inodes it
9736 * would require 5 item modifications, so we'll assume their normal
9737 * inodes. So 5 * 2 is 10, plus 2 for the new links, so 12 total items
9738 * should cover the worst case number of items we'll modify.
9740 trans = btrfs_start_transaction(root, 12);
9741 if (IS_ERR(trans)) {
9742 ret = PTR_ERR(trans);
9747 * We need to find a free sequence number both in the source and
9748 * in the destination directory for the exchange.
9750 ret = btrfs_set_inode_index(BTRFS_I(new_dir), &old_idx);
9753 ret = btrfs_set_inode_index(BTRFS_I(old_dir), &new_idx);
9757 BTRFS_I(old_inode)->dir_index = 0ULL;
9758 BTRFS_I(new_inode)->dir_index = 0ULL;
9760 /* Reference for the source. */
9761 if (old_ino == BTRFS_FIRST_FREE_OBJECTID) {
9762 /* force full log commit if subvolume involved. */
9763 btrfs_set_log_full_commit(fs_info, trans);
9765 btrfs_pin_log_trans(root);
9766 root_log_pinned = true;
9767 ret = btrfs_insert_inode_ref(trans, dest,
9768 new_dentry->d_name.name,
9769 new_dentry->d_name.len,
9771 btrfs_ino(BTRFS_I(new_dir)),
9777 /* And now for the dest. */
9778 if (new_ino == BTRFS_FIRST_FREE_OBJECTID) {
9779 /* force full log commit if subvolume involved. */
9780 btrfs_set_log_full_commit(fs_info, trans);
9782 btrfs_pin_log_trans(dest);
9783 dest_log_pinned = true;
9784 ret = btrfs_insert_inode_ref(trans, root,
9785 old_dentry->d_name.name,
9786 old_dentry->d_name.len,
9788 btrfs_ino(BTRFS_I(old_dir)),
9794 /* Update inode version and ctime/mtime. */
9795 inode_inc_iversion(old_dir);
9796 inode_inc_iversion(new_dir);
9797 inode_inc_iversion(old_inode);
9798 inode_inc_iversion(new_inode);
9799 old_dir->i_ctime = old_dir->i_mtime = ctime;
9800 new_dir->i_ctime = new_dir->i_mtime = ctime;
9801 old_inode->i_ctime = ctime;
9802 new_inode->i_ctime = ctime;
9804 if (old_dentry->d_parent != new_dentry->d_parent) {
9805 btrfs_record_unlink_dir(trans, BTRFS_I(old_dir),
9806 BTRFS_I(old_inode), 1);
9807 btrfs_record_unlink_dir(trans, BTRFS_I(new_dir),
9808 BTRFS_I(new_inode), 1);
9811 /* src is a subvolume */
9812 if (old_ino == BTRFS_FIRST_FREE_OBJECTID) {
9813 root_objectid = BTRFS_I(old_inode)->root->root_key.objectid;
9814 ret = btrfs_unlink_subvol(trans, root, old_dir,
9816 old_dentry->d_name.name,
9817 old_dentry->d_name.len);
9818 } else { /* src is an inode */
9819 ret = __btrfs_unlink_inode(trans, root, BTRFS_I(old_dir),
9820 BTRFS_I(old_dentry->d_inode),
9821 old_dentry->d_name.name,
9822 old_dentry->d_name.len);
9824 ret = btrfs_update_inode(trans, root, old_inode);
9827 btrfs_abort_transaction(trans, ret);
9831 /* dest is a subvolume */
9832 if (new_ino == BTRFS_FIRST_FREE_OBJECTID) {
9833 root_objectid = BTRFS_I(new_inode)->root->root_key.objectid;
9834 ret = btrfs_unlink_subvol(trans, dest, new_dir,
9836 new_dentry->d_name.name,
9837 new_dentry->d_name.len);
9838 } else { /* dest is an inode */
9839 ret = __btrfs_unlink_inode(trans, dest, BTRFS_I(new_dir),
9840 BTRFS_I(new_dentry->d_inode),
9841 new_dentry->d_name.name,
9842 new_dentry->d_name.len);
9844 ret = btrfs_update_inode(trans, dest, new_inode);
9847 btrfs_abort_transaction(trans, ret);
9851 ret = btrfs_add_link(trans, BTRFS_I(new_dir), BTRFS_I(old_inode),
9852 new_dentry->d_name.name,
9853 new_dentry->d_name.len, 0, old_idx);
9855 btrfs_abort_transaction(trans, ret);
9859 ret = btrfs_add_link(trans, BTRFS_I(old_dir), BTRFS_I(new_inode),
9860 old_dentry->d_name.name,
9861 old_dentry->d_name.len, 0, new_idx);
9863 btrfs_abort_transaction(trans, ret);
9867 if (old_inode->i_nlink == 1)
9868 BTRFS_I(old_inode)->dir_index = old_idx;
9869 if (new_inode->i_nlink == 1)
9870 BTRFS_I(new_inode)->dir_index = new_idx;
9872 if (root_log_pinned) {
9873 parent = new_dentry->d_parent;
9874 btrfs_log_new_name(trans, BTRFS_I(old_inode), BTRFS_I(old_dir),
9876 btrfs_end_log_trans(root);
9877 root_log_pinned = false;
9879 if (dest_log_pinned) {
9880 parent = old_dentry->d_parent;
9881 btrfs_log_new_name(trans, BTRFS_I(new_inode), BTRFS_I(new_dir),
9883 btrfs_end_log_trans(dest);
9884 dest_log_pinned = false;
9888 * If we have pinned a log and an error happened, we unpin tasks
9889 * trying to sync the log and force them to fallback to a transaction
9890 * commit if the log currently contains any of the inodes involved in
9891 * this rename operation (to ensure we do not persist a log with an
9892 * inconsistent state for any of these inodes or leading to any
9893 * inconsistencies when replayed). If the transaction was aborted, the
9894 * abortion reason is propagated to userspace when attempting to commit
9895 * the transaction. If the log does not contain any of these inodes, we
9896 * allow the tasks to sync it.
9898 if (ret && (root_log_pinned || dest_log_pinned)) {
9899 if (btrfs_inode_in_log(BTRFS_I(old_dir), fs_info->generation) ||
9900 btrfs_inode_in_log(BTRFS_I(new_dir), fs_info->generation) ||
9901 btrfs_inode_in_log(BTRFS_I(old_inode), fs_info->generation) ||
9903 btrfs_inode_in_log(BTRFS_I(new_inode), fs_info->generation)))
9904 btrfs_set_log_full_commit(fs_info, trans);
9906 if (root_log_pinned) {
9907 btrfs_end_log_trans(root);
9908 root_log_pinned = false;
9910 if (dest_log_pinned) {
9911 btrfs_end_log_trans(dest);
9912 dest_log_pinned = false;
9915 ret = btrfs_end_transaction(trans);
9917 if (new_ino == BTRFS_FIRST_FREE_OBJECTID)
9918 up_read(&fs_info->subvol_sem);
9919 if (old_ino == BTRFS_FIRST_FREE_OBJECTID)
9920 up_read(&fs_info->subvol_sem);
9925 static int btrfs_whiteout_for_rename(struct btrfs_trans_handle *trans,
9926 struct btrfs_root *root,
9928 struct dentry *dentry)
9931 struct inode *inode;
9935 ret = btrfs_find_free_ino(root, &objectid);
9939 inode = btrfs_new_inode(trans, root, dir,
9940 dentry->d_name.name,
9942 btrfs_ino(BTRFS_I(dir)),
9944 S_IFCHR | WHITEOUT_MODE,
9947 if (IS_ERR(inode)) {
9948 ret = PTR_ERR(inode);
9952 inode->i_op = &btrfs_special_inode_operations;
9953 init_special_inode(inode, inode->i_mode,
9956 ret = btrfs_init_inode_security(trans, inode, dir,
9961 ret = btrfs_add_nondir(trans, BTRFS_I(dir), dentry,
9962 BTRFS_I(inode), 0, index);
9966 ret = btrfs_update_inode(trans, root, inode);
9968 unlock_new_inode(inode);
9970 inode_dec_link_count(inode);
9976 static int btrfs_rename(struct inode *old_dir, struct dentry *old_dentry,
9977 struct inode *new_dir, struct dentry *new_dentry,
9980 struct btrfs_fs_info *fs_info = btrfs_sb(old_dir->i_sb);
9981 struct btrfs_trans_handle *trans;
9982 unsigned int trans_num_items;
9983 struct btrfs_root *root = BTRFS_I(old_dir)->root;
9984 struct btrfs_root *dest = BTRFS_I(new_dir)->root;
9985 struct inode *new_inode = d_inode(new_dentry);
9986 struct inode *old_inode = d_inode(old_dentry);
9990 u64 old_ino = btrfs_ino(BTRFS_I(old_inode));
9991 bool log_pinned = false;
9993 if (btrfs_ino(BTRFS_I(new_dir)) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)
9996 /* we only allow rename subvolume link between subvolumes */
9997 if (old_ino != BTRFS_FIRST_FREE_OBJECTID && root != dest)
10000 if (old_ino == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID ||
10001 (new_inode && btrfs_ino(BTRFS_I(new_inode)) == BTRFS_FIRST_FREE_OBJECTID))
10004 if (S_ISDIR(old_inode->i_mode) && new_inode &&
10005 new_inode->i_size > BTRFS_EMPTY_DIR_SIZE)
10009 /* check for collisions, even if the name isn't there */
10010 ret = btrfs_check_dir_item_collision(dest, new_dir->i_ino,
10011 new_dentry->d_name.name,
10012 new_dentry->d_name.len);
10015 if (ret == -EEXIST) {
10016 /* we shouldn't get
10017 * eexist without a new_inode */
10018 if (WARN_ON(!new_inode)) {
10022 /* maybe -EOVERFLOW */
10029 * we're using rename to replace one file with another. Start IO on it
10030 * now so we don't add too much work to the end of the transaction
10032 if (new_inode && S_ISREG(old_inode->i_mode) && new_inode->i_size)
10033 filemap_flush(old_inode->i_mapping);
10035 /* close the racy window with snapshot create/destroy ioctl */
10036 if (old_ino == BTRFS_FIRST_FREE_OBJECTID)
10037 down_read(&fs_info->subvol_sem);
10039 * We want to reserve the absolute worst case amount of items. So if
10040 * both inodes are subvols and we need to unlink them then that would
10041 * require 4 item modifications, but if they are both normal inodes it
10042 * would require 5 item modifications, so we'll assume they are normal
10043 * inodes. So 5 * 2 is 10, plus 1 for the new link, so 11 total items
10044 * should cover the worst case number of items we'll modify.
10045 * If our rename has the whiteout flag, we need more 5 units for the
10046 * new inode (1 inode item, 1 inode ref, 2 dir items and 1 xattr item
10047 * when selinux is enabled).
10049 trans_num_items = 11;
10050 if (flags & RENAME_WHITEOUT)
10051 trans_num_items += 5;
10052 trans = btrfs_start_transaction(root, trans_num_items);
10053 if (IS_ERR(trans)) {
10054 ret = PTR_ERR(trans);
10059 btrfs_record_root_in_trans(trans, dest);
10061 ret = btrfs_set_inode_index(BTRFS_I(new_dir), &index);
10065 BTRFS_I(old_inode)->dir_index = 0ULL;
10066 if (unlikely(old_ino == BTRFS_FIRST_FREE_OBJECTID)) {
10067 /* force full log commit if subvolume involved. */
10068 btrfs_set_log_full_commit(fs_info, trans);
10070 btrfs_pin_log_trans(root);
10072 ret = btrfs_insert_inode_ref(trans, dest,
10073 new_dentry->d_name.name,
10074 new_dentry->d_name.len,
10076 btrfs_ino(BTRFS_I(new_dir)), index);
10081 inode_inc_iversion(old_dir);
10082 inode_inc_iversion(new_dir);
10083 inode_inc_iversion(old_inode);
10084 old_dir->i_ctime = old_dir->i_mtime =
10085 new_dir->i_ctime = new_dir->i_mtime =
10086 old_inode->i_ctime = current_time(old_dir);
10088 if (old_dentry->d_parent != new_dentry->d_parent)
10089 btrfs_record_unlink_dir(trans, BTRFS_I(old_dir),
10090 BTRFS_I(old_inode), 1);
10092 if (unlikely(old_ino == BTRFS_FIRST_FREE_OBJECTID)) {
10093 root_objectid = BTRFS_I(old_inode)->root->root_key.objectid;
10094 ret = btrfs_unlink_subvol(trans, root, old_dir, root_objectid,
10095 old_dentry->d_name.name,
10096 old_dentry->d_name.len);
10098 ret = __btrfs_unlink_inode(trans, root, BTRFS_I(old_dir),
10099 BTRFS_I(d_inode(old_dentry)),
10100 old_dentry->d_name.name,
10101 old_dentry->d_name.len);
10103 ret = btrfs_update_inode(trans, root, old_inode);
10106 btrfs_abort_transaction(trans, ret);
10111 inode_inc_iversion(new_inode);
10112 new_inode->i_ctime = current_time(new_inode);
10113 if (unlikely(btrfs_ino(BTRFS_I(new_inode)) ==
10114 BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)) {
10115 root_objectid = BTRFS_I(new_inode)->location.objectid;
10116 ret = btrfs_unlink_subvol(trans, dest, new_dir,
10118 new_dentry->d_name.name,
10119 new_dentry->d_name.len);
10120 BUG_ON(new_inode->i_nlink == 0);
10122 ret = btrfs_unlink_inode(trans, dest, BTRFS_I(new_dir),
10123 BTRFS_I(d_inode(new_dentry)),
10124 new_dentry->d_name.name,
10125 new_dentry->d_name.len);
10127 if (!ret && new_inode->i_nlink == 0)
10128 ret = btrfs_orphan_add(trans,
10129 BTRFS_I(d_inode(new_dentry)));
10131 btrfs_abort_transaction(trans, ret);
10136 ret = btrfs_add_link(trans, BTRFS_I(new_dir), BTRFS_I(old_inode),
10137 new_dentry->d_name.name,
10138 new_dentry->d_name.len, 0, index);
10140 btrfs_abort_transaction(trans, ret);
10144 if (old_inode->i_nlink == 1)
10145 BTRFS_I(old_inode)->dir_index = index;
10148 struct dentry *parent = new_dentry->d_parent;
10150 btrfs_log_new_name(trans, BTRFS_I(old_inode), BTRFS_I(old_dir),
10152 btrfs_end_log_trans(root);
10153 log_pinned = false;
10156 if (flags & RENAME_WHITEOUT) {
10157 ret = btrfs_whiteout_for_rename(trans, root, old_dir,
10161 btrfs_abort_transaction(trans, ret);
10167 * If we have pinned the log and an error happened, we unpin tasks
10168 * trying to sync the log and force them to fallback to a transaction
10169 * commit if the log currently contains any of the inodes involved in
10170 * this rename operation (to ensure we do not persist a log with an
10171 * inconsistent state for any of these inodes or leading to any
10172 * inconsistencies when replayed). If the transaction was aborted, the
10173 * abortion reason is propagated to userspace when attempting to commit
10174 * the transaction. If the log does not contain any of these inodes, we
10175 * allow the tasks to sync it.
10177 if (ret && log_pinned) {
10178 if (btrfs_inode_in_log(BTRFS_I(old_dir), fs_info->generation) ||
10179 btrfs_inode_in_log(BTRFS_I(new_dir), fs_info->generation) ||
10180 btrfs_inode_in_log(BTRFS_I(old_inode), fs_info->generation) ||
10182 btrfs_inode_in_log(BTRFS_I(new_inode), fs_info->generation)))
10183 btrfs_set_log_full_commit(fs_info, trans);
10185 btrfs_end_log_trans(root);
10186 log_pinned = false;
10188 btrfs_end_transaction(trans);
10190 if (old_ino == BTRFS_FIRST_FREE_OBJECTID)
10191 up_read(&fs_info->subvol_sem);
10196 static int btrfs_rename2(struct inode *old_dir, struct dentry *old_dentry,
10197 struct inode *new_dir, struct dentry *new_dentry,
10198 unsigned int flags)
10200 if (flags & ~(RENAME_NOREPLACE | RENAME_EXCHANGE | RENAME_WHITEOUT))
10203 if (flags & RENAME_EXCHANGE)
10204 return btrfs_rename_exchange(old_dir, old_dentry, new_dir,
10207 return btrfs_rename(old_dir, old_dentry, new_dir, new_dentry, flags);
10210 static void btrfs_run_delalloc_work(struct btrfs_work *work)
10212 struct btrfs_delalloc_work *delalloc_work;
10213 struct inode *inode;
10215 delalloc_work = container_of(work, struct btrfs_delalloc_work,
10217 inode = delalloc_work->inode;
10218 filemap_flush(inode->i_mapping);
10219 if (test_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
10220 &BTRFS_I(inode)->runtime_flags))
10221 filemap_flush(inode->i_mapping);
10223 if (delalloc_work->delay_iput)
10224 btrfs_add_delayed_iput(inode);
10227 complete(&delalloc_work->completion);
10230 struct btrfs_delalloc_work *btrfs_alloc_delalloc_work(struct inode *inode,
10233 struct btrfs_delalloc_work *work;
10235 work = kmalloc(sizeof(*work), GFP_NOFS);
10239 init_completion(&work->completion);
10240 INIT_LIST_HEAD(&work->list);
10241 work->inode = inode;
10242 work->delay_iput = delay_iput;
10243 WARN_ON_ONCE(!inode);
10244 btrfs_init_work(&work->work, btrfs_flush_delalloc_helper,
10245 btrfs_run_delalloc_work, NULL, NULL);
10250 void btrfs_wait_and_free_delalloc_work(struct btrfs_delalloc_work *work)
10252 wait_for_completion(&work->completion);
10257 * some fairly slow code that needs optimization. This walks the list
10258 * of all the inodes with pending delalloc and forces them to disk.
10260 static int __start_delalloc_inodes(struct btrfs_root *root, int delay_iput,
10263 struct btrfs_inode *binode;
10264 struct inode *inode;
10265 struct btrfs_delalloc_work *work, *next;
10266 struct list_head works;
10267 struct list_head splice;
10270 INIT_LIST_HEAD(&works);
10271 INIT_LIST_HEAD(&splice);
10273 mutex_lock(&root->delalloc_mutex);
10274 spin_lock(&root->delalloc_lock);
10275 list_splice_init(&root->delalloc_inodes, &splice);
10276 while (!list_empty(&splice)) {
10277 binode = list_entry(splice.next, struct btrfs_inode,
10280 list_move_tail(&binode->delalloc_inodes,
10281 &root->delalloc_inodes);
10282 inode = igrab(&binode->vfs_inode);
10284 cond_resched_lock(&root->delalloc_lock);
10287 spin_unlock(&root->delalloc_lock);
10289 work = btrfs_alloc_delalloc_work(inode, delay_iput);
10292 btrfs_add_delayed_iput(inode);
10298 list_add_tail(&work->list, &works);
10299 btrfs_queue_work(root->fs_info->flush_workers,
10302 if (nr != -1 && ret >= nr)
10305 spin_lock(&root->delalloc_lock);
10307 spin_unlock(&root->delalloc_lock);
10310 list_for_each_entry_safe(work, next, &works, list) {
10311 list_del_init(&work->list);
10312 btrfs_wait_and_free_delalloc_work(work);
10315 if (!list_empty_careful(&splice)) {
10316 spin_lock(&root->delalloc_lock);
10317 list_splice_tail(&splice, &root->delalloc_inodes);
10318 spin_unlock(&root->delalloc_lock);
10320 mutex_unlock(&root->delalloc_mutex);
10324 int btrfs_start_delalloc_inodes(struct btrfs_root *root, int delay_iput)
10326 struct btrfs_fs_info *fs_info = root->fs_info;
10329 if (test_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state))
10332 ret = __start_delalloc_inodes(root, delay_iput, -1);
10336 * the filemap_flush will queue IO into the worker threads, but
10337 * we have to make sure the IO is actually started and that
10338 * ordered extents get created before we return
10340 atomic_inc(&fs_info->async_submit_draining);
10341 while (atomic_read(&fs_info->nr_async_submits) ||
10342 atomic_read(&fs_info->async_delalloc_pages)) {
10343 wait_event(fs_info->async_submit_wait,
10344 (atomic_read(&fs_info->nr_async_submits) == 0 &&
10345 atomic_read(&fs_info->async_delalloc_pages) == 0));
10347 atomic_dec(&fs_info->async_submit_draining);
10351 int btrfs_start_delalloc_roots(struct btrfs_fs_info *fs_info, int delay_iput,
10354 struct btrfs_root *root;
10355 struct list_head splice;
10358 if (test_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state))
10361 INIT_LIST_HEAD(&splice);
10363 mutex_lock(&fs_info->delalloc_root_mutex);
10364 spin_lock(&fs_info->delalloc_root_lock);
10365 list_splice_init(&fs_info->delalloc_roots, &splice);
10366 while (!list_empty(&splice) && nr) {
10367 root = list_first_entry(&splice, struct btrfs_root,
10369 root = btrfs_grab_fs_root(root);
10371 list_move_tail(&root->delalloc_root,
10372 &fs_info->delalloc_roots);
10373 spin_unlock(&fs_info->delalloc_root_lock);
10375 ret = __start_delalloc_inodes(root, delay_iput, nr);
10376 btrfs_put_fs_root(root);
10384 spin_lock(&fs_info->delalloc_root_lock);
10386 spin_unlock(&fs_info->delalloc_root_lock);
10389 atomic_inc(&fs_info->async_submit_draining);
10390 while (atomic_read(&fs_info->nr_async_submits) ||
10391 atomic_read(&fs_info->async_delalloc_pages)) {
10392 wait_event(fs_info->async_submit_wait,
10393 (atomic_read(&fs_info->nr_async_submits) == 0 &&
10394 atomic_read(&fs_info->async_delalloc_pages) == 0));
10396 atomic_dec(&fs_info->async_submit_draining);
10398 if (!list_empty_careful(&splice)) {
10399 spin_lock(&fs_info->delalloc_root_lock);
10400 list_splice_tail(&splice, &fs_info->delalloc_roots);
10401 spin_unlock(&fs_info->delalloc_root_lock);
10403 mutex_unlock(&fs_info->delalloc_root_mutex);
10407 static int btrfs_symlink(struct inode *dir, struct dentry *dentry,
10408 const char *symname)
10410 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
10411 struct btrfs_trans_handle *trans;
10412 struct btrfs_root *root = BTRFS_I(dir)->root;
10413 struct btrfs_path *path;
10414 struct btrfs_key key;
10415 struct inode *inode = NULL;
10417 int drop_inode = 0;
10423 struct btrfs_file_extent_item *ei;
10424 struct extent_buffer *leaf;
10426 name_len = strlen(symname);
10427 if (name_len > BTRFS_MAX_INLINE_DATA_SIZE(fs_info))
10428 return -ENAMETOOLONG;
10431 * 2 items for inode item and ref
10432 * 2 items for dir items
10433 * 1 item for updating parent inode item
10434 * 1 item for the inline extent item
10435 * 1 item for xattr if selinux is on
10437 trans = btrfs_start_transaction(root, 7);
10439 return PTR_ERR(trans);
10441 err = btrfs_find_free_ino(root, &objectid);
10445 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
10446 dentry->d_name.len, btrfs_ino(BTRFS_I(dir)),
10447 objectid, S_IFLNK|S_IRWXUGO, &index);
10448 if (IS_ERR(inode)) {
10449 err = PTR_ERR(inode);
10454 * If the active LSM wants to access the inode during
10455 * d_instantiate it needs these. Smack checks to see
10456 * if the filesystem supports xattrs by looking at the
10459 inode->i_fop = &btrfs_file_operations;
10460 inode->i_op = &btrfs_file_inode_operations;
10461 inode->i_mapping->a_ops = &btrfs_aops;
10462 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
10464 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
10466 goto out_unlock_inode;
10468 path = btrfs_alloc_path();
10471 goto out_unlock_inode;
10473 key.objectid = btrfs_ino(BTRFS_I(inode));
10475 key.type = BTRFS_EXTENT_DATA_KEY;
10476 datasize = btrfs_file_extent_calc_inline_size(name_len);
10477 err = btrfs_insert_empty_item(trans, root, path, &key,
10480 btrfs_free_path(path);
10481 goto out_unlock_inode;
10483 leaf = path->nodes[0];
10484 ei = btrfs_item_ptr(leaf, path->slots[0],
10485 struct btrfs_file_extent_item);
10486 btrfs_set_file_extent_generation(leaf, ei, trans->transid);
10487 btrfs_set_file_extent_type(leaf, ei,
10488 BTRFS_FILE_EXTENT_INLINE);
10489 btrfs_set_file_extent_encryption(leaf, ei, 0);
10490 btrfs_set_file_extent_compression(leaf, ei, 0);
10491 btrfs_set_file_extent_other_encoding(leaf, ei, 0);
10492 btrfs_set_file_extent_ram_bytes(leaf, ei, name_len);
10494 ptr = btrfs_file_extent_inline_start(ei);
10495 write_extent_buffer(leaf, symname, ptr, name_len);
10496 btrfs_mark_buffer_dirty(leaf);
10497 btrfs_free_path(path);
10499 inode->i_op = &btrfs_symlink_inode_operations;
10500 inode_nohighmem(inode);
10501 inode->i_mapping->a_ops = &btrfs_symlink_aops;
10502 inode_set_bytes(inode, name_len);
10503 btrfs_i_size_write(BTRFS_I(inode), name_len);
10504 err = btrfs_update_inode(trans, root, inode);
10506 * Last step, add directory indexes for our symlink inode. This is the
10507 * last step to avoid extra cleanup of these indexes if an error happens
10511 err = btrfs_add_nondir(trans, BTRFS_I(dir), dentry,
10512 BTRFS_I(inode), 0, index);
10515 goto out_unlock_inode;
10518 unlock_new_inode(inode);
10519 d_instantiate(dentry, inode);
10522 btrfs_end_transaction(trans);
10524 inode_dec_link_count(inode);
10527 btrfs_btree_balance_dirty(fs_info);
10532 unlock_new_inode(inode);
10536 static int __btrfs_prealloc_file_range(struct inode *inode, int mode,
10537 u64 start, u64 num_bytes, u64 min_size,
10538 loff_t actual_len, u64 *alloc_hint,
10539 struct btrfs_trans_handle *trans)
10541 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
10542 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
10543 struct extent_map *em;
10544 struct btrfs_root *root = BTRFS_I(inode)->root;
10545 struct btrfs_key ins;
10546 u64 cur_offset = start;
10549 u64 last_alloc = (u64)-1;
10551 bool own_trans = true;
10552 u64 end = start + num_bytes - 1;
10556 while (num_bytes > 0) {
10558 trans = btrfs_start_transaction(root, 3);
10559 if (IS_ERR(trans)) {
10560 ret = PTR_ERR(trans);
10565 cur_bytes = min_t(u64, num_bytes, SZ_256M);
10566 cur_bytes = max(cur_bytes, min_size);
10568 * If we are severely fragmented we could end up with really
10569 * small allocations, so if the allocator is returning small
10570 * chunks lets make its job easier by only searching for those
10573 cur_bytes = min(cur_bytes, last_alloc);
10574 ret = btrfs_reserve_extent(root, cur_bytes, cur_bytes,
10575 min_size, 0, *alloc_hint, &ins, 1, 0);
10578 btrfs_end_transaction(trans);
10581 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
10583 last_alloc = ins.offset;
10584 ret = insert_reserved_file_extent(trans, inode,
10585 cur_offset, ins.objectid,
10586 ins.offset, ins.offset,
10587 ins.offset, 0, 0, 0,
10588 BTRFS_FILE_EXTENT_PREALLOC);
10590 btrfs_free_reserved_extent(fs_info, ins.objectid,
10592 btrfs_abort_transaction(trans, ret);
10594 btrfs_end_transaction(trans);
10598 btrfs_drop_extent_cache(BTRFS_I(inode), cur_offset,
10599 cur_offset + ins.offset -1, 0);
10601 em = alloc_extent_map();
10603 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
10604 &BTRFS_I(inode)->runtime_flags);
10608 em->start = cur_offset;
10609 em->orig_start = cur_offset;
10610 em->len = ins.offset;
10611 em->block_start = ins.objectid;
10612 em->block_len = ins.offset;
10613 em->orig_block_len = ins.offset;
10614 em->ram_bytes = ins.offset;
10615 em->bdev = fs_info->fs_devices->latest_bdev;
10616 set_bit(EXTENT_FLAG_PREALLOC, &em->flags);
10617 em->generation = trans->transid;
10620 write_lock(&em_tree->lock);
10621 ret = add_extent_mapping(em_tree, em, 1);
10622 write_unlock(&em_tree->lock);
10623 if (ret != -EEXIST)
10625 btrfs_drop_extent_cache(BTRFS_I(inode), cur_offset,
10626 cur_offset + ins.offset - 1,
10629 free_extent_map(em);
10631 num_bytes -= ins.offset;
10632 cur_offset += ins.offset;
10633 *alloc_hint = ins.objectid + ins.offset;
10635 inode_inc_iversion(inode);
10636 inode->i_ctime = current_time(inode);
10637 BTRFS_I(inode)->flags |= BTRFS_INODE_PREALLOC;
10638 if (!(mode & FALLOC_FL_KEEP_SIZE) &&
10639 (actual_len > inode->i_size) &&
10640 (cur_offset > inode->i_size)) {
10641 if (cur_offset > actual_len)
10642 i_size = actual_len;
10644 i_size = cur_offset;
10645 i_size_write(inode, i_size);
10646 btrfs_ordered_update_i_size(inode, i_size, NULL);
10649 ret = btrfs_update_inode(trans, root, inode);
10652 btrfs_abort_transaction(trans, ret);
10654 btrfs_end_transaction(trans);
10659 btrfs_end_transaction(trans);
10661 if (cur_offset < end)
10662 btrfs_free_reserved_data_space(inode, NULL, cur_offset,
10663 end - cur_offset + 1);
10667 int btrfs_prealloc_file_range(struct inode *inode, int mode,
10668 u64 start, u64 num_bytes, u64 min_size,
10669 loff_t actual_len, u64 *alloc_hint)
10671 return __btrfs_prealloc_file_range(inode, mode, start, num_bytes,
10672 min_size, actual_len, alloc_hint,
10676 int btrfs_prealloc_file_range_trans(struct inode *inode,
10677 struct btrfs_trans_handle *trans, int mode,
10678 u64 start, u64 num_bytes, u64 min_size,
10679 loff_t actual_len, u64 *alloc_hint)
10681 return __btrfs_prealloc_file_range(inode, mode, start, num_bytes,
10682 min_size, actual_len, alloc_hint, trans);
10685 static int btrfs_set_page_dirty(struct page *page)
10687 return __set_page_dirty_nobuffers(page);
10690 static int btrfs_permission(struct inode *inode, int mask)
10692 struct btrfs_root *root = BTRFS_I(inode)->root;
10693 umode_t mode = inode->i_mode;
10695 if (mask & MAY_WRITE &&
10696 (S_ISREG(mode) || S_ISDIR(mode) || S_ISLNK(mode))) {
10697 if (btrfs_root_readonly(root))
10699 if (BTRFS_I(inode)->flags & BTRFS_INODE_READONLY)
10702 return generic_permission(inode, mask);
10705 static int btrfs_tmpfile(struct inode *dir, struct dentry *dentry, umode_t mode)
10707 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
10708 struct btrfs_trans_handle *trans;
10709 struct btrfs_root *root = BTRFS_I(dir)->root;
10710 struct inode *inode = NULL;
10716 * 5 units required for adding orphan entry
10718 trans = btrfs_start_transaction(root, 5);
10720 return PTR_ERR(trans);
10722 ret = btrfs_find_free_ino(root, &objectid);
10726 inode = btrfs_new_inode(trans, root, dir, NULL, 0,
10727 btrfs_ino(BTRFS_I(dir)), objectid, mode, &index);
10728 if (IS_ERR(inode)) {
10729 ret = PTR_ERR(inode);
10734 inode->i_fop = &btrfs_file_operations;
10735 inode->i_op = &btrfs_file_inode_operations;
10737 inode->i_mapping->a_ops = &btrfs_aops;
10738 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
10740 ret = btrfs_init_inode_security(trans, inode, dir, NULL);
10744 ret = btrfs_update_inode(trans, root, inode);
10747 ret = btrfs_orphan_add(trans, BTRFS_I(inode));
10752 * We set number of links to 0 in btrfs_new_inode(), and here we set
10753 * it to 1 because d_tmpfile() will issue a warning if the count is 0,
10756 * d_tmpfile() -> inode_dec_link_count() -> drop_nlink()
10758 set_nlink(inode, 1);
10759 unlock_new_inode(inode);
10760 d_tmpfile(dentry, inode);
10761 mark_inode_dirty(inode);
10764 btrfs_end_transaction(trans);
10767 btrfs_balance_delayed_items(fs_info);
10768 btrfs_btree_balance_dirty(fs_info);
10772 unlock_new_inode(inode);
10777 __attribute__((const))
10778 static int btrfs_readpage_io_failed_hook(struct page *page, int failed_mirror)
10783 static struct btrfs_fs_info *iotree_fs_info(void *private_data)
10785 struct inode *inode = private_data;
10786 return btrfs_sb(inode->i_sb);
10789 static void btrfs_check_extent_io_range(void *private_data, const char *caller,
10790 u64 start, u64 end)
10792 struct inode *inode = private_data;
10795 isize = i_size_read(inode);
10796 if (end >= PAGE_SIZE && (end % 2) == 0 && end != isize - 1) {
10797 btrfs_debug_rl(BTRFS_I(inode)->root->fs_info,
10798 "%s: ino %llu isize %llu odd range [%llu,%llu]",
10799 caller, btrfs_ino(BTRFS_I(inode)), isize, start, end);
10803 void btrfs_set_range_writeback(void *private_data, u64 start, u64 end)
10805 struct inode *inode = private_data;
10806 unsigned long index = start >> PAGE_SHIFT;
10807 unsigned long end_index = end >> PAGE_SHIFT;
10810 while (index <= end_index) {
10811 page = find_get_page(inode->i_mapping, index);
10812 ASSERT(page); /* Pages should be in the extent_io_tree */
10813 set_page_writeback(page);
10819 static const struct inode_operations btrfs_dir_inode_operations = {
10820 .getattr = btrfs_getattr,
10821 .lookup = btrfs_lookup,
10822 .create = btrfs_create,
10823 .unlink = btrfs_unlink,
10824 .link = btrfs_link,
10825 .mkdir = btrfs_mkdir,
10826 .rmdir = btrfs_rmdir,
10827 .rename = btrfs_rename2,
10828 .symlink = btrfs_symlink,
10829 .setattr = btrfs_setattr,
10830 .mknod = btrfs_mknod,
10831 .listxattr = btrfs_listxattr,
10832 .permission = btrfs_permission,
10833 .get_acl = btrfs_get_acl,
10834 .set_acl = btrfs_set_acl,
10835 .update_time = btrfs_update_time,
10836 .tmpfile = btrfs_tmpfile,
10838 static const struct inode_operations btrfs_dir_ro_inode_operations = {
10839 .lookup = btrfs_lookup,
10840 .permission = btrfs_permission,
10841 .update_time = btrfs_update_time,
10844 static const struct file_operations btrfs_dir_file_operations = {
10845 .llseek = generic_file_llseek,
10846 .read = generic_read_dir,
10847 .iterate_shared = btrfs_real_readdir,
10848 .open = btrfs_opendir,
10849 .unlocked_ioctl = btrfs_ioctl,
10850 #ifdef CONFIG_COMPAT
10851 .compat_ioctl = btrfs_compat_ioctl,
10853 .release = btrfs_release_file,
10854 .fsync = btrfs_sync_file,
10857 static const struct extent_io_ops btrfs_extent_io_ops = {
10858 /* mandatory callbacks */
10859 .submit_bio_hook = btrfs_submit_bio_hook,
10860 .readpage_end_io_hook = btrfs_readpage_end_io_hook,
10861 .merge_bio_hook = btrfs_merge_bio_hook,
10862 .readpage_io_failed_hook = btrfs_readpage_io_failed_hook,
10863 .tree_fs_info = iotree_fs_info,
10864 .set_range_writeback = btrfs_set_range_writeback,
10866 /* optional callbacks */
10867 .fill_delalloc = run_delalloc_range,
10868 .writepage_end_io_hook = btrfs_writepage_end_io_hook,
10869 .writepage_start_hook = btrfs_writepage_start_hook,
10870 .set_bit_hook = btrfs_set_bit_hook,
10871 .clear_bit_hook = btrfs_clear_bit_hook,
10872 .merge_extent_hook = btrfs_merge_extent_hook,
10873 .split_extent_hook = btrfs_split_extent_hook,
10874 .check_extent_io_range = btrfs_check_extent_io_range,
10878 * btrfs doesn't support the bmap operation because swapfiles
10879 * use bmap to make a mapping of extents in the file. They assume
10880 * these extents won't change over the life of the file and they
10881 * use the bmap result to do IO directly to the drive.
10883 * the btrfs bmap call would return logical addresses that aren't
10884 * suitable for IO and they also will change frequently as COW
10885 * operations happen. So, swapfile + btrfs == corruption.
10887 * For now we're avoiding this by dropping bmap.
10889 static const struct address_space_operations btrfs_aops = {
10890 .readpage = btrfs_readpage,
10891 .writepage = btrfs_writepage,
10892 .writepages = btrfs_writepages,
10893 .readpages = btrfs_readpages,
10894 .direct_IO = btrfs_direct_IO,
10895 .invalidatepage = btrfs_invalidatepage,
10896 .releasepage = btrfs_releasepage,
10897 .set_page_dirty = btrfs_set_page_dirty,
10898 .error_remove_page = generic_error_remove_page,
10901 static const struct address_space_operations btrfs_symlink_aops = {
10902 .readpage = btrfs_readpage,
10903 .writepage = btrfs_writepage,
10904 .invalidatepage = btrfs_invalidatepage,
10905 .releasepage = btrfs_releasepage,
10908 static const struct inode_operations btrfs_file_inode_operations = {
10909 .getattr = btrfs_getattr,
10910 .setattr = btrfs_setattr,
10911 .listxattr = btrfs_listxattr,
10912 .permission = btrfs_permission,
10913 .fiemap = btrfs_fiemap,
10914 .get_acl = btrfs_get_acl,
10915 .set_acl = btrfs_set_acl,
10916 .update_time = btrfs_update_time,
10918 static const struct inode_operations btrfs_special_inode_operations = {
10919 .getattr = btrfs_getattr,
10920 .setattr = btrfs_setattr,
10921 .permission = btrfs_permission,
10922 .listxattr = btrfs_listxattr,
10923 .get_acl = btrfs_get_acl,
10924 .set_acl = btrfs_set_acl,
10925 .update_time = btrfs_update_time,
10927 static const struct inode_operations btrfs_symlink_inode_operations = {
10928 .get_link = page_get_link,
10929 .getattr = btrfs_getattr,
10930 .setattr = btrfs_setattr,
10931 .permission = btrfs_permission,
10932 .listxattr = btrfs_listxattr,
10933 .update_time = btrfs_update_time,
10936 const struct dentry_operations btrfs_dentry_operations = {
10937 .d_delete = btrfs_dentry_delete,
10938 .d_release = btrfs_dentry_release,