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/statfs.h>
34 #include <linux/compat.h>
35 #include <linux/bit_spinlock.h>
36 #include <linux/xattr.h>
37 #include <linux/posix_acl.h>
38 #include <linux/falloc.h>
39 #include <linux/slab.h>
40 #include <linux/ratelimit.h>
41 #include <linux/mount.h>
42 #include <linux/btrfs.h>
43 #include <linux/blkdev.h>
44 #include <linux/posix_acl_xattr.h>
45 #include <linux/uio.h>
48 #include "transaction.h"
49 #include "btrfs_inode.h"
50 #include "print-tree.h"
51 #include "ordered-data.h"
55 #include "compression.h"
57 #include "free-space-cache.h"
58 #include "inode-map.h"
65 struct btrfs_iget_args {
66 struct btrfs_key *location;
67 struct btrfs_root *root;
70 struct btrfs_dio_data {
71 u64 outstanding_extents;
73 u64 unsubmitted_oe_range_start;
74 u64 unsubmitted_oe_range_end;
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_transaction_cachep;
90 struct kmem_cache *btrfs_path_cachep;
91 struct kmem_cache *btrfs_free_space_cachep;
94 static const unsigned char btrfs_type_by_mode[S_IFMT >> S_SHIFT] = {
95 [S_IFREG >> S_SHIFT] = BTRFS_FT_REG_FILE,
96 [S_IFDIR >> S_SHIFT] = BTRFS_FT_DIR,
97 [S_IFCHR >> S_SHIFT] = BTRFS_FT_CHRDEV,
98 [S_IFBLK >> S_SHIFT] = BTRFS_FT_BLKDEV,
99 [S_IFIFO >> S_SHIFT] = BTRFS_FT_FIFO,
100 [S_IFSOCK >> S_SHIFT] = BTRFS_FT_SOCK,
101 [S_IFLNK >> S_SHIFT] = BTRFS_FT_SYMLINK,
104 static int btrfs_setsize(struct inode *inode, struct iattr *attr);
105 static int btrfs_truncate(struct inode *inode);
106 static int btrfs_finish_ordered_io(struct btrfs_ordered_extent *ordered_extent);
107 static noinline int cow_file_range(struct inode *inode,
108 struct page *locked_page,
109 u64 start, u64 end, u64 delalloc_end,
110 int *page_started, unsigned long *nr_written,
111 int unlock, struct btrfs_dedupe_hash *hash);
112 static struct extent_map *create_pinned_em(struct inode *inode, u64 start,
113 u64 len, u64 orig_start,
114 u64 block_start, u64 block_len,
115 u64 orig_block_len, u64 ram_bytes,
118 static int btrfs_dirty_inode(struct inode *inode);
120 #ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
121 void btrfs_test_inode_set_ops(struct inode *inode)
123 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
127 static int btrfs_init_inode_security(struct btrfs_trans_handle *trans,
128 struct inode *inode, struct inode *dir,
129 const struct qstr *qstr)
133 err = btrfs_init_acl(trans, inode, dir);
135 err = btrfs_xattr_security_init(trans, inode, dir, qstr);
140 * this does all the hard work for inserting an inline extent into
141 * the btree. The caller should have done a btrfs_drop_extents so that
142 * no overlapping inline items exist in the btree
144 static int insert_inline_extent(struct btrfs_trans_handle *trans,
145 struct btrfs_path *path, int extent_inserted,
146 struct btrfs_root *root, struct inode *inode,
147 u64 start, size_t size, size_t compressed_size,
149 struct page **compressed_pages)
151 struct extent_buffer *leaf;
152 struct page *page = NULL;
155 struct btrfs_file_extent_item *ei;
158 size_t cur_size = size;
159 unsigned long offset;
161 if (compressed_size && compressed_pages)
162 cur_size = compressed_size;
164 inode_add_bytes(inode, size);
166 if (!extent_inserted) {
167 struct btrfs_key key;
170 key.objectid = btrfs_ino(inode);
172 key.type = BTRFS_EXTENT_DATA_KEY;
174 datasize = btrfs_file_extent_calc_inline_size(cur_size);
175 path->leave_spinning = 1;
176 ret = btrfs_insert_empty_item(trans, root, path, &key,
183 leaf = path->nodes[0];
184 ei = btrfs_item_ptr(leaf, path->slots[0],
185 struct btrfs_file_extent_item);
186 btrfs_set_file_extent_generation(leaf, ei, trans->transid);
187 btrfs_set_file_extent_type(leaf, ei, BTRFS_FILE_EXTENT_INLINE);
188 btrfs_set_file_extent_encryption(leaf, ei, 0);
189 btrfs_set_file_extent_other_encoding(leaf, ei, 0);
190 btrfs_set_file_extent_ram_bytes(leaf, ei, size);
191 ptr = btrfs_file_extent_inline_start(ei);
193 if (compress_type != BTRFS_COMPRESS_NONE) {
196 while (compressed_size > 0) {
197 cpage = compressed_pages[i];
198 cur_size = min_t(unsigned long, compressed_size,
201 kaddr = kmap_atomic(cpage);
202 write_extent_buffer(leaf, kaddr, ptr, cur_size);
203 kunmap_atomic(kaddr);
207 compressed_size -= cur_size;
209 btrfs_set_file_extent_compression(leaf, ei,
212 page = find_get_page(inode->i_mapping,
213 start >> PAGE_SHIFT);
214 btrfs_set_file_extent_compression(leaf, ei, 0);
215 kaddr = kmap_atomic(page);
216 offset = start & (PAGE_SIZE - 1);
217 write_extent_buffer(leaf, kaddr + offset, ptr, size);
218 kunmap_atomic(kaddr);
221 btrfs_mark_buffer_dirty(leaf);
222 btrfs_release_path(path);
225 * we're an inline extent, so nobody can
226 * extend the file past i_size without locking
227 * a page we already have locked.
229 * We must do any isize and inode updates
230 * before we unlock the pages. Otherwise we
231 * could end up racing with unlink.
233 BTRFS_I(inode)->disk_i_size = inode->i_size;
234 ret = btrfs_update_inode(trans, root, inode);
243 * conditionally insert an inline extent into the file. This
244 * does the checks required to make sure the data is small enough
245 * to fit as an inline extent.
247 static noinline int cow_file_range_inline(struct btrfs_root *root,
248 struct inode *inode, u64 start,
249 u64 end, size_t compressed_size,
251 struct page **compressed_pages)
253 struct btrfs_trans_handle *trans;
254 u64 isize = i_size_read(inode);
255 u64 actual_end = min(end + 1, isize);
256 u64 inline_len = actual_end - start;
257 u64 aligned_end = ALIGN(end, root->sectorsize);
258 u64 data_len = inline_len;
260 struct btrfs_path *path;
261 int extent_inserted = 0;
262 u32 extent_item_size;
265 data_len = compressed_size;
268 actual_end > root->sectorsize ||
269 data_len > BTRFS_MAX_INLINE_DATA_SIZE(root) ||
271 (actual_end & (root->sectorsize - 1)) == 0) ||
273 data_len > root->fs_info->max_inline) {
277 path = btrfs_alloc_path();
281 trans = btrfs_join_transaction(root);
283 btrfs_free_path(path);
284 return PTR_ERR(trans);
286 trans->block_rsv = &root->fs_info->delalloc_block_rsv;
288 if (compressed_size && compressed_pages)
289 extent_item_size = btrfs_file_extent_calc_inline_size(
292 extent_item_size = btrfs_file_extent_calc_inline_size(
295 ret = __btrfs_drop_extents(trans, root, inode, path,
296 start, aligned_end, NULL,
297 1, 1, extent_item_size, &extent_inserted);
299 btrfs_abort_transaction(trans, ret);
303 if (isize > actual_end)
304 inline_len = min_t(u64, isize, actual_end);
305 ret = insert_inline_extent(trans, path, extent_inserted,
307 inline_len, compressed_size,
308 compress_type, compressed_pages);
309 if (ret && ret != -ENOSPC) {
310 btrfs_abort_transaction(trans, ret);
312 } else if (ret == -ENOSPC) {
317 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &BTRFS_I(inode)->runtime_flags);
318 btrfs_delalloc_release_metadata(inode, end + 1 - start);
319 btrfs_drop_extent_cache(inode, start, aligned_end - 1, 0);
322 * Don't forget to free the reserved space, as for inlined extent
323 * it won't count as data extent, free them directly here.
324 * And at reserve time, it's always aligned to page size, so
325 * just free one page here.
327 btrfs_qgroup_free_data(inode, 0, PAGE_SIZE);
328 btrfs_free_path(path);
329 btrfs_end_transaction(trans, root);
333 struct async_extent {
338 unsigned long nr_pages;
340 struct list_head list;
345 struct btrfs_root *root;
346 struct page *locked_page;
349 struct list_head extents;
350 struct btrfs_work work;
353 static noinline int add_async_extent(struct async_cow *cow,
354 u64 start, u64 ram_size,
357 unsigned long nr_pages,
360 struct async_extent *async_extent;
362 async_extent = kmalloc(sizeof(*async_extent), GFP_NOFS);
363 BUG_ON(!async_extent); /* -ENOMEM */
364 async_extent->start = start;
365 async_extent->ram_size = ram_size;
366 async_extent->compressed_size = compressed_size;
367 async_extent->pages = pages;
368 async_extent->nr_pages = nr_pages;
369 async_extent->compress_type = compress_type;
370 list_add_tail(&async_extent->list, &cow->extents);
374 static inline int inode_need_compress(struct inode *inode)
376 struct btrfs_root *root = BTRFS_I(inode)->root;
379 if (btrfs_test_opt(root->fs_info, FORCE_COMPRESS))
381 /* bad compression ratios */
382 if (BTRFS_I(inode)->flags & BTRFS_INODE_NOCOMPRESS)
384 if (btrfs_test_opt(root->fs_info, COMPRESS) ||
385 BTRFS_I(inode)->flags & BTRFS_INODE_COMPRESS ||
386 BTRFS_I(inode)->force_compress)
392 * we create compressed extents in two phases. The first
393 * phase compresses a range of pages that have already been
394 * locked (both pages and state bits are locked).
396 * This is done inside an ordered work queue, and the compression
397 * is spread across many cpus. The actual IO submission is step
398 * two, and the ordered work queue takes care of making sure that
399 * happens in the same order things were put onto the queue by
400 * writepages and friends.
402 * If this code finds it can't get good compression, it puts an
403 * entry onto the work queue to write the uncompressed bytes. This
404 * makes sure that both compressed inodes and uncompressed inodes
405 * are written in the same order that the flusher thread sent them
408 static noinline void compress_file_range(struct inode *inode,
409 struct page *locked_page,
411 struct async_cow *async_cow,
414 struct btrfs_root *root = BTRFS_I(inode)->root;
416 u64 blocksize = root->sectorsize;
418 u64 isize = i_size_read(inode);
420 struct page **pages = NULL;
421 unsigned long nr_pages;
422 unsigned long nr_pages_ret = 0;
423 unsigned long total_compressed = 0;
424 unsigned long total_in = 0;
425 unsigned long max_compressed = SZ_128K;
426 unsigned long max_uncompressed = SZ_128K;
429 int compress_type = root->fs_info->compress_type;
432 /* if this is a small write inside eof, kick off a defrag */
433 if ((end - start + 1) < SZ_16K &&
434 (start > 0 || end + 1 < BTRFS_I(inode)->disk_i_size))
435 btrfs_add_inode_defrag(NULL, inode);
437 actual_end = min_t(u64, isize, end + 1);
440 nr_pages = (end >> PAGE_SHIFT) - (start >> PAGE_SHIFT) + 1;
441 nr_pages = min_t(unsigned long, nr_pages, SZ_128K / PAGE_SIZE);
444 * we don't want to send crud past the end of i_size through
445 * compression, that's just a waste of CPU time. So, if the
446 * end of the file is before the start of our current
447 * requested range of bytes, we bail out to the uncompressed
448 * cleanup code that can deal with all of this.
450 * It isn't really the fastest way to fix things, but this is a
451 * very uncommon corner.
453 if (actual_end <= start)
454 goto cleanup_and_bail_uncompressed;
456 total_compressed = actual_end - start;
459 * skip compression for a small file range(<=blocksize) that
460 * isn't an inline extent, since it doesn't save disk space at all.
462 if (total_compressed <= blocksize &&
463 (start > 0 || end + 1 < BTRFS_I(inode)->disk_i_size))
464 goto cleanup_and_bail_uncompressed;
466 /* we want to make sure that amount of ram required to uncompress
467 * an extent is reasonable, so we limit the total size in ram
468 * of a compressed extent to 128k. This is a crucial number
469 * because it also controls how easily we can spread reads across
470 * cpus for decompression.
472 * We also want to make sure the amount of IO required to do
473 * a random read is reasonably small, so we limit the size of
474 * a compressed extent to 128k.
476 total_compressed = min(total_compressed, max_uncompressed);
477 num_bytes = ALIGN(end - start + 1, blocksize);
478 num_bytes = max(blocksize, num_bytes);
483 * we do compression for mount -o compress and when the
484 * inode has not been flagged as nocompress. This flag can
485 * change at any time if we discover bad compression ratios.
487 if (inode_need_compress(inode)) {
489 pages = kcalloc(nr_pages, sizeof(struct page *), GFP_NOFS);
491 /* just bail out to the uncompressed code */
495 if (BTRFS_I(inode)->force_compress)
496 compress_type = BTRFS_I(inode)->force_compress;
499 * we need to call clear_page_dirty_for_io on each
500 * page in the range. Otherwise applications with the file
501 * mmap'd can wander in and change the page contents while
502 * we are compressing them.
504 * If the compression fails for any reason, we set the pages
505 * dirty again later on.
507 extent_range_clear_dirty_for_io(inode, start, end);
509 ret = btrfs_compress_pages(compress_type,
510 inode->i_mapping, start,
511 total_compressed, pages,
512 nr_pages, &nr_pages_ret,
518 unsigned long offset = total_compressed &
520 struct page *page = pages[nr_pages_ret - 1];
523 /* zero the tail end of the last page, we might be
524 * sending it down to disk
527 kaddr = kmap_atomic(page);
528 memset(kaddr + offset, 0,
530 kunmap_atomic(kaddr);
537 /* lets try to make an inline extent */
538 if (ret || total_in < (actual_end - start)) {
539 /* we didn't compress the entire range, try
540 * to make an uncompressed inline extent.
542 ret = cow_file_range_inline(root, inode, start, end,
545 /* try making a compressed inline extent */
546 ret = cow_file_range_inline(root, inode, start, end,
548 compress_type, pages);
551 unsigned long clear_flags = EXTENT_DELALLOC |
553 unsigned long page_error_op;
555 clear_flags |= (ret < 0) ? EXTENT_DO_ACCOUNTING : 0;
556 page_error_op = ret < 0 ? PAGE_SET_ERROR : 0;
559 * inline extent creation worked or returned error,
560 * we don't need to create any more async work items.
561 * Unlock and free up our temp pages.
563 extent_clear_unlock_delalloc(inode, start, end, NULL,
564 clear_flags, PAGE_UNLOCK |
575 * we aren't doing an inline extent round the compressed size
576 * up to a block size boundary so the allocator does sane
579 total_compressed = ALIGN(total_compressed, blocksize);
582 * one last check to make sure the compression is really a
583 * win, compare the page count read with the blocks on disk
585 total_in = ALIGN(total_in, PAGE_SIZE);
586 if (total_compressed >= total_in) {
589 num_bytes = total_in;
593 * The async work queues will take care of doing actual
594 * allocation on disk for these compressed pages, and
595 * will submit them to the elevator.
597 add_async_extent(async_cow, start, num_bytes,
598 total_compressed, pages, nr_pages_ret,
601 if (start + num_bytes < end) {
612 * the compression code ran but failed to make things smaller,
613 * free any pages it allocated and our page pointer array
615 for (i = 0; i < nr_pages_ret; i++) {
616 WARN_ON(pages[i]->mapping);
621 total_compressed = 0;
624 /* flag the file so we don't compress in the future */
625 if (!btrfs_test_opt(root->fs_info, FORCE_COMPRESS) &&
626 !(BTRFS_I(inode)->force_compress)) {
627 BTRFS_I(inode)->flags |= BTRFS_INODE_NOCOMPRESS;
630 cleanup_and_bail_uncompressed:
632 * No compression, but we still need to write the pages in the file
633 * we've been given so far. redirty the locked page if it corresponds
634 * to our extent and set things up for the async work queue to run
635 * cow_file_range to do the normal delalloc dance.
637 if (page_offset(locked_page) >= start &&
638 page_offset(locked_page) <= end)
639 __set_page_dirty_nobuffers(locked_page);
640 /* unlocked later on in the async handlers */
643 extent_range_redirty_for_io(inode, start, end);
644 add_async_extent(async_cow, start, end - start + 1, 0, NULL, 0,
645 BTRFS_COMPRESS_NONE);
651 for (i = 0; i < nr_pages_ret; i++) {
652 WARN_ON(pages[i]->mapping);
658 static void free_async_extent_pages(struct async_extent *async_extent)
662 if (!async_extent->pages)
665 for (i = 0; i < async_extent->nr_pages; i++) {
666 WARN_ON(async_extent->pages[i]->mapping);
667 put_page(async_extent->pages[i]);
669 kfree(async_extent->pages);
670 async_extent->nr_pages = 0;
671 async_extent->pages = NULL;
675 * phase two of compressed writeback. This is the ordered portion
676 * of the code, which only gets called in the order the work was
677 * queued. We walk all the async extents created by compress_file_range
678 * and send them down to the disk.
680 static noinline void submit_compressed_extents(struct inode *inode,
681 struct async_cow *async_cow)
683 struct async_extent *async_extent;
685 struct btrfs_key ins;
686 struct extent_map *em;
687 struct btrfs_root *root = BTRFS_I(inode)->root;
688 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
689 struct extent_io_tree *io_tree;
693 while (!list_empty(&async_cow->extents)) {
694 async_extent = list_entry(async_cow->extents.next,
695 struct async_extent, list);
696 list_del(&async_extent->list);
698 io_tree = &BTRFS_I(inode)->io_tree;
701 /* did the compression code fall back to uncompressed IO? */
702 if (!async_extent->pages) {
703 int page_started = 0;
704 unsigned long nr_written = 0;
706 lock_extent(io_tree, async_extent->start,
707 async_extent->start +
708 async_extent->ram_size - 1);
710 /* allocate blocks */
711 ret = cow_file_range(inode, async_cow->locked_page,
713 async_extent->start +
714 async_extent->ram_size - 1,
715 async_extent->start +
716 async_extent->ram_size - 1,
717 &page_started, &nr_written, 0,
723 * if page_started, cow_file_range inserted an
724 * inline extent and took care of all the unlocking
725 * and IO for us. Otherwise, we need to submit
726 * all those pages down to the drive.
728 if (!page_started && !ret)
729 extent_write_locked_range(io_tree,
730 inode, async_extent->start,
731 async_extent->start +
732 async_extent->ram_size - 1,
736 unlock_page(async_cow->locked_page);
742 lock_extent(io_tree, async_extent->start,
743 async_extent->start + async_extent->ram_size - 1);
745 ret = btrfs_reserve_extent(root,
746 async_extent->compressed_size,
747 async_extent->compressed_size,
748 0, alloc_hint, &ins, 1, 1);
750 free_async_extent_pages(async_extent);
752 if (ret == -ENOSPC) {
753 unlock_extent(io_tree, async_extent->start,
754 async_extent->start +
755 async_extent->ram_size - 1);
758 * we need to redirty the pages if we decide to
759 * fallback to uncompressed IO, otherwise we
760 * will not submit these pages down to lower
763 extent_range_redirty_for_io(inode,
765 async_extent->start +
766 async_extent->ram_size - 1);
773 * here we're doing allocation and writeback of the
776 btrfs_drop_extent_cache(inode, async_extent->start,
777 async_extent->start +
778 async_extent->ram_size - 1, 0);
780 em = alloc_extent_map();
783 goto out_free_reserve;
785 em->start = async_extent->start;
786 em->len = async_extent->ram_size;
787 em->orig_start = em->start;
788 em->mod_start = em->start;
789 em->mod_len = em->len;
791 em->block_start = ins.objectid;
792 em->block_len = ins.offset;
793 em->orig_block_len = ins.offset;
794 em->ram_bytes = async_extent->ram_size;
795 em->bdev = root->fs_info->fs_devices->latest_bdev;
796 em->compress_type = async_extent->compress_type;
797 set_bit(EXTENT_FLAG_PINNED, &em->flags);
798 set_bit(EXTENT_FLAG_COMPRESSED, &em->flags);
802 write_lock(&em_tree->lock);
803 ret = add_extent_mapping(em_tree, em, 1);
804 write_unlock(&em_tree->lock);
805 if (ret != -EEXIST) {
809 btrfs_drop_extent_cache(inode, async_extent->start,
810 async_extent->start +
811 async_extent->ram_size - 1, 0);
815 goto out_free_reserve;
817 ret = btrfs_add_ordered_extent_compress(inode,
820 async_extent->ram_size,
822 BTRFS_ORDERED_COMPRESSED,
823 async_extent->compress_type);
825 btrfs_drop_extent_cache(inode, async_extent->start,
826 async_extent->start +
827 async_extent->ram_size - 1, 0);
828 goto out_free_reserve;
830 btrfs_dec_block_group_reservations(root->fs_info, ins.objectid);
833 * clear dirty, set writeback and unlock the pages.
835 extent_clear_unlock_delalloc(inode, async_extent->start,
836 async_extent->start +
837 async_extent->ram_size - 1,
838 NULL, EXTENT_LOCKED | EXTENT_DELALLOC,
839 PAGE_UNLOCK | PAGE_CLEAR_DIRTY |
841 ret = btrfs_submit_compressed_write(inode,
843 async_extent->ram_size,
845 ins.offset, async_extent->pages,
846 async_extent->nr_pages);
848 struct extent_io_tree *tree = &BTRFS_I(inode)->io_tree;
849 struct page *p = async_extent->pages[0];
850 const u64 start = async_extent->start;
851 const u64 end = start + async_extent->ram_size - 1;
853 p->mapping = inode->i_mapping;
854 tree->ops->writepage_end_io_hook(p, start, end,
857 extent_clear_unlock_delalloc(inode, start, end, NULL, 0,
860 free_async_extent_pages(async_extent);
862 alloc_hint = ins.objectid + ins.offset;
868 btrfs_dec_block_group_reservations(root->fs_info, ins.objectid);
869 btrfs_free_reserved_extent(root, ins.objectid, ins.offset, 1);
871 extent_clear_unlock_delalloc(inode, async_extent->start,
872 async_extent->start +
873 async_extent->ram_size - 1,
874 NULL, EXTENT_LOCKED | EXTENT_DELALLOC |
875 EXTENT_DEFRAG | EXTENT_DO_ACCOUNTING,
876 PAGE_UNLOCK | PAGE_CLEAR_DIRTY |
877 PAGE_SET_WRITEBACK | PAGE_END_WRITEBACK |
879 free_async_extent_pages(async_extent);
884 static u64 get_extent_allocation_hint(struct inode *inode, u64 start,
887 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
888 struct extent_map *em;
891 read_lock(&em_tree->lock);
892 em = search_extent_mapping(em_tree, start, num_bytes);
895 * if block start isn't an actual block number then find the
896 * first block in this inode and use that as a hint. If that
897 * block is also bogus then just don't worry about it.
899 if (em->block_start >= EXTENT_MAP_LAST_BYTE) {
901 em = search_extent_mapping(em_tree, 0, 0);
902 if (em && em->block_start < EXTENT_MAP_LAST_BYTE)
903 alloc_hint = em->block_start;
907 alloc_hint = em->block_start;
911 read_unlock(&em_tree->lock);
917 * when extent_io.c finds a delayed allocation range in the file,
918 * the call backs end up in this code. The basic idea is to
919 * allocate extents on disk for the range, and create ordered data structs
920 * in ram to track those extents.
922 * locked_page is the page that writepage had locked already. We use
923 * it to make sure we don't do extra locks or unlocks.
925 * *page_started is set to one if we unlock locked_page and do everything
926 * required to start IO on it. It may be clean and already done with
929 static noinline int cow_file_range(struct inode *inode,
930 struct page *locked_page,
931 u64 start, u64 end, u64 delalloc_end,
932 int *page_started, unsigned long *nr_written,
933 int unlock, struct btrfs_dedupe_hash *hash)
935 struct btrfs_root *root = BTRFS_I(inode)->root;
938 unsigned long ram_size;
941 u64 blocksize = root->sectorsize;
942 struct btrfs_key ins;
943 struct extent_map *em;
944 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
947 if (btrfs_is_free_space_inode(inode)) {
953 num_bytes = ALIGN(end - start + 1, blocksize);
954 num_bytes = max(blocksize, num_bytes);
955 disk_num_bytes = num_bytes;
957 /* if this is a small write inside eof, kick off defrag */
958 if (num_bytes < SZ_64K &&
959 (start > 0 || end + 1 < BTRFS_I(inode)->disk_i_size))
960 btrfs_add_inode_defrag(NULL, inode);
963 /* lets try to make an inline extent */
964 ret = cow_file_range_inline(root, inode, start, end, 0, 0,
967 extent_clear_unlock_delalloc(inode, start, end, NULL,
968 EXTENT_LOCKED | EXTENT_DELALLOC |
969 EXTENT_DEFRAG, PAGE_UNLOCK |
970 PAGE_CLEAR_DIRTY | PAGE_SET_WRITEBACK |
973 *nr_written = *nr_written +
974 (end - start + PAGE_SIZE) / PAGE_SIZE;
977 } else if (ret < 0) {
982 BUG_ON(disk_num_bytes >
983 btrfs_super_total_bytes(root->fs_info->super_copy));
985 alloc_hint = get_extent_allocation_hint(inode, start, num_bytes);
986 btrfs_drop_extent_cache(inode, start, start + num_bytes - 1, 0);
988 while (disk_num_bytes > 0) {
991 cur_alloc_size = disk_num_bytes;
992 ret = btrfs_reserve_extent(root, cur_alloc_size,
993 root->sectorsize, 0, alloc_hint,
998 em = alloc_extent_map();
1004 em->orig_start = em->start;
1005 ram_size = ins.offset;
1006 em->len = ins.offset;
1007 em->mod_start = em->start;
1008 em->mod_len = em->len;
1010 em->block_start = ins.objectid;
1011 em->block_len = ins.offset;
1012 em->orig_block_len = ins.offset;
1013 em->ram_bytes = ram_size;
1014 em->bdev = root->fs_info->fs_devices->latest_bdev;
1015 set_bit(EXTENT_FLAG_PINNED, &em->flags);
1016 em->generation = -1;
1019 write_lock(&em_tree->lock);
1020 ret = add_extent_mapping(em_tree, em, 1);
1021 write_unlock(&em_tree->lock);
1022 if (ret != -EEXIST) {
1023 free_extent_map(em);
1026 btrfs_drop_extent_cache(inode, start,
1027 start + ram_size - 1, 0);
1032 cur_alloc_size = ins.offset;
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 goto out_drop_extent_cache;
1046 btrfs_dec_block_group_reservations(root->fs_info, ins.objectid);
1048 if (disk_num_bytes < cur_alloc_size)
1051 /* we're not doing compressed IO, don't unlock the first
1052 * page (which the caller expects to stay locked), don't
1053 * clear any dirty bits and don't set any writeback bits
1055 * Do set the Private2 bit so we know this page was properly
1056 * setup for writepage
1058 op = unlock ? PAGE_UNLOCK : 0;
1059 op |= PAGE_SET_PRIVATE2;
1061 extent_clear_unlock_delalloc(inode, start,
1062 start + ram_size - 1, locked_page,
1063 EXTENT_LOCKED | EXTENT_DELALLOC,
1065 disk_num_bytes -= cur_alloc_size;
1066 num_bytes -= cur_alloc_size;
1067 alloc_hint = ins.objectid + ins.offset;
1068 start += cur_alloc_size;
1073 out_drop_extent_cache:
1074 btrfs_drop_extent_cache(inode, start, start + ram_size - 1, 0);
1076 btrfs_dec_block_group_reservations(root->fs_info, ins.objectid);
1077 btrfs_free_reserved_extent(root, ins.objectid, ins.offset, 1);
1079 extent_clear_unlock_delalloc(inode, start, end, locked_page,
1080 EXTENT_LOCKED | EXTENT_DO_ACCOUNTING |
1081 EXTENT_DELALLOC | EXTENT_DEFRAG,
1082 PAGE_UNLOCK | PAGE_CLEAR_DIRTY |
1083 PAGE_SET_WRITEBACK | PAGE_END_WRITEBACK);
1088 * work queue call back to started compression on a file and pages
1090 static noinline void async_cow_start(struct btrfs_work *work)
1092 struct async_cow *async_cow;
1094 async_cow = container_of(work, struct async_cow, work);
1096 compress_file_range(async_cow->inode, async_cow->locked_page,
1097 async_cow->start, async_cow->end, async_cow,
1099 if (num_added == 0) {
1100 btrfs_add_delayed_iput(async_cow->inode);
1101 async_cow->inode = NULL;
1106 * work queue call back to submit previously compressed pages
1108 static noinline void async_cow_submit(struct btrfs_work *work)
1110 struct async_cow *async_cow;
1111 struct btrfs_root *root;
1112 unsigned long nr_pages;
1114 async_cow = container_of(work, struct async_cow, work);
1116 root = async_cow->root;
1117 nr_pages = (async_cow->end - async_cow->start + PAGE_SIZE) >>
1121 * atomic_sub_return implies a barrier for waitqueue_active
1123 if (atomic_sub_return(nr_pages, &root->fs_info->async_delalloc_pages) <
1125 waitqueue_active(&root->fs_info->async_submit_wait))
1126 wake_up(&root->fs_info->async_submit_wait);
1128 if (async_cow->inode)
1129 submit_compressed_extents(async_cow->inode, async_cow);
1132 static noinline void async_cow_free(struct btrfs_work *work)
1134 struct async_cow *async_cow;
1135 async_cow = container_of(work, struct async_cow, work);
1136 if (async_cow->inode)
1137 btrfs_add_delayed_iput(async_cow->inode);
1141 static int cow_file_range_async(struct inode *inode, struct page *locked_page,
1142 u64 start, u64 end, int *page_started,
1143 unsigned long *nr_written)
1145 struct async_cow *async_cow;
1146 struct btrfs_root *root = BTRFS_I(inode)->root;
1147 unsigned long nr_pages;
1149 int limit = 10 * SZ_1M;
1151 clear_extent_bit(&BTRFS_I(inode)->io_tree, start, end, EXTENT_LOCKED,
1152 1, 0, NULL, GFP_NOFS);
1153 while (start < end) {
1154 async_cow = kmalloc(sizeof(*async_cow), GFP_NOFS);
1155 BUG_ON(!async_cow); /* -ENOMEM */
1156 async_cow->inode = igrab(inode);
1157 async_cow->root = root;
1158 async_cow->locked_page = locked_page;
1159 async_cow->start = start;
1161 if (BTRFS_I(inode)->flags & BTRFS_INODE_NOCOMPRESS &&
1162 !btrfs_test_opt(root->fs_info, FORCE_COMPRESS))
1165 cur_end = min(end, start + SZ_512K - 1);
1167 async_cow->end = cur_end;
1168 INIT_LIST_HEAD(&async_cow->extents);
1170 btrfs_init_work(&async_cow->work,
1171 btrfs_delalloc_helper,
1172 async_cow_start, async_cow_submit,
1175 nr_pages = (cur_end - start + PAGE_SIZE) >>
1177 atomic_add(nr_pages, &root->fs_info->async_delalloc_pages);
1179 btrfs_queue_work(root->fs_info->delalloc_workers,
1182 if (atomic_read(&root->fs_info->async_delalloc_pages) > limit) {
1183 wait_event(root->fs_info->async_submit_wait,
1184 (atomic_read(&root->fs_info->async_delalloc_pages) <
1188 while (atomic_read(&root->fs_info->async_submit_draining) &&
1189 atomic_read(&root->fs_info->async_delalloc_pages)) {
1190 wait_event(root->fs_info->async_submit_wait,
1191 (atomic_read(&root->fs_info->async_delalloc_pages) ==
1195 *nr_written += nr_pages;
1196 start = cur_end + 1;
1202 static noinline int csum_exist_in_range(struct btrfs_root *root,
1203 u64 bytenr, u64 num_bytes)
1206 struct btrfs_ordered_sum *sums;
1209 ret = btrfs_lookup_csums_range(root->fs_info->csum_root, bytenr,
1210 bytenr + num_bytes - 1, &list, 0);
1211 if (ret == 0 && list_empty(&list))
1214 while (!list_empty(&list)) {
1215 sums = list_entry(list.next, struct btrfs_ordered_sum, list);
1216 list_del(&sums->list);
1223 * when nowcow writeback call back. This checks for snapshots or COW copies
1224 * of the extents that exist in the file, and COWs the file as required.
1226 * If no cow copies or snapshots exist, we write directly to the existing
1229 static noinline int run_delalloc_nocow(struct inode *inode,
1230 struct page *locked_page,
1231 u64 start, u64 end, int *page_started, int force,
1232 unsigned long *nr_written)
1234 struct btrfs_root *root = BTRFS_I(inode)->root;
1235 struct btrfs_trans_handle *trans;
1236 struct extent_buffer *leaf;
1237 struct btrfs_path *path;
1238 struct btrfs_file_extent_item *fi;
1239 struct btrfs_key found_key;
1254 u64 ino = btrfs_ino(inode);
1256 path = btrfs_alloc_path();
1258 extent_clear_unlock_delalloc(inode, start, end, locked_page,
1259 EXTENT_LOCKED | EXTENT_DELALLOC |
1260 EXTENT_DO_ACCOUNTING |
1261 EXTENT_DEFRAG, PAGE_UNLOCK |
1263 PAGE_SET_WRITEBACK |
1264 PAGE_END_WRITEBACK);
1268 nolock = btrfs_is_free_space_inode(inode);
1271 trans = btrfs_join_transaction_nolock(root);
1273 trans = btrfs_join_transaction(root);
1275 if (IS_ERR(trans)) {
1276 extent_clear_unlock_delalloc(inode, start, end, locked_page,
1277 EXTENT_LOCKED | EXTENT_DELALLOC |
1278 EXTENT_DO_ACCOUNTING |
1279 EXTENT_DEFRAG, PAGE_UNLOCK |
1281 PAGE_SET_WRITEBACK |
1282 PAGE_END_WRITEBACK);
1283 btrfs_free_path(path);
1284 return PTR_ERR(trans);
1287 trans->block_rsv = &root->fs_info->delalloc_block_rsv;
1289 cow_start = (u64)-1;
1292 ret = btrfs_lookup_file_extent(trans, root, path, ino,
1296 if (ret > 0 && path->slots[0] > 0 && check_prev) {
1297 leaf = path->nodes[0];
1298 btrfs_item_key_to_cpu(leaf, &found_key,
1299 path->slots[0] - 1);
1300 if (found_key.objectid == ino &&
1301 found_key.type == BTRFS_EXTENT_DATA_KEY)
1306 leaf = path->nodes[0];
1307 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
1308 ret = btrfs_next_leaf(root, path);
1313 leaf = path->nodes[0];
1319 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
1321 if (found_key.objectid > ino)
1323 if (WARN_ON_ONCE(found_key.objectid < ino) ||
1324 found_key.type < BTRFS_EXTENT_DATA_KEY) {
1328 if (found_key.type > BTRFS_EXTENT_DATA_KEY ||
1329 found_key.offset > end)
1332 if (found_key.offset > cur_offset) {
1333 extent_end = found_key.offset;
1338 fi = btrfs_item_ptr(leaf, path->slots[0],
1339 struct btrfs_file_extent_item);
1340 extent_type = btrfs_file_extent_type(leaf, fi);
1342 ram_bytes = btrfs_file_extent_ram_bytes(leaf, fi);
1343 if (extent_type == BTRFS_FILE_EXTENT_REG ||
1344 extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
1345 disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
1346 extent_offset = btrfs_file_extent_offset(leaf, fi);
1347 extent_end = found_key.offset +
1348 btrfs_file_extent_num_bytes(leaf, fi);
1350 btrfs_file_extent_disk_num_bytes(leaf, fi);
1351 if (extent_end <= start) {
1355 if (disk_bytenr == 0)
1357 if (btrfs_file_extent_compression(leaf, fi) ||
1358 btrfs_file_extent_encryption(leaf, fi) ||
1359 btrfs_file_extent_other_encoding(leaf, fi))
1361 if (extent_type == BTRFS_FILE_EXTENT_REG && !force)
1363 if (btrfs_extent_readonly(root, disk_bytenr))
1365 if (btrfs_cross_ref_exist(trans, root, ino,
1367 extent_offset, disk_bytenr))
1369 disk_bytenr += extent_offset;
1370 disk_bytenr += cur_offset - found_key.offset;
1371 num_bytes = min(end + 1, extent_end) - cur_offset;
1373 * if there are pending snapshots for this root,
1374 * we fall into common COW way.
1377 err = btrfs_start_write_no_snapshoting(root);
1382 * force cow if csum exists in the range.
1383 * this ensure that csum for a given extent are
1384 * either valid or do not exist.
1386 if (csum_exist_in_range(root, disk_bytenr, num_bytes))
1388 if (!btrfs_inc_nocow_writers(root->fs_info,
1392 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
1393 extent_end = found_key.offset +
1394 btrfs_file_extent_inline_len(leaf,
1395 path->slots[0], fi);
1396 extent_end = ALIGN(extent_end, root->sectorsize);
1401 if (extent_end <= start) {
1403 if (!nolock && nocow)
1404 btrfs_end_write_no_snapshoting(root);
1406 btrfs_dec_nocow_writers(root->fs_info,
1411 if (cow_start == (u64)-1)
1412 cow_start = cur_offset;
1413 cur_offset = extent_end;
1414 if (cur_offset > end)
1420 btrfs_release_path(path);
1421 if (cow_start != (u64)-1) {
1422 ret = cow_file_range(inode, locked_page,
1423 cow_start, found_key.offset - 1,
1424 end, page_started, nr_written, 1,
1427 if (!nolock && nocow)
1428 btrfs_end_write_no_snapshoting(root);
1430 btrfs_dec_nocow_writers(root->fs_info,
1434 cow_start = (u64)-1;
1437 if (extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
1438 struct extent_map *em;
1439 struct extent_map_tree *em_tree;
1440 em_tree = &BTRFS_I(inode)->extent_tree;
1441 em = alloc_extent_map();
1442 BUG_ON(!em); /* -ENOMEM */
1443 em->start = cur_offset;
1444 em->orig_start = found_key.offset - extent_offset;
1445 em->len = num_bytes;
1446 em->block_len = num_bytes;
1447 em->block_start = disk_bytenr;
1448 em->orig_block_len = disk_num_bytes;
1449 em->ram_bytes = ram_bytes;
1450 em->bdev = root->fs_info->fs_devices->latest_bdev;
1451 em->mod_start = em->start;
1452 em->mod_len = em->len;
1453 set_bit(EXTENT_FLAG_PINNED, &em->flags);
1454 set_bit(EXTENT_FLAG_FILLING, &em->flags);
1455 em->generation = -1;
1457 write_lock(&em_tree->lock);
1458 ret = add_extent_mapping(em_tree, em, 1);
1459 write_unlock(&em_tree->lock);
1460 if (ret != -EEXIST) {
1461 free_extent_map(em);
1464 btrfs_drop_extent_cache(inode, em->start,
1465 em->start + em->len - 1, 0);
1467 type = BTRFS_ORDERED_PREALLOC;
1469 type = BTRFS_ORDERED_NOCOW;
1472 ret = btrfs_add_ordered_extent(inode, cur_offset, disk_bytenr,
1473 num_bytes, num_bytes, type);
1475 btrfs_dec_nocow_writers(root->fs_info, disk_bytenr);
1476 BUG_ON(ret); /* -ENOMEM */
1478 if (root->root_key.objectid ==
1479 BTRFS_DATA_RELOC_TREE_OBJECTID) {
1480 ret = btrfs_reloc_clone_csums(inode, cur_offset,
1483 if (!nolock && nocow)
1484 btrfs_end_write_no_snapshoting(root);
1489 extent_clear_unlock_delalloc(inode, cur_offset,
1490 cur_offset + num_bytes - 1,
1491 locked_page, EXTENT_LOCKED |
1492 EXTENT_DELALLOC, PAGE_UNLOCK |
1494 if (!nolock && nocow)
1495 btrfs_end_write_no_snapshoting(root);
1496 cur_offset = extent_end;
1497 if (cur_offset > end)
1500 btrfs_release_path(path);
1502 if (cur_offset <= end && cow_start == (u64)-1) {
1503 cow_start = cur_offset;
1507 if (cow_start != (u64)-1) {
1508 ret = cow_file_range(inode, locked_page, cow_start, end, end,
1509 page_started, nr_written, 1, NULL);
1515 err = btrfs_end_transaction(trans, root);
1519 if (ret && cur_offset < end)
1520 extent_clear_unlock_delalloc(inode, cur_offset, end,
1521 locked_page, EXTENT_LOCKED |
1522 EXTENT_DELALLOC | EXTENT_DEFRAG |
1523 EXTENT_DO_ACCOUNTING, PAGE_UNLOCK |
1525 PAGE_SET_WRITEBACK |
1526 PAGE_END_WRITEBACK);
1527 btrfs_free_path(path);
1531 static inline int need_force_cow(struct inode *inode, u64 start, u64 end)
1534 if (!(BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW) &&
1535 !(BTRFS_I(inode)->flags & BTRFS_INODE_PREALLOC))
1539 * @defrag_bytes is a hint value, no spinlock held here,
1540 * if is not zero, it means the file is defragging.
1541 * Force cow if given extent needs to be defragged.
1543 if (BTRFS_I(inode)->defrag_bytes &&
1544 test_range_bit(&BTRFS_I(inode)->io_tree, start, end,
1545 EXTENT_DEFRAG, 0, NULL))
1552 * extent_io.c call back to do delayed allocation processing
1554 static int run_delalloc_range(struct inode *inode, struct page *locked_page,
1555 u64 start, u64 end, int *page_started,
1556 unsigned long *nr_written)
1559 int force_cow = need_force_cow(inode, start, end);
1561 if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW && !force_cow) {
1562 ret = run_delalloc_nocow(inode, locked_page, start, end,
1563 page_started, 1, nr_written);
1564 } else if (BTRFS_I(inode)->flags & BTRFS_INODE_PREALLOC && !force_cow) {
1565 ret = run_delalloc_nocow(inode, locked_page, start, end,
1566 page_started, 0, nr_written);
1567 } else if (!inode_need_compress(inode)) {
1568 ret = cow_file_range(inode, locked_page, start, end, end,
1569 page_started, nr_written, 1, NULL);
1571 set_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
1572 &BTRFS_I(inode)->runtime_flags);
1573 ret = cow_file_range_async(inode, locked_page, start, end,
1574 page_started, nr_written);
1579 static void btrfs_split_extent_hook(struct inode *inode,
1580 struct extent_state *orig, u64 split)
1584 /* not delalloc, ignore it */
1585 if (!(orig->state & EXTENT_DELALLOC))
1588 size = orig->end - orig->start + 1;
1589 if (size > BTRFS_MAX_EXTENT_SIZE) {
1594 * See the explanation in btrfs_merge_extent_hook, the same
1595 * applies here, just in reverse.
1597 new_size = orig->end - split + 1;
1598 num_extents = div64_u64(new_size + BTRFS_MAX_EXTENT_SIZE - 1,
1599 BTRFS_MAX_EXTENT_SIZE);
1600 new_size = split - orig->start;
1601 num_extents += div64_u64(new_size + BTRFS_MAX_EXTENT_SIZE - 1,
1602 BTRFS_MAX_EXTENT_SIZE);
1603 if (div64_u64(size + BTRFS_MAX_EXTENT_SIZE - 1,
1604 BTRFS_MAX_EXTENT_SIZE) >= num_extents)
1608 spin_lock(&BTRFS_I(inode)->lock);
1609 BTRFS_I(inode)->outstanding_extents++;
1610 spin_unlock(&BTRFS_I(inode)->lock);
1614 * extent_io.c merge_extent_hook, used to track merged delayed allocation
1615 * extents so we can keep track of new extents that are just merged onto old
1616 * extents, such as when we are doing sequential writes, so we can properly
1617 * account for the metadata space we'll need.
1619 static void btrfs_merge_extent_hook(struct inode *inode,
1620 struct extent_state *new,
1621 struct extent_state *other)
1623 u64 new_size, old_size;
1626 /* not delalloc, ignore it */
1627 if (!(other->state & EXTENT_DELALLOC))
1630 if (new->start > other->start)
1631 new_size = new->end - other->start + 1;
1633 new_size = other->end - new->start + 1;
1635 /* we're not bigger than the max, unreserve the space and go */
1636 if (new_size <= BTRFS_MAX_EXTENT_SIZE) {
1637 spin_lock(&BTRFS_I(inode)->lock);
1638 BTRFS_I(inode)->outstanding_extents--;
1639 spin_unlock(&BTRFS_I(inode)->lock);
1644 * We have to add up either side to figure out how many extents were
1645 * accounted for before we merged into one big extent. If the number of
1646 * extents we accounted for is <= the amount we need for the new range
1647 * then we can return, otherwise drop. Think of it like this
1651 * So we've grown the extent by a MAX_SIZE extent, this would mean we
1652 * need 2 outstanding extents, on one side we have 1 and the other side
1653 * we have 1 so they are == and we can return. But in this case
1655 * [MAX_SIZE+4k][MAX_SIZE+4k]
1657 * Each range on their own accounts for 2 extents, but merged together
1658 * they are only 3 extents worth of accounting, so we need to drop in
1661 old_size = other->end - other->start + 1;
1662 num_extents = div64_u64(old_size + BTRFS_MAX_EXTENT_SIZE - 1,
1663 BTRFS_MAX_EXTENT_SIZE);
1664 old_size = new->end - new->start + 1;
1665 num_extents += div64_u64(old_size + BTRFS_MAX_EXTENT_SIZE - 1,
1666 BTRFS_MAX_EXTENT_SIZE);
1668 if (div64_u64(new_size + BTRFS_MAX_EXTENT_SIZE - 1,
1669 BTRFS_MAX_EXTENT_SIZE) >= num_extents)
1672 spin_lock(&BTRFS_I(inode)->lock);
1673 BTRFS_I(inode)->outstanding_extents--;
1674 spin_unlock(&BTRFS_I(inode)->lock);
1677 static void btrfs_add_delalloc_inodes(struct btrfs_root *root,
1678 struct inode *inode)
1680 spin_lock(&root->delalloc_lock);
1681 if (list_empty(&BTRFS_I(inode)->delalloc_inodes)) {
1682 list_add_tail(&BTRFS_I(inode)->delalloc_inodes,
1683 &root->delalloc_inodes);
1684 set_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1685 &BTRFS_I(inode)->runtime_flags);
1686 root->nr_delalloc_inodes++;
1687 if (root->nr_delalloc_inodes == 1) {
1688 spin_lock(&root->fs_info->delalloc_root_lock);
1689 BUG_ON(!list_empty(&root->delalloc_root));
1690 list_add_tail(&root->delalloc_root,
1691 &root->fs_info->delalloc_roots);
1692 spin_unlock(&root->fs_info->delalloc_root_lock);
1695 spin_unlock(&root->delalloc_lock);
1698 static void btrfs_del_delalloc_inode(struct btrfs_root *root,
1699 struct inode *inode)
1701 spin_lock(&root->delalloc_lock);
1702 if (!list_empty(&BTRFS_I(inode)->delalloc_inodes)) {
1703 list_del_init(&BTRFS_I(inode)->delalloc_inodes);
1704 clear_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1705 &BTRFS_I(inode)->runtime_flags);
1706 root->nr_delalloc_inodes--;
1707 if (!root->nr_delalloc_inodes) {
1708 spin_lock(&root->fs_info->delalloc_root_lock);
1709 BUG_ON(list_empty(&root->delalloc_root));
1710 list_del_init(&root->delalloc_root);
1711 spin_unlock(&root->fs_info->delalloc_root_lock);
1714 spin_unlock(&root->delalloc_lock);
1718 * extent_io.c set_bit_hook, used to track delayed allocation
1719 * bytes in this file, and to maintain the list of inodes that
1720 * have pending delalloc work to be done.
1722 static void btrfs_set_bit_hook(struct inode *inode,
1723 struct extent_state *state, unsigned *bits)
1726 if ((*bits & EXTENT_DEFRAG) && !(*bits & EXTENT_DELALLOC))
1729 * set_bit and clear bit hooks normally require _irqsave/restore
1730 * but in this case, we are only testing for the DELALLOC
1731 * bit, which is only set or cleared with irqs on
1733 if (!(state->state & EXTENT_DELALLOC) && (*bits & EXTENT_DELALLOC)) {
1734 struct btrfs_root *root = BTRFS_I(inode)->root;
1735 u64 len = state->end + 1 - state->start;
1736 bool do_list = !btrfs_is_free_space_inode(inode);
1738 if (*bits & EXTENT_FIRST_DELALLOC) {
1739 *bits &= ~EXTENT_FIRST_DELALLOC;
1741 spin_lock(&BTRFS_I(inode)->lock);
1742 BTRFS_I(inode)->outstanding_extents++;
1743 spin_unlock(&BTRFS_I(inode)->lock);
1746 /* For sanity tests */
1747 if (btrfs_is_testing(root->fs_info))
1750 __percpu_counter_add(&root->fs_info->delalloc_bytes, len,
1751 root->fs_info->delalloc_batch);
1752 spin_lock(&BTRFS_I(inode)->lock);
1753 BTRFS_I(inode)->delalloc_bytes += len;
1754 if (*bits & EXTENT_DEFRAG)
1755 BTRFS_I(inode)->defrag_bytes += len;
1756 if (do_list && !test_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1757 &BTRFS_I(inode)->runtime_flags))
1758 btrfs_add_delalloc_inodes(root, inode);
1759 spin_unlock(&BTRFS_I(inode)->lock);
1764 * extent_io.c clear_bit_hook, see set_bit_hook for why
1766 static void btrfs_clear_bit_hook(struct inode *inode,
1767 struct extent_state *state,
1770 u64 len = state->end + 1 - state->start;
1771 u64 num_extents = div64_u64(len + BTRFS_MAX_EXTENT_SIZE -1,
1772 BTRFS_MAX_EXTENT_SIZE);
1774 spin_lock(&BTRFS_I(inode)->lock);
1775 if ((state->state & EXTENT_DEFRAG) && (*bits & EXTENT_DEFRAG))
1776 BTRFS_I(inode)->defrag_bytes -= len;
1777 spin_unlock(&BTRFS_I(inode)->lock);
1780 * set_bit and clear bit hooks normally require _irqsave/restore
1781 * but in this case, we are only testing for the DELALLOC
1782 * bit, which is only set or cleared with irqs on
1784 if ((state->state & EXTENT_DELALLOC) && (*bits & EXTENT_DELALLOC)) {
1785 struct btrfs_root *root = BTRFS_I(inode)->root;
1786 bool do_list = !btrfs_is_free_space_inode(inode);
1788 if (*bits & EXTENT_FIRST_DELALLOC) {
1789 *bits &= ~EXTENT_FIRST_DELALLOC;
1790 } else if (!(*bits & EXTENT_DO_ACCOUNTING)) {
1791 spin_lock(&BTRFS_I(inode)->lock);
1792 BTRFS_I(inode)->outstanding_extents -= num_extents;
1793 spin_unlock(&BTRFS_I(inode)->lock);
1797 * We don't reserve metadata space for space cache inodes so we
1798 * don't need to call dellalloc_release_metadata if there is an
1801 if (*bits & EXTENT_DO_ACCOUNTING &&
1802 root != root->fs_info->tree_root)
1803 btrfs_delalloc_release_metadata(inode, len);
1805 /* For sanity tests. */
1806 if (btrfs_is_testing(root->fs_info))
1809 if (root->root_key.objectid != BTRFS_DATA_RELOC_TREE_OBJECTID
1810 && do_list && !(state->state & EXTENT_NORESERVE))
1811 btrfs_free_reserved_data_space_noquota(inode,
1814 __percpu_counter_add(&root->fs_info->delalloc_bytes, -len,
1815 root->fs_info->delalloc_batch);
1816 spin_lock(&BTRFS_I(inode)->lock);
1817 BTRFS_I(inode)->delalloc_bytes -= len;
1818 if (do_list && BTRFS_I(inode)->delalloc_bytes == 0 &&
1819 test_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1820 &BTRFS_I(inode)->runtime_flags))
1821 btrfs_del_delalloc_inode(root, inode);
1822 spin_unlock(&BTRFS_I(inode)->lock);
1827 * extent_io.c merge_bio_hook, this must check the chunk tree to make sure
1828 * we don't create bios that span stripes or chunks
1830 * return 1 if page cannot be merged to bio
1831 * return 0 if page can be merged to bio
1832 * return error otherwise
1834 int btrfs_merge_bio_hook(struct page *page, unsigned long offset,
1835 size_t size, struct bio *bio,
1836 unsigned long bio_flags)
1838 struct btrfs_root *root = BTRFS_I(page->mapping->host)->root;
1839 u64 logical = (u64)bio->bi_iter.bi_sector << 9;
1844 if (bio_flags & EXTENT_BIO_COMPRESSED)
1847 length = bio->bi_iter.bi_size;
1848 map_length = length;
1849 ret = btrfs_map_block(root->fs_info, bio_op(bio), logical,
1850 &map_length, NULL, 0);
1853 if (map_length < length + size)
1859 * in order to insert checksums into the metadata in large chunks,
1860 * we wait until bio submission time. All the pages in the bio are
1861 * checksummed and sums are attached onto the ordered extent record.
1863 * At IO completion time the cums attached on the ordered extent record
1864 * are inserted into the btree
1866 static int __btrfs_submit_bio_start(struct inode *inode, struct bio *bio,
1867 int mirror_num, unsigned long bio_flags,
1870 struct btrfs_root *root = BTRFS_I(inode)->root;
1873 ret = btrfs_csum_one_bio(root, inode, bio, 0, 0);
1874 BUG_ON(ret); /* -ENOMEM */
1879 * in order to insert checksums into the metadata in large chunks,
1880 * we wait until bio submission time. All the pages in the bio are
1881 * checksummed and sums are attached onto the ordered extent record.
1883 * At IO completion time the cums attached on the ordered extent record
1884 * are inserted into the btree
1886 static int __btrfs_submit_bio_done(struct inode *inode, struct bio *bio,
1887 int mirror_num, unsigned long bio_flags,
1890 struct btrfs_root *root = BTRFS_I(inode)->root;
1893 ret = btrfs_map_bio(root, bio, mirror_num, 1);
1895 bio->bi_error = ret;
1902 * extent_io.c submission hook. This does the right thing for csum calculation
1903 * on write, or reading the csums from the tree before a read
1905 static int btrfs_submit_bio_hook(struct inode *inode, struct bio *bio,
1906 int mirror_num, unsigned long bio_flags,
1909 struct btrfs_root *root = BTRFS_I(inode)->root;
1910 enum btrfs_wq_endio_type metadata = BTRFS_WQ_ENDIO_DATA;
1913 int async = !atomic_read(&BTRFS_I(inode)->sync_writers);
1915 skip_sum = BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM;
1917 if (btrfs_is_free_space_inode(inode))
1918 metadata = BTRFS_WQ_ENDIO_FREE_SPACE;
1920 if (bio_op(bio) != REQ_OP_WRITE) {
1921 ret = btrfs_bio_wq_end_io(root->fs_info, bio, metadata);
1925 if (bio_flags & EXTENT_BIO_COMPRESSED) {
1926 ret = btrfs_submit_compressed_read(inode, bio,
1930 } else if (!skip_sum) {
1931 ret = btrfs_lookup_bio_sums(root, inode, bio, NULL);
1936 } else if (async && !skip_sum) {
1937 /* csum items have already been cloned */
1938 if (root->root_key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID)
1940 /* we're doing a write, do the async checksumming */
1941 ret = btrfs_wq_submit_bio(BTRFS_I(inode)->root->fs_info,
1942 inode, bio, mirror_num,
1943 bio_flags, bio_offset,
1944 __btrfs_submit_bio_start,
1945 __btrfs_submit_bio_done);
1947 } else if (!skip_sum) {
1948 ret = btrfs_csum_one_bio(root, inode, bio, 0, 0);
1954 ret = btrfs_map_bio(root, bio, mirror_num, 0);
1958 bio->bi_error = ret;
1965 * given a list of ordered sums record them in the inode. This happens
1966 * at IO completion time based on sums calculated at bio submission time.
1968 static noinline int add_pending_csums(struct btrfs_trans_handle *trans,
1969 struct inode *inode, u64 file_offset,
1970 struct list_head *list)
1972 struct btrfs_ordered_sum *sum;
1974 list_for_each_entry(sum, list, list) {
1975 trans->adding_csums = 1;
1976 btrfs_csum_file_blocks(trans,
1977 BTRFS_I(inode)->root->fs_info->csum_root, sum);
1978 trans->adding_csums = 0;
1983 int btrfs_set_extent_delalloc(struct inode *inode, u64 start, u64 end,
1984 struct extent_state **cached_state)
1986 WARN_ON((end & (PAGE_SIZE - 1)) == 0);
1987 return set_extent_delalloc(&BTRFS_I(inode)->io_tree, start, end,
1991 /* see btrfs_writepage_start_hook for details on why this is required */
1992 struct btrfs_writepage_fixup {
1994 struct btrfs_work work;
1997 static void btrfs_writepage_fixup_worker(struct btrfs_work *work)
1999 struct btrfs_writepage_fixup *fixup;
2000 struct btrfs_ordered_extent *ordered;
2001 struct extent_state *cached_state = NULL;
2003 struct inode *inode;
2008 fixup = container_of(work, struct btrfs_writepage_fixup, work);
2012 if (!page->mapping || !PageDirty(page) || !PageChecked(page)) {
2013 ClearPageChecked(page);
2017 inode = page->mapping->host;
2018 page_start = page_offset(page);
2019 page_end = page_offset(page) + PAGE_SIZE - 1;
2021 lock_extent_bits(&BTRFS_I(inode)->io_tree, page_start, page_end,
2024 /* already ordered? We're done */
2025 if (PagePrivate2(page))
2028 ordered = btrfs_lookup_ordered_range(inode, page_start,
2031 unlock_extent_cached(&BTRFS_I(inode)->io_tree, page_start,
2032 page_end, &cached_state, GFP_NOFS);
2034 btrfs_start_ordered_extent(inode, ordered, 1);
2035 btrfs_put_ordered_extent(ordered);
2039 ret = btrfs_delalloc_reserve_space(inode, page_start,
2042 mapping_set_error(page->mapping, ret);
2043 end_extent_writepage(page, ret, page_start, page_end);
2044 ClearPageChecked(page);
2048 btrfs_set_extent_delalloc(inode, page_start, page_end, &cached_state);
2049 ClearPageChecked(page);
2050 set_page_dirty(page);
2052 unlock_extent_cached(&BTRFS_I(inode)->io_tree, page_start, page_end,
2053 &cached_state, GFP_NOFS);
2061 * There are a few paths in the higher layers of the kernel that directly
2062 * set the page dirty bit without asking the filesystem if it is a
2063 * good idea. This causes problems because we want to make sure COW
2064 * properly happens and the data=ordered rules are followed.
2066 * In our case any range that doesn't have the ORDERED bit set
2067 * hasn't been properly setup for IO. We kick off an async process
2068 * to fix it up. The async helper will wait for ordered extents, set
2069 * the delalloc bit and make it safe to write the page.
2071 static int btrfs_writepage_start_hook(struct page *page, u64 start, u64 end)
2073 struct inode *inode = page->mapping->host;
2074 struct btrfs_writepage_fixup *fixup;
2075 struct btrfs_root *root = BTRFS_I(inode)->root;
2077 /* this page is properly in the ordered list */
2078 if (TestClearPagePrivate2(page))
2081 if (PageChecked(page))
2084 fixup = kzalloc(sizeof(*fixup), GFP_NOFS);
2088 SetPageChecked(page);
2090 btrfs_init_work(&fixup->work, btrfs_fixup_helper,
2091 btrfs_writepage_fixup_worker, NULL, NULL);
2093 btrfs_queue_work(root->fs_info->fixup_workers, &fixup->work);
2097 static int insert_reserved_file_extent(struct btrfs_trans_handle *trans,
2098 struct inode *inode, u64 file_pos,
2099 u64 disk_bytenr, u64 disk_num_bytes,
2100 u64 num_bytes, u64 ram_bytes,
2101 u8 compression, u8 encryption,
2102 u16 other_encoding, int extent_type)
2104 struct btrfs_root *root = BTRFS_I(inode)->root;
2105 struct btrfs_file_extent_item *fi;
2106 struct btrfs_path *path;
2107 struct extent_buffer *leaf;
2108 struct btrfs_key ins;
2109 int extent_inserted = 0;
2112 path = btrfs_alloc_path();
2117 * we may be replacing one extent in the tree with another.
2118 * The new extent is pinned in the extent map, and we don't want
2119 * to drop it from the cache until it is completely in the btree.
2121 * So, tell btrfs_drop_extents to leave this extent in the cache.
2122 * the caller is expected to unpin it and allow it to be merged
2125 ret = __btrfs_drop_extents(trans, root, inode, path, file_pos,
2126 file_pos + num_bytes, NULL, 0,
2127 1, sizeof(*fi), &extent_inserted);
2131 if (!extent_inserted) {
2132 ins.objectid = btrfs_ino(inode);
2133 ins.offset = file_pos;
2134 ins.type = BTRFS_EXTENT_DATA_KEY;
2136 path->leave_spinning = 1;
2137 ret = btrfs_insert_empty_item(trans, root, path, &ins,
2142 leaf = path->nodes[0];
2143 fi = btrfs_item_ptr(leaf, path->slots[0],
2144 struct btrfs_file_extent_item);
2145 btrfs_set_file_extent_generation(leaf, fi, trans->transid);
2146 btrfs_set_file_extent_type(leaf, fi, extent_type);
2147 btrfs_set_file_extent_disk_bytenr(leaf, fi, disk_bytenr);
2148 btrfs_set_file_extent_disk_num_bytes(leaf, fi, disk_num_bytes);
2149 btrfs_set_file_extent_offset(leaf, fi, 0);
2150 btrfs_set_file_extent_num_bytes(leaf, fi, num_bytes);
2151 btrfs_set_file_extent_ram_bytes(leaf, fi, ram_bytes);
2152 btrfs_set_file_extent_compression(leaf, fi, compression);
2153 btrfs_set_file_extent_encryption(leaf, fi, encryption);
2154 btrfs_set_file_extent_other_encoding(leaf, fi, other_encoding);
2156 btrfs_mark_buffer_dirty(leaf);
2157 btrfs_release_path(path);
2159 inode_add_bytes(inode, num_bytes);
2161 ins.objectid = disk_bytenr;
2162 ins.offset = disk_num_bytes;
2163 ins.type = BTRFS_EXTENT_ITEM_KEY;
2164 ret = btrfs_alloc_reserved_file_extent(trans, root,
2165 root->root_key.objectid,
2166 btrfs_ino(inode), file_pos,
2169 * Release the reserved range from inode dirty range map, as it is
2170 * already moved into delayed_ref_head
2172 btrfs_qgroup_release_data(inode, file_pos, ram_bytes);
2174 btrfs_free_path(path);
2179 /* snapshot-aware defrag */
2180 struct sa_defrag_extent_backref {
2181 struct rb_node node;
2182 struct old_sa_defrag_extent *old;
2191 struct old_sa_defrag_extent {
2192 struct list_head list;
2193 struct new_sa_defrag_extent *new;
2202 struct new_sa_defrag_extent {
2203 struct rb_root root;
2204 struct list_head head;
2205 struct btrfs_path *path;
2206 struct inode *inode;
2214 static int backref_comp(struct sa_defrag_extent_backref *b1,
2215 struct sa_defrag_extent_backref *b2)
2217 if (b1->root_id < b2->root_id)
2219 else if (b1->root_id > b2->root_id)
2222 if (b1->inum < b2->inum)
2224 else if (b1->inum > b2->inum)
2227 if (b1->file_pos < b2->file_pos)
2229 else if (b1->file_pos > b2->file_pos)
2233 * [------------------------------] ===> (a range of space)
2234 * |<--->| |<---->| =============> (fs/file tree A)
2235 * |<---------------------------->| ===> (fs/file tree B)
2237 * A range of space can refer to two file extents in one tree while
2238 * refer to only one file extent in another tree.
2240 * So we may process a disk offset more than one time(two extents in A)
2241 * and locate at the same extent(one extent in B), then insert two same
2242 * backrefs(both refer to the extent in B).
2247 static void backref_insert(struct rb_root *root,
2248 struct sa_defrag_extent_backref *backref)
2250 struct rb_node **p = &root->rb_node;
2251 struct rb_node *parent = NULL;
2252 struct sa_defrag_extent_backref *entry;
2257 entry = rb_entry(parent, struct sa_defrag_extent_backref, node);
2259 ret = backref_comp(backref, entry);
2263 p = &(*p)->rb_right;
2266 rb_link_node(&backref->node, parent, p);
2267 rb_insert_color(&backref->node, root);
2271 * Note the backref might has changed, and in this case we just return 0.
2273 static noinline int record_one_backref(u64 inum, u64 offset, u64 root_id,
2276 struct btrfs_file_extent_item *extent;
2277 struct btrfs_fs_info *fs_info;
2278 struct old_sa_defrag_extent *old = ctx;
2279 struct new_sa_defrag_extent *new = old->new;
2280 struct btrfs_path *path = new->path;
2281 struct btrfs_key key;
2282 struct btrfs_root *root;
2283 struct sa_defrag_extent_backref *backref;
2284 struct extent_buffer *leaf;
2285 struct inode *inode = new->inode;
2291 if (BTRFS_I(inode)->root->root_key.objectid == root_id &&
2292 inum == btrfs_ino(inode))
2295 key.objectid = root_id;
2296 key.type = BTRFS_ROOT_ITEM_KEY;
2297 key.offset = (u64)-1;
2299 fs_info = BTRFS_I(inode)->root->fs_info;
2300 root = btrfs_read_fs_root_no_name(fs_info, &key);
2302 if (PTR_ERR(root) == -ENOENT)
2305 pr_debug("inum=%llu, offset=%llu, root_id=%llu\n",
2306 inum, offset, root_id);
2307 return PTR_ERR(root);
2310 key.objectid = inum;
2311 key.type = BTRFS_EXTENT_DATA_KEY;
2312 if (offset > (u64)-1 << 32)
2315 key.offset = offset;
2317 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2318 if (WARN_ON(ret < 0))
2325 leaf = path->nodes[0];
2326 slot = path->slots[0];
2328 if (slot >= btrfs_header_nritems(leaf)) {
2329 ret = btrfs_next_leaf(root, path);
2332 } else if (ret > 0) {
2341 btrfs_item_key_to_cpu(leaf, &key, slot);
2343 if (key.objectid > inum)
2346 if (key.objectid < inum || key.type != BTRFS_EXTENT_DATA_KEY)
2349 extent = btrfs_item_ptr(leaf, slot,
2350 struct btrfs_file_extent_item);
2352 if (btrfs_file_extent_disk_bytenr(leaf, extent) != old->bytenr)
2356 * 'offset' refers to the exact key.offset,
2357 * NOT the 'offset' field in btrfs_extent_data_ref, ie.
2358 * (key.offset - extent_offset).
2360 if (key.offset != offset)
2363 extent_offset = btrfs_file_extent_offset(leaf, extent);
2364 num_bytes = btrfs_file_extent_num_bytes(leaf, extent);
2366 if (extent_offset >= old->extent_offset + old->offset +
2367 old->len || extent_offset + num_bytes <=
2368 old->extent_offset + old->offset)
2373 backref = kmalloc(sizeof(*backref), GFP_NOFS);
2379 backref->root_id = root_id;
2380 backref->inum = inum;
2381 backref->file_pos = offset;
2382 backref->num_bytes = num_bytes;
2383 backref->extent_offset = extent_offset;
2384 backref->generation = btrfs_file_extent_generation(leaf, extent);
2386 backref_insert(&new->root, backref);
2389 btrfs_release_path(path);
2394 static noinline bool record_extent_backrefs(struct btrfs_path *path,
2395 struct new_sa_defrag_extent *new)
2397 struct btrfs_fs_info *fs_info = BTRFS_I(new->inode)->root->fs_info;
2398 struct old_sa_defrag_extent *old, *tmp;
2403 list_for_each_entry_safe(old, tmp, &new->head, list) {
2404 ret = iterate_inodes_from_logical(old->bytenr +
2405 old->extent_offset, fs_info,
2406 path, record_one_backref,
2408 if (ret < 0 && ret != -ENOENT)
2411 /* no backref to be processed for this extent */
2413 list_del(&old->list);
2418 if (list_empty(&new->head))
2424 static int relink_is_mergable(struct extent_buffer *leaf,
2425 struct btrfs_file_extent_item *fi,
2426 struct new_sa_defrag_extent *new)
2428 if (btrfs_file_extent_disk_bytenr(leaf, fi) != new->bytenr)
2431 if (btrfs_file_extent_type(leaf, fi) != BTRFS_FILE_EXTENT_REG)
2434 if (btrfs_file_extent_compression(leaf, fi) != new->compress_type)
2437 if (btrfs_file_extent_encryption(leaf, fi) ||
2438 btrfs_file_extent_other_encoding(leaf, fi))
2445 * Note the backref might has changed, and in this case we just return 0.
2447 static noinline int relink_extent_backref(struct btrfs_path *path,
2448 struct sa_defrag_extent_backref *prev,
2449 struct sa_defrag_extent_backref *backref)
2451 struct btrfs_file_extent_item *extent;
2452 struct btrfs_file_extent_item *item;
2453 struct btrfs_ordered_extent *ordered;
2454 struct btrfs_trans_handle *trans;
2455 struct btrfs_fs_info *fs_info;
2456 struct btrfs_root *root;
2457 struct btrfs_key key;
2458 struct extent_buffer *leaf;
2459 struct old_sa_defrag_extent *old = backref->old;
2460 struct new_sa_defrag_extent *new = old->new;
2461 struct inode *src_inode = new->inode;
2462 struct inode *inode;
2463 struct extent_state *cached = NULL;
2472 if (prev && prev->root_id == backref->root_id &&
2473 prev->inum == backref->inum &&
2474 prev->file_pos + prev->num_bytes == backref->file_pos)
2477 /* step 1: get root */
2478 key.objectid = backref->root_id;
2479 key.type = BTRFS_ROOT_ITEM_KEY;
2480 key.offset = (u64)-1;
2482 fs_info = BTRFS_I(src_inode)->root->fs_info;
2483 index = srcu_read_lock(&fs_info->subvol_srcu);
2485 root = btrfs_read_fs_root_no_name(fs_info, &key);
2487 srcu_read_unlock(&fs_info->subvol_srcu, index);
2488 if (PTR_ERR(root) == -ENOENT)
2490 return PTR_ERR(root);
2493 if (btrfs_root_readonly(root)) {
2494 srcu_read_unlock(&fs_info->subvol_srcu, index);
2498 /* step 2: get inode */
2499 key.objectid = backref->inum;
2500 key.type = BTRFS_INODE_ITEM_KEY;
2503 inode = btrfs_iget(fs_info->sb, &key, root, NULL);
2504 if (IS_ERR(inode)) {
2505 srcu_read_unlock(&fs_info->subvol_srcu, index);
2509 srcu_read_unlock(&fs_info->subvol_srcu, index);
2511 /* step 3: relink backref */
2512 lock_start = backref->file_pos;
2513 lock_end = backref->file_pos + backref->num_bytes - 1;
2514 lock_extent_bits(&BTRFS_I(inode)->io_tree, lock_start, lock_end,
2517 ordered = btrfs_lookup_first_ordered_extent(inode, lock_end);
2519 btrfs_put_ordered_extent(ordered);
2523 trans = btrfs_join_transaction(root);
2524 if (IS_ERR(trans)) {
2525 ret = PTR_ERR(trans);
2529 key.objectid = backref->inum;
2530 key.type = BTRFS_EXTENT_DATA_KEY;
2531 key.offset = backref->file_pos;
2533 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2536 } else if (ret > 0) {
2541 extent = btrfs_item_ptr(path->nodes[0], path->slots[0],
2542 struct btrfs_file_extent_item);
2544 if (btrfs_file_extent_generation(path->nodes[0], extent) !=
2545 backref->generation)
2548 btrfs_release_path(path);
2550 start = backref->file_pos;
2551 if (backref->extent_offset < old->extent_offset + old->offset)
2552 start += old->extent_offset + old->offset -
2553 backref->extent_offset;
2555 len = min(backref->extent_offset + backref->num_bytes,
2556 old->extent_offset + old->offset + old->len);
2557 len -= max(backref->extent_offset, old->extent_offset + old->offset);
2559 ret = btrfs_drop_extents(trans, root, inode, start,
2564 key.objectid = btrfs_ino(inode);
2565 key.type = BTRFS_EXTENT_DATA_KEY;
2568 path->leave_spinning = 1;
2570 struct btrfs_file_extent_item *fi;
2572 struct btrfs_key found_key;
2574 ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
2579 leaf = path->nodes[0];
2580 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
2582 fi = btrfs_item_ptr(leaf, path->slots[0],
2583 struct btrfs_file_extent_item);
2584 extent_len = btrfs_file_extent_num_bytes(leaf, fi);
2586 if (extent_len + found_key.offset == start &&
2587 relink_is_mergable(leaf, fi, new)) {
2588 btrfs_set_file_extent_num_bytes(leaf, fi,
2590 btrfs_mark_buffer_dirty(leaf);
2591 inode_add_bytes(inode, len);
2597 btrfs_release_path(path);
2602 ret = btrfs_insert_empty_item(trans, root, path, &key,
2605 btrfs_abort_transaction(trans, ret);
2609 leaf = path->nodes[0];
2610 item = btrfs_item_ptr(leaf, path->slots[0],
2611 struct btrfs_file_extent_item);
2612 btrfs_set_file_extent_disk_bytenr(leaf, item, new->bytenr);
2613 btrfs_set_file_extent_disk_num_bytes(leaf, item, new->disk_len);
2614 btrfs_set_file_extent_offset(leaf, item, start - new->file_pos);
2615 btrfs_set_file_extent_num_bytes(leaf, item, len);
2616 btrfs_set_file_extent_ram_bytes(leaf, item, new->len);
2617 btrfs_set_file_extent_generation(leaf, item, trans->transid);
2618 btrfs_set_file_extent_type(leaf, item, BTRFS_FILE_EXTENT_REG);
2619 btrfs_set_file_extent_compression(leaf, item, new->compress_type);
2620 btrfs_set_file_extent_encryption(leaf, item, 0);
2621 btrfs_set_file_extent_other_encoding(leaf, item, 0);
2623 btrfs_mark_buffer_dirty(leaf);
2624 inode_add_bytes(inode, len);
2625 btrfs_release_path(path);
2627 ret = btrfs_inc_extent_ref(trans, root, new->bytenr,
2629 backref->root_id, backref->inum,
2630 new->file_pos); /* start - extent_offset */
2632 btrfs_abort_transaction(trans, ret);
2638 btrfs_release_path(path);
2639 path->leave_spinning = 0;
2640 btrfs_end_transaction(trans, root);
2642 unlock_extent_cached(&BTRFS_I(inode)->io_tree, lock_start, lock_end,
2648 static void free_sa_defrag_extent(struct new_sa_defrag_extent *new)
2650 struct old_sa_defrag_extent *old, *tmp;
2655 list_for_each_entry_safe(old, tmp, &new->head, list) {
2661 static void relink_file_extents(struct new_sa_defrag_extent *new)
2663 struct btrfs_path *path;
2664 struct sa_defrag_extent_backref *backref;
2665 struct sa_defrag_extent_backref *prev = NULL;
2666 struct inode *inode;
2667 struct btrfs_root *root;
2668 struct rb_node *node;
2672 root = BTRFS_I(inode)->root;
2674 path = btrfs_alloc_path();
2678 if (!record_extent_backrefs(path, new)) {
2679 btrfs_free_path(path);
2682 btrfs_release_path(path);
2685 node = rb_first(&new->root);
2688 rb_erase(node, &new->root);
2690 backref = rb_entry(node, struct sa_defrag_extent_backref, node);
2692 ret = relink_extent_backref(path, prev, backref);
2705 btrfs_free_path(path);
2707 free_sa_defrag_extent(new);
2709 atomic_dec(&root->fs_info->defrag_running);
2710 wake_up(&root->fs_info->transaction_wait);
2713 static struct new_sa_defrag_extent *
2714 record_old_file_extents(struct inode *inode,
2715 struct btrfs_ordered_extent *ordered)
2717 struct btrfs_root *root = BTRFS_I(inode)->root;
2718 struct btrfs_path *path;
2719 struct btrfs_key key;
2720 struct old_sa_defrag_extent *old;
2721 struct new_sa_defrag_extent *new;
2724 new = kmalloc(sizeof(*new), GFP_NOFS);
2729 new->file_pos = ordered->file_offset;
2730 new->len = ordered->len;
2731 new->bytenr = ordered->start;
2732 new->disk_len = ordered->disk_len;
2733 new->compress_type = ordered->compress_type;
2734 new->root = RB_ROOT;
2735 INIT_LIST_HEAD(&new->head);
2737 path = btrfs_alloc_path();
2741 key.objectid = btrfs_ino(inode);
2742 key.type = BTRFS_EXTENT_DATA_KEY;
2743 key.offset = new->file_pos;
2745 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2748 if (ret > 0 && path->slots[0] > 0)
2751 /* find out all the old extents for the file range */
2753 struct btrfs_file_extent_item *extent;
2754 struct extent_buffer *l;
2763 slot = path->slots[0];
2765 if (slot >= btrfs_header_nritems(l)) {
2766 ret = btrfs_next_leaf(root, path);
2774 btrfs_item_key_to_cpu(l, &key, slot);
2776 if (key.objectid != btrfs_ino(inode))
2778 if (key.type != BTRFS_EXTENT_DATA_KEY)
2780 if (key.offset >= new->file_pos + new->len)
2783 extent = btrfs_item_ptr(l, slot, struct btrfs_file_extent_item);
2785 num_bytes = btrfs_file_extent_num_bytes(l, extent);
2786 if (key.offset + num_bytes < new->file_pos)
2789 disk_bytenr = btrfs_file_extent_disk_bytenr(l, extent);
2793 extent_offset = btrfs_file_extent_offset(l, extent);
2795 old = kmalloc(sizeof(*old), GFP_NOFS);
2799 offset = max(new->file_pos, key.offset);
2800 end = min(new->file_pos + new->len, key.offset + num_bytes);
2802 old->bytenr = disk_bytenr;
2803 old->extent_offset = extent_offset;
2804 old->offset = offset - key.offset;
2805 old->len = end - offset;
2808 list_add_tail(&old->list, &new->head);
2814 btrfs_free_path(path);
2815 atomic_inc(&root->fs_info->defrag_running);
2820 btrfs_free_path(path);
2822 free_sa_defrag_extent(new);
2826 static void btrfs_release_delalloc_bytes(struct btrfs_root *root,
2829 struct btrfs_block_group_cache *cache;
2831 cache = btrfs_lookup_block_group(root->fs_info, start);
2834 spin_lock(&cache->lock);
2835 cache->delalloc_bytes -= len;
2836 spin_unlock(&cache->lock);
2838 btrfs_put_block_group(cache);
2841 /* as ordered data IO finishes, this gets called so we can finish
2842 * an ordered extent if the range of bytes in the file it covers are
2845 static int btrfs_finish_ordered_io(struct btrfs_ordered_extent *ordered_extent)
2847 struct inode *inode = ordered_extent->inode;
2848 struct btrfs_root *root = BTRFS_I(inode)->root;
2849 struct btrfs_trans_handle *trans = NULL;
2850 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
2851 struct extent_state *cached_state = NULL;
2852 struct new_sa_defrag_extent *new = NULL;
2853 int compress_type = 0;
2855 u64 logical_len = ordered_extent->len;
2857 bool truncated = false;
2859 nolock = btrfs_is_free_space_inode(inode);
2861 if (test_bit(BTRFS_ORDERED_IOERR, &ordered_extent->flags)) {
2866 btrfs_free_io_failure_record(inode, ordered_extent->file_offset,
2867 ordered_extent->file_offset +
2868 ordered_extent->len - 1);
2870 if (test_bit(BTRFS_ORDERED_TRUNCATED, &ordered_extent->flags)) {
2872 logical_len = ordered_extent->truncated_len;
2873 /* Truncated the entire extent, don't bother adding */
2878 if (test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags)) {
2879 BUG_ON(!list_empty(&ordered_extent->list)); /* Logic error */
2882 * For mwrite(mmap + memset to write) case, we still reserve
2883 * space for NOCOW range.
2884 * As NOCOW won't cause a new delayed ref, just free the space
2886 btrfs_qgroup_free_data(inode, ordered_extent->file_offset,
2887 ordered_extent->len);
2888 btrfs_ordered_update_i_size(inode, 0, ordered_extent);
2890 trans = btrfs_join_transaction_nolock(root);
2892 trans = btrfs_join_transaction(root);
2893 if (IS_ERR(trans)) {
2894 ret = PTR_ERR(trans);
2898 trans->block_rsv = &root->fs_info->delalloc_block_rsv;
2899 ret = btrfs_update_inode_fallback(trans, root, inode);
2900 if (ret) /* -ENOMEM or corruption */
2901 btrfs_abort_transaction(trans, ret);
2905 lock_extent_bits(io_tree, ordered_extent->file_offset,
2906 ordered_extent->file_offset + ordered_extent->len - 1,
2909 ret = test_range_bit(io_tree, ordered_extent->file_offset,
2910 ordered_extent->file_offset + ordered_extent->len - 1,
2911 EXTENT_DEFRAG, 1, cached_state);
2913 u64 last_snapshot = btrfs_root_last_snapshot(&root->root_item);
2914 if (0 && last_snapshot >= BTRFS_I(inode)->generation)
2915 /* the inode is shared */
2916 new = record_old_file_extents(inode, ordered_extent);
2918 clear_extent_bit(io_tree, ordered_extent->file_offset,
2919 ordered_extent->file_offset + ordered_extent->len - 1,
2920 EXTENT_DEFRAG, 0, 0, &cached_state, GFP_NOFS);
2924 trans = btrfs_join_transaction_nolock(root);
2926 trans = btrfs_join_transaction(root);
2927 if (IS_ERR(trans)) {
2928 ret = PTR_ERR(trans);
2933 trans->block_rsv = &root->fs_info->delalloc_block_rsv;
2935 if (test_bit(BTRFS_ORDERED_COMPRESSED, &ordered_extent->flags))
2936 compress_type = ordered_extent->compress_type;
2937 if (test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags)) {
2938 BUG_ON(compress_type);
2939 ret = btrfs_mark_extent_written(trans, inode,
2940 ordered_extent->file_offset,
2941 ordered_extent->file_offset +
2944 BUG_ON(root == root->fs_info->tree_root);
2945 ret = insert_reserved_file_extent(trans, inode,
2946 ordered_extent->file_offset,
2947 ordered_extent->start,
2948 ordered_extent->disk_len,
2949 logical_len, logical_len,
2950 compress_type, 0, 0,
2951 BTRFS_FILE_EXTENT_REG);
2953 btrfs_release_delalloc_bytes(root,
2954 ordered_extent->start,
2955 ordered_extent->disk_len);
2957 unpin_extent_cache(&BTRFS_I(inode)->extent_tree,
2958 ordered_extent->file_offset, ordered_extent->len,
2961 btrfs_abort_transaction(trans, ret);
2965 add_pending_csums(trans, inode, ordered_extent->file_offset,
2966 &ordered_extent->list);
2968 btrfs_ordered_update_i_size(inode, 0, ordered_extent);
2969 ret = btrfs_update_inode_fallback(trans, root, inode);
2970 if (ret) { /* -ENOMEM or corruption */
2971 btrfs_abort_transaction(trans, ret);
2976 unlock_extent_cached(io_tree, ordered_extent->file_offset,
2977 ordered_extent->file_offset +
2978 ordered_extent->len - 1, &cached_state, GFP_NOFS);
2980 if (root != root->fs_info->tree_root)
2981 btrfs_delalloc_release_metadata(inode, ordered_extent->len);
2983 btrfs_end_transaction(trans, root);
2985 if (ret || truncated) {
2989 start = ordered_extent->file_offset + logical_len;
2991 start = ordered_extent->file_offset;
2992 end = ordered_extent->file_offset + ordered_extent->len - 1;
2993 clear_extent_uptodate(io_tree, start, end, NULL, GFP_NOFS);
2995 /* Drop the cache for the part of the extent we didn't write. */
2996 btrfs_drop_extent_cache(inode, start, end, 0);
2999 * If the ordered extent had an IOERR or something else went
3000 * wrong we need to return the space for this ordered extent
3001 * back to the allocator. We only free the extent in the
3002 * truncated case if we didn't write out the extent at all.
3004 if ((ret || !logical_len) &&
3005 !test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags) &&
3006 !test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags))
3007 btrfs_free_reserved_extent(root, ordered_extent->start,
3008 ordered_extent->disk_len, 1);
3013 * This needs to be done to make sure anybody waiting knows we are done
3014 * updating everything for this ordered extent.
3016 btrfs_remove_ordered_extent(inode, ordered_extent);
3018 /* for snapshot-aware defrag */
3021 free_sa_defrag_extent(new);
3022 atomic_dec(&root->fs_info->defrag_running);
3024 relink_file_extents(new);
3029 btrfs_put_ordered_extent(ordered_extent);
3030 /* once for the tree */
3031 btrfs_put_ordered_extent(ordered_extent);
3036 static void finish_ordered_fn(struct btrfs_work *work)
3038 struct btrfs_ordered_extent *ordered_extent;
3039 ordered_extent = container_of(work, struct btrfs_ordered_extent, work);
3040 btrfs_finish_ordered_io(ordered_extent);
3043 static int btrfs_writepage_end_io_hook(struct page *page, u64 start, u64 end,
3044 struct extent_state *state, int uptodate)
3046 struct inode *inode = page->mapping->host;
3047 struct btrfs_root *root = BTRFS_I(inode)->root;
3048 struct btrfs_ordered_extent *ordered_extent = NULL;
3049 struct btrfs_workqueue *wq;
3050 btrfs_work_func_t func;
3052 trace_btrfs_writepage_end_io_hook(page, start, end, uptodate);
3054 ClearPagePrivate2(page);
3055 if (!btrfs_dec_test_ordered_pending(inode, &ordered_extent, start,
3056 end - start + 1, uptodate))
3059 if (btrfs_is_free_space_inode(inode)) {
3060 wq = root->fs_info->endio_freespace_worker;
3061 func = btrfs_freespace_write_helper;
3063 wq = root->fs_info->endio_write_workers;
3064 func = btrfs_endio_write_helper;
3067 btrfs_init_work(&ordered_extent->work, func, finish_ordered_fn, NULL,
3069 btrfs_queue_work(wq, &ordered_extent->work);
3074 static int __readpage_endio_check(struct inode *inode,
3075 struct btrfs_io_bio *io_bio,
3076 int icsum, struct page *page,
3077 int pgoff, u64 start, size_t len)
3083 csum_expected = *(((u32 *)io_bio->csum) + icsum);
3085 kaddr = kmap_atomic(page);
3086 csum = btrfs_csum_data(kaddr + pgoff, csum, len);
3087 btrfs_csum_final(csum, (char *)&csum);
3088 if (csum != csum_expected)
3091 kunmap_atomic(kaddr);
3094 btrfs_warn_rl(BTRFS_I(inode)->root->fs_info,
3095 "csum failed ino %llu off %llu csum %u expected csum %u",
3096 btrfs_ino(inode), start, csum, csum_expected);
3097 memset(kaddr + pgoff, 1, len);
3098 flush_dcache_page(page);
3099 kunmap_atomic(kaddr);
3100 if (csum_expected == 0)
3106 * when reads are done, we need to check csums to verify the data is correct
3107 * if there's a match, we allow the bio to finish. If not, the code in
3108 * extent_io.c will try to find good copies for us.
3110 static int btrfs_readpage_end_io_hook(struct btrfs_io_bio *io_bio,
3111 u64 phy_offset, struct page *page,
3112 u64 start, u64 end, int mirror)
3114 size_t offset = start - page_offset(page);
3115 struct inode *inode = page->mapping->host;
3116 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
3117 struct btrfs_root *root = BTRFS_I(inode)->root;
3119 if (PageChecked(page)) {
3120 ClearPageChecked(page);
3124 if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)
3127 if (root->root_key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID &&
3128 test_range_bit(io_tree, start, end, EXTENT_NODATASUM, 1, NULL)) {
3129 clear_extent_bits(io_tree, start, end, EXTENT_NODATASUM);
3133 phy_offset >>= inode->i_sb->s_blocksize_bits;
3134 return __readpage_endio_check(inode, io_bio, phy_offset, page, offset,
3135 start, (size_t)(end - start + 1));
3138 void btrfs_add_delayed_iput(struct inode *inode)
3140 struct btrfs_fs_info *fs_info = BTRFS_I(inode)->root->fs_info;
3141 struct btrfs_inode *binode = BTRFS_I(inode);
3143 if (atomic_add_unless(&inode->i_count, -1, 1))
3146 spin_lock(&fs_info->delayed_iput_lock);
3147 if (binode->delayed_iput_count == 0) {
3148 ASSERT(list_empty(&binode->delayed_iput));
3149 list_add_tail(&binode->delayed_iput, &fs_info->delayed_iputs);
3151 binode->delayed_iput_count++;
3153 spin_unlock(&fs_info->delayed_iput_lock);
3156 void btrfs_run_delayed_iputs(struct btrfs_root *root)
3158 struct btrfs_fs_info *fs_info = root->fs_info;
3160 spin_lock(&fs_info->delayed_iput_lock);
3161 while (!list_empty(&fs_info->delayed_iputs)) {
3162 struct btrfs_inode *inode;
3164 inode = list_first_entry(&fs_info->delayed_iputs,
3165 struct btrfs_inode, delayed_iput);
3166 if (inode->delayed_iput_count) {
3167 inode->delayed_iput_count--;
3168 list_move_tail(&inode->delayed_iput,
3169 &fs_info->delayed_iputs);
3171 list_del_init(&inode->delayed_iput);
3173 spin_unlock(&fs_info->delayed_iput_lock);
3174 iput(&inode->vfs_inode);
3175 spin_lock(&fs_info->delayed_iput_lock);
3177 spin_unlock(&fs_info->delayed_iput_lock);
3181 * This is called in transaction commit time. If there are no orphan
3182 * files in the subvolume, it removes orphan item and frees block_rsv
3185 void btrfs_orphan_commit_root(struct btrfs_trans_handle *trans,
3186 struct btrfs_root *root)
3188 struct btrfs_block_rsv *block_rsv;
3191 if (atomic_read(&root->orphan_inodes) ||
3192 root->orphan_cleanup_state != ORPHAN_CLEANUP_DONE)
3195 spin_lock(&root->orphan_lock);
3196 if (atomic_read(&root->orphan_inodes)) {
3197 spin_unlock(&root->orphan_lock);
3201 if (root->orphan_cleanup_state != ORPHAN_CLEANUP_DONE) {
3202 spin_unlock(&root->orphan_lock);
3206 block_rsv = root->orphan_block_rsv;
3207 root->orphan_block_rsv = NULL;
3208 spin_unlock(&root->orphan_lock);
3210 if (test_bit(BTRFS_ROOT_ORPHAN_ITEM_INSERTED, &root->state) &&
3211 btrfs_root_refs(&root->root_item) > 0) {
3212 ret = btrfs_del_orphan_item(trans, root->fs_info->tree_root,
3213 root->root_key.objectid);
3215 btrfs_abort_transaction(trans, ret);
3217 clear_bit(BTRFS_ROOT_ORPHAN_ITEM_INSERTED,
3222 WARN_ON(block_rsv->size > 0);
3223 btrfs_free_block_rsv(root, block_rsv);
3228 * This creates an orphan entry for the given inode in case something goes
3229 * wrong in the middle of an unlink/truncate.
3231 * NOTE: caller of this function should reserve 5 units of metadata for
3234 int btrfs_orphan_add(struct btrfs_trans_handle *trans, struct inode *inode)
3236 struct btrfs_root *root = BTRFS_I(inode)->root;
3237 struct btrfs_block_rsv *block_rsv = NULL;
3242 if (!root->orphan_block_rsv) {
3243 block_rsv = btrfs_alloc_block_rsv(root, BTRFS_BLOCK_RSV_TEMP);
3248 spin_lock(&root->orphan_lock);
3249 if (!root->orphan_block_rsv) {
3250 root->orphan_block_rsv = block_rsv;
3251 } else if (block_rsv) {
3252 btrfs_free_block_rsv(root, block_rsv);
3256 if (!test_and_set_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
3257 &BTRFS_I(inode)->runtime_flags)) {
3260 * For proper ENOSPC handling, we should do orphan
3261 * cleanup when mounting. But this introduces backward
3262 * compatibility issue.
3264 if (!xchg(&root->orphan_item_inserted, 1))
3270 atomic_inc(&root->orphan_inodes);
3273 if (!test_and_set_bit(BTRFS_INODE_ORPHAN_META_RESERVED,
3274 &BTRFS_I(inode)->runtime_flags))
3276 spin_unlock(&root->orphan_lock);
3278 /* grab metadata reservation from transaction handle */
3280 ret = btrfs_orphan_reserve_metadata(trans, inode);
3283 atomic_dec(&root->orphan_inodes);
3284 clear_bit(BTRFS_INODE_ORPHAN_META_RESERVED,
3285 &BTRFS_I(inode)->runtime_flags);
3287 clear_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
3288 &BTRFS_I(inode)->runtime_flags);
3293 /* insert an orphan item to track this unlinked/truncated file */
3295 ret = btrfs_insert_orphan_item(trans, root, btrfs_ino(inode));
3297 atomic_dec(&root->orphan_inodes);
3299 clear_bit(BTRFS_INODE_ORPHAN_META_RESERVED,
3300 &BTRFS_I(inode)->runtime_flags);
3301 btrfs_orphan_release_metadata(inode);
3303 if (ret != -EEXIST) {
3304 clear_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
3305 &BTRFS_I(inode)->runtime_flags);
3306 btrfs_abort_transaction(trans, ret);
3313 /* insert an orphan item to track subvolume contains orphan files */
3315 ret = btrfs_insert_orphan_item(trans, root->fs_info->tree_root,
3316 root->root_key.objectid);
3317 if (ret && ret != -EEXIST) {
3318 btrfs_abort_transaction(trans, ret);
3326 * We have done the truncate/delete so we can go ahead and remove the orphan
3327 * item for this particular inode.
3329 static int btrfs_orphan_del(struct btrfs_trans_handle *trans,
3330 struct inode *inode)
3332 struct btrfs_root *root = BTRFS_I(inode)->root;
3333 int delete_item = 0;
3334 int release_rsv = 0;
3337 spin_lock(&root->orphan_lock);
3338 if (test_and_clear_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
3339 &BTRFS_I(inode)->runtime_flags))
3342 if (test_and_clear_bit(BTRFS_INODE_ORPHAN_META_RESERVED,
3343 &BTRFS_I(inode)->runtime_flags))
3345 spin_unlock(&root->orphan_lock);
3348 atomic_dec(&root->orphan_inodes);
3350 ret = btrfs_del_orphan_item(trans, root,
3355 btrfs_orphan_release_metadata(inode);
3361 * this cleans up any orphans that may be left on the list from the last use
3364 int btrfs_orphan_cleanup(struct btrfs_root *root)
3366 struct btrfs_path *path;
3367 struct extent_buffer *leaf;
3368 struct btrfs_key key, found_key;
3369 struct btrfs_trans_handle *trans;
3370 struct inode *inode;
3371 u64 last_objectid = 0;
3372 int ret = 0, nr_unlink = 0, nr_truncate = 0;
3374 if (cmpxchg(&root->orphan_cleanup_state, 0, ORPHAN_CLEANUP_STARTED))
3377 path = btrfs_alloc_path();
3382 path->reada = READA_BACK;
3384 key.objectid = BTRFS_ORPHAN_OBJECTID;
3385 key.type = BTRFS_ORPHAN_ITEM_KEY;
3386 key.offset = (u64)-1;
3389 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
3394 * if ret == 0 means we found what we were searching for, which
3395 * is weird, but possible, so only screw with path if we didn't
3396 * find the key and see if we have stuff that matches
3400 if (path->slots[0] == 0)
3405 /* pull out the item */
3406 leaf = path->nodes[0];
3407 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
3409 /* make sure the item matches what we want */
3410 if (found_key.objectid != BTRFS_ORPHAN_OBJECTID)
3412 if (found_key.type != BTRFS_ORPHAN_ITEM_KEY)
3415 /* release the path since we're done with it */
3416 btrfs_release_path(path);
3419 * this is where we are basically btrfs_lookup, without the
3420 * crossing root thing. we store the inode number in the
3421 * offset of the orphan item.
3424 if (found_key.offset == last_objectid) {
3425 btrfs_err(root->fs_info,
3426 "Error removing orphan entry, stopping orphan cleanup");
3431 last_objectid = found_key.offset;
3433 found_key.objectid = found_key.offset;
3434 found_key.type = BTRFS_INODE_ITEM_KEY;
3435 found_key.offset = 0;
3436 inode = btrfs_iget(root->fs_info->sb, &found_key, root, NULL);
3437 ret = PTR_ERR_OR_ZERO(inode);
3438 if (ret && ret != -ENOENT)
3441 if (ret == -ENOENT && root == root->fs_info->tree_root) {
3442 struct btrfs_root *dead_root;
3443 struct btrfs_fs_info *fs_info = root->fs_info;
3444 int is_dead_root = 0;
3447 * this is an orphan in the tree root. Currently these
3448 * could come from 2 sources:
3449 * a) a snapshot deletion in progress
3450 * b) a free space cache inode
3451 * We need to distinguish those two, as the snapshot
3452 * orphan must not get deleted.
3453 * find_dead_roots already ran before us, so if this
3454 * is a snapshot deletion, we should find the root
3455 * in the dead_roots list
3457 spin_lock(&fs_info->trans_lock);
3458 list_for_each_entry(dead_root, &fs_info->dead_roots,
3460 if (dead_root->root_key.objectid ==
3461 found_key.objectid) {
3466 spin_unlock(&fs_info->trans_lock);
3468 /* prevent this orphan from being found again */
3469 key.offset = found_key.objectid - 1;
3474 * Inode is already gone but the orphan item is still there,
3475 * kill the orphan item.
3477 if (ret == -ENOENT) {
3478 trans = btrfs_start_transaction(root, 1);
3479 if (IS_ERR(trans)) {
3480 ret = PTR_ERR(trans);
3483 btrfs_debug(root->fs_info, "auto deleting %Lu",
3484 found_key.objectid);
3485 ret = btrfs_del_orphan_item(trans, root,
3486 found_key.objectid);
3487 btrfs_end_transaction(trans, root);
3494 * add this inode to the orphan list so btrfs_orphan_del does
3495 * the proper thing when we hit it
3497 set_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
3498 &BTRFS_I(inode)->runtime_flags);
3499 atomic_inc(&root->orphan_inodes);
3501 /* if we have links, this was a truncate, lets do that */
3502 if (inode->i_nlink) {
3503 if (WARN_ON(!S_ISREG(inode->i_mode))) {
3509 /* 1 for the orphan item deletion. */
3510 trans = btrfs_start_transaction(root, 1);
3511 if (IS_ERR(trans)) {
3513 ret = PTR_ERR(trans);
3516 ret = btrfs_orphan_add(trans, inode);
3517 btrfs_end_transaction(trans, root);
3523 ret = btrfs_truncate(inode);
3525 btrfs_orphan_del(NULL, inode);
3530 /* this will do delete_inode and everything for us */
3535 /* release the path since we're done with it */
3536 btrfs_release_path(path);
3538 root->orphan_cleanup_state = ORPHAN_CLEANUP_DONE;
3540 if (root->orphan_block_rsv)
3541 btrfs_block_rsv_release(root, root->orphan_block_rsv,
3544 if (root->orphan_block_rsv ||
3545 test_bit(BTRFS_ROOT_ORPHAN_ITEM_INSERTED, &root->state)) {
3546 trans = btrfs_join_transaction(root);
3548 btrfs_end_transaction(trans, root);
3552 btrfs_debug(root->fs_info, "unlinked %d orphans", nr_unlink);
3554 btrfs_debug(root->fs_info, "truncated %d orphans", nr_truncate);
3558 btrfs_err(root->fs_info,
3559 "could not do orphan cleanup %d", ret);
3560 btrfs_free_path(path);
3565 * very simple check to peek ahead in the leaf looking for xattrs. If we
3566 * don't find any xattrs, we know there can't be any acls.
3568 * slot is the slot the inode is in, objectid is the objectid of the inode
3570 static noinline int acls_after_inode_item(struct extent_buffer *leaf,
3571 int slot, u64 objectid,
3572 int *first_xattr_slot)
3574 u32 nritems = btrfs_header_nritems(leaf);
3575 struct btrfs_key found_key;
3576 static u64 xattr_access = 0;
3577 static u64 xattr_default = 0;
3580 if (!xattr_access) {
3581 xattr_access = btrfs_name_hash(XATTR_NAME_POSIX_ACL_ACCESS,
3582 strlen(XATTR_NAME_POSIX_ACL_ACCESS));
3583 xattr_default = btrfs_name_hash(XATTR_NAME_POSIX_ACL_DEFAULT,
3584 strlen(XATTR_NAME_POSIX_ACL_DEFAULT));
3588 *first_xattr_slot = -1;
3589 while (slot < nritems) {
3590 btrfs_item_key_to_cpu(leaf, &found_key, slot);
3592 /* we found a different objectid, there must not be acls */
3593 if (found_key.objectid != objectid)
3596 /* we found an xattr, assume we've got an acl */
3597 if (found_key.type == BTRFS_XATTR_ITEM_KEY) {
3598 if (*first_xattr_slot == -1)
3599 *first_xattr_slot = slot;
3600 if (found_key.offset == xattr_access ||
3601 found_key.offset == xattr_default)
3606 * we found a key greater than an xattr key, there can't
3607 * be any acls later on
3609 if (found_key.type > BTRFS_XATTR_ITEM_KEY)
3616 * it goes inode, inode backrefs, xattrs, extents,
3617 * so if there are a ton of hard links to an inode there can
3618 * be a lot of backrefs. Don't waste time searching too hard,
3619 * this is just an optimization
3624 /* we hit the end of the leaf before we found an xattr or
3625 * something larger than an xattr. We have to assume the inode
3628 if (*first_xattr_slot == -1)
3629 *first_xattr_slot = slot;
3634 * read an inode from the btree into the in-memory inode
3636 static int btrfs_read_locked_inode(struct inode *inode)
3638 struct btrfs_path *path;
3639 struct extent_buffer *leaf;
3640 struct btrfs_inode_item *inode_item;
3641 struct btrfs_root *root = BTRFS_I(inode)->root;
3642 struct btrfs_key location;
3647 bool filled = false;
3648 int first_xattr_slot;
3650 ret = btrfs_fill_inode(inode, &rdev);
3654 path = btrfs_alloc_path();
3660 memcpy(&location, &BTRFS_I(inode)->location, sizeof(location));
3662 ret = btrfs_lookup_inode(NULL, root, path, &location, 0);
3669 leaf = path->nodes[0];
3674 inode_item = btrfs_item_ptr(leaf, path->slots[0],
3675 struct btrfs_inode_item);
3676 inode->i_mode = btrfs_inode_mode(leaf, inode_item);
3677 set_nlink(inode, btrfs_inode_nlink(leaf, inode_item));
3678 i_uid_write(inode, btrfs_inode_uid(leaf, inode_item));
3679 i_gid_write(inode, btrfs_inode_gid(leaf, inode_item));
3680 btrfs_i_size_write(inode, btrfs_inode_size(leaf, inode_item));
3682 inode->i_atime.tv_sec = btrfs_timespec_sec(leaf, &inode_item->atime);
3683 inode->i_atime.tv_nsec = btrfs_timespec_nsec(leaf, &inode_item->atime);
3685 inode->i_mtime.tv_sec = btrfs_timespec_sec(leaf, &inode_item->mtime);
3686 inode->i_mtime.tv_nsec = btrfs_timespec_nsec(leaf, &inode_item->mtime);
3688 inode->i_ctime.tv_sec = btrfs_timespec_sec(leaf, &inode_item->ctime);
3689 inode->i_ctime.tv_nsec = btrfs_timespec_nsec(leaf, &inode_item->ctime);
3691 BTRFS_I(inode)->i_otime.tv_sec =
3692 btrfs_timespec_sec(leaf, &inode_item->otime);
3693 BTRFS_I(inode)->i_otime.tv_nsec =
3694 btrfs_timespec_nsec(leaf, &inode_item->otime);
3696 inode_set_bytes(inode, btrfs_inode_nbytes(leaf, inode_item));
3697 BTRFS_I(inode)->generation = btrfs_inode_generation(leaf, inode_item);
3698 BTRFS_I(inode)->last_trans = btrfs_inode_transid(leaf, inode_item);
3700 inode->i_version = btrfs_inode_sequence(leaf, inode_item);
3701 inode->i_generation = BTRFS_I(inode)->generation;
3703 rdev = btrfs_inode_rdev(leaf, inode_item);
3705 BTRFS_I(inode)->index_cnt = (u64)-1;
3706 BTRFS_I(inode)->flags = btrfs_inode_flags(leaf, inode_item);
3710 * If we were modified in the current generation and evicted from memory
3711 * and then re-read we need to do a full sync since we don't have any
3712 * idea about which extents were modified before we were evicted from
3715 * This is required for both inode re-read from disk and delayed inode
3716 * in delayed_nodes_tree.
3718 if (BTRFS_I(inode)->last_trans == root->fs_info->generation)
3719 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
3720 &BTRFS_I(inode)->runtime_flags);
3723 * We don't persist the id of the transaction where an unlink operation
3724 * against the inode was last made. So here we assume the inode might
3725 * have been evicted, and therefore the exact value of last_unlink_trans
3726 * lost, and set it to last_trans to avoid metadata inconsistencies
3727 * between the inode and its parent if the inode is fsync'ed and the log
3728 * replayed. For example, in the scenario:
3731 * ln mydir/foo mydir/bar
3734 * echo 2 > /proc/sys/vm/drop_caches # evicts inode
3735 * xfs_io -c fsync mydir/foo
3737 * mount fs, triggers fsync log replay
3739 * We must make sure that when we fsync our inode foo we also log its
3740 * parent inode, otherwise after log replay the parent still has the
3741 * dentry with the "bar" name but our inode foo has a link count of 1
3742 * and doesn't have an inode ref with the name "bar" anymore.
3744 * Setting last_unlink_trans to last_trans is a pessimistic approach,
3745 * but it guarantees correctness at the expense of occasional full
3746 * transaction commits on fsync if our inode is a directory, or if our
3747 * inode is not a directory, logging its parent unnecessarily.
3749 BTRFS_I(inode)->last_unlink_trans = BTRFS_I(inode)->last_trans;
3752 if (inode->i_nlink != 1 ||
3753 path->slots[0] >= btrfs_header_nritems(leaf))
3756 btrfs_item_key_to_cpu(leaf, &location, path->slots[0]);
3757 if (location.objectid != btrfs_ino(inode))
3760 ptr = btrfs_item_ptr_offset(leaf, path->slots[0]);
3761 if (location.type == BTRFS_INODE_REF_KEY) {
3762 struct btrfs_inode_ref *ref;
3764 ref = (struct btrfs_inode_ref *)ptr;
3765 BTRFS_I(inode)->dir_index = btrfs_inode_ref_index(leaf, ref);
3766 } else if (location.type == BTRFS_INODE_EXTREF_KEY) {
3767 struct btrfs_inode_extref *extref;
3769 extref = (struct btrfs_inode_extref *)ptr;
3770 BTRFS_I(inode)->dir_index = btrfs_inode_extref_index(leaf,
3775 * try to precache a NULL acl entry for files that don't have
3776 * any xattrs or acls
3778 maybe_acls = acls_after_inode_item(leaf, path->slots[0],
3779 btrfs_ino(inode), &first_xattr_slot);
3780 if (first_xattr_slot != -1) {
3781 path->slots[0] = first_xattr_slot;
3782 ret = btrfs_load_inode_props(inode, path);
3784 btrfs_err(root->fs_info,
3785 "error loading props for ino %llu (root %llu): %d",
3787 root->root_key.objectid, ret);
3789 btrfs_free_path(path);
3792 cache_no_acl(inode);
3794 switch (inode->i_mode & S_IFMT) {
3796 inode->i_mapping->a_ops = &btrfs_aops;
3797 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
3798 inode->i_fop = &btrfs_file_operations;
3799 inode->i_op = &btrfs_file_inode_operations;
3802 inode->i_fop = &btrfs_dir_file_operations;
3803 if (root == root->fs_info->tree_root)
3804 inode->i_op = &btrfs_dir_ro_inode_operations;
3806 inode->i_op = &btrfs_dir_inode_operations;
3809 inode->i_op = &btrfs_symlink_inode_operations;
3810 inode_nohighmem(inode);
3811 inode->i_mapping->a_ops = &btrfs_symlink_aops;
3814 inode->i_op = &btrfs_special_inode_operations;
3815 init_special_inode(inode, inode->i_mode, rdev);
3819 btrfs_update_iflags(inode);
3823 btrfs_free_path(path);
3824 make_bad_inode(inode);
3829 * given a leaf and an inode, copy the inode fields into the leaf
3831 static void fill_inode_item(struct btrfs_trans_handle *trans,
3832 struct extent_buffer *leaf,
3833 struct btrfs_inode_item *item,
3834 struct inode *inode)
3836 struct btrfs_map_token token;
3838 btrfs_init_map_token(&token);
3840 btrfs_set_token_inode_uid(leaf, item, i_uid_read(inode), &token);
3841 btrfs_set_token_inode_gid(leaf, item, i_gid_read(inode), &token);
3842 btrfs_set_token_inode_size(leaf, item, BTRFS_I(inode)->disk_i_size,
3844 btrfs_set_token_inode_mode(leaf, item, inode->i_mode, &token);
3845 btrfs_set_token_inode_nlink(leaf, item, inode->i_nlink, &token);
3847 btrfs_set_token_timespec_sec(leaf, &item->atime,
3848 inode->i_atime.tv_sec, &token);
3849 btrfs_set_token_timespec_nsec(leaf, &item->atime,
3850 inode->i_atime.tv_nsec, &token);
3852 btrfs_set_token_timespec_sec(leaf, &item->mtime,
3853 inode->i_mtime.tv_sec, &token);
3854 btrfs_set_token_timespec_nsec(leaf, &item->mtime,
3855 inode->i_mtime.tv_nsec, &token);
3857 btrfs_set_token_timespec_sec(leaf, &item->ctime,
3858 inode->i_ctime.tv_sec, &token);
3859 btrfs_set_token_timespec_nsec(leaf, &item->ctime,
3860 inode->i_ctime.tv_nsec, &token);
3862 btrfs_set_token_timespec_sec(leaf, &item->otime,
3863 BTRFS_I(inode)->i_otime.tv_sec, &token);
3864 btrfs_set_token_timespec_nsec(leaf, &item->otime,
3865 BTRFS_I(inode)->i_otime.tv_nsec, &token);
3867 btrfs_set_token_inode_nbytes(leaf, item, inode_get_bytes(inode),
3869 btrfs_set_token_inode_generation(leaf, item, BTRFS_I(inode)->generation,
3871 btrfs_set_token_inode_sequence(leaf, item, inode->i_version, &token);
3872 btrfs_set_token_inode_transid(leaf, item, trans->transid, &token);
3873 btrfs_set_token_inode_rdev(leaf, item, inode->i_rdev, &token);
3874 btrfs_set_token_inode_flags(leaf, item, BTRFS_I(inode)->flags, &token);
3875 btrfs_set_token_inode_block_group(leaf, item, 0, &token);
3879 * copy everything in the in-memory inode into the btree.
3881 static noinline int btrfs_update_inode_item(struct btrfs_trans_handle *trans,
3882 struct btrfs_root *root, struct inode *inode)
3884 struct btrfs_inode_item *inode_item;
3885 struct btrfs_path *path;
3886 struct extent_buffer *leaf;
3889 path = btrfs_alloc_path();
3893 path->leave_spinning = 1;
3894 ret = btrfs_lookup_inode(trans, root, path, &BTRFS_I(inode)->location,
3902 leaf = path->nodes[0];
3903 inode_item = btrfs_item_ptr(leaf, path->slots[0],
3904 struct btrfs_inode_item);
3906 fill_inode_item(trans, leaf, inode_item, inode);
3907 btrfs_mark_buffer_dirty(leaf);
3908 btrfs_set_inode_last_trans(trans, inode);
3911 btrfs_free_path(path);
3916 * copy everything in the in-memory inode into the btree.
3918 noinline int btrfs_update_inode(struct btrfs_trans_handle *trans,
3919 struct btrfs_root *root, struct inode *inode)
3924 * If the inode is a free space inode, we can deadlock during commit
3925 * if we put it into the delayed code.
3927 * The data relocation inode should also be directly updated
3930 if (!btrfs_is_free_space_inode(inode)
3931 && root->root_key.objectid != BTRFS_DATA_RELOC_TREE_OBJECTID
3932 && !root->fs_info->log_root_recovering) {
3933 btrfs_update_root_times(trans, root);
3935 ret = btrfs_delayed_update_inode(trans, root, inode);
3937 btrfs_set_inode_last_trans(trans, inode);
3941 return btrfs_update_inode_item(trans, root, inode);
3944 noinline int btrfs_update_inode_fallback(struct btrfs_trans_handle *trans,
3945 struct btrfs_root *root,
3946 struct inode *inode)
3950 ret = btrfs_update_inode(trans, root, inode);
3952 return btrfs_update_inode_item(trans, root, inode);
3957 * unlink helper that gets used here in inode.c and in the tree logging
3958 * recovery code. It remove a link in a directory with a given name, and
3959 * also drops the back refs in the inode to the directory
3961 static int __btrfs_unlink_inode(struct btrfs_trans_handle *trans,
3962 struct btrfs_root *root,
3963 struct inode *dir, struct inode *inode,
3964 const char *name, int name_len)
3966 struct btrfs_path *path;
3968 struct extent_buffer *leaf;
3969 struct btrfs_dir_item *di;
3970 struct btrfs_key key;
3972 u64 ino = btrfs_ino(inode);
3973 u64 dir_ino = btrfs_ino(dir);
3975 path = btrfs_alloc_path();
3981 path->leave_spinning = 1;
3982 di = btrfs_lookup_dir_item(trans, root, path, dir_ino,
3983 name, name_len, -1);
3992 leaf = path->nodes[0];
3993 btrfs_dir_item_key_to_cpu(leaf, di, &key);
3994 ret = btrfs_delete_one_dir_name(trans, root, path, di);
3997 btrfs_release_path(path);
4000 * If we don't have dir index, we have to get it by looking up
4001 * the inode ref, since we get the inode ref, remove it directly,
4002 * it is unnecessary to do delayed deletion.
4004 * But if we have dir index, needn't search inode ref to get it.
4005 * Since the inode ref is close to the inode item, it is better
4006 * that we delay to delete it, and just do this deletion when
4007 * we update the inode item.
4009 if (BTRFS_I(inode)->dir_index) {
4010 ret = btrfs_delayed_delete_inode_ref(inode);
4012 index = BTRFS_I(inode)->dir_index;
4017 ret = btrfs_del_inode_ref(trans, root, name, name_len, ino,
4020 btrfs_info(root->fs_info,
4021 "failed to delete reference to %.*s, inode %llu parent %llu",
4022 name_len, name, ino, dir_ino);
4023 btrfs_abort_transaction(trans, ret);
4027 ret = btrfs_delete_delayed_dir_index(trans, root, dir, index);
4029 btrfs_abort_transaction(trans, ret);
4033 ret = btrfs_del_inode_ref_in_log(trans, root, name, name_len,
4035 if (ret != 0 && ret != -ENOENT) {
4036 btrfs_abort_transaction(trans, ret);
4040 ret = btrfs_del_dir_entries_in_log(trans, root, name, name_len,
4045 btrfs_abort_transaction(trans, ret);
4047 btrfs_free_path(path);
4051 btrfs_i_size_write(dir, dir->i_size - name_len * 2);
4052 inode_inc_iversion(inode);
4053 inode_inc_iversion(dir);
4054 inode->i_ctime = dir->i_mtime =
4055 dir->i_ctime = current_fs_time(inode->i_sb);
4056 ret = btrfs_update_inode(trans, root, dir);
4061 int btrfs_unlink_inode(struct btrfs_trans_handle *trans,
4062 struct btrfs_root *root,
4063 struct inode *dir, struct inode *inode,
4064 const char *name, int name_len)
4067 ret = __btrfs_unlink_inode(trans, root, dir, inode, name, name_len);
4070 ret = btrfs_update_inode(trans, root, inode);
4076 * helper to start transaction for unlink and rmdir.
4078 * unlink and rmdir are special in btrfs, they do not always free space, so
4079 * if we cannot make our reservations the normal way try and see if there is
4080 * plenty of slack room in the global reserve to migrate, otherwise we cannot
4081 * allow the unlink to occur.
4083 static struct btrfs_trans_handle *__unlink_start_trans(struct inode *dir)
4085 struct btrfs_root *root = BTRFS_I(dir)->root;
4088 * 1 for the possible orphan item
4089 * 1 for the dir item
4090 * 1 for the dir index
4091 * 1 for the inode ref
4094 return btrfs_start_transaction_fallback_global_rsv(root, 5, 5);
4097 static int btrfs_unlink(struct inode *dir, struct dentry *dentry)
4099 struct btrfs_root *root = BTRFS_I(dir)->root;
4100 struct btrfs_trans_handle *trans;
4101 struct inode *inode = d_inode(dentry);
4104 trans = __unlink_start_trans(dir);
4106 return PTR_ERR(trans);
4108 btrfs_record_unlink_dir(trans, dir, d_inode(dentry), 0);
4110 ret = btrfs_unlink_inode(trans, root, dir, d_inode(dentry),
4111 dentry->d_name.name, dentry->d_name.len);
4115 if (inode->i_nlink == 0) {
4116 ret = btrfs_orphan_add(trans, inode);
4122 btrfs_end_transaction(trans, root);
4123 btrfs_btree_balance_dirty(root);
4127 int btrfs_unlink_subvol(struct btrfs_trans_handle *trans,
4128 struct btrfs_root *root,
4129 struct inode *dir, u64 objectid,
4130 const char *name, int name_len)
4132 struct btrfs_path *path;
4133 struct extent_buffer *leaf;
4134 struct btrfs_dir_item *di;
4135 struct btrfs_key key;
4138 u64 dir_ino = btrfs_ino(dir);
4140 path = btrfs_alloc_path();
4144 di = btrfs_lookup_dir_item(trans, root, path, dir_ino,
4145 name, name_len, -1);
4146 if (IS_ERR_OR_NULL(di)) {
4154 leaf = path->nodes[0];
4155 btrfs_dir_item_key_to_cpu(leaf, di, &key);
4156 WARN_ON(key.type != BTRFS_ROOT_ITEM_KEY || key.objectid != objectid);
4157 ret = btrfs_delete_one_dir_name(trans, root, path, di);
4159 btrfs_abort_transaction(trans, ret);
4162 btrfs_release_path(path);
4164 ret = btrfs_del_root_ref(trans, root->fs_info->tree_root,
4165 objectid, root->root_key.objectid,
4166 dir_ino, &index, name, name_len);
4168 if (ret != -ENOENT) {
4169 btrfs_abort_transaction(trans, ret);
4172 di = btrfs_search_dir_index_item(root, path, dir_ino,
4174 if (IS_ERR_OR_NULL(di)) {
4179 btrfs_abort_transaction(trans, ret);
4183 leaf = path->nodes[0];
4184 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
4185 btrfs_release_path(path);
4188 btrfs_release_path(path);
4190 ret = btrfs_delete_delayed_dir_index(trans, root, dir, index);
4192 btrfs_abort_transaction(trans, ret);
4196 btrfs_i_size_write(dir, dir->i_size - name_len * 2);
4197 inode_inc_iversion(dir);
4198 dir->i_mtime = dir->i_ctime = current_fs_time(dir->i_sb);
4199 ret = btrfs_update_inode_fallback(trans, root, dir);
4201 btrfs_abort_transaction(trans, ret);
4203 btrfs_free_path(path);
4207 static int btrfs_rmdir(struct inode *dir, struct dentry *dentry)
4209 struct inode *inode = d_inode(dentry);
4211 struct btrfs_root *root = BTRFS_I(dir)->root;
4212 struct btrfs_trans_handle *trans;
4213 u64 last_unlink_trans;
4215 if (inode->i_size > BTRFS_EMPTY_DIR_SIZE)
4217 if (btrfs_ino(inode) == BTRFS_FIRST_FREE_OBJECTID)
4220 trans = __unlink_start_trans(dir);
4222 return PTR_ERR(trans);
4224 if (unlikely(btrfs_ino(inode) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)) {
4225 err = btrfs_unlink_subvol(trans, root, dir,
4226 BTRFS_I(inode)->location.objectid,
4227 dentry->d_name.name,
4228 dentry->d_name.len);
4232 err = btrfs_orphan_add(trans, inode);
4236 last_unlink_trans = BTRFS_I(inode)->last_unlink_trans;
4238 /* now the directory is empty */
4239 err = btrfs_unlink_inode(trans, root, dir, d_inode(dentry),
4240 dentry->d_name.name, dentry->d_name.len);
4242 btrfs_i_size_write(inode, 0);
4244 * Propagate the last_unlink_trans value of the deleted dir to
4245 * its parent directory. This is to prevent an unrecoverable
4246 * log tree in the case we do something like this:
4248 * 2) create snapshot under dir foo
4249 * 3) delete the snapshot
4252 * 6) fsync foo or some file inside foo
4254 if (last_unlink_trans >= trans->transid)
4255 BTRFS_I(dir)->last_unlink_trans = last_unlink_trans;
4258 btrfs_end_transaction(trans, root);
4259 btrfs_btree_balance_dirty(root);
4264 static int truncate_space_check(struct btrfs_trans_handle *trans,
4265 struct btrfs_root *root,
4271 * This is only used to apply pressure to the enospc system, we don't
4272 * intend to use this reservation at all.
4274 bytes_deleted = btrfs_csum_bytes_to_leaves(root, bytes_deleted);
4275 bytes_deleted *= root->nodesize;
4276 ret = btrfs_block_rsv_add(root, &root->fs_info->trans_block_rsv,
4277 bytes_deleted, BTRFS_RESERVE_NO_FLUSH);
4279 trace_btrfs_space_reservation(root->fs_info, "transaction",
4282 trans->bytes_reserved += bytes_deleted;
4288 static int truncate_inline_extent(struct inode *inode,
4289 struct btrfs_path *path,
4290 struct btrfs_key *found_key,
4294 struct extent_buffer *leaf = path->nodes[0];
4295 int slot = path->slots[0];
4296 struct btrfs_file_extent_item *fi;
4297 u32 size = (u32)(new_size - found_key->offset);
4298 struct btrfs_root *root = BTRFS_I(inode)->root;
4300 fi = btrfs_item_ptr(leaf, slot, struct btrfs_file_extent_item);
4302 if (btrfs_file_extent_compression(leaf, fi) != BTRFS_COMPRESS_NONE) {
4303 loff_t offset = new_size;
4304 loff_t page_end = ALIGN(offset, PAGE_SIZE);
4307 * Zero out the remaining of the last page of our inline extent,
4308 * instead of directly truncating our inline extent here - that
4309 * would be much more complex (decompressing all the data, then
4310 * compressing the truncated data, which might be bigger than
4311 * the size of the inline extent, resize the extent, etc).
4312 * We release the path because to get the page we might need to
4313 * read the extent item from disk (data not in the page cache).
4315 btrfs_release_path(path);
4316 return btrfs_truncate_block(inode, offset, page_end - offset,
4320 btrfs_set_file_extent_ram_bytes(leaf, fi, size);
4321 size = btrfs_file_extent_calc_inline_size(size);
4322 btrfs_truncate_item(root, path, size, 1);
4324 if (test_bit(BTRFS_ROOT_REF_COWS, &root->state))
4325 inode_sub_bytes(inode, item_end + 1 - new_size);
4331 * this can truncate away extent items, csum items and directory items.
4332 * It starts at a high offset and removes keys until it can't find
4333 * any higher than new_size
4335 * csum items that cross the new i_size are truncated to the new size
4338 * min_type is the minimum key type to truncate down to. If set to 0, this
4339 * will kill all the items on this inode, including the INODE_ITEM_KEY.
4341 int btrfs_truncate_inode_items(struct btrfs_trans_handle *trans,
4342 struct btrfs_root *root,
4343 struct inode *inode,
4344 u64 new_size, u32 min_type)
4346 struct btrfs_path *path;
4347 struct extent_buffer *leaf;
4348 struct btrfs_file_extent_item *fi;
4349 struct btrfs_key key;
4350 struct btrfs_key found_key;
4351 u64 extent_start = 0;
4352 u64 extent_num_bytes = 0;
4353 u64 extent_offset = 0;
4355 u64 last_size = new_size;
4356 u32 found_type = (u8)-1;
4359 int pending_del_nr = 0;
4360 int pending_del_slot = 0;
4361 int extent_type = -1;
4364 u64 ino = btrfs_ino(inode);
4365 u64 bytes_deleted = 0;
4367 bool should_throttle = 0;
4368 bool should_end = 0;
4370 BUG_ON(new_size > 0 && min_type != BTRFS_EXTENT_DATA_KEY);
4373 * for non-free space inodes and ref cows, we want to back off from
4376 if (!btrfs_is_free_space_inode(inode) &&
4377 test_bit(BTRFS_ROOT_REF_COWS, &root->state))
4380 path = btrfs_alloc_path();
4383 path->reada = READA_BACK;
4386 * We want to drop from the next block forward in case this new size is
4387 * not block aligned since we will be keeping the last block of the
4388 * extent just the way it is.
4390 if (test_bit(BTRFS_ROOT_REF_COWS, &root->state) ||
4391 root == root->fs_info->tree_root)
4392 btrfs_drop_extent_cache(inode, ALIGN(new_size,
4393 root->sectorsize), (u64)-1, 0);
4396 * This function is also used to drop the items in the log tree before
4397 * we relog the inode, so if root != BTRFS_I(inode)->root, it means
4398 * it is used to drop the loged items. So we shouldn't kill the delayed
4401 if (min_type == 0 && root == BTRFS_I(inode)->root)
4402 btrfs_kill_delayed_inode_items(inode);
4405 key.offset = (u64)-1;
4410 * with a 16K leaf size and 128MB extents, you can actually queue
4411 * up a huge file in a single leaf. Most of the time that
4412 * bytes_deleted is > 0, it will be huge by the time we get here
4414 if (be_nice && bytes_deleted > SZ_32M) {
4415 if (btrfs_should_end_transaction(trans, root)) {
4422 path->leave_spinning = 1;
4423 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
4430 /* there are no items in the tree for us to truncate, we're
4433 if (path->slots[0] == 0)
4440 leaf = path->nodes[0];
4441 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
4442 found_type = found_key.type;
4444 if (found_key.objectid != ino)
4447 if (found_type < min_type)
4450 item_end = found_key.offset;
4451 if (found_type == BTRFS_EXTENT_DATA_KEY) {
4452 fi = btrfs_item_ptr(leaf, path->slots[0],
4453 struct btrfs_file_extent_item);
4454 extent_type = btrfs_file_extent_type(leaf, fi);
4455 if (extent_type != BTRFS_FILE_EXTENT_INLINE) {
4457 btrfs_file_extent_num_bytes(leaf, fi);
4458 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
4459 item_end += btrfs_file_extent_inline_len(leaf,
4460 path->slots[0], fi);
4464 if (found_type > min_type) {
4467 if (item_end < new_size)
4469 if (found_key.offset >= new_size)
4475 /* FIXME, shrink the extent if the ref count is only 1 */
4476 if (found_type != BTRFS_EXTENT_DATA_KEY)
4480 last_size = found_key.offset;
4482 last_size = new_size;
4484 if (extent_type != BTRFS_FILE_EXTENT_INLINE) {
4486 extent_start = btrfs_file_extent_disk_bytenr(leaf, fi);
4488 u64 orig_num_bytes =
4489 btrfs_file_extent_num_bytes(leaf, fi);
4490 extent_num_bytes = ALIGN(new_size -
4493 btrfs_set_file_extent_num_bytes(leaf, fi,
4495 num_dec = (orig_num_bytes -
4497 if (test_bit(BTRFS_ROOT_REF_COWS,
4500 inode_sub_bytes(inode, num_dec);
4501 btrfs_mark_buffer_dirty(leaf);
4504 btrfs_file_extent_disk_num_bytes(leaf,
4506 extent_offset = found_key.offset -
4507 btrfs_file_extent_offset(leaf, fi);
4509 /* FIXME blocksize != 4096 */
4510 num_dec = btrfs_file_extent_num_bytes(leaf, fi);
4511 if (extent_start != 0) {
4513 if (test_bit(BTRFS_ROOT_REF_COWS,
4515 inode_sub_bytes(inode, num_dec);
4518 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
4520 * we can't truncate inline items that have had
4524 btrfs_file_extent_encryption(leaf, fi) == 0 &&
4525 btrfs_file_extent_other_encoding(leaf, fi) == 0) {
4528 * Need to release path in order to truncate a
4529 * compressed extent. So delete any accumulated
4530 * extent items so far.
4532 if (btrfs_file_extent_compression(leaf, fi) !=
4533 BTRFS_COMPRESS_NONE && pending_del_nr) {
4534 err = btrfs_del_items(trans, root, path,
4538 btrfs_abort_transaction(trans,
4545 err = truncate_inline_extent(inode, path,
4550 btrfs_abort_transaction(trans, err);
4553 } else if (test_bit(BTRFS_ROOT_REF_COWS,
4555 inode_sub_bytes(inode, item_end + 1 - new_size);
4560 if (!pending_del_nr) {
4561 /* no pending yet, add ourselves */
4562 pending_del_slot = path->slots[0];
4564 } else if (pending_del_nr &&
4565 path->slots[0] + 1 == pending_del_slot) {
4566 /* hop on the pending chunk */
4568 pending_del_slot = path->slots[0];
4575 should_throttle = 0;
4578 (test_bit(BTRFS_ROOT_REF_COWS, &root->state) ||
4579 root == root->fs_info->tree_root)) {
4580 btrfs_set_path_blocking(path);
4581 bytes_deleted += extent_num_bytes;
4582 ret = btrfs_free_extent(trans, root, extent_start,
4583 extent_num_bytes, 0,
4584 btrfs_header_owner(leaf),
4585 ino, extent_offset);
4587 if (btrfs_should_throttle_delayed_refs(trans, root))
4588 btrfs_async_run_delayed_refs(root,
4590 trans->delayed_ref_updates * 2, 0);
4592 if (truncate_space_check(trans, root,
4593 extent_num_bytes)) {
4596 if (btrfs_should_throttle_delayed_refs(trans,
4598 should_throttle = 1;
4603 if (found_type == BTRFS_INODE_ITEM_KEY)
4606 if (path->slots[0] == 0 ||
4607 path->slots[0] != pending_del_slot ||
4608 should_throttle || should_end) {
4609 if (pending_del_nr) {
4610 ret = btrfs_del_items(trans, root, path,
4614 btrfs_abort_transaction(trans, ret);
4619 btrfs_release_path(path);
4620 if (should_throttle) {
4621 unsigned long updates = trans->delayed_ref_updates;
4623 trans->delayed_ref_updates = 0;
4624 ret = btrfs_run_delayed_refs(trans, root, updates * 2);
4630 * if we failed to refill our space rsv, bail out
4631 * and let the transaction restart
4643 if (pending_del_nr) {
4644 ret = btrfs_del_items(trans, root, path, pending_del_slot,
4647 btrfs_abort_transaction(trans, ret);
4650 if (root->root_key.objectid != BTRFS_TREE_LOG_OBJECTID)
4651 btrfs_ordered_update_i_size(inode, last_size, NULL);
4653 btrfs_free_path(path);
4655 if (be_nice && bytes_deleted > SZ_32M) {
4656 unsigned long updates = trans->delayed_ref_updates;
4658 trans->delayed_ref_updates = 0;
4659 ret = btrfs_run_delayed_refs(trans, root, updates * 2);
4668 * btrfs_truncate_block - read, zero a chunk and write a block
4669 * @inode - inode that we're zeroing
4670 * @from - the offset to start zeroing
4671 * @len - the length to zero, 0 to zero the entire range respective to the
4673 * @front - zero up to the offset instead of from the offset on
4675 * This will find the block for the "from" offset and cow the block and zero the
4676 * part we want to zero. This is used with truncate and hole punching.
4678 int btrfs_truncate_block(struct inode *inode, loff_t from, loff_t len,
4681 struct address_space *mapping = inode->i_mapping;
4682 struct btrfs_root *root = BTRFS_I(inode)->root;
4683 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
4684 struct btrfs_ordered_extent *ordered;
4685 struct extent_state *cached_state = NULL;
4687 u32 blocksize = root->sectorsize;
4688 pgoff_t index = from >> PAGE_SHIFT;
4689 unsigned offset = from & (blocksize - 1);
4691 gfp_t mask = btrfs_alloc_write_mask(mapping);
4696 if ((offset & (blocksize - 1)) == 0 &&
4697 (!len || ((len & (blocksize - 1)) == 0)))
4700 ret = btrfs_delalloc_reserve_space(inode,
4701 round_down(from, blocksize), blocksize);
4706 page = find_or_create_page(mapping, index, mask);
4708 btrfs_delalloc_release_space(inode,
4709 round_down(from, blocksize),
4715 block_start = round_down(from, blocksize);
4716 block_end = block_start + blocksize - 1;
4718 if (!PageUptodate(page)) {
4719 ret = btrfs_readpage(NULL, page);
4721 if (page->mapping != mapping) {
4726 if (!PageUptodate(page)) {
4731 wait_on_page_writeback(page);
4733 lock_extent_bits(io_tree, block_start, block_end, &cached_state);
4734 set_page_extent_mapped(page);
4736 ordered = btrfs_lookup_ordered_extent(inode, block_start);
4738 unlock_extent_cached(io_tree, block_start, block_end,
4739 &cached_state, GFP_NOFS);
4742 btrfs_start_ordered_extent(inode, ordered, 1);
4743 btrfs_put_ordered_extent(ordered);
4747 clear_extent_bit(&BTRFS_I(inode)->io_tree, block_start, block_end,
4748 EXTENT_DIRTY | EXTENT_DELALLOC |
4749 EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG,
4750 0, 0, &cached_state, GFP_NOFS);
4752 ret = btrfs_set_extent_delalloc(inode, block_start, block_end,
4755 unlock_extent_cached(io_tree, block_start, block_end,
4756 &cached_state, GFP_NOFS);
4760 if (offset != blocksize) {
4762 len = blocksize - offset;
4765 memset(kaddr + (block_start - page_offset(page)),
4768 memset(kaddr + (block_start - page_offset(page)) + offset,
4770 flush_dcache_page(page);
4773 ClearPageChecked(page);
4774 set_page_dirty(page);
4775 unlock_extent_cached(io_tree, block_start, block_end, &cached_state,
4780 btrfs_delalloc_release_space(inode, block_start,
4788 static int maybe_insert_hole(struct btrfs_root *root, struct inode *inode,
4789 u64 offset, u64 len)
4791 struct btrfs_trans_handle *trans;
4795 * Still need to make sure the inode looks like it's been updated so
4796 * that any holes get logged if we fsync.
4798 if (btrfs_fs_incompat(root->fs_info, NO_HOLES)) {
4799 BTRFS_I(inode)->last_trans = root->fs_info->generation;
4800 BTRFS_I(inode)->last_sub_trans = root->log_transid;
4801 BTRFS_I(inode)->last_log_commit = root->last_log_commit;
4806 * 1 - for the one we're dropping
4807 * 1 - for the one we're adding
4808 * 1 - for updating the inode.
4810 trans = btrfs_start_transaction(root, 3);
4812 return PTR_ERR(trans);
4814 ret = btrfs_drop_extents(trans, root, inode, offset, offset + len, 1);
4816 btrfs_abort_transaction(trans, ret);
4817 btrfs_end_transaction(trans, root);
4821 ret = btrfs_insert_file_extent(trans, root, btrfs_ino(inode), offset,
4822 0, 0, len, 0, len, 0, 0, 0);
4824 btrfs_abort_transaction(trans, ret);
4826 btrfs_update_inode(trans, root, inode);
4827 btrfs_end_transaction(trans, root);
4832 * This function puts in dummy file extents for the area we're creating a hole
4833 * for. So if we are truncating this file to a larger size we need to insert
4834 * these file extents so that btrfs_get_extent will return a EXTENT_MAP_HOLE for
4835 * the range between oldsize and size
4837 int btrfs_cont_expand(struct inode *inode, loff_t oldsize, loff_t size)
4839 struct btrfs_root *root = BTRFS_I(inode)->root;
4840 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
4841 struct extent_map *em = NULL;
4842 struct extent_state *cached_state = NULL;
4843 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
4844 u64 hole_start = ALIGN(oldsize, root->sectorsize);
4845 u64 block_end = ALIGN(size, root->sectorsize);
4852 * If our size started in the middle of a block we need to zero out the
4853 * rest of the block before we expand the i_size, otherwise we could
4854 * expose stale data.
4856 err = btrfs_truncate_block(inode, oldsize, 0, 0);
4860 if (size <= hole_start)
4864 struct btrfs_ordered_extent *ordered;
4866 lock_extent_bits(io_tree, hole_start, block_end - 1,
4868 ordered = btrfs_lookup_ordered_range(inode, hole_start,
4869 block_end - hole_start);
4872 unlock_extent_cached(io_tree, hole_start, block_end - 1,
4873 &cached_state, GFP_NOFS);
4874 btrfs_start_ordered_extent(inode, ordered, 1);
4875 btrfs_put_ordered_extent(ordered);
4878 cur_offset = hole_start;
4880 em = btrfs_get_extent(inode, NULL, 0, cur_offset,
4881 block_end - cur_offset, 0);
4887 last_byte = min(extent_map_end(em), block_end);
4888 last_byte = ALIGN(last_byte , root->sectorsize);
4889 if (!test_bit(EXTENT_FLAG_PREALLOC, &em->flags)) {
4890 struct extent_map *hole_em;
4891 hole_size = last_byte - cur_offset;
4893 err = maybe_insert_hole(root, inode, cur_offset,
4897 btrfs_drop_extent_cache(inode, cur_offset,
4898 cur_offset + hole_size - 1, 0);
4899 hole_em = alloc_extent_map();
4901 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
4902 &BTRFS_I(inode)->runtime_flags);
4905 hole_em->start = cur_offset;
4906 hole_em->len = hole_size;
4907 hole_em->orig_start = cur_offset;
4909 hole_em->block_start = EXTENT_MAP_HOLE;
4910 hole_em->block_len = 0;
4911 hole_em->orig_block_len = 0;
4912 hole_em->ram_bytes = hole_size;
4913 hole_em->bdev = root->fs_info->fs_devices->latest_bdev;
4914 hole_em->compress_type = BTRFS_COMPRESS_NONE;
4915 hole_em->generation = root->fs_info->generation;
4918 write_lock(&em_tree->lock);
4919 err = add_extent_mapping(em_tree, hole_em, 1);
4920 write_unlock(&em_tree->lock);
4923 btrfs_drop_extent_cache(inode, cur_offset,
4927 free_extent_map(hole_em);
4930 free_extent_map(em);
4932 cur_offset = last_byte;
4933 if (cur_offset >= block_end)
4936 free_extent_map(em);
4937 unlock_extent_cached(io_tree, hole_start, block_end - 1, &cached_state,
4942 static int btrfs_setsize(struct inode *inode, struct iattr *attr)
4944 struct btrfs_root *root = BTRFS_I(inode)->root;
4945 struct btrfs_trans_handle *trans;
4946 loff_t oldsize = i_size_read(inode);
4947 loff_t newsize = attr->ia_size;
4948 int mask = attr->ia_valid;
4952 * The regular truncate() case without ATTR_CTIME and ATTR_MTIME is a
4953 * special case where we need to update the times despite not having
4954 * these flags set. For all other operations the VFS set these flags
4955 * explicitly if it wants a timestamp update.
4957 if (newsize != oldsize) {
4958 inode_inc_iversion(inode);
4959 if (!(mask & (ATTR_CTIME | ATTR_MTIME)))
4960 inode->i_ctime = inode->i_mtime =
4961 current_fs_time(inode->i_sb);
4964 if (newsize > oldsize) {
4966 * Don't do an expanding truncate while snapshoting is ongoing.
4967 * This is to ensure the snapshot captures a fully consistent
4968 * state of this file - if the snapshot captures this expanding
4969 * truncation, it must capture all writes that happened before
4972 btrfs_wait_for_snapshot_creation(root);
4973 ret = btrfs_cont_expand(inode, oldsize, newsize);
4975 btrfs_end_write_no_snapshoting(root);
4979 trans = btrfs_start_transaction(root, 1);
4980 if (IS_ERR(trans)) {
4981 btrfs_end_write_no_snapshoting(root);
4982 return PTR_ERR(trans);
4985 i_size_write(inode, newsize);
4986 btrfs_ordered_update_i_size(inode, i_size_read(inode), NULL);
4987 pagecache_isize_extended(inode, oldsize, newsize);
4988 ret = btrfs_update_inode(trans, root, inode);
4989 btrfs_end_write_no_snapshoting(root);
4990 btrfs_end_transaction(trans, root);
4994 * We're truncating a file that used to have good data down to
4995 * zero. Make sure it gets into the ordered flush list so that
4996 * any new writes get down to disk quickly.
4999 set_bit(BTRFS_INODE_ORDERED_DATA_CLOSE,
5000 &BTRFS_I(inode)->runtime_flags);
5003 * 1 for the orphan item we're going to add
5004 * 1 for the orphan item deletion.
5006 trans = btrfs_start_transaction(root, 2);
5008 return PTR_ERR(trans);
5011 * We need to do this in case we fail at _any_ point during the
5012 * actual truncate. Once we do the truncate_setsize we could
5013 * invalidate pages which forces any outstanding ordered io to
5014 * be instantly completed which will give us extents that need
5015 * to be truncated. If we fail to get an orphan inode down we
5016 * could have left over extents that were never meant to live,
5017 * so we need to guarantee from this point on that everything
5018 * will be consistent.
5020 ret = btrfs_orphan_add(trans, inode);
5021 btrfs_end_transaction(trans, root);
5025 /* we don't support swapfiles, so vmtruncate shouldn't fail */
5026 truncate_setsize(inode, newsize);
5028 /* Disable nonlocked read DIO to avoid the end less truncate */
5029 btrfs_inode_block_unlocked_dio(inode);
5030 inode_dio_wait(inode);
5031 btrfs_inode_resume_unlocked_dio(inode);
5033 ret = btrfs_truncate(inode);
5034 if (ret && inode->i_nlink) {
5038 * failed to truncate, disk_i_size is only adjusted down
5039 * as we remove extents, so it should represent the true
5040 * size of the inode, so reset the in memory size and
5041 * delete our orphan entry.
5043 trans = btrfs_join_transaction(root);
5044 if (IS_ERR(trans)) {
5045 btrfs_orphan_del(NULL, inode);
5048 i_size_write(inode, BTRFS_I(inode)->disk_i_size);
5049 err = btrfs_orphan_del(trans, inode);
5051 btrfs_abort_transaction(trans, err);
5052 btrfs_end_transaction(trans, root);
5059 static int btrfs_setattr(struct dentry *dentry, struct iattr *attr)
5061 struct inode *inode = d_inode(dentry);
5062 struct btrfs_root *root = BTRFS_I(inode)->root;
5065 if (btrfs_root_readonly(root))
5068 err = inode_change_ok(inode, attr);
5072 if (S_ISREG(inode->i_mode) && (attr->ia_valid & ATTR_SIZE)) {
5073 err = btrfs_setsize(inode, attr);
5078 if (attr->ia_valid) {
5079 setattr_copy(inode, attr);
5080 inode_inc_iversion(inode);
5081 err = btrfs_dirty_inode(inode);
5083 if (!err && attr->ia_valid & ATTR_MODE)
5084 err = posix_acl_chmod(inode, inode->i_mode);
5091 * While truncating the inode pages during eviction, we get the VFS calling
5092 * btrfs_invalidatepage() against each page of the inode. This is slow because
5093 * the calls to btrfs_invalidatepage() result in a huge amount of calls to
5094 * lock_extent_bits() and clear_extent_bit(), which keep merging and splitting
5095 * extent_state structures over and over, wasting lots of time.
5097 * Therefore if the inode is being evicted, let btrfs_invalidatepage() skip all
5098 * those expensive operations on a per page basis and do only the ordered io
5099 * finishing, while we release here the extent_map and extent_state structures,
5100 * without the excessive merging and splitting.
5102 static void evict_inode_truncate_pages(struct inode *inode)
5104 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
5105 struct extent_map_tree *map_tree = &BTRFS_I(inode)->extent_tree;
5106 struct rb_node *node;
5108 ASSERT(inode->i_state & I_FREEING);
5109 truncate_inode_pages_final(&inode->i_data);
5111 write_lock(&map_tree->lock);
5112 while (!RB_EMPTY_ROOT(&map_tree->map)) {
5113 struct extent_map *em;
5115 node = rb_first(&map_tree->map);
5116 em = rb_entry(node, struct extent_map, rb_node);
5117 clear_bit(EXTENT_FLAG_PINNED, &em->flags);
5118 clear_bit(EXTENT_FLAG_LOGGING, &em->flags);
5119 remove_extent_mapping(map_tree, em);
5120 free_extent_map(em);
5121 if (need_resched()) {
5122 write_unlock(&map_tree->lock);
5124 write_lock(&map_tree->lock);
5127 write_unlock(&map_tree->lock);
5130 * Keep looping until we have no more ranges in the io tree.
5131 * We can have ongoing bios started by readpages (called from readahead)
5132 * that have their endio callback (extent_io.c:end_bio_extent_readpage)
5133 * still in progress (unlocked the pages in the bio but did not yet
5134 * unlocked the ranges in the io tree). Therefore this means some
5135 * ranges can still be locked and eviction started because before
5136 * submitting those bios, which are executed by a separate task (work
5137 * queue kthread), inode references (inode->i_count) were not taken
5138 * (which would be dropped in the end io callback of each bio).
5139 * Therefore here we effectively end up waiting for those bios and
5140 * anyone else holding locked ranges without having bumped the inode's
5141 * reference count - if we don't do it, when they access the inode's
5142 * io_tree to unlock a range it may be too late, leading to an
5143 * use-after-free issue.
5145 spin_lock(&io_tree->lock);
5146 while (!RB_EMPTY_ROOT(&io_tree->state)) {
5147 struct extent_state *state;
5148 struct extent_state *cached_state = NULL;
5152 node = rb_first(&io_tree->state);
5153 state = rb_entry(node, struct extent_state, rb_node);
5154 start = state->start;
5156 spin_unlock(&io_tree->lock);
5158 lock_extent_bits(io_tree, start, end, &cached_state);
5161 * If still has DELALLOC flag, the extent didn't reach disk,
5162 * and its reserved space won't be freed by delayed_ref.
5163 * So we need to free its reserved space here.
5164 * (Refer to comment in btrfs_invalidatepage, case 2)
5166 * Note, end is the bytenr of last byte, so we need + 1 here.
5168 if (state->state & EXTENT_DELALLOC)
5169 btrfs_qgroup_free_data(inode, start, end - start + 1);
5171 clear_extent_bit(io_tree, start, end,
5172 EXTENT_LOCKED | EXTENT_DIRTY |
5173 EXTENT_DELALLOC | EXTENT_DO_ACCOUNTING |
5174 EXTENT_DEFRAG, 1, 1,
5175 &cached_state, GFP_NOFS);
5178 spin_lock(&io_tree->lock);
5180 spin_unlock(&io_tree->lock);
5183 void btrfs_evict_inode(struct inode *inode)
5185 struct btrfs_trans_handle *trans;
5186 struct btrfs_root *root = BTRFS_I(inode)->root;
5187 struct btrfs_block_rsv *rsv, *global_rsv;
5188 int steal_from_global = 0;
5192 trace_btrfs_inode_evict(inode);
5195 kmem_cache_free(btrfs_inode_cachep, BTRFS_I(inode));
5199 min_size = btrfs_calc_trunc_metadata_size(root, 1);
5201 evict_inode_truncate_pages(inode);
5203 if (inode->i_nlink &&
5204 ((btrfs_root_refs(&root->root_item) != 0 &&
5205 root->root_key.objectid != BTRFS_ROOT_TREE_OBJECTID) ||
5206 btrfs_is_free_space_inode(inode)))
5209 if (is_bad_inode(inode)) {
5210 btrfs_orphan_del(NULL, inode);
5213 /* do we really want it for ->i_nlink > 0 and zero btrfs_root_refs? */
5214 if (!special_file(inode->i_mode))
5215 btrfs_wait_ordered_range(inode, 0, (u64)-1);
5217 btrfs_free_io_failure_record(inode, 0, (u64)-1);
5219 if (root->fs_info->log_root_recovering) {
5220 BUG_ON(test_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
5221 &BTRFS_I(inode)->runtime_flags));
5225 if (inode->i_nlink > 0) {
5226 BUG_ON(btrfs_root_refs(&root->root_item) != 0 &&
5227 root->root_key.objectid != BTRFS_ROOT_TREE_OBJECTID);
5231 ret = btrfs_commit_inode_delayed_inode(inode);
5233 btrfs_orphan_del(NULL, inode);
5237 rsv = btrfs_alloc_block_rsv(root, BTRFS_BLOCK_RSV_TEMP);
5239 btrfs_orphan_del(NULL, inode);
5242 rsv->size = min_size;
5244 global_rsv = &root->fs_info->global_block_rsv;
5246 btrfs_i_size_write(inode, 0);
5249 * This is a bit simpler than btrfs_truncate since we've already
5250 * reserved our space for our orphan item in the unlink, so we just
5251 * need to reserve some slack space in case we add bytes and update
5252 * inode item when doing the truncate.
5255 ret = btrfs_block_rsv_refill(root, rsv, min_size,
5256 BTRFS_RESERVE_FLUSH_LIMIT);
5259 * Try and steal from the global reserve since we will
5260 * likely not use this space anyway, we want to try as
5261 * hard as possible to get this to work.
5264 steal_from_global++;
5266 steal_from_global = 0;
5270 * steal_from_global == 0: we reserved stuff, hooray!
5271 * steal_from_global == 1: we didn't reserve stuff, boo!
5272 * steal_from_global == 2: we've committed, still not a lot of
5273 * room but maybe we'll have room in the global reserve this
5275 * steal_from_global == 3: abandon all hope!
5277 if (steal_from_global > 2) {
5278 btrfs_warn(root->fs_info,
5279 "Could not get space for a delete, will truncate on mount %d",
5281 btrfs_orphan_del(NULL, inode);
5282 btrfs_free_block_rsv(root, rsv);
5286 trans = btrfs_join_transaction(root);
5287 if (IS_ERR(trans)) {
5288 btrfs_orphan_del(NULL, inode);
5289 btrfs_free_block_rsv(root, rsv);
5294 * We can't just steal from the global reserve, we need to make
5295 * sure there is room to do it, if not we need to commit and try
5298 if (steal_from_global) {
5299 if (!btrfs_check_space_for_delayed_refs(trans, root))
5300 ret = btrfs_block_rsv_migrate(global_rsv, rsv,
5307 * Couldn't steal from the global reserve, we have too much
5308 * pending stuff built up, commit the transaction and try it
5312 ret = btrfs_commit_transaction(trans, root);
5314 btrfs_orphan_del(NULL, inode);
5315 btrfs_free_block_rsv(root, rsv);
5320 steal_from_global = 0;
5323 trans->block_rsv = rsv;
5325 ret = btrfs_truncate_inode_items(trans, root, inode, 0, 0);
5326 if (ret != -ENOSPC && ret != -EAGAIN)
5329 trans->block_rsv = &root->fs_info->trans_block_rsv;
5330 btrfs_end_transaction(trans, root);
5332 btrfs_btree_balance_dirty(root);
5335 btrfs_free_block_rsv(root, rsv);
5338 * Errors here aren't a big deal, it just means we leave orphan items
5339 * in the tree. They will be cleaned up on the next mount.
5342 trans->block_rsv = root->orphan_block_rsv;
5343 btrfs_orphan_del(trans, inode);
5345 btrfs_orphan_del(NULL, inode);
5348 trans->block_rsv = &root->fs_info->trans_block_rsv;
5349 if (!(root == root->fs_info->tree_root ||
5350 root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID))
5351 btrfs_return_ino(root, btrfs_ino(inode));
5353 btrfs_end_transaction(trans, root);
5354 btrfs_btree_balance_dirty(root);
5356 btrfs_remove_delayed_node(inode);
5361 * this returns the key found in the dir entry in the location pointer.
5362 * If no dir entries were found, location->objectid is 0.
5364 static int btrfs_inode_by_name(struct inode *dir, struct dentry *dentry,
5365 struct btrfs_key *location)
5367 const char *name = dentry->d_name.name;
5368 int namelen = dentry->d_name.len;
5369 struct btrfs_dir_item *di;
5370 struct btrfs_path *path;
5371 struct btrfs_root *root = BTRFS_I(dir)->root;
5374 path = btrfs_alloc_path();
5378 di = btrfs_lookup_dir_item(NULL, root, path, btrfs_ino(dir), name,
5383 if (IS_ERR_OR_NULL(di))
5386 btrfs_dir_item_key_to_cpu(path->nodes[0], di, location);
5388 btrfs_free_path(path);
5391 location->objectid = 0;
5396 * when we hit a tree root in a directory, the btrfs part of the inode
5397 * needs to be changed to reflect the root directory of the tree root. This
5398 * is kind of like crossing a mount point.
5400 static int fixup_tree_root_location(struct btrfs_root *root,
5402 struct dentry *dentry,
5403 struct btrfs_key *location,
5404 struct btrfs_root **sub_root)
5406 struct btrfs_path *path;
5407 struct btrfs_root *new_root;
5408 struct btrfs_root_ref *ref;
5409 struct extent_buffer *leaf;
5410 struct btrfs_key key;
5414 path = btrfs_alloc_path();
5421 key.objectid = BTRFS_I(dir)->root->root_key.objectid;
5422 key.type = BTRFS_ROOT_REF_KEY;
5423 key.offset = location->objectid;
5425 ret = btrfs_search_slot(NULL, root->fs_info->tree_root, &key, path,
5433 leaf = path->nodes[0];
5434 ref = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_root_ref);
5435 if (btrfs_root_ref_dirid(leaf, ref) != btrfs_ino(dir) ||
5436 btrfs_root_ref_name_len(leaf, ref) != dentry->d_name.len)
5439 ret = memcmp_extent_buffer(leaf, dentry->d_name.name,
5440 (unsigned long)(ref + 1),
5441 dentry->d_name.len);
5445 btrfs_release_path(path);
5447 new_root = btrfs_read_fs_root_no_name(root->fs_info, location);
5448 if (IS_ERR(new_root)) {
5449 err = PTR_ERR(new_root);
5453 *sub_root = new_root;
5454 location->objectid = btrfs_root_dirid(&new_root->root_item);
5455 location->type = BTRFS_INODE_ITEM_KEY;
5456 location->offset = 0;
5459 btrfs_free_path(path);
5463 static void inode_tree_add(struct inode *inode)
5465 struct btrfs_root *root = BTRFS_I(inode)->root;
5466 struct btrfs_inode *entry;
5468 struct rb_node *parent;
5469 struct rb_node *new = &BTRFS_I(inode)->rb_node;
5470 u64 ino = btrfs_ino(inode);
5472 if (inode_unhashed(inode))
5475 spin_lock(&root->inode_lock);
5476 p = &root->inode_tree.rb_node;
5479 entry = rb_entry(parent, struct btrfs_inode, rb_node);
5481 if (ino < btrfs_ino(&entry->vfs_inode))
5482 p = &parent->rb_left;
5483 else if (ino > btrfs_ino(&entry->vfs_inode))
5484 p = &parent->rb_right;
5486 WARN_ON(!(entry->vfs_inode.i_state &
5487 (I_WILL_FREE | I_FREEING)));
5488 rb_replace_node(parent, new, &root->inode_tree);
5489 RB_CLEAR_NODE(parent);
5490 spin_unlock(&root->inode_lock);
5494 rb_link_node(new, parent, p);
5495 rb_insert_color(new, &root->inode_tree);
5496 spin_unlock(&root->inode_lock);
5499 static void inode_tree_del(struct inode *inode)
5501 struct btrfs_root *root = BTRFS_I(inode)->root;
5504 spin_lock(&root->inode_lock);
5505 if (!RB_EMPTY_NODE(&BTRFS_I(inode)->rb_node)) {
5506 rb_erase(&BTRFS_I(inode)->rb_node, &root->inode_tree);
5507 RB_CLEAR_NODE(&BTRFS_I(inode)->rb_node);
5508 empty = RB_EMPTY_ROOT(&root->inode_tree);
5510 spin_unlock(&root->inode_lock);
5512 if (empty && btrfs_root_refs(&root->root_item) == 0) {
5513 synchronize_srcu(&root->fs_info->subvol_srcu);
5514 spin_lock(&root->inode_lock);
5515 empty = RB_EMPTY_ROOT(&root->inode_tree);
5516 spin_unlock(&root->inode_lock);
5518 btrfs_add_dead_root(root);
5522 void btrfs_invalidate_inodes(struct btrfs_root *root)
5524 struct rb_node *node;
5525 struct rb_node *prev;
5526 struct btrfs_inode *entry;
5527 struct inode *inode;
5530 if (!test_bit(BTRFS_FS_STATE_ERROR, &root->fs_info->fs_state))
5531 WARN_ON(btrfs_root_refs(&root->root_item) != 0);
5533 spin_lock(&root->inode_lock);
5535 node = root->inode_tree.rb_node;
5539 entry = rb_entry(node, struct btrfs_inode, rb_node);
5541 if (objectid < btrfs_ino(&entry->vfs_inode))
5542 node = node->rb_left;
5543 else if (objectid > btrfs_ino(&entry->vfs_inode))
5544 node = node->rb_right;
5550 entry = rb_entry(prev, struct btrfs_inode, rb_node);
5551 if (objectid <= btrfs_ino(&entry->vfs_inode)) {
5555 prev = rb_next(prev);
5559 entry = rb_entry(node, struct btrfs_inode, rb_node);
5560 objectid = btrfs_ino(&entry->vfs_inode) + 1;
5561 inode = igrab(&entry->vfs_inode);
5563 spin_unlock(&root->inode_lock);
5564 if (atomic_read(&inode->i_count) > 1)
5565 d_prune_aliases(inode);
5567 * btrfs_drop_inode will have it removed from
5568 * the inode cache when its usage count
5573 spin_lock(&root->inode_lock);
5577 if (cond_resched_lock(&root->inode_lock))
5580 node = rb_next(node);
5582 spin_unlock(&root->inode_lock);
5585 static int btrfs_init_locked_inode(struct inode *inode, void *p)
5587 struct btrfs_iget_args *args = p;
5588 inode->i_ino = args->location->objectid;
5589 memcpy(&BTRFS_I(inode)->location, args->location,
5590 sizeof(*args->location));
5591 BTRFS_I(inode)->root = args->root;
5595 static int btrfs_find_actor(struct inode *inode, void *opaque)
5597 struct btrfs_iget_args *args = opaque;
5598 return args->location->objectid == BTRFS_I(inode)->location.objectid &&
5599 args->root == BTRFS_I(inode)->root;
5602 static struct inode *btrfs_iget_locked(struct super_block *s,
5603 struct btrfs_key *location,
5604 struct btrfs_root *root)
5606 struct inode *inode;
5607 struct btrfs_iget_args args;
5608 unsigned long hashval = btrfs_inode_hash(location->objectid, root);
5610 args.location = location;
5613 inode = iget5_locked(s, hashval, btrfs_find_actor,
5614 btrfs_init_locked_inode,
5619 /* Get an inode object given its location and corresponding root.
5620 * Returns in *is_new if the inode was read from disk
5622 struct inode *btrfs_iget(struct super_block *s, struct btrfs_key *location,
5623 struct btrfs_root *root, int *new)
5625 struct inode *inode;
5627 inode = btrfs_iget_locked(s, location, root);
5629 return ERR_PTR(-ENOMEM);
5631 if (inode->i_state & I_NEW) {
5634 ret = btrfs_read_locked_inode(inode);
5635 if (!is_bad_inode(inode)) {
5636 inode_tree_add(inode);
5637 unlock_new_inode(inode);
5641 unlock_new_inode(inode);
5644 inode = ERR_PTR(ret < 0 ? ret : -ESTALE);
5651 static struct inode *new_simple_dir(struct super_block *s,
5652 struct btrfs_key *key,
5653 struct btrfs_root *root)
5655 struct inode *inode = new_inode(s);
5658 return ERR_PTR(-ENOMEM);
5660 BTRFS_I(inode)->root = root;
5661 memcpy(&BTRFS_I(inode)->location, key, sizeof(*key));
5662 set_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags);
5664 inode->i_ino = BTRFS_EMPTY_SUBVOL_DIR_OBJECTID;
5665 inode->i_op = &btrfs_dir_ro_inode_operations;
5666 inode->i_fop = &simple_dir_operations;
5667 inode->i_mode = S_IFDIR | S_IRUGO | S_IWUSR | S_IXUGO;
5668 inode->i_mtime = current_fs_time(inode->i_sb);
5669 inode->i_atime = inode->i_mtime;
5670 inode->i_ctime = inode->i_mtime;
5671 BTRFS_I(inode)->i_otime = inode->i_mtime;
5676 struct inode *btrfs_lookup_dentry(struct inode *dir, struct dentry *dentry)
5678 struct inode *inode;
5679 struct btrfs_root *root = BTRFS_I(dir)->root;
5680 struct btrfs_root *sub_root = root;
5681 struct btrfs_key location;
5685 if (dentry->d_name.len > BTRFS_NAME_LEN)
5686 return ERR_PTR(-ENAMETOOLONG);
5688 ret = btrfs_inode_by_name(dir, dentry, &location);
5690 return ERR_PTR(ret);
5692 if (location.objectid == 0)
5693 return ERR_PTR(-ENOENT);
5695 if (location.type == BTRFS_INODE_ITEM_KEY) {
5696 inode = btrfs_iget(dir->i_sb, &location, root, NULL);
5700 BUG_ON(location.type != BTRFS_ROOT_ITEM_KEY);
5702 index = srcu_read_lock(&root->fs_info->subvol_srcu);
5703 ret = fixup_tree_root_location(root, dir, dentry,
5704 &location, &sub_root);
5707 inode = ERR_PTR(ret);
5709 inode = new_simple_dir(dir->i_sb, &location, sub_root);
5711 inode = btrfs_iget(dir->i_sb, &location, sub_root, NULL);
5713 srcu_read_unlock(&root->fs_info->subvol_srcu, index);
5715 if (!IS_ERR(inode) && root != sub_root) {
5716 down_read(&root->fs_info->cleanup_work_sem);
5717 if (!(inode->i_sb->s_flags & MS_RDONLY))
5718 ret = btrfs_orphan_cleanup(sub_root);
5719 up_read(&root->fs_info->cleanup_work_sem);
5722 inode = ERR_PTR(ret);
5729 static int btrfs_dentry_delete(const struct dentry *dentry)
5731 struct btrfs_root *root;
5732 struct inode *inode = d_inode(dentry);
5734 if (!inode && !IS_ROOT(dentry))
5735 inode = d_inode(dentry->d_parent);
5738 root = BTRFS_I(inode)->root;
5739 if (btrfs_root_refs(&root->root_item) == 0)
5742 if (btrfs_ino(inode) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)
5748 static void btrfs_dentry_release(struct dentry *dentry)
5750 kfree(dentry->d_fsdata);
5753 static struct dentry *btrfs_lookup(struct inode *dir, struct dentry *dentry,
5756 struct inode *inode;
5758 inode = btrfs_lookup_dentry(dir, dentry);
5759 if (IS_ERR(inode)) {
5760 if (PTR_ERR(inode) == -ENOENT)
5763 return ERR_CAST(inode);
5766 return d_splice_alias(inode, dentry);
5769 unsigned char btrfs_filetype_table[] = {
5770 DT_UNKNOWN, DT_REG, DT_DIR, DT_CHR, DT_BLK, DT_FIFO, DT_SOCK, DT_LNK
5773 static int btrfs_real_readdir(struct file *file, struct dir_context *ctx)
5775 struct inode *inode = file_inode(file);
5776 struct btrfs_root *root = BTRFS_I(inode)->root;
5777 struct btrfs_item *item;
5778 struct btrfs_dir_item *di;
5779 struct btrfs_key key;
5780 struct btrfs_key found_key;
5781 struct btrfs_path *path;
5782 struct list_head ins_list;
5783 struct list_head del_list;
5785 struct extent_buffer *leaf;
5787 unsigned char d_type;
5792 int key_type = BTRFS_DIR_INDEX_KEY;
5796 int is_curr = 0; /* ctx->pos points to the current index? */
5800 /* FIXME, use a real flag for deciding about the key type */
5801 if (root->fs_info->tree_root == root)
5802 key_type = BTRFS_DIR_ITEM_KEY;
5804 if (!dir_emit_dots(file, ctx))
5807 path = btrfs_alloc_path();
5811 path->reada = READA_FORWARD;
5813 if (key_type == BTRFS_DIR_INDEX_KEY) {
5814 INIT_LIST_HEAD(&ins_list);
5815 INIT_LIST_HEAD(&del_list);
5816 put = btrfs_readdir_get_delayed_items(inode, &ins_list,
5820 key.type = key_type;
5821 key.offset = ctx->pos;
5822 key.objectid = btrfs_ino(inode);
5824 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
5830 leaf = path->nodes[0];
5831 slot = path->slots[0];
5832 if (slot >= btrfs_header_nritems(leaf)) {
5833 ret = btrfs_next_leaf(root, path);
5841 item = btrfs_item_nr(slot);
5842 btrfs_item_key_to_cpu(leaf, &found_key, slot);
5844 if (found_key.objectid != key.objectid)
5846 if (found_key.type != key_type)
5848 if (found_key.offset < ctx->pos)
5850 if (key_type == BTRFS_DIR_INDEX_KEY &&
5851 btrfs_should_delete_dir_index(&del_list,
5855 ctx->pos = found_key.offset;
5858 di = btrfs_item_ptr(leaf, slot, struct btrfs_dir_item);
5860 di_total = btrfs_item_size(leaf, item);
5862 while (di_cur < di_total) {
5863 struct btrfs_key location;
5865 if (verify_dir_item(root, leaf, di))
5868 name_len = btrfs_dir_name_len(leaf, di);
5869 if (name_len <= sizeof(tmp_name)) {
5870 name_ptr = tmp_name;
5872 name_ptr = kmalloc(name_len, GFP_KERNEL);
5878 read_extent_buffer(leaf, name_ptr,
5879 (unsigned long)(di + 1), name_len);
5881 d_type = btrfs_filetype_table[btrfs_dir_type(leaf, di)];
5882 btrfs_dir_item_key_to_cpu(leaf, di, &location);
5885 /* is this a reference to our own snapshot? If so
5888 * In contrast to old kernels, we insert the snapshot's
5889 * dir item and dir index after it has been created, so
5890 * we won't find a reference to our own snapshot. We
5891 * still keep the following code for backward
5894 if (location.type == BTRFS_ROOT_ITEM_KEY &&
5895 location.objectid == root->root_key.objectid) {
5899 over = !dir_emit(ctx, name_ptr, name_len,
5900 location.objectid, d_type);
5903 if (name_ptr != tmp_name)
5909 di_len = btrfs_dir_name_len(leaf, di) +
5910 btrfs_dir_data_len(leaf, di) + sizeof(*di);
5912 di = (struct btrfs_dir_item *)((char *)di + di_len);
5918 if (key_type == BTRFS_DIR_INDEX_KEY) {
5921 ret = btrfs_readdir_delayed_dir_index(ctx, &ins_list, &emitted);
5927 * If we haven't emitted any dir entry, we must not touch ctx->pos as
5928 * it was was set to the termination value in previous call. We assume
5929 * that "." and ".." were emitted if we reach this point and set the
5930 * termination value as well for an empty directory.
5932 if (ctx->pos > 2 && !emitted)
5935 /* Reached end of directory/root. Bump pos past the last item. */
5939 * Stop new entries from being returned after we return the last
5942 * New directory entries are assigned a strictly increasing
5943 * offset. This means that new entries created during readdir
5944 * are *guaranteed* to be seen in the future by that readdir.
5945 * This has broken buggy programs which operate on names as
5946 * they're returned by readdir. Until we re-use freed offsets
5947 * we have this hack to stop new entries from being returned
5948 * under the assumption that they'll never reach this huge
5951 * This is being careful not to overflow 32bit loff_t unless the
5952 * last entry requires it because doing so has broken 32bit apps
5955 if (key_type == BTRFS_DIR_INDEX_KEY) {
5956 if (ctx->pos >= INT_MAX)
5957 ctx->pos = LLONG_MAX;
5965 btrfs_readdir_put_delayed_items(inode, &ins_list, &del_list);
5966 btrfs_free_path(path);
5970 int btrfs_write_inode(struct inode *inode, struct writeback_control *wbc)
5972 struct btrfs_root *root = BTRFS_I(inode)->root;
5973 struct btrfs_trans_handle *trans;
5975 bool nolock = false;
5977 if (test_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags))
5980 if (btrfs_fs_closing(root->fs_info) && btrfs_is_free_space_inode(inode))
5983 if (wbc->sync_mode == WB_SYNC_ALL) {
5985 trans = btrfs_join_transaction_nolock(root);
5987 trans = btrfs_join_transaction(root);
5989 return PTR_ERR(trans);
5990 ret = btrfs_commit_transaction(trans, root);
5996 * This is somewhat expensive, updating the tree every time the
5997 * inode changes. But, it is most likely to find the inode in cache.
5998 * FIXME, needs more benchmarking...there are no reasons other than performance
5999 * to keep or drop this code.
6001 static int btrfs_dirty_inode(struct inode *inode)
6003 struct btrfs_root *root = BTRFS_I(inode)->root;
6004 struct btrfs_trans_handle *trans;
6007 if (test_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags))
6010 trans = btrfs_join_transaction(root);
6012 return PTR_ERR(trans);
6014 ret = btrfs_update_inode(trans, root, inode);
6015 if (ret && ret == -ENOSPC) {
6016 /* whoops, lets try again with the full transaction */
6017 btrfs_end_transaction(trans, root);
6018 trans = btrfs_start_transaction(root, 1);
6020 return PTR_ERR(trans);
6022 ret = btrfs_update_inode(trans, root, inode);
6024 btrfs_end_transaction(trans, root);
6025 if (BTRFS_I(inode)->delayed_node)
6026 btrfs_balance_delayed_items(root);
6032 * This is a copy of file_update_time. We need this so we can return error on
6033 * ENOSPC for updating the inode in the case of file write and mmap writes.
6035 static int btrfs_update_time(struct inode *inode, struct timespec *now,
6038 struct btrfs_root *root = BTRFS_I(inode)->root;
6040 if (btrfs_root_readonly(root))
6043 if (flags & S_VERSION)
6044 inode_inc_iversion(inode);
6045 if (flags & S_CTIME)
6046 inode->i_ctime = *now;
6047 if (flags & S_MTIME)
6048 inode->i_mtime = *now;
6049 if (flags & S_ATIME)
6050 inode->i_atime = *now;
6051 return btrfs_dirty_inode(inode);
6055 * find the highest existing sequence number in a directory
6056 * and then set the in-memory index_cnt variable to reflect
6057 * free sequence numbers
6059 static int btrfs_set_inode_index_count(struct inode *inode)
6061 struct btrfs_root *root = BTRFS_I(inode)->root;
6062 struct btrfs_key key, found_key;
6063 struct btrfs_path *path;
6064 struct extent_buffer *leaf;
6067 key.objectid = btrfs_ino(inode);
6068 key.type = BTRFS_DIR_INDEX_KEY;
6069 key.offset = (u64)-1;
6071 path = btrfs_alloc_path();
6075 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
6078 /* FIXME: we should be able to handle this */
6084 * MAGIC NUMBER EXPLANATION:
6085 * since we search a directory based on f_pos we have to start at 2
6086 * since '.' and '..' have f_pos of 0 and 1 respectively, so everybody
6087 * else has to start at 2
6089 if (path->slots[0] == 0) {
6090 BTRFS_I(inode)->index_cnt = 2;
6096 leaf = path->nodes[0];
6097 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
6099 if (found_key.objectid != btrfs_ino(inode) ||
6100 found_key.type != BTRFS_DIR_INDEX_KEY) {
6101 BTRFS_I(inode)->index_cnt = 2;
6105 BTRFS_I(inode)->index_cnt = found_key.offset + 1;
6107 btrfs_free_path(path);
6112 * helper to find a free sequence number in a given directory. This current
6113 * code is very simple, later versions will do smarter things in the btree
6115 int btrfs_set_inode_index(struct inode *dir, u64 *index)
6119 if (BTRFS_I(dir)->index_cnt == (u64)-1) {
6120 ret = btrfs_inode_delayed_dir_index_count(dir);
6122 ret = btrfs_set_inode_index_count(dir);
6128 *index = BTRFS_I(dir)->index_cnt;
6129 BTRFS_I(dir)->index_cnt++;
6134 static int btrfs_insert_inode_locked(struct inode *inode)
6136 struct btrfs_iget_args args;
6137 args.location = &BTRFS_I(inode)->location;
6138 args.root = BTRFS_I(inode)->root;
6140 return insert_inode_locked4(inode,
6141 btrfs_inode_hash(inode->i_ino, BTRFS_I(inode)->root),
6142 btrfs_find_actor, &args);
6145 static struct inode *btrfs_new_inode(struct btrfs_trans_handle *trans,
6146 struct btrfs_root *root,
6148 const char *name, int name_len,
6149 u64 ref_objectid, u64 objectid,
6150 umode_t mode, u64 *index)
6152 struct inode *inode;
6153 struct btrfs_inode_item *inode_item;
6154 struct btrfs_key *location;
6155 struct btrfs_path *path;
6156 struct btrfs_inode_ref *ref;
6157 struct btrfs_key key[2];
6159 int nitems = name ? 2 : 1;
6163 path = btrfs_alloc_path();
6165 return ERR_PTR(-ENOMEM);
6167 inode = new_inode(root->fs_info->sb);
6169 btrfs_free_path(path);
6170 return ERR_PTR(-ENOMEM);
6174 * O_TMPFILE, set link count to 0, so that after this point,
6175 * we fill in an inode item with the correct link count.
6178 set_nlink(inode, 0);
6181 * we have to initialize this early, so we can reclaim the inode
6182 * number if we fail afterwards in this function.
6184 inode->i_ino = objectid;
6187 trace_btrfs_inode_request(dir);
6189 ret = btrfs_set_inode_index(dir, index);
6191 btrfs_free_path(path);
6193 return ERR_PTR(ret);
6199 * index_cnt is ignored for everything but a dir,
6200 * btrfs_get_inode_index_count has an explanation for the magic
6203 BTRFS_I(inode)->index_cnt = 2;
6204 BTRFS_I(inode)->dir_index = *index;
6205 BTRFS_I(inode)->root = root;
6206 BTRFS_I(inode)->generation = trans->transid;
6207 inode->i_generation = BTRFS_I(inode)->generation;
6210 * We could have gotten an inode number from somebody who was fsynced
6211 * and then removed in this same transaction, so let's just set full
6212 * sync since it will be a full sync anyway and this will blow away the
6213 * old info in the log.
6215 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &BTRFS_I(inode)->runtime_flags);
6217 key[0].objectid = objectid;
6218 key[0].type = BTRFS_INODE_ITEM_KEY;
6221 sizes[0] = sizeof(struct btrfs_inode_item);
6225 * Start new inodes with an inode_ref. This is slightly more
6226 * efficient for small numbers of hard links since they will
6227 * be packed into one item. Extended refs will kick in if we
6228 * add more hard links than can fit in the ref item.
6230 key[1].objectid = objectid;
6231 key[1].type = BTRFS_INODE_REF_KEY;
6232 key[1].offset = ref_objectid;
6234 sizes[1] = name_len + sizeof(*ref);
6237 location = &BTRFS_I(inode)->location;
6238 location->objectid = objectid;
6239 location->offset = 0;
6240 location->type = BTRFS_INODE_ITEM_KEY;
6242 ret = btrfs_insert_inode_locked(inode);
6246 path->leave_spinning = 1;
6247 ret = btrfs_insert_empty_items(trans, root, path, key, sizes, nitems);
6251 inode_init_owner(inode, dir, mode);
6252 inode_set_bytes(inode, 0);
6254 inode->i_mtime = current_fs_time(inode->i_sb);
6255 inode->i_atime = inode->i_mtime;
6256 inode->i_ctime = inode->i_mtime;
6257 BTRFS_I(inode)->i_otime = inode->i_mtime;
6259 inode_item = btrfs_item_ptr(path->nodes[0], path->slots[0],
6260 struct btrfs_inode_item);
6261 memset_extent_buffer(path->nodes[0], 0, (unsigned long)inode_item,
6262 sizeof(*inode_item));
6263 fill_inode_item(trans, path->nodes[0], inode_item, inode);
6266 ref = btrfs_item_ptr(path->nodes[0], path->slots[0] + 1,
6267 struct btrfs_inode_ref);
6268 btrfs_set_inode_ref_name_len(path->nodes[0], ref, name_len);
6269 btrfs_set_inode_ref_index(path->nodes[0], ref, *index);
6270 ptr = (unsigned long)(ref + 1);
6271 write_extent_buffer(path->nodes[0], name, ptr, name_len);
6274 btrfs_mark_buffer_dirty(path->nodes[0]);
6275 btrfs_free_path(path);
6277 btrfs_inherit_iflags(inode, dir);
6279 if (S_ISREG(mode)) {
6280 if (btrfs_test_opt(root->fs_info, NODATASUM))
6281 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATASUM;
6282 if (btrfs_test_opt(root->fs_info, NODATACOW))
6283 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATACOW |
6284 BTRFS_INODE_NODATASUM;
6287 inode_tree_add(inode);
6289 trace_btrfs_inode_new(inode);
6290 btrfs_set_inode_last_trans(trans, inode);
6292 btrfs_update_root_times(trans, root);
6294 ret = btrfs_inode_inherit_props(trans, inode, dir);
6296 btrfs_err(root->fs_info,
6297 "error inheriting props for ino %llu (root %llu): %d",
6298 btrfs_ino(inode), root->root_key.objectid, ret);
6303 unlock_new_inode(inode);
6306 BTRFS_I(dir)->index_cnt--;
6307 btrfs_free_path(path);
6309 return ERR_PTR(ret);
6312 static inline u8 btrfs_inode_type(struct inode *inode)
6314 return btrfs_type_by_mode[(inode->i_mode & S_IFMT) >> S_SHIFT];
6318 * utility function to add 'inode' into 'parent_inode' with
6319 * a give name and a given sequence number.
6320 * if 'add_backref' is true, also insert a backref from the
6321 * inode to the parent directory.
6323 int btrfs_add_link(struct btrfs_trans_handle *trans,
6324 struct inode *parent_inode, struct inode *inode,
6325 const char *name, int name_len, int add_backref, u64 index)
6328 struct btrfs_key key;
6329 struct btrfs_root *root = BTRFS_I(parent_inode)->root;
6330 u64 ino = btrfs_ino(inode);
6331 u64 parent_ino = btrfs_ino(parent_inode);
6333 if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
6334 memcpy(&key, &BTRFS_I(inode)->root->root_key, sizeof(key));
6337 key.type = BTRFS_INODE_ITEM_KEY;
6341 if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
6342 ret = btrfs_add_root_ref(trans, root->fs_info->tree_root,
6343 key.objectid, root->root_key.objectid,
6344 parent_ino, index, name, name_len);
6345 } else if (add_backref) {
6346 ret = btrfs_insert_inode_ref(trans, root, name, name_len, ino,
6350 /* Nothing to clean up yet */
6354 ret = btrfs_insert_dir_item(trans, root, name, name_len,
6356 btrfs_inode_type(inode), index);
6357 if (ret == -EEXIST || ret == -EOVERFLOW)
6360 btrfs_abort_transaction(trans, ret);
6364 btrfs_i_size_write(parent_inode, parent_inode->i_size +
6366 inode_inc_iversion(parent_inode);
6367 parent_inode->i_mtime = parent_inode->i_ctime =
6368 current_fs_time(parent_inode->i_sb);
6369 ret = btrfs_update_inode(trans, root, parent_inode);
6371 btrfs_abort_transaction(trans, ret);
6375 if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
6378 err = btrfs_del_root_ref(trans, root->fs_info->tree_root,
6379 key.objectid, root->root_key.objectid,
6380 parent_ino, &local_index, name, name_len);
6382 } else if (add_backref) {
6386 err = btrfs_del_inode_ref(trans, root, name, name_len,
6387 ino, parent_ino, &local_index);
6392 static int btrfs_add_nondir(struct btrfs_trans_handle *trans,
6393 struct inode *dir, struct dentry *dentry,
6394 struct inode *inode, int backref, u64 index)
6396 int err = btrfs_add_link(trans, dir, inode,
6397 dentry->d_name.name, dentry->d_name.len,
6404 static int btrfs_mknod(struct inode *dir, struct dentry *dentry,
6405 umode_t mode, dev_t rdev)
6407 struct btrfs_trans_handle *trans;
6408 struct btrfs_root *root = BTRFS_I(dir)->root;
6409 struct inode *inode = NULL;
6416 * 2 for inode item and ref
6418 * 1 for xattr if selinux is on
6420 trans = btrfs_start_transaction(root, 5);
6422 return PTR_ERR(trans);
6424 err = btrfs_find_free_ino(root, &objectid);
6428 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
6429 dentry->d_name.len, btrfs_ino(dir), objectid,
6431 if (IS_ERR(inode)) {
6432 err = PTR_ERR(inode);
6437 * If the active LSM wants to access the inode during
6438 * d_instantiate it needs these. Smack checks to see
6439 * if the filesystem supports xattrs by looking at the
6442 inode->i_op = &btrfs_special_inode_operations;
6443 init_special_inode(inode, inode->i_mode, rdev);
6445 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
6447 goto out_unlock_inode;
6449 err = btrfs_add_nondir(trans, dir, dentry, inode, 0, index);
6451 goto out_unlock_inode;
6453 btrfs_update_inode(trans, root, inode);
6454 unlock_new_inode(inode);
6455 d_instantiate(dentry, inode);
6459 btrfs_end_transaction(trans, root);
6460 btrfs_balance_delayed_items(root);
6461 btrfs_btree_balance_dirty(root);
6463 inode_dec_link_count(inode);
6470 unlock_new_inode(inode);
6475 static int btrfs_create(struct inode *dir, struct dentry *dentry,
6476 umode_t mode, bool excl)
6478 struct btrfs_trans_handle *trans;
6479 struct btrfs_root *root = BTRFS_I(dir)->root;
6480 struct inode *inode = NULL;
6481 int drop_inode_on_err = 0;
6487 * 2 for inode item and ref
6489 * 1 for xattr if selinux is on
6491 trans = btrfs_start_transaction(root, 5);
6493 return PTR_ERR(trans);
6495 err = btrfs_find_free_ino(root, &objectid);
6499 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
6500 dentry->d_name.len, btrfs_ino(dir), objectid,
6502 if (IS_ERR(inode)) {
6503 err = PTR_ERR(inode);
6506 drop_inode_on_err = 1;
6508 * If the active LSM wants to access the inode during
6509 * d_instantiate it needs these. Smack checks to see
6510 * if the filesystem supports xattrs by looking at the
6513 inode->i_fop = &btrfs_file_operations;
6514 inode->i_op = &btrfs_file_inode_operations;
6515 inode->i_mapping->a_ops = &btrfs_aops;
6517 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
6519 goto out_unlock_inode;
6521 err = btrfs_update_inode(trans, root, inode);
6523 goto out_unlock_inode;
6525 err = btrfs_add_nondir(trans, dir, dentry, inode, 0, index);
6527 goto out_unlock_inode;
6529 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
6530 unlock_new_inode(inode);
6531 d_instantiate(dentry, inode);
6534 btrfs_end_transaction(trans, root);
6535 if (err && drop_inode_on_err) {
6536 inode_dec_link_count(inode);
6539 btrfs_balance_delayed_items(root);
6540 btrfs_btree_balance_dirty(root);
6544 unlock_new_inode(inode);
6549 static int btrfs_link(struct dentry *old_dentry, struct inode *dir,
6550 struct dentry *dentry)
6552 struct btrfs_trans_handle *trans = NULL;
6553 struct btrfs_root *root = BTRFS_I(dir)->root;
6554 struct inode *inode = d_inode(old_dentry);
6559 /* do not allow sys_link's with other subvols of the same device */
6560 if (root->objectid != BTRFS_I(inode)->root->objectid)
6563 if (inode->i_nlink >= BTRFS_LINK_MAX)
6566 err = btrfs_set_inode_index(dir, &index);
6571 * 2 items for inode and inode ref
6572 * 2 items for dir items
6573 * 1 item for parent inode
6575 trans = btrfs_start_transaction(root, 5);
6576 if (IS_ERR(trans)) {
6577 err = PTR_ERR(trans);
6582 /* There are several dir indexes for this inode, clear the cache. */
6583 BTRFS_I(inode)->dir_index = 0ULL;
6585 inode_inc_iversion(inode);
6586 inode->i_ctime = current_fs_time(inode->i_sb);
6588 set_bit(BTRFS_INODE_COPY_EVERYTHING, &BTRFS_I(inode)->runtime_flags);
6590 err = btrfs_add_nondir(trans, dir, dentry, inode, 1, index);
6595 struct dentry *parent = dentry->d_parent;
6596 err = btrfs_update_inode(trans, root, inode);
6599 if (inode->i_nlink == 1) {
6601 * If new hard link count is 1, it's a file created
6602 * with open(2) O_TMPFILE flag.
6604 err = btrfs_orphan_del(trans, inode);
6608 d_instantiate(dentry, inode);
6609 btrfs_log_new_name(trans, inode, NULL, parent);
6612 btrfs_balance_delayed_items(root);
6615 btrfs_end_transaction(trans, root);
6617 inode_dec_link_count(inode);
6620 btrfs_btree_balance_dirty(root);
6624 static int btrfs_mkdir(struct inode *dir, struct dentry *dentry, umode_t mode)
6626 struct inode *inode = NULL;
6627 struct btrfs_trans_handle *trans;
6628 struct btrfs_root *root = BTRFS_I(dir)->root;
6630 int drop_on_err = 0;
6635 * 2 items for inode and ref
6636 * 2 items for dir items
6637 * 1 for xattr if selinux is on
6639 trans = btrfs_start_transaction(root, 5);
6641 return PTR_ERR(trans);
6643 err = btrfs_find_free_ino(root, &objectid);
6647 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
6648 dentry->d_name.len, btrfs_ino(dir), objectid,
6649 S_IFDIR | mode, &index);
6650 if (IS_ERR(inode)) {
6651 err = PTR_ERR(inode);
6656 /* these must be set before we unlock the inode */
6657 inode->i_op = &btrfs_dir_inode_operations;
6658 inode->i_fop = &btrfs_dir_file_operations;
6660 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
6662 goto out_fail_inode;
6664 btrfs_i_size_write(inode, 0);
6665 err = btrfs_update_inode(trans, root, inode);
6667 goto out_fail_inode;
6669 err = btrfs_add_link(trans, dir, inode, dentry->d_name.name,
6670 dentry->d_name.len, 0, index);
6672 goto out_fail_inode;
6674 d_instantiate(dentry, inode);
6676 * mkdir is special. We're unlocking after we call d_instantiate
6677 * to avoid a race with nfsd calling d_instantiate.
6679 unlock_new_inode(inode);
6683 btrfs_end_transaction(trans, root);
6685 inode_dec_link_count(inode);
6688 btrfs_balance_delayed_items(root);
6689 btrfs_btree_balance_dirty(root);
6693 unlock_new_inode(inode);
6697 /* Find next extent map of a given extent map, caller needs to ensure locks */
6698 static struct extent_map *next_extent_map(struct extent_map *em)
6700 struct rb_node *next;
6702 next = rb_next(&em->rb_node);
6705 return container_of(next, struct extent_map, rb_node);
6708 static struct extent_map *prev_extent_map(struct extent_map *em)
6710 struct rb_node *prev;
6712 prev = rb_prev(&em->rb_node);
6715 return container_of(prev, struct extent_map, rb_node);
6718 /* helper for btfs_get_extent. Given an existing extent in the tree,
6719 * the existing extent is the nearest extent to map_start,
6720 * and an extent that you want to insert, deal with overlap and insert
6721 * the best fitted new extent into the tree.
6723 static int merge_extent_mapping(struct extent_map_tree *em_tree,
6724 struct extent_map *existing,
6725 struct extent_map *em,
6728 struct extent_map *prev;
6729 struct extent_map *next;
6734 BUG_ON(map_start < em->start || map_start >= extent_map_end(em));
6736 if (existing->start > map_start) {
6738 prev = prev_extent_map(next);
6741 next = next_extent_map(prev);
6744 start = prev ? extent_map_end(prev) : em->start;
6745 start = max_t(u64, start, em->start);
6746 end = next ? next->start : extent_map_end(em);
6747 end = min_t(u64, end, extent_map_end(em));
6748 start_diff = start - em->start;
6750 em->len = end - start;
6751 if (em->block_start < EXTENT_MAP_LAST_BYTE &&
6752 !test_bit(EXTENT_FLAG_COMPRESSED, &em->flags)) {
6753 em->block_start += start_diff;
6754 em->block_len -= start_diff;
6756 return add_extent_mapping(em_tree, em, 0);
6759 static noinline int uncompress_inline(struct btrfs_path *path,
6761 size_t pg_offset, u64 extent_offset,
6762 struct btrfs_file_extent_item *item)
6765 struct extent_buffer *leaf = path->nodes[0];
6768 unsigned long inline_size;
6772 WARN_ON(pg_offset != 0);
6773 compress_type = btrfs_file_extent_compression(leaf, item);
6774 max_size = btrfs_file_extent_ram_bytes(leaf, item);
6775 inline_size = btrfs_file_extent_inline_item_len(leaf,
6776 btrfs_item_nr(path->slots[0]));
6777 tmp = kmalloc(inline_size, GFP_NOFS);
6780 ptr = btrfs_file_extent_inline_start(item);
6782 read_extent_buffer(leaf, tmp, ptr, inline_size);
6784 max_size = min_t(unsigned long, PAGE_SIZE, max_size);
6785 ret = btrfs_decompress(compress_type, tmp, page,
6786 extent_offset, inline_size, max_size);
6792 * a bit scary, this does extent mapping from logical file offset to the disk.
6793 * the ugly parts come from merging extents from the disk with the in-ram
6794 * representation. This gets more complex because of the data=ordered code,
6795 * where the in-ram extents might be locked pending data=ordered completion.
6797 * This also copies inline extents directly into the page.
6800 struct extent_map *btrfs_get_extent(struct inode *inode, struct page *page,
6801 size_t pg_offset, u64 start, u64 len,
6806 u64 extent_start = 0;
6808 u64 objectid = btrfs_ino(inode);
6810 struct btrfs_path *path = NULL;
6811 struct btrfs_root *root = BTRFS_I(inode)->root;
6812 struct btrfs_file_extent_item *item;
6813 struct extent_buffer *leaf;
6814 struct btrfs_key found_key;
6815 struct extent_map *em = NULL;
6816 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
6817 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
6818 struct btrfs_trans_handle *trans = NULL;
6819 const bool new_inline = !page || create;
6822 read_lock(&em_tree->lock);
6823 em = lookup_extent_mapping(em_tree, start, len);
6825 em->bdev = root->fs_info->fs_devices->latest_bdev;
6826 read_unlock(&em_tree->lock);
6829 if (em->start > start || em->start + em->len <= start)
6830 free_extent_map(em);
6831 else if (em->block_start == EXTENT_MAP_INLINE && page)
6832 free_extent_map(em);
6836 em = alloc_extent_map();
6841 em->bdev = root->fs_info->fs_devices->latest_bdev;
6842 em->start = EXTENT_MAP_HOLE;
6843 em->orig_start = EXTENT_MAP_HOLE;
6845 em->block_len = (u64)-1;
6848 path = btrfs_alloc_path();
6854 * Chances are we'll be called again, so go ahead and do
6857 path->reada = READA_FORWARD;
6860 ret = btrfs_lookup_file_extent(trans, root, path,
6861 objectid, start, trans != NULL);
6868 if (path->slots[0] == 0)
6873 leaf = path->nodes[0];
6874 item = btrfs_item_ptr(leaf, path->slots[0],
6875 struct btrfs_file_extent_item);
6876 /* are we inside the extent that was found? */
6877 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
6878 found_type = found_key.type;
6879 if (found_key.objectid != objectid ||
6880 found_type != BTRFS_EXTENT_DATA_KEY) {
6882 * If we backup past the first extent we want to move forward
6883 * and see if there is an extent in front of us, otherwise we'll
6884 * say there is a hole for our whole search range which can
6891 found_type = btrfs_file_extent_type(leaf, item);
6892 extent_start = found_key.offset;
6893 if (found_type == BTRFS_FILE_EXTENT_REG ||
6894 found_type == BTRFS_FILE_EXTENT_PREALLOC) {
6895 extent_end = extent_start +
6896 btrfs_file_extent_num_bytes(leaf, item);
6897 } else if (found_type == BTRFS_FILE_EXTENT_INLINE) {
6899 size = btrfs_file_extent_inline_len(leaf, path->slots[0], item);
6900 extent_end = ALIGN(extent_start + size, root->sectorsize);
6903 if (start >= extent_end) {
6905 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
6906 ret = btrfs_next_leaf(root, path);
6913 leaf = path->nodes[0];
6915 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
6916 if (found_key.objectid != objectid ||
6917 found_key.type != BTRFS_EXTENT_DATA_KEY)
6919 if (start + len <= found_key.offset)
6921 if (start > found_key.offset)
6924 em->orig_start = start;
6925 em->len = found_key.offset - start;
6929 btrfs_extent_item_to_extent_map(inode, path, item, new_inline, em);
6931 if (found_type == BTRFS_FILE_EXTENT_REG ||
6932 found_type == BTRFS_FILE_EXTENT_PREALLOC) {
6934 } else if (found_type == BTRFS_FILE_EXTENT_INLINE) {
6938 size_t extent_offset;
6944 size = btrfs_file_extent_inline_len(leaf, path->slots[0], item);
6945 extent_offset = page_offset(page) + pg_offset - extent_start;
6946 copy_size = min_t(u64, PAGE_SIZE - pg_offset,
6947 size - extent_offset);
6948 em->start = extent_start + extent_offset;
6949 em->len = ALIGN(copy_size, root->sectorsize);
6950 em->orig_block_len = em->len;
6951 em->orig_start = em->start;
6952 ptr = btrfs_file_extent_inline_start(item) + extent_offset;
6953 if (create == 0 && !PageUptodate(page)) {
6954 if (btrfs_file_extent_compression(leaf, item) !=
6955 BTRFS_COMPRESS_NONE) {
6956 ret = uncompress_inline(path, page, pg_offset,
6957 extent_offset, item);
6964 read_extent_buffer(leaf, map + pg_offset, ptr,
6966 if (pg_offset + copy_size < PAGE_SIZE) {
6967 memset(map + pg_offset + copy_size, 0,
6968 PAGE_SIZE - pg_offset -
6973 flush_dcache_page(page);
6974 } else if (create && PageUptodate(page)) {
6978 free_extent_map(em);
6981 btrfs_release_path(path);
6982 trans = btrfs_join_transaction(root);
6985 return ERR_CAST(trans);
6989 write_extent_buffer(leaf, map + pg_offset, ptr,
6992 btrfs_mark_buffer_dirty(leaf);
6994 set_extent_uptodate(io_tree, em->start,
6995 extent_map_end(em) - 1, NULL, GFP_NOFS);
7000 em->orig_start = start;
7003 em->block_start = EXTENT_MAP_HOLE;
7004 set_bit(EXTENT_FLAG_VACANCY, &em->flags);
7006 btrfs_release_path(path);
7007 if (em->start > start || extent_map_end(em) <= start) {
7008 btrfs_err(root->fs_info, "bad extent! em: [%llu %llu] passed [%llu %llu]",
7009 em->start, em->len, start, len);
7015 write_lock(&em_tree->lock);
7016 ret = add_extent_mapping(em_tree, em, 0);
7017 /* it is possible that someone inserted the extent into the tree
7018 * while we had the lock dropped. It is also possible that
7019 * an overlapping map exists in the tree
7021 if (ret == -EEXIST) {
7022 struct extent_map *existing;
7026 existing = search_extent_mapping(em_tree, start, len);
7028 * existing will always be non-NULL, since there must be
7029 * extent causing the -EEXIST.
7031 if (existing->start == em->start &&
7032 extent_map_end(existing) == extent_map_end(em) &&
7033 em->block_start == existing->block_start) {
7035 * these two extents are the same, it happens
7036 * with inlines especially
7038 free_extent_map(em);
7042 } else if (start >= extent_map_end(existing) ||
7043 start <= existing->start) {
7045 * The existing extent map is the one nearest to
7046 * the [start, start + len) range which overlaps
7048 err = merge_extent_mapping(em_tree, existing,
7050 free_extent_map(existing);
7052 free_extent_map(em);
7056 free_extent_map(em);
7061 write_unlock(&em_tree->lock);
7064 trace_btrfs_get_extent(root, em);
7066 btrfs_free_path(path);
7068 ret = btrfs_end_transaction(trans, root);
7073 free_extent_map(em);
7074 return ERR_PTR(err);
7076 BUG_ON(!em); /* Error is always set */
7080 struct extent_map *btrfs_get_extent_fiemap(struct inode *inode, struct page *page,
7081 size_t pg_offset, u64 start, u64 len,
7084 struct extent_map *em;
7085 struct extent_map *hole_em = NULL;
7086 u64 range_start = start;
7092 em = btrfs_get_extent(inode, page, pg_offset, start, len, create);
7099 * - a pre-alloc extent,
7100 * there might actually be delalloc bytes behind it.
7102 if (em->block_start != EXTENT_MAP_HOLE &&
7103 !test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
7109 /* check to see if we've wrapped (len == -1 or similar) */
7118 /* ok, we didn't find anything, lets look for delalloc */
7119 found = count_range_bits(&BTRFS_I(inode)->io_tree, &range_start,
7120 end, len, EXTENT_DELALLOC, 1);
7121 found_end = range_start + found;
7122 if (found_end < range_start)
7123 found_end = (u64)-1;
7126 * we didn't find anything useful, return
7127 * the original results from get_extent()
7129 if (range_start > end || found_end <= start) {
7135 /* adjust the range_start to make sure it doesn't
7136 * go backwards from the start they passed in
7138 range_start = max(start, range_start);
7139 found = found_end - range_start;
7142 u64 hole_start = start;
7145 em = alloc_extent_map();
7151 * when btrfs_get_extent can't find anything it
7152 * returns one huge hole
7154 * make sure what it found really fits our range, and
7155 * adjust to make sure it is based on the start from
7159 u64 calc_end = extent_map_end(hole_em);
7161 if (calc_end <= start || (hole_em->start > end)) {
7162 free_extent_map(hole_em);
7165 hole_start = max(hole_em->start, start);
7166 hole_len = calc_end - hole_start;
7170 if (hole_em && range_start > hole_start) {
7171 /* our hole starts before our delalloc, so we
7172 * have to return just the parts of the hole
7173 * that go until the delalloc starts
7175 em->len = min(hole_len,
7176 range_start - hole_start);
7177 em->start = hole_start;
7178 em->orig_start = hole_start;
7180 * don't adjust block start at all,
7181 * it is fixed at EXTENT_MAP_HOLE
7183 em->block_start = hole_em->block_start;
7184 em->block_len = hole_len;
7185 if (test_bit(EXTENT_FLAG_PREALLOC, &hole_em->flags))
7186 set_bit(EXTENT_FLAG_PREALLOC, &em->flags);
7188 em->start = range_start;
7190 em->orig_start = range_start;
7191 em->block_start = EXTENT_MAP_DELALLOC;
7192 em->block_len = found;
7194 } else if (hole_em) {
7199 free_extent_map(hole_em);
7201 free_extent_map(em);
7202 return ERR_PTR(err);
7207 static struct extent_map *btrfs_create_dio_extent(struct inode *inode,
7210 const u64 orig_start,
7211 const u64 block_start,
7212 const u64 block_len,
7213 const u64 orig_block_len,
7214 const u64 ram_bytes,
7217 struct extent_map *em = NULL;
7220 down_read(&BTRFS_I(inode)->dio_sem);
7221 if (type != BTRFS_ORDERED_NOCOW) {
7222 em = create_pinned_em(inode, start, len, orig_start,
7223 block_start, block_len, orig_block_len,
7228 ret = btrfs_add_ordered_extent_dio(inode, start, block_start,
7229 len, block_len, type);
7232 free_extent_map(em);
7233 btrfs_drop_extent_cache(inode, start,
7234 start + len - 1, 0);
7239 up_read(&BTRFS_I(inode)->dio_sem);
7244 static struct extent_map *btrfs_new_extent_direct(struct inode *inode,
7247 struct btrfs_root *root = BTRFS_I(inode)->root;
7248 struct extent_map *em;
7249 struct btrfs_key ins;
7253 alloc_hint = get_extent_allocation_hint(inode, start, len);
7254 ret = btrfs_reserve_extent(root, len, root->sectorsize, 0,
7255 alloc_hint, &ins, 1, 1);
7257 return ERR_PTR(ret);
7259 em = btrfs_create_dio_extent(inode, start, ins.offset, start,
7260 ins.objectid, ins.offset, ins.offset,
7262 btrfs_dec_block_group_reservations(root->fs_info, ins.objectid);
7264 btrfs_free_reserved_extent(root, ins.objectid, ins.offset, 1);
7270 * returns 1 when the nocow is safe, < 1 on error, 0 if the
7271 * block must be cow'd
7273 noinline int can_nocow_extent(struct inode *inode, u64 offset, u64 *len,
7274 u64 *orig_start, u64 *orig_block_len,
7277 struct btrfs_trans_handle *trans;
7278 struct btrfs_path *path;
7280 struct extent_buffer *leaf;
7281 struct btrfs_root *root = BTRFS_I(inode)->root;
7282 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
7283 struct btrfs_file_extent_item *fi;
7284 struct btrfs_key key;
7291 bool nocow = (BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW);
7293 path = btrfs_alloc_path();
7297 ret = btrfs_lookup_file_extent(NULL, root, path, btrfs_ino(inode),
7302 slot = path->slots[0];
7305 /* can't find the item, must cow */
7312 leaf = path->nodes[0];
7313 btrfs_item_key_to_cpu(leaf, &key, slot);
7314 if (key.objectid != btrfs_ino(inode) ||
7315 key.type != BTRFS_EXTENT_DATA_KEY) {
7316 /* not our file or wrong item type, must cow */
7320 if (key.offset > offset) {
7321 /* Wrong offset, must cow */
7325 fi = btrfs_item_ptr(leaf, slot, struct btrfs_file_extent_item);
7326 found_type = btrfs_file_extent_type(leaf, fi);
7327 if (found_type != BTRFS_FILE_EXTENT_REG &&
7328 found_type != BTRFS_FILE_EXTENT_PREALLOC) {
7329 /* not a regular extent, must cow */
7333 if (!nocow && found_type == BTRFS_FILE_EXTENT_REG)
7336 extent_end = key.offset + btrfs_file_extent_num_bytes(leaf, fi);
7337 if (extent_end <= offset)
7340 disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
7341 if (disk_bytenr == 0)
7344 if (btrfs_file_extent_compression(leaf, fi) ||
7345 btrfs_file_extent_encryption(leaf, fi) ||
7346 btrfs_file_extent_other_encoding(leaf, fi))
7349 backref_offset = btrfs_file_extent_offset(leaf, fi);
7352 *orig_start = key.offset - backref_offset;
7353 *orig_block_len = btrfs_file_extent_disk_num_bytes(leaf, fi);
7354 *ram_bytes = btrfs_file_extent_ram_bytes(leaf, fi);
7357 if (btrfs_extent_readonly(root, disk_bytenr))
7360 num_bytes = min(offset + *len, extent_end) - offset;
7361 if (!nocow && found_type == BTRFS_FILE_EXTENT_PREALLOC) {
7364 range_end = round_up(offset + num_bytes, root->sectorsize) - 1;
7365 ret = test_range_bit(io_tree, offset, range_end,
7366 EXTENT_DELALLOC, 0, NULL);
7373 btrfs_release_path(path);
7376 * look for other files referencing this extent, if we
7377 * find any we must cow
7379 trans = btrfs_join_transaction(root);
7380 if (IS_ERR(trans)) {
7385 ret = btrfs_cross_ref_exist(trans, root, btrfs_ino(inode),
7386 key.offset - backref_offset, disk_bytenr);
7387 btrfs_end_transaction(trans, root);
7394 * adjust disk_bytenr and num_bytes to cover just the bytes
7395 * in this extent we are about to write. If there
7396 * are any csums in that range we have to cow in order
7397 * to keep the csums correct
7399 disk_bytenr += backref_offset;
7400 disk_bytenr += offset - key.offset;
7401 if (csum_exist_in_range(root, disk_bytenr, num_bytes))
7404 * all of the above have passed, it is safe to overwrite this extent
7410 btrfs_free_path(path);
7414 bool btrfs_page_exists_in_range(struct inode *inode, loff_t start, loff_t end)
7416 struct radix_tree_root *root = &inode->i_mapping->page_tree;
7418 void **pagep = NULL;
7419 struct page *page = NULL;
7423 start_idx = start >> PAGE_SHIFT;
7426 * end is the last byte in the last page. end == start is legal
7428 end_idx = end >> PAGE_SHIFT;
7432 /* Most of the code in this while loop is lifted from
7433 * find_get_page. It's been modified to begin searching from a
7434 * page and return just the first page found in that range. If the
7435 * found idx is less than or equal to the end idx then we know that
7436 * a page exists. If no pages are found or if those pages are
7437 * outside of the range then we're fine (yay!) */
7438 while (page == NULL &&
7439 radix_tree_gang_lookup_slot(root, &pagep, NULL, start_idx, 1)) {
7440 page = radix_tree_deref_slot(pagep);
7441 if (unlikely(!page))
7444 if (radix_tree_exception(page)) {
7445 if (radix_tree_deref_retry(page)) {
7450 * Otherwise, shmem/tmpfs must be storing a swap entry
7451 * here as an exceptional entry: so return it without
7452 * attempting to raise page count.
7455 break; /* TODO: Is this relevant for this use case? */
7458 if (!page_cache_get_speculative(page)) {
7464 * Has the page moved?
7465 * This is part of the lockless pagecache protocol. See
7466 * include/linux/pagemap.h for details.
7468 if (unlikely(page != *pagep)) {
7475 if (page->index <= end_idx)
7484 static int lock_extent_direct(struct inode *inode, u64 lockstart, u64 lockend,
7485 struct extent_state **cached_state, int writing)
7487 struct btrfs_ordered_extent *ordered;
7491 lock_extent_bits(&BTRFS_I(inode)->io_tree, lockstart, lockend,
7494 * We're concerned with the entire range that we're going to be
7495 * doing DIO to, so we need to make sure there's no ordered
7496 * extents in this range.
7498 ordered = btrfs_lookup_ordered_range(inode, lockstart,
7499 lockend - lockstart + 1);
7502 * We need to make sure there are no buffered pages in this
7503 * range either, we could have raced between the invalidate in
7504 * generic_file_direct_write and locking the extent. The
7505 * invalidate needs to happen so that reads after a write do not
7510 !btrfs_page_exists_in_range(inode, lockstart, lockend)))
7513 unlock_extent_cached(&BTRFS_I(inode)->io_tree, lockstart, lockend,
7514 cached_state, GFP_NOFS);
7518 * If we are doing a DIO read and the ordered extent we
7519 * found is for a buffered write, we can not wait for it
7520 * to complete and retry, because if we do so we can
7521 * deadlock with concurrent buffered writes on page
7522 * locks. This happens only if our DIO read covers more
7523 * than one extent map, if at this point has already
7524 * created an ordered extent for a previous extent map
7525 * and locked its range in the inode's io tree, and a
7526 * concurrent write against that previous extent map's
7527 * range and this range started (we unlock the ranges
7528 * in the io tree only when the bios complete and
7529 * buffered writes always lock pages before attempting
7530 * to lock range in the io tree).
7533 test_bit(BTRFS_ORDERED_DIRECT, &ordered->flags))
7534 btrfs_start_ordered_extent(inode, ordered, 1);
7537 btrfs_put_ordered_extent(ordered);
7540 * We could trigger writeback for this range (and wait
7541 * for it to complete) and then invalidate the pages for
7542 * this range (through invalidate_inode_pages2_range()),
7543 * but that can lead us to a deadlock with a concurrent
7544 * call to readpages() (a buffered read or a defrag call
7545 * triggered a readahead) on a page lock due to an
7546 * ordered dio extent we created before but did not have
7547 * yet a corresponding bio submitted (whence it can not
7548 * complete), which makes readpages() wait for that
7549 * ordered extent to complete while holding a lock on
7564 static struct extent_map *create_pinned_em(struct inode *inode, u64 start,
7565 u64 len, u64 orig_start,
7566 u64 block_start, u64 block_len,
7567 u64 orig_block_len, u64 ram_bytes,
7570 struct extent_map_tree *em_tree;
7571 struct extent_map *em;
7572 struct btrfs_root *root = BTRFS_I(inode)->root;
7575 em_tree = &BTRFS_I(inode)->extent_tree;
7576 em = alloc_extent_map();
7578 return ERR_PTR(-ENOMEM);
7581 em->orig_start = orig_start;
7582 em->mod_start = start;
7585 em->block_len = block_len;
7586 em->block_start = block_start;
7587 em->bdev = root->fs_info->fs_devices->latest_bdev;
7588 em->orig_block_len = orig_block_len;
7589 em->ram_bytes = ram_bytes;
7590 em->generation = -1;
7591 set_bit(EXTENT_FLAG_PINNED, &em->flags);
7592 if (type == BTRFS_ORDERED_PREALLOC)
7593 set_bit(EXTENT_FLAG_FILLING, &em->flags);
7596 btrfs_drop_extent_cache(inode, em->start,
7597 em->start + em->len - 1, 0);
7598 write_lock(&em_tree->lock);
7599 ret = add_extent_mapping(em_tree, em, 1);
7600 write_unlock(&em_tree->lock);
7601 } while (ret == -EEXIST);
7604 free_extent_map(em);
7605 return ERR_PTR(ret);
7611 static void adjust_dio_outstanding_extents(struct inode *inode,
7612 struct btrfs_dio_data *dio_data,
7615 unsigned num_extents;
7617 num_extents = (unsigned) div64_u64(len + BTRFS_MAX_EXTENT_SIZE - 1,
7618 BTRFS_MAX_EXTENT_SIZE);
7620 * If we have an outstanding_extents count still set then we're
7621 * within our reservation, otherwise we need to adjust our inode
7622 * counter appropriately.
7624 if (dio_data->outstanding_extents) {
7625 dio_data->outstanding_extents -= num_extents;
7627 spin_lock(&BTRFS_I(inode)->lock);
7628 BTRFS_I(inode)->outstanding_extents += num_extents;
7629 spin_unlock(&BTRFS_I(inode)->lock);
7633 static int btrfs_get_blocks_direct(struct inode *inode, sector_t iblock,
7634 struct buffer_head *bh_result, int create)
7636 struct extent_map *em;
7637 struct btrfs_root *root = BTRFS_I(inode)->root;
7638 struct extent_state *cached_state = NULL;
7639 struct btrfs_dio_data *dio_data = NULL;
7640 u64 start = iblock << inode->i_blkbits;
7641 u64 lockstart, lockend;
7642 u64 len = bh_result->b_size;
7643 int unlock_bits = EXTENT_LOCKED;
7647 unlock_bits |= EXTENT_DIRTY;
7649 len = min_t(u64, len, root->sectorsize);
7652 lockend = start + len - 1;
7654 if (current->journal_info) {
7656 * Need to pull our outstanding extents and set journal_info to NULL so
7657 * that anything that needs to check if there's a transaction doesn't get
7660 dio_data = current->journal_info;
7661 current->journal_info = NULL;
7665 * If this errors out it's because we couldn't invalidate pagecache for
7666 * this range and we need to fallback to buffered.
7668 if (lock_extent_direct(inode, lockstart, lockend, &cached_state,
7674 em = btrfs_get_extent(inode, NULL, 0, start, len, 0);
7681 * Ok for INLINE and COMPRESSED extents we need to fallback on buffered
7682 * io. INLINE is special, and we could probably kludge it in here, but
7683 * it's still buffered so for safety lets just fall back to the generic
7686 * For COMPRESSED we _have_ to read the entire extent in so we can
7687 * decompress it, so there will be buffering required no matter what we
7688 * do, so go ahead and fallback to buffered.
7690 * We return -ENOTBLK because that's what makes DIO go ahead and go back
7691 * to buffered IO. Don't blame me, this is the price we pay for using
7694 if (test_bit(EXTENT_FLAG_COMPRESSED, &em->flags) ||
7695 em->block_start == EXTENT_MAP_INLINE) {
7696 free_extent_map(em);
7701 /* Just a good old fashioned hole, return */
7702 if (!create && (em->block_start == EXTENT_MAP_HOLE ||
7703 test_bit(EXTENT_FLAG_PREALLOC, &em->flags))) {
7704 free_extent_map(em);
7709 * We don't allocate a new extent in the following cases
7711 * 1) The inode is marked as NODATACOW. In this case we'll just use the
7713 * 2) The extent is marked as PREALLOC. We're good to go here and can
7714 * just use the extent.
7718 len = min(len, em->len - (start - em->start));
7719 lockstart = start + len;
7723 if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags) ||
7724 ((BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW) &&
7725 em->block_start != EXTENT_MAP_HOLE)) {
7727 u64 block_start, orig_start, orig_block_len, ram_bytes;
7729 if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
7730 type = BTRFS_ORDERED_PREALLOC;
7732 type = BTRFS_ORDERED_NOCOW;
7733 len = min(len, em->len - (start - em->start));
7734 block_start = em->block_start + (start - em->start);
7736 if (can_nocow_extent(inode, start, &len, &orig_start,
7737 &orig_block_len, &ram_bytes) == 1 &&
7738 btrfs_inc_nocow_writers(root->fs_info, block_start)) {
7739 struct extent_map *em2;
7741 em2 = btrfs_create_dio_extent(inode, start, len,
7742 orig_start, block_start,
7743 len, orig_block_len,
7745 btrfs_dec_nocow_writers(root->fs_info, block_start);
7746 if (type == BTRFS_ORDERED_PREALLOC) {
7747 free_extent_map(em);
7750 if (em2 && IS_ERR(em2)) {
7759 * this will cow the extent, reset the len in case we changed
7762 len = bh_result->b_size;
7763 free_extent_map(em);
7764 em = btrfs_new_extent_direct(inode, start, len);
7769 len = min(len, em->len - (start - em->start));
7771 bh_result->b_blocknr = (em->block_start + (start - em->start)) >>
7773 bh_result->b_size = len;
7774 bh_result->b_bdev = em->bdev;
7775 set_buffer_mapped(bh_result);
7777 if (!test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
7778 set_buffer_new(bh_result);
7781 * Need to update the i_size under the extent lock so buffered
7782 * readers will get the updated i_size when we unlock.
7784 if (start + len > i_size_read(inode))
7785 i_size_write(inode, start + len);
7787 adjust_dio_outstanding_extents(inode, dio_data, len);
7788 btrfs_free_reserved_data_space(inode, start, len);
7789 WARN_ON(dio_data->reserve < len);
7790 dio_data->reserve -= len;
7791 dio_data->unsubmitted_oe_range_end = start + len;
7792 current->journal_info = dio_data;
7796 * In the case of write we need to clear and unlock the entire range,
7797 * in the case of read we need to unlock only the end area that we
7798 * aren't using if there is any left over space.
7800 if (lockstart < lockend) {
7801 clear_extent_bit(&BTRFS_I(inode)->io_tree, lockstart,
7802 lockend, unlock_bits, 1, 0,
7803 &cached_state, GFP_NOFS);
7805 free_extent_state(cached_state);
7808 free_extent_map(em);
7813 clear_extent_bit(&BTRFS_I(inode)->io_tree, lockstart, lockend,
7814 unlock_bits, 1, 0, &cached_state, GFP_NOFS);
7817 current->journal_info = dio_data;
7819 * Compensate the delalloc release we do in btrfs_direct_IO() when we
7820 * write less data then expected, so that we don't underflow our inode's
7821 * outstanding extents counter.
7823 if (create && dio_data)
7824 adjust_dio_outstanding_extents(inode, dio_data, len);
7829 static inline int submit_dio_repair_bio(struct inode *inode, struct bio *bio,
7832 struct btrfs_root *root = BTRFS_I(inode)->root;
7835 BUG_ON(bio_op(bio) == REQ_OP_WRITE);
7839 ret = btrfs_bio_wq_end_io(root->fs_info, bio,
7840 BTRFS_WQ_ENDIO_DIO_REPAIR);
7844 ret = btrfs_map_bio(root, bio, mirror_num, 0);
7850 static int btrfs_check_dio_repairable(struct inode *inode,
7851 struct bio *failed_bio,
7852 struct io_failure_record *failrec,
7857 num_copies = btrfs_num_copies(BTRFS_I(inode)->root->fs_info,
7858 failrec->logical, failrec->len);
7859 if (num_copies == 1) {
7861 * we only have a single copy of the data, so don't bother with
7862 * all the retry and error correction code that follows. no
7863 * matter what the error is, it is very likely to persist.
7865 pr_debug("Check DIO Repairable: cannot repair, num_copies=%d, next_mirror %d, failed_mirror %d\n",
7866 num_copies, failrec->this_mirror, failed_mirror);
7870 failrec->failed_mirror = failed_mirror;
7871 failrec->this_mirror++;
7872 if (failrec->this_mirror == failed_mirror)
7873 failrec->this_mirror++;
7875 if (failrec->this_mirror > num_copies) {
7876 pr_debug("Check DIO Repairable: (fail) num_copies=%d, next_mirror %d, failed_mirror %d\n",
7877 num_copies, failrec->this_mirror, failed_mirror);
7884 static int dio_read_error(struct inode *inode, struct bio *failed_bio,
7885 struct page *page, unsigned int pgoff,
7886 u64 start, u64 end, int failed_mirror,
7887 bio_end_io_t *repair_endio, void *repair_arg)
7889 struct io_failure_record *failrec;
7895 BUG_ON(bio_op(failed_bio) == REQ_OP_WRITE);
7897 ret = btrfs_get_io_failure_record(inode, start, end, &failrec);
7901 ret = btrfs_check_dio_repairable(inode, failed_bio, failrec,
7904 free_io_failure(inode, failrec);
7908 if ((failed_bio->bi_vcnt > 1)
7909 || (failed_bio->bi_io_vec->bv_len
7910 > BTRFS_I(inode)->root->sectorsize))
7911 read_mode = READ_SYNC | REQ_FAILFAST_DEV;
7913 read_mode = READ_SYNC;
7915 isector = start - btrfs_io_bio(failed_bio)->logical;
7916 isector >>= inode->i_sb->s_blocksize_bits;
7917 bio = btrfs_create_repair_bio(inode, failed_bio, failrec, page,
7918 pgoff, isector, repair_endio, repair_arg);
7920 free_io_failure(inode, failrec);
7923 bio_set_op_attrs(bio, REQ_OP_READ, read_mode);
7925 btrfs_debug(BTRFS_I(inode)->root->fs_info,
7926 "Repair DIO Read Error: submitting new dio read[%#x] to this_mirror=%d, in_validation=%d\n",
7927 read_mode, failrec->this_mirror, failrec->in_validation);
7929 ret = submit_dio_repair_bio(inode, bio, failrec->this_mirror);
7931 free_io_failure(inode, failrec);
7938 struct btrfs_retry_complete {
7939 struct completion done;
7940 struct inode *inode;
7945 static void btrfs_retry_endio_nocsum(struct bio *bio)
7947 struct btrfs_retry_complete *done = bio->bi_private;
7948 struct inode *inode;
7949 struct bio_vec *bvec;
7955 ASSERT(bio->bi_vcnt == 1);
7956 inode = bio->bi_io_vec->bv_page->mapping->host;
7957 ASSERT(bio->bi_io_vec->bv_len == BTRFS_I(inode)->root->sectorsize);
7960 bio_for_each_segment_all(bvec, bio, i)
7961 clean_io_failure(done->inode, done->start, bvec->bv_page, 0);
7963 complete(&done->done);
7967 static int __btrfs_correct_data_nocsum(struct inode *inode,
7968 struct btrfs_io_bio *io_bio)
7970 struct btrfs_fs_info *fs_info;
7971 struct bio_vec *bvec;
7972 struct btrfs_retry_complete done;
7980 fs_info = BTRFS_I(inode)->root->fs_info;
7981 sectorsize = BTRFS_I(inode)->root->sectorsize;
7983 start = io_bio->logical;
7986 bio_for_each_segment_all(bvec, &io_bio->bio, i) {
7987 nr_sectors = BTRFS_BYTES_TO_BLKS(fs_info, bvec->bv_len);
7988 pgoff = bvec->bv_offset;
7990 next_block_or_try_again:
7993 init_completion(&done.done);
7995 ret = dio_read_error(inode, &io_bio->bio, bvec->bv_page,
7996 pgoff, start, start + sectorsize - 1,
7998 btrfs_retry_endio_nocsum, &done);
8002 wait_for_completion(&done.done);
8004 if (!done.uptodate) {
8005 /* We might have another mirror, so try again */
8006 goto next_block_or_try_again;
8009 start += sectorsize;
8012 pgoff += sectorsize;
8013 goto next_block_or_try_again;
8020 static void btrfs_retry_endio(struct bio *bio)
8022 struct btrfs_retry_complete *done = bio->bi_private;
8023 struct btrfs_io_bio *io_bio = btrfs_io_bio(bio);
8024 struct inode *inode;
8025 struct bio_vec *bvec;
8036 start = done->start;
8038 ASSERT(bio->bi_vcnt == 1);
8039 inode = bio->bi_io_vec->bv_page->mapping->host;
8040 ASSERT(bio->bi_io_vec->bv_len == BTRFS_I(inode)->root->sectorsize);
8042 bio_for_each_segment_all(bvec, bio, i) {
8043 ret = __readpage_endio_check(done->inode, io_bio, i,
8044 bvec->bv_page, bvec->bv_offset,
8045 done->start, bvec->bv_len);
8047 clean_io_failure(done->inode, done->start,
8048 bvec->bv_page, bvec->bv_offset);
8053 done->uptodate = uptodate;
8055 complete(&done->done);
8059 static int __btrfs_subio_endio_read(struct inode *inode,
8060 struct btrfs_io_bio *io_bio, int err)
8062 struct btrfs_fs_info *fs_info;
8063 struct bio_vec *bvec;
8064 struct btrfs_retry_complete done;
8074 fs_info = BTRFS_I(inode)->root->fs_info;
8075 sectorsize = BTRFS_I(inode)->root->sectorsize;
8078 start = io_bio->logical;
8081 bio_for_each_segment_all(bvec, &io_bio->bio, i) {
8082 nr_sectors = BTRFS_BYTES_TO_BLKS(fs_info, bvec->bv_len);
8084 pgoff = bvec->bv_offset;
8086 csum_pos = BTRFS_BYTES_TO_BLKS(fs_info, offset);
8087 ret = __readpage_endio_check(inode, io_bio, csum_pos,
8088 bvec->bv_page, pgoff, start,
8095 init_completion(&done.done);
8097 ret = dio_read_error(inode, &io_bio->bio, bvec->bv_page,
8098 pgoff, start, start + sectorsize - 1,
8100 btrfs_retry_endio, &done);
8106 wait_for_completion(&done.done);
8108 if (!done.uptodate) {
8109 /* We might have another mirror, so try again */
8113 offset += sectorsize;
8114 start += sectorsize;
8119 pgoff += sectorsize;
8127 static int btrfs_subio_endio_read(struct inode *inode,
8128 struct btrfs_io_bio *io_bio, int err)
8130 bool skip_csum = BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM;
8134 return __btrfs_correct_data_nocsum(inode, io_bio);
8138 return __btrfs_subio_endio_read(inode, io_bio, err);
8142 static void btrfs_endio_direct_read(struct bio *bio)
8144 struct btrfs_dio_private *dip = bio->bi_private;
8145 struct inode *inode = dip->inode;
8146 struct bio *dio_bio;
8147 struct btrfs_io_bio *io_bio = btrfs_io_bio(bio);
8148 int err = bio->bi_error;
8150 if (dip->flags & BTRFS_DIO_ORIG_BIO_SUBMITTED)
8151 err = btrfs_subio_endio_read(inode, io_bio, err);
8153 unlock_extent(&BTRFS_I(inode)->io_tree, dip->logical_offset,
8154 dip->logical_offset + dip->bytes - 1);
8155 dio_bio = dip->dio_bio;
8159 dio_bio->bi_error = bio->bi_error;
8160 dio_end_io(dio_bio, bio->bi_error);
8163 io_bio->end_io(io_bio, err);
8167 static void btrfs_endio_direct_write_update_ordered(struct inode *inode,
8172 struct btrfs_root *root = BTRFS_I(inode)->root;
8173 struct btrfs_ordered_extent *ordered = NULL;
8174 u64 ordered_offset = offset;
8175 u64 ordered_bytes = bytes;
8179 ret = btrfs_dec_test_first_ordered_pending(inode, &ordered,
8186 btrfs_init_work(&ordered->work, btrfs_endio_write_helper,
8187 finish_ordered_fn, NULL, NULL);
8188 btrfs_queue_work(root->fs_info->endio_write_workers,
8192 * our bio might span multiple ordered extents. If we haven't
8193 * completed the accounting for the whole dio, go back and try again
8195 if (ordered_offset < offset + bytes) {
8196 ordered_bytes = offset + bytes - ordered_offset;
8202 static void btrfs_endio_direct_write(struct bio *bio)
8204 struct btrfs_dio_private *dip = bio->bi_private;
8205 struct bio *dio_bio = dip->dio_bio;
8207 btrfs_endio_direct_write_update_ordered(dip->inode,
8208 dip->logical_offset,
8214 dio_bio->bi_error = bio->bi_error;
8215 dio_end_io(dio_bio, bio->bi_error);
8219 static int __btrfs_submit_bio_start_direct_io(struct inode *inode,
8220 struct bio *bio, int mirror_num,
8221 unsigned long bio_flags, u64 offset)
8224 struct btrfs_root *root = BTRFS_I(inode)->root;
8225 ret = btrfs_csum_one_bio(root, inode, bio, offset, 1);
8226 BUG_ON(ret); /* -ENOMEM */
8230 static void btrfs_end_dio_bio(struct bio *bio)
8232 struct btrfs_dio_private *dip = bio->bi_private;
8233 int err = bio->bi_error;
8236 btrfs_warn(BTRFS_I(dip->inode)->root->fs_info,
8237 "direct IO failed ino %llu rw %d,%u sector %#Lx len %u err no %d",
8238 btrfs_ino(dip->inode), bio_op(bio), bio->bi_opf,
8239 (unsigned long long)bio->bi_iter.bi_sector,
8240 bio->bi_iter.bi_size, err);
8242 if (dip->subio_endio)
8243 err = dip->subio_endio(dip->inode, btrfs_io_bio(bio), err);
8249 * before atomic variable goto zero, we must make sure
8250 * dip->errors is perceived to be set.
8252 smp_mb__before_atomic();
8255 /* if there are more bios still pending for this dio, just exit */
8256 if (!atomic_dec_and_test(&dip->pending_bios))
8260 bio_io_error(dip->orig_bio);
8262 dip->dio_bio->bi_error = 0;
8263 bio_endio(dip->orig_bio);
8269 static struct bio *btrfs_dio_bio_alloc(struct block_device *bdev,
8270 u64 first_sector, gfp_t gfp_flags)
8273 bio = btrfs_bio_alloc(bdev, first_sector, BIO_MAX_PAGES, gfp_flags);
8275 bio_associate_current(bio);
8279 static inline int btrfs_lookup_and_bind_dio_csum(struct btrfs_root *root,
8280 struct inode *inode,
8281 struct btrfs_dio_private *dip,
8285 struct btrfs_io_bio *io_bio = btrfs_io_bio(bio);
8286 struct btrfs_io_bio *orig_io_bio = btrfs_io_bio(dip->orig_bio);
8290 * We load all the csum data we need when we submit
8291 * the first bio to reduce the csum tree search and
8294 if (dip->logical_offset == file_offset) {
8295 ret = btrfs_lookup_bio_sums_dio(root, inode, dip->orig_bio,
8301 if (bio == dip->orig_bio)
8304 file_offset -= dip->logical_offset;
8305 file_offset >>= inode->i_sb->s_blocksize_bits;
8306 io_bio->csum = (u8 *)(((u32 *)orig_io_bio->csum) + file_offset);
8311 static inline int __btrfs_submit_dio_bio(struct bio *bio, struct inode *inode,
8312 u64 file_offset, int skip_sum,
8315 struct btrfs_dio_private *dip = bio->bi_private;
8316 bool write = bio_op(bio) == REQ_OP_WRITE;
8317 struct btrfs_root *root = BTRFS_I(inode)->root;
8321 async_submit = !atomic_read(&BTRFS_I(inode)->sync_writers);
8326 ret = btrfs_bio_wq_end_io(root->fs_info, bio,
8327 BTRFS_WQ_ENDIO_DATA);
8335 if (write && async_submit) {
8336 ret = btrfs_wq_submit_bio(root->fs_info,
8337 inode, bio, 0, 0, file_offset,
8338 __btrfs_submit_bio_start_direct_io,
8339 __btrfs_submit_bio_done);
8343 * If we aren't doing async submit, calculate the csum of the
8346 ret = btrfs_csum_one_bio(root, inode, bio, file_offset, 1);
8350 ret = btrfs_lookup_and_bind_dio_csum(root, inode, dip, bio,
8356 ret = btrfs_map_bio(root, bio, 0, async_submit);
8362 static int btrfs_submit_direct_hook(struct btrfs_dio_private *dip,
8365 struct inode *inode = dip->inode;
8366 struct btrfs_root *root = BTRFS_I(inode)->root;
8368 struct bio *orig_bio = dip->orig_bio;
8369 struct bio_vec *bvec = orig_bio->bi_io_vec;
8370 u64 start_sector = orig_bio->bi_iter.bi_sector;
8371 u64 file_offset = dip->logical_offset;
8374 u32 blocksize = root->sectorsize;
8375 int async_submit = 0;
8380 map_length = orig_bio->bi_iter.bi_size;
8381 ret = btrfs_map_block(root->fs_info, bio_op(orig_bio),
8382 start_sector << 9, &map_length, NULL, 0);
8386 if (map_length >= orig_bio->bi_iter.bi_size) {
8388 dip->flags |= BTRFS_DIO_ORIG_BIO_SUBMITTED;
8392 /* async crcs make it difficult to collect full stripe writes. */
8393 if (btrfs_get_alloc_profile(root, 1) & BTRFS_BLOCK_GROUP_RAID56_MASK)
8398 bio = btrfs_dio_bio_alloc(orig_bio->bi_bdev, start_sector, GFP_NOFS);
8402 bio_set_op_attrs(bio, bio_op(orig_bio), orig_bio->bi_opf);
8403 bio->bi_private = dip;
8404 bio->bi_end_io = btrfs_end_dio_bio;
8405 btrfs_io_bio(bio)->logical = file_offset;
8406 atomic_inc(&dip->pending_bios);
8408 while (bvec <= (orig_bio->bi_io_vec + orig_bio->bi_vcnt - 1)) {
8409 nr_sectors = BTRFS_BYTES_TO_BLKS(root->fs_info, bvec->bv_len);
8412 if (unlikely(map_length < submit_len + blocksize ||
8413 bio_add_page(bio, bvec->bv_page, blocksize,
8414 bvec->bv_offset + (i * blocksize)) < blocksize)) {
8416 * inc the count before we submit the bio so
8417 * we know the end IO handler won't happen before
8418 * we inc the count. Otherwise, the dip might get freed
8419 * before we're done setting it up
8421 atomic_inc(&dip->pending_bios);
8422 ret = __btrfs_submit_dio_bio(bio, inode,
8423 file_offset, skip_sum,
8427 atomic_dec(&dip->pending_bios);
8431 start_sector += submit_len >> 9;
8432 file_offset += submit_len;
8436 bio = btrfs_dio_bio_alloc(orig_bio->bi_bdev,
8437 start_sector, GFP_NOFS);
8440 bio_set_op_attrs(bio, bio_op(orig_bio), orig_bio->bi_opf);
8441 bio->bi_private = dip;
8442 bio->bi_end_io = btrfs_end_dio_bio;
8443 btrfs_io_bio(bio)->logical = file_offset;
8445 map_length = orig_bio->bi_iter.bi_size;
8446 ret = btrfs_map_block(root->fs_info, bio_op(orig_bio),
8448 &map_length, NULL, 0);
8456 submit_len += blocksize;
8466 ret = __btrfs_submit_dio_bio(bio, inode, file_offset, skip_sum,
8475 * before atomic variable goto zero, we must
8476 * make sure dip->errors is perceived to be set.
8478 smp_mb__before_atomic();
8479 if (atomic_dec_and_test(&dip->pending_bios))
8480 bio_io_error(dip->orig_bio);
8482 /* bio_end_io() will handle error, so we needn't return it */
8486 static void btrfs_submit_direct(struct bio *dio_bio, struct inode *inode,
8489 struct btrfs_dio_private *dip = NULL;
8490 struct bio *io_bio = NULL;
8491 struct btrfs_io_bio *btrfs_bio;
8493 bool write = (bio_op(dio_bio) == REQ_OP_WRITE);
8496 skip_sum = BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM;
8498 io_bio = btrfs_bio_clone(dio_bio, GFP_NOFS);
8504 dip = kzalloc(sizeof(*dip), GFP_NOFS);
8510 dip->private = dio_bio->bi_private;
8512 dip->logical_offset = file_offset;
8513 dip->bytes = dio_bio->bi_iter.bi_size;
8514 dip->disk_bytenr = (u64)dio_bio->bi_iter.bi_sector << 9;
8515 io_bio->bi_private = dip;
8516 dip->orig_bio = io_bio;
8517 dip->dio_bio = dio_bio;
8518 atomic_set(&dip->pending_bios, 0);
8519 btrfs_bio = btrfs_io_bio(io_bio);
8520 btrfs_bio->logical = file_offset;
8523 io_bio->bi_end_io = btrfs_endio_direct_write;
8525 io_bio->bi_end_io = btrfs_endio_direct_read;
8526 dip->subio_endio = btrfs_subio_endio_read;
8530 * Reset the range for unsubmitted ordered extents (to a 0 length range)
8531 * even if we fail to submit a bio, because in such case we do the
8532 * corresponding error handling below and it must not be done a second
8533 * time by btrfs_direct_IO().
8536 struct btrfs_dio_data *dio_data = current->journal_info;
8538 dio_data->unsubmitted_oe_range_end = dip->logical_offset +
8540 dio_data->unsubmitted_oe_range_start =
8541 dio_data->unsubmitted_oe_range_end;
8544 ret = btrfs_submit_direct_hook(dip, skip_sum);
8548 if (btrfs_bio->end_io)
8549 btrfs_bio->end_io(btrfs_bio, ret);
8553 * If we arrived here it means either we failed to submit the dip
8554 * or we either failed to clone the dio_bio or failed to allocate the
8555 * dip. If we cloned the dio_bio and allocated the dip, we can just
8556 * call bio_endio against our io_bio so that we get proper resource
8557 * cleanup if we fail to submit the dip, otherwise, we must do the
8558 * same as btrfs_endio_direct_[write|read] because we can't call these
8559 * callbacks - they require an allocated dip and a clone of dio_bio.
8561 if (io_bio && dip) {
8562 io_bio->bi_error = -EIO;
8565 * The end io callbacks free our dip, do the final put on io_bio
8566 * and all the cleanup and final put for dio_bio (through
8573 btrfs_endio_direct_write_update_ordered(inode,
8575 dio_bio->bi_iter.bi_size,
8578 unlock_extent(&BTRFS_I(inode)->io_tree, file_offset,
8579 file_offset + dio_bio->bi_iter.bi_size - 1);
8581 dio_bio->bi_error = -EIO;
8583 * Releases and cleans up our dio_bio, no need to bio_put()
8584 * nor bio_endio()/bio_io_error() against dio_bio.
8586 dio_end_io(dio_bio, ret);
8593 static ssize_t check_direct_IO(struct btrfs_root *root, struct kiocb *iocb,
8594 const struct iov_iter *iter, loff_t offset)
8598 unsigned blocksize_mask = root->sectorsize - 1;
8599 ssize_t retval = -EINVAL;
8601 if (offset & blocksize_mask)
8604 if (iov_iter_alignment(iter) & blocksize_mask)
8607 /* If this is a write we don't need to check anymore */
8608 if (iov_iter_rw(iter) == WRITE)
8611 * Check to make sure we don't have duplicate iov_base's in this
8612 * iovec, if so return EINVAL, otherwise we'll get csum errors
8613 * when reading back.
8615 for (seg = 0; seg < iter->nr_segs; seg++) {
8616 for (i = seg + 1; i < iter->nr_segs; i++) {
8617 if (iter->iov[seg].iov_base == iter->iov[i].iov_base)
8626 static ssize_t btrfs_direct_IO(struct kiocb *iocb, struct iov_iter *iter)
8628 struct file *file = iocb->ki_filp;
8629 struct inode *inode = file->f_mapping->host;
8630 struct btrfs_root *root = BTRFS_I(inode)->root;
8631 struct btrfs_dio_data dio_data = { 0 };
8632 loff_t offset = iocb->ki_pos;
8636 bool relock = false;
8639 if (check_direct_IO(BTRFS_I(inode)->root, iocb, iter, offset))
8642 inode_dio_begin(inode);
8643 smp_mb__after_atomic();
8646 * The generic stuff only does filemap_write_and_wait_range, which
8647 * isn't enough if we've written compressed pages to this area, so
8648 * we need to flush the dirty pages again to make absolutely sure
8649 * that any outstanding dirty pages are on disk.
8651 count = iov_iter_count(iter);
8652 if (test_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
8653 &BTRFS_I(inode)->runtime_flags))
8654 filemap_fdatawrite_range(inode->i_mapping, offset,
8655 offset + count - 1);
8657 if (iov_iter_rw(iter) == WRITE) {
8659 * If the write DIO is beyond the EOF, we need update
8660 * the isize, but it is protected by i_mutex. So we can
8661 * not unlock the i_mutex at this case.
8663 if (offset + count <= inode->i_size) {
8664 inode_unlock(inode);
8667 ret = btrfs_delalloc_reserve_space(inode, offset, count);
8670 dio_data.outstanding_extents = div64_u64(count +
8671 BTRFS_MAX_EXTENT_SIZE - 1,
8672 BTRFS_MAX_EXTENT_SIZE);
8675 * We need to know how many extents we reserved so that we can
8676 * do the accounting properly if we go over the number we
8677 * originally calculated. Abuse current->journal_info for this.
8679 dio_data.reserve = round_up(count, root->sectorsize);
8680 dio_data.unsubmitted_oe_range_start = (u64)offset;
8681 dio_data.unsubmitted_oe_range_end = (u64)offset;
8682 current->journal_info = &dio_data;
8683 } else if (test_bit(BTRFS_INODE_READDIO_NEED_LOCK,
8684 &BTRFS_I(inode)->runtime_flags)) {
8685 inode_dio_end(inode);
8686 flags = DIO_LOCKING | DIO_SKIP_HOLES;
8690 ret = __blockdev_direct_IO(iocb, inode,
8691 BTRFS_I(inode)->root->fs_info->fs_devices->latest_bdev,
8692 iter, btrfs_get_blocks_direct, NULL,
8693 btrfs_submit_direct, flags);
8694 if (iov_iter_rw(iter) == WRITE) {
8695 current->journal_info = NULL;
8696 if (ret < 0 && ret != -EIOCBQUEUED) {
8697 if (dio_data.reserve)
8698 btrfs_delalloc_release_space(inode, offset,
8701 * On error we might have left some ordered extents
8702 * without submitting corresponding bios for them, so
8703 * cleanup them up to avoid other tasks getting them
8704 * and waiting for them to complete forever.
8706 if (dio_data.unsubmitted_oe_range_start <
8707 dio_data.unsubmitted_oe_range_end)
8708 btrfs_endio_direct_write_update_ordered(inode,
8709 dio_data.unsubmitted_oe_range_start,
8710 dio_data.unsubmitted_oe_range_end -
8711 dio_data.unsubmitted_oe_range_start,
8713 } else if (ret >= 0 && (size_t)ret < count)
8714 btrfs_delalloc_release_space(inode, offset,
8715 count - (size_t)ret);
8719 inode_dio_end(inode);
8726 #define BTRFS_FIEMAP_FLAGS (FIEMAP_FLAG_SYNC)
8728 static int btrfs_fiemap(struct inode *inode, struct fiemap_extent_info *fieinfo,
8729 __u64 start, __u64 len)
8733 ret = fiemap_check_flags(fieinfo, BTRFS_FIEMAP_FLAGS);
8737 return extent_fiemap(inode, fieinfo, start, len, btrfs_get_extent_fiemap);
8740 int btrfs_readpage(struct file *file, struct page *page)
8742 struct extent_io_tree *tree;
8743 tree = &BTRFS_I(page->mapping->host)->io_tree;
8744 return extent_read_full_page(tree, page, btrfs_get_extent, 0);
8747 static int btrfs_writepage(struct page *page, struct writeback_control *wbc)
8749 struct extent_io_tree *tree;
8750 struct inode *inode = page->mapping->host;
8753 if (current->flags & PF_MEMALLOC) {
8754 redirty_page_for_writepage(wbc, page);
8760 * If we are under memory pressure we will call this directly from the
8761 * VM, we need to make sure we have the inode referenced for the ordered
8762 * extent. If not just return like we didn't do anything.
8764 if (!igrab(inode)) {
8765 redirty_page_for_writepage(wbc, page);
8766 return AOP_WRITEPAGE_ACTIVATE;
8768 tree = &BTRFS_I(page->mapping->host)->io_tree;
8769 ret = extent_write_full_page(tree, page, btrfs_get_extent, wbc);
8770 btrfs_add_delayed_iput(inode);
8774 static int btrfs_writepages(struct address_space *mapping,
8775 struct writeback_control *wbc)
8777 struct extent_io_tree *tree;
8779 tree = &BTRFS_I(mapping->host)->io_tree;
8780 return extent_writepages(tree, mapping, btrfs_get_extent, wbc);
8784 btrfs_readpages(struct file *file, struct address_space *mapping,
8785 struct list_head *pages, unsigned nr_pages)
8787 struct extent_io_tree *tree;
8788 tree = &BTRFS_I(mapping->host)->io_tree;
8789 return extent_readpages(tree, mapping, pages, nr_pages,
8792 static int __btrfs_releasepage(struct page *page, gfp_t gfp_flags)
8794 struct extent_io_tree *tree;
8795 struct extent_map_tree *map;
8798 tree = &BTRFS_I(page->mapping->host)->io_tree;
8799 map = &BTRFS_I(page->mapping->host)->extent_tree;
8800 ret = try_release_extent_mapping(map, tree, page, gfp_flags);
8802 ClearPagePrivate(page);
8803 set_page_private(page, 0);
8809 static int btrfs_releasepage(struct page *page, gfp_t gfp_flags)
8811 if (PageWriteback(page) || PageDirty(page))
8813 return __btrfs_releasepage(page, gfp_flags & GFP_NOFS);
8816 static void btrfs_invalidatepage(struct page *page, unsigned int offset,
8817 unsigned int length)
8819 struct inode *inode = page->mapping->host;
8820 struct extent_io_tree *tree;
8821 struct btrfs_ordered_extent *ordered;
8822 struct extent_state *cached_state = NULL;
8823 u64 page_start = page_offset(page);
8824 u64 page_end = page_start + PAGE_SIZE - 1;
8827 int inode_evicting = inode->i_state & I_FREEING;
8830 * we have the page locked, so new writeback can't start,
8831 * and the dirty bit won't be cleared while we are here.
8833 * Wait for IO on this page so that we can safely clear
8834 * the PagePrivate2 bit and do ordered accounting
8836 wait_on_page_writeback(page);
8838 tree = &BTRFS_I(inode)->io_tree;
8840 btrfs_releasepage(page, GFP_NOFS);
8844 if (!inode_evicting)
8845 lock_extent_bits(tree, page_start, page_end, &cached_state);
8848 ordered = btrfs_lookup_ordered_range(inode, start,
8849 page_end - start + 1);
8851 end = min(page_end, ordered->file_offset + ordered->len - 1);
8853 * IO on this page will never be started, so we need
8854 * to account for any ordered extents now
8856 if (!inode_evicting)
8857 clear_extent_bit(tree, start, end,
8858 EXTENT_DIRTY | EXTENT_DELALLOC |
8859 EXTENT_LOCKED | EXTENT_DO_ACCOUNTING |
8860 EXTENT_DEFRAG, 1, 0, &cached_state,
8863 * whoever cleared the private bit is responsible
8864 * for the finish_ordered_io
8866 if (TestClearPagePrivate2(page)) {
8867 struct btrfs_ordered_inode_tree *tree;
8870 tree = &BTRFS_I(inode)->ordered_tree;
8872 spin_lock_irq(&tree->lock);
8873 set_bit(BTRFS_ORDERED_TRUNCATED, &ordered->flags);
8874 new_len = start - ordered->file_offset;
8875 if (new_len < ordered->truncated_len)
8876 ordered->truncated_len = new_len;
8877 spin_unlock_irq(&tree->lock);
8879 if (btrfs_dec_test_ordered_pending(inode, &ordered,
8881 end - start + 1, 1))
8882 btrfs_finish_ordered_io(ordered);
8884 btrfs_put_ordered_extent(ordered);
8885 if (!inode_evicting) {
8886 cached_state = NULL;
8887 lock_extent_bits(tree, start, end,
8892 if (start < page_end)
8897 * Qgroup reserved space handler
8898 * Page here will be either
8899 * 1) Already written to disk
8900 * In this case, its reserved space is released from data rsv map
8901 * and will be freed by delayed_ref handler finally.
8902 * So even we call qgroup_free_data(), it won't decrease reserved
8904 * 2) Not written to disk
8905 * This means the reserved space should be freed here.
8907 btrfs_qgroup_free_data(inode, page_start, PAGE_SIZE);
8908 if (!inode_evicting) {
8909 clear_extent_bit(tree, page_start, page_end,
8910 EXTENT_LOCKED | EXTENT_DIRTY |
8911 EXTENT_DELALLOC | EXTENT_DO_ACCOUNTING |
8912 EXTENT_DEFRAG, 1, 1,
8913 &cached_state, GFP_NOFS);
8915 __btrfs_releasepage(page, GFP_NOFS);
8918 ClearPageChecked(page);
8919 if (PagePrivate(page)) {
8920 ClearPagePrivate(page);
8921 set_page_private(page, 0);
8927 * btrfs_page_mkwrite() is not allowed to change the file size as it gets
8928 * called from a page fault handler when a page is first dirtied. Hence we must
8929 * be careful to check for EOF conditions here. We set the page up correctly
8930 * for a written page which means we get ENOSPC checking when writing into
8931 * holes and correct delalloc and unwritten extent mapping on filesystems that
8932 * support these features.
8934 * We are not allowed to take the i_mutex here so we have to play games to
8935 * protect against truncate races as the page could now be beyond EOF. Because
8936 * vmtruncate() writes the inode size before removing pages, once we have the
8937 * page lock we can determine safely if the page is beyond EOF. If it is not
8938 * beyond EOF, then the page is guaranteed safe against truncation until we
8941 int btrfs_page_mkwrite(struct vm_area_struct *vma, struct vm_fault *vmf)
8943 struct page *page = vmf->page;
8944 struct inode *inode = file_inode(vma->vm_file);
8945 struct btrfs_root *root = BTRFS_I(inode)->root;
8946 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
8947 struct btrfs_ordered_extent *ordered;
8948 struct extent_state *cached_state = NULL;
8950 unsigned long zero_start;
8959 reserved_space = PAGE_SIZE;
8961 sb_start_pagefault(inode->i_sb);
8962 page_start = page_offset(page);
8963 page_end = page_start + PAGE_SIZE - 1;
8967 * Reserving delalloc space after obtaining the page lock can lead to
8968 * deadlock. For example, if a dirty page is locked by this function
8969 * and the call to btrfs_delalloc_reserve_space() ends up triggering
8970 * dirty page write out, then the btrfs_writepage() function could
8971 * end up waiting indefinitely to get a lock on the page currently
8972 * being processed by btrfs_page_mkwrite() function.
8974 ret = btrfs_delalloc_reserve_space(inode, page_start,
8977 ret = file_update_time(vma->vm_file);
8983 else /* -ENOSPC, -EIO, etc */
8984 ret = VM_FAULT_SIGBUS;
8990 ret = VM_FAULT_NOPAGE; /* make the VM retry the fault */
8993 size = i_size_read(inode);
8995 if ((page->mapping != inode->i_mapping) ||
8996 (page_start >= size)) {
8997 /* page got truncated out from underneath us */
9000 wait_on_page_writeback(page);
9002 lock_extent_bits(io_tree, page_start, page_end, &cached_state);
9003 set_page_extent_mapped(page);
9006 * we can't set the delalloc bits if there are pending ordered
9007 * extents. Drop our locks and wait for them to finish
9009 ordered = btrfs_lookup_ordered_range(inode, page_start, page_end);
9011 unlock_extent_cached(io_tree, page_start, page_end,
9012 &cached_state, GFP_NOFS);
9014 btrfs_start_ordered_extent(inode, ordered, 1);
9015 btrfs_put_ordered_extent(ordered);
9019 if (page->index == ((size - 1) >> PAGE_SHIFT)) {
9020 reserved_space = round_up(size - page_start, root->sectorsize);
9021 if (reserved_space < PAGE_SIZE) {
9022 end = page_start + reserved_space - 1;
9023 spin_lock(&BTRFS_I(inode)->lock);
9024 BTRFS_I(inode)->outstanding_extents++;
9025 spin_unlock(&BTRFS_I(inode)->lock);
9026 btrfs_delalloc_release_space(inode, page_start,
9027 PAGE_SIZE - reserved_space);
9032 * XXX - page_mkwrite gets called every time the page is dirtied, even
9033 * if it was already dirty, so for space accounting reasons we need to
9034 * clear any delalloc bits for the range we are fixing to save. There
9035 * is probably a better way to do this, but for now keep consistent with
9036 * prepare_pages in the normal write path.
9038 clear_extent_bit(&BTRFS_I(inode)->io_tree, page_start, end,
9039 EXTENT_DIRTY | EXTENT_DELALLOC |
9040 EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG,
9041 0, 0, &cached_state, GFP_NOFS);
9043 ret = btrfs_set_extent_delalloc(inode, page_start, end,
9046 unlock_extent_cached(io_tree, page_start, page_end,
9047 &cached_state, GFP_NOFS);
9048 ret = VM_FAULT_SIGBUS;
9053 /* page is wholly or partially inside EOF */
9054 if (page_start + PAGE_SIZE > size)
9055 zero_start = size & ~PAGE_MASK;
9057 zero_start = PAGE_SIZE;
9059 if (zero_start != PAGE_SIZE) {
9061 memset(kaddr + zero_start, 0, PAGE_SIZE - zero_start);
9062 flush_dcache_page(page);
9065 ClearPageChecked(page);
9066 set_page_dirty(page);
9067 SetPageUptodate(page);
9069 BTRFS_I(inode)->last_trans = root->fs_info->generation;
9070 BTRFS_I(inode)->last_sub_trans = BTRFS_I(inode)->root->log_transid;
9071 BTRFS_I(inode)->last_log_commit = BTRFS_I(inode)->root->last_log_commit;
9073 unlock_extent_cached(io_tree, page_start, page_end, &cached_state, GFP_NOFS);
9077 sb_end_pagefault(inode->i_sb);
9078 return VM_FAULT_LOCKED;
9082 btrfs_delalloc_release_space(inode, page_start, reserved_space);
9084 sb_end_pagefault(inode->i_sb);
9088 static int btrfs_truncate(struct inode *inode)
9090 struct btrfs_root *root = BTRFS_I(inode)->root;
9091 struct btrfs_block_rsv *rsv;
9094 struct btrfs_trans_handle *trans;
9095 u64 mask = root->sectorsize - 1;
9096 u64 min_size = btrfs_calc_trunc_metadata_size(root, 1);
9098 ret = btrfs_wait_ordered_range(inode, inode->i_size & (~mask),
9104 * Yes ladies and gentlemen, this is indeed ugly. The fact is we have
9105 * 3 things going on here
9107 * 1) We need to reserve space for our orphan item and the space to
9108 * delete our orphan item. Lord knows we don't want to have a dangling
9109 * orphan item because we didn't reserve space to remove it.
9111 * 2) We need to reserve space to update our inode.
9113 * 3) We need to have something to cache all the space that is going to
9114 * be free'd up by the truncate operation, but also have some slack
9115 * space reserved in case it uses space during the truncate (thank you
9116 * very much snapshotting).
9118 * And we need these to all be separate. The fact is we can use a lot of
9119 * space doing the truncate, and we have no earthly idea how much space
9120 * we will use, so we need the truncate reservation to be separate so it
9121 * doesn't end up using space reserved for updating the inode or
9122 * removing the orphan item. We also need to be able to stop the
9123 * transaction and start a new one, which means we need to be able to
9124 * update the inode several times, and we have no idea of knowing how
9125 * many times that will be, so we can't just reserve 1 item for the
9126 * entirety of the operation, so that has to be done separately as well.
9127 * Then there is the orphan item, which does indeed need to be held on
9128 * to for the whole operation, and we need nobody to touch this reserved
9129 * space except the orphan code.
9131 * So that leaves us with
9133 * 1) root->orphan_block_rsv - for the orphan deletion.
9134 * 2) rsv - for the truncate reservation, which we will steal from the
9135 * transaction reservation.
9136 * 3) fs_info->trans_block_rsv - this will have 1 items worth left for
9137 * updating the inode.
9139 rsv = btrfs_alloc_block_rsv(root, BTRFS_BLOCK_RSV_TEMP);
9142 rsv->size = min_size;
9146 * 1 for the truncate slack space
9147 * 1 for updating the inode.
9149 trans = btrfs_start_transaction(root, 2);
9150 if (IS_ERR(trans)) {
9151 err = PTR_ERR(trans);
9155 /* Migrate the slack space for the truncate to our reserve */
9156 ret = btrfs_block_rsv_migrate(&root->fs_info->trans_block_rsv, rsv,
9161 * So if we truncate and then write and fsync we normally would just
9162 * write the extents that changed, which is a problem if we need to
9163 * first truncate that entire inode. So set this flag so we write out
9164 * all of the extents in the inode to the sync log so we're completely
9167 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &BTRFS_I(inode)->runtime_flags);
9168 trans->block_rsv = rsv;
9171 ret = btrfs_truncate_inode_items(trans, root, inode,
9173 BTRFS_EXTENT_DATA_KEY);
9174 if (ret != -ENOSPC && ret != -EAGAIN) {
9179 trans->block_rsv = &root->fs_info->trans_block_rsv;
9180 ret = btrfs_update_inode(trans, root, inode);
9186 btrfs_end_transaction(trans, root);
9187 btrfs_btree_balance_dirty(root);
9189 trans = btrfs_start_transaction(root, 2);
9190 if (IS_ERR(trans)) {
9191 ret = err = PTR_ERR(trans);
9196 ret = btrfs_block_rsv_migrate(&root->fs_info->trans_block_rsv,
9198 BUG_ON(ret); /* shouldn't happen */
9199 trans->block_rsv = rsv;
9202 if (ret == 0 && inode->i_nlink > 0) {
9203 trans->block_rsv = root->orphan_block_rsv;
9204 ret = btrfs_orphan_del(trans, inode);
9210 trans->block_rsv = &root->fs_info->trans_block_rsv;
9211 ret = btrfs_update_inode(trans, root, inode);
9215 ret = btrfs_end_transaction(trans, root);
9216 btrfs_btree_balance_dirty(root);
9219 btrfs_free_block_rsv(root, rsv);
9228 * create a new subvolume directory/inode (helper for the ioctl).
9230 int btrfs_create_subvol_root(struct btrfs_trans_handle *trans,
9231 struct btrfs_root *new_root,
9232 struct btrfs_root *parent_root,
9235 struct inode *inode;
9239 inode = btrfs_new_inode(trans, new_root, NULL, "..", 2,
9240 new_dirid, new_dirid,
9241 S_IFDIR | (~current_umask() & S_IRWXUGO),
9244 return PTR_ERR(inode);
9245 inode->i_op = &btrfs_dir_inode_operations;
9246 inode->i_fop = &btrfs_dir_file_operations;
9248 set_nlink(inode, 1);
9249 btrfs_i_size_write(inode, 0);
9250 unlock_new_inode(inode);
9252 err = btrfs_subvol_inherit_props(trans, new_root, parent_root);
9254 btrfs_err(new_root->fs_info,
9255 "error inheriting subvolume %llu properties: %d",
9256 new_root->root_key.objectid, err);
9258 err = btrfs_update_inode(trans, new_root, inode);
9264 struct inode *btrfs_alloc_inode(struct super_block *sb)
9266 struct btrfs_inode *ei;
9267 struct inode *inode;
9269 ei = kmem_cache_alloc(btrfs_inode_cachep, GFP_NOFS);
9276 ei->last_sub_trans = 0;
9277 ei->logged_trans = 0;
9278 ei->delalloc_bytes = 0;
9279 ei->defrag_bytes = 0;
9280 ei->disk_i_size = 0;
9283 ei->index_cnt = (u64)-1;
9285 ei->last_unlink_trans = 0;
9286 ei->last_log_commit = 0;
9287 ei->delayed_iput_count = 0;
9289 spin_lock_init(&ei->lock);
9290 ei->outstanding_extents = 0;
9291 ei->reserved_extents = 0;
9293 ei->runtime_flags = 0;
9294 ei->force_compress = BTRFS_COMPRESS_NONE;
9296 ei->delayed_node = NULL;
9298 ei->i_otime.tv_sec = 0;
9299 ei->i_otime.tv_nsec = 0;
9301 inode = &ei->vfs_inode;
9302 extent_map_tree_init(&ei->extent_tree);
9303 extent_io_tree_init(&ei->io_tree, &inode->i_data);
9304 extent_io_tree_init(&ei->io_failure_tree, &inode->i_data);
9305 ei->io_tree.track_uptodate = 1;
9306 ei->io_failure_tree.track_uptodate = 1;
9307 atomic_set(&ei->sync_writers, 0);
9308 mutex_init(&ei->log_mutex);
9309 mutex_init(&ei->delalloc_mutex);
9310 btrfs_ordered_inode_tree_init(&ei->ordered_tree);
9311 INIT_LIST_HEAD(&ei->delalloc_inodes);
9312 INIT_LIST_HEAD(&ei->delayed_iput);
9313 RB_CLEAR_NODE(&ei->rb_node);
9314 init_rwsem(&ei->dio_sem);
9319 #ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
9320 void btrfs_test_destroy_inode(struct inode *inode)
9322 btrfs_drop_extent_cache(inode, 0, (u64)-1, 0);
9323 kmem_cache_free(btrfs_inode_cachep, BTRFS_I(inode));
9327 static void btrfs_i_callback(struct rcu_head *head)
9329 struct inode *inode = container_of(head, struct inode, i_rcu);
9330 kmem_cache_free(btrfs_inode_cachep, BTRFS_I(inode));
9333 void btrfs_destroy_inode(struct inode *inode)
9335 struct btrfs_ordered_extent *ordered;
9336 struct btrfs_root *root = BTRFS_I(inode)->root;
9338 WARN_ON(!hlist_empty(&inode->i_dentry));
9339 WARN_ON(inode->i_data.nrpages);
9340 WARN_ON(BTRFS_I(inode)->outstanding_extents);
9341 WARN_ON(BTRFS_I(inode)->reserved_extents);
9342 WARN_ON(BTRFS_I(inode)->delalloc_bytes);
9343 WARN_ON(BTRFS_I(inode)->csum_bytes);
9344 WARN_ON(BTRFS_I(inode)->defrag_bytes);
9347 * This can happen where we create an inode, but somebody else also
9348 * created the same inode and we need to destroy the one we already
9354 if (test_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
9355 &BTRFS_I(inode)->runtime_flags)) {
9356 btrfs_info(root->fs_info, "inode %llu still on the orphan list",
9358 atomic_dec(&root->orphan_inodes);
9362 ordered = btrfs_lookup_first_ordered_extent(inode, (u64)-1);
9366 btrfs_err(root->fs_info, "found ordered extent %llu %llu on inode cleanup",
9367 ordered->file_offset, ordered->len);
9368 btrfs_remove_ordered_extent(inode, ordered);
9369 btrfs_put_ordered_extent(ordered);
9370 btrfs_put_ordered_extent(ordered);
9373 btrfs_qgroup_check_reserved_leak(inode);
9374 inode_tree_del(inode);
9375 btrfs_drop_extent_cache(inode, 0, (u64)-1, 0);
9377 call_rcu(&inode->i_rcu, btrfs_i_callback);
9380 int btrfs_drop_inode(struct inode *inode)
9382 struct btrfs_root *root = BTRFS_I(inode)->root;
9387 /* the snap/subvol tree is on deleting */
9388 if (btrfs_root_refs(&root->root_item) == 0)
9391 return generic_drop_inode(inode);
9394 static void init_once(void *foo)
9396 struct btrfs_inode *ei = (struct btrfs_inode *) foo;
9398 inode_init_once(&ei->vfs_inode);
9401 void btrfs_destroy_cachep(void)
9404 * Make sure all delayed rcu free inodes are flushed before we
9408 kmem_cache_destroy(btrfs_inode_cachep);
9409 kmem_cache_destroy(btrfs_trans_handle_cachep);
9410 kmem_cache_destroy(btrfs_transaction_cachep);
9411 kmem_cache_destroy(btrfs_path_cachep);
9412 kmem_cache_destroy(btrfs_free_space_cachep);
9415 int btrfs_init_cachep(void)
9417 btrfs_inode_cachep = kmem_cache_create("btrfs_inode",
9418 sizeof(struct btrfs_inode), 0,
9419 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD | SLAB_ACCOUNT,
9421 if (!btrfs_inode_cachep)
9424 btrfs_trans_handle_cachep = kmem_cache_create("btrfs_trans_handle",
9425 sizeof(struct btrfs_trans_handle), 0,
9426 SLAB_TEMPORARY | SLAB_MEM_SPREAD, NULL);
9427 if (!btrfs_trans_handle_cachep)
9430 btrfs_transaction_cachep = kmem_cache_create("btrfs_transaction",
9431 sizeof(struct btrfs_transaction), 0,
9432 SLAB_TEMPORARY | SLAB_MEM_SPREAD, NULL);
9433 if (!btrfs_transaction_cachep)
9436 btrfs_path_cachep = kmem_cache_create("btrfs_path",
9437 sizeof(struct btrfs_path), 0,
9438 SLAB_MEM_SPREAD, NULL);
9439 if (!btrfs_path_cachep)
9442 btrfs_free_space_cachep = kmem_cache_create("btrfs_free_space",
9443 sizeof(struct btrfs_free_space), 0,
9444 SLAB_MEM_SPREAD, NULL);
9445 if (!btrfs_free_space_cachep)
9450 btrfs_destroy_cachep();
9454 static int btrfs_getattr(struct vfsmount *mnt,
9455 struct dentry *dentry, struct kstat *stat)
9458 struct inode *inode = d_inode(dentry);
9459 u32 blocksize = inode->i_sb->s_blocksize;
9461 generic_fillattr(inode, stat);
9462 stat->dev = BTRFS_I(inode)->root->anon_dev;
9464 spin_lock(&BTRFS_I(inode)->lock);
9465 delalloc_bytes = BTRFS_I(inode)->delalloc_bytes;
9466 spin_unlock(&BTRFS_I(inode)->lock);
9467 stat->blocks = (ALIGN(inode_get_bytes(inode), blocksize) +
9468 ALIGN(delalloc_bytes, blocksize)) >> 9;
9472 static int btrfs_rename_exchange(struct inode *old_dir,
9473 struct dentry *old_dentry,
9474 struct inode *new_dir,
9475 struct dentry *new_dentry)
9477 struct btrfs_trans_handle *trans;
9478 struct btrfs_root *root = BTRFS_I(old_dir)->root;
9479 struct btrfs_root *dest = BTRFS_I(new_dir)->root;
9480 struct inode *new_inode = new_dentry->d_inode;
9481 struct inode *old_inode = old_dentry->d_inode;
9482 struct timespec ctime = CURRENT_TIME;
9483 struct dentry *parent;
9484 u64 old_ino = btrfs_ino(old_inode);
9485 u64 new_ino = btrfs_ino(new_inode);
9490 bool root_log_pinned = false;
9491 bool dest_log_pinned = false;
9493 /* we only allow rename subvolume link between subvolumes */
9494 if (old_ino != BTRFS_FIRST_FREE_OBJECTID && root != dest)
9497 /* close the race window with snapshot create/destroy ioctl */
9498 if (old_ino == BTRFS_FIRST_FREE_OBJECTID)
9499 down_read(&root->fs_info->subvol_sem);
9500 if (new_ino == BTRFS_FIRST_FREE_OBJECTID)
9501 down_read(&dest->fs_info->subvol_sem);
9504 * We want to reserve the absolute worst case amount of items. So if
9505 * both inodes are subvols and we need to unlink them then that would
9506 * require 4 item modifications, but if they are both normal inodes it
9507 * would require 5 item modifications, so we'll assume their normal
9508 * inodes. So 5 * 2 is 10, plus 2 for the new links, so 12 total items
9509 * should cover the worst case number of items we'll modify.
9511 trans = btrfs_start_transaction(root, 12);
9512 if (IS_ERR(trans)) {
9513 ret = PTR_ERR(trans);
9518 * We need to find a free sequence number both in the source and
9519 * in the destination directory for the exchange.
9521 ret = btrfs_set_inode_index(new_dir, &old_idx);
9524 ret = btrfs_set_inode_index(old_dir, &new_idx);
9528 BTRFS_I(old_inode)->dir_index = 0ULL;
9529 BTRFS_I(new_inode)->dir_index = 0ULL;
9531 /* Reference for the source. */
9532 if (old_ino == BTRFS_FIRST_FREE_OBJECTID) {
9533 /* force full log commit if subvolume involved. */
9534 btrfs_set_log_full_commit(root->fs_info, trans);
9536 btrfs_pin_log_trans(root);
9537 root_log_pinned = true;
9538 ret = btrfs_insert_inode_ref(trans, dest,
9539 new_dentry->d_name.name,
9540 new_dentry->d_name.len,
9542 btrfs_ino(new_dir), old_idx);
9547 /* And now for the dest. */
9548 if (new_ino == BTRFS_FIRST_FREE_OBJECTID) {
9549 /* force full log commit if subvolume involved. */
9550 btrfs_set_log_full_commit(dest->fs_info, trans);
9552 btrfs_pin_log_trans(dest);
9553 dest_log_pinned = true;
9554 ret = btrfs_insert_inode_ref(trans, root,
9555 old_dentry->d_name.name,
9556 old_dentry->d_name.len,
9558 btrfs_ino(old_dir), new_idx);
9563 /* Update inode version and ctime/mtime. */
9564 inode_inc_iversion(old_dir);
9565 inode_inc_iversion(new_dir);
9566 inode_inc_iversion(old_inode);
9567 inode_inc_iversion(new_inode);
9568 old_dir->i_ctime = old_dir->i_mtime = ctime;
9569 new_dir->i_ctime = new_dir->i_mtime = ctime;
9570 old_inode->i_ctime = ctime;
9571 new_inode->i_ctime = ctime;
9573 if (old_dentry->d_parent != new_dentry->d_parent) {
9574 btrfs_record_unlink_dir(trans, old_dir, old_inode, 1);
9575 btrfs_record_unlink_dir(trans, new_dir, new_inode, 1);
9578 /* src is a subvolume */
9579 if (old_ino == BTRFS_FIRST_FREE_OBJECTID) {
9580 root_objectid = BTRFS_I(old_inode)->root->root_key.objectid;
9581 ret = btrfs_unlink_subvol(trans, root, old_dir,
9583 old_dentry->d_name.name,
9584 old_dentry->d_name.len);
9585 } else { /* src is an inode */
9586 ret = __btrfs_unlink_inode(trans, root, old_dir,
9587 old_dentry->d_inode,
9588 old_dentry->d_name.name,
9589 old_dentry->d_name.len);
9591 ret = btrfs_update_inode(trans, root, old_inode);
9594 btrfs_abort_transaction(trans, ret);
9598 /* dest is a subvolume */
9599 if (new_ino == BTRFS_FIRST_FREE_OBJECTID) {
9600 root_objectid = BTRFS_I(new_inode)->root->root_key.objectid;
9601 ret = btrfs_unlink_subvol(trans, dest, new_dir,
9603 new_dentry->d_name.name,
9604 new_dentry->d_name.len);
9605 } else { /* dest is an inode */
9606 ret = __btrfs_unlink_inode(trans, dest, new_dir,
9607 new_dentry->d_inode,
9608 new_dentry->d_name.name,
9609 new_dentry->d_name.len);
9611 ret = btrfs_update_inode(trans, dest, new_inode);
9614 btrfs_abort_transaction(trans, ret);
9618 ret = btrfs_add_link(trans, new_dir, old_inode,
9619 new_dentry->d_name.name,
9620 new_dentry->d_name.len, 0, old_idx);
9622 btrfs_abort_transaction(trans, ret);
9626 ret = btrfs_add_link(trans, old_dir, new_inode,
9627 old_dentry->d_name.name,
9628 old_dentry->d_name.len, 0, new_idx);
9630 btrfs_abort_transaction(trans, ret);
9634 if (old_inode->i_nlink == 1)
9635 BTRFS_I(old_inode)->dir_index = old_idx;
9636 if (new_inode->i_nlink == 1)
9637 BTRFS_I(new_inode)->dir_index = new_idx;
9639 if (root_log_pinned) {
9640 parent = new_dentry->d_parent;
9641 btrfs_log_new_name(trans, old_inode, old_dir, parent);
9642 btrfs_end_log_trans(root);
9643 root_log_pinned = false;
9645 if (dest_log_pinned) {
9646 parent = old_dentry->d_parent;
9647 btrfs_log_new_name(trans, new_inode, new_dir, parent);
9648 btrfs_end_log_trans(dest);
9649 dest_log_pinned = false;
9653 * If we have pinned a log and an error happened, we unpin tasks
9654 * trying to sync the log and force them to fallback to a transaction
9655 * commit if the log currently contains any of the inodes involved in
9656 * this rename operation (to ensure we do not persist a log with an
9657 * inconsistent state for any of these inodes or leading to any
9658 * inconsistencies when replayed). If the transaction was aborted, the
9659 * abortion reason is propagated to userspace when attempting to commit
9660 * the transaction. If the log does not contain any of these inodes, we
9661 * allow the tasks to sync it.
9663 if (ret && (root_log_pinned || dest_log_pinned)) {
9664 if (btrfs_inode_in_log(old_dir, root->fs_info->generation) ||
9665 btrfs_inode_in_log(new_dir, root->fs_info->generation) ||
9666 btrfs_inode_in_log(old_inode, root->fs_info->generation) ||
9668 btrfs_inode_in_log(new_inode, root->fs_info->generation)))
9669 btrfs_set_log_full_commit(root->fs_info, trans);
9671 if (root_log_pinned) {
9672 btrfs_end_log_trans(root);
9673 root_log_pinned = false;
9675 if (dest_log_pinned) {
9676 btrfs_end_log_trans(dest);
9677 dest_log_pinned = false;
9680 ret = btrfs_end_transaction(trans, root);
9682 if (new_ino == BTRFS_FIRST_FREE_OBJECTID)
9683 up_read(&dest->fs_info->subvol_sem);
9684 if (old_ino == BTRFS_FIRST_FREE_OBJECTID)
9685 up_read(&root->fs_info->subvol_sem);
9690 static int btrfs_whiteout_for_rename(struct btrfs_trans_handle *trans,
9691 struct btrfs_root *root,
9693 struct dentry *dentry)
9696 struct inode *inode;
9700 ret = btrfs_find_free_ino(root, &objectid);
9704 inode = btrfs_new_inode(trans, root, dir,
9705 dentry->d_name.name,
9709 S_IFCHR | WHITEOUT_MODE,
9712 if (IS_ERR(inode)) {
9713 ret = PTR_ERR(inode);
9717 inode->i_op = &btrfs_special_inode_operations;
9718 init_special_inode(inode, inode->i_mode,
9721 ret = btrfs_init_inode_security(trans, inode, dir,
9726 ret = btrfs_add_nondir(trans, dir, dentry,
9731 ret = btrfs_update_inode(trans, root, inode);
9733 unlock_new_inode(inode);
9735 inode_dec_link_count(inode);
9741 static int btrfs_rename(struct inode *old_dir, struct dentry *old_dentry,
9742 struct inode *new_dir, struct dentry *new_dentry,
9745 struct btrfs_trans_handle *trans;
9746 unsigned int trans_num_items;
9747 struct btrfs_root *root = BTRFS_I(old_dir)->root;
9748 struct btrfs_root *dest = BTRFS_I(new_dir)->root;
9749 struct inode *new_inode = d_inode(new_dentry);
9750 struct inode *old_inode = d_inode(old_dentry);
9754 u64 old_ino = btrfs_ino(old_inode);
9755 bool log_pinned = false;
9757 if (btrfs_ino(new_dir) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)
9760 /* we only allow rename subvolume link between subvolumes */
9761 if (old_ino != BTRFS_FIRST_FREE_OBJECTID && root != dest)
9764 if (old_ino == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID ||
9765 (new_inode && btrfs_ino(new_inode) == BTRFS_FIRST_FREE_OBJECTID))
9768 if (S_ISDIR(old_inode->i_mode) && new_inode &&
9769 new_inode->i_size > BTRFS_EMPTY_DIR_SIZE)
9773 /* check for collisions, even if the name isn't there */
9774 ret = btrfs_check_dir_item_collision(dest, new_dir->i_ino,
9775 new_dentry->d_name.name,
9776 new_dentry->d_name.len);
9779 if (ret == -EEXIST) {
9781 * eexist without a new_inode */
9782 if (WARN_ON(!new_inode)) {
9786 /* maybe -EOVERFLOW */
9793 * we're using rename to replace one file with another. Start IO on it
9794 * now so we don't add too much work to the end of the transaction
9796 if (new_inode && S_ISREG(old_inode->i_mode) && new_inode->i_size)
9797 filemap_flush(old_inode->i_mapping);
9799 /* close the racy window with snapshot create/destroy ioctl */
9800 if (old_ino == BTRFS_FIRST_FREE_OBJECTID)
9801 down_read(&root->fs_info->subvol_sem);
9803 * We want to reserve the absolute worst case amount of items. So if
9804 * both inodes are subvols and we need to unlink them then that would
9805 * require 4 item modifications, but if they are both normal inodes it
9806 * would require 5 item modifications, so we'll assume they are normal
9807 * inodes. So 5 * 2 is 10, plus 1 for the new link, so 11 total items
9808 * should cover the worst case number of items we'll modify.
9809 * If our rename has the whiteout flag, we need more 5 units for the
9810 * new inode (1 inode item, 1 inode ref, 2 dir items and 1 xattr item
9811 * when selinux is enabled).
9813 trans_num_items = 11;
9814 if (flags & RENAME_WHITEOUT)
9815 trans_num_items += 5;
9816 trans = btrfs_start_transaction(root, trans_num_items);
9817 if (IS_ERR(trans)) {
9818 ret = PTR_ERR(trans);
9823 btrfs_record_root_in_trans(trans, dest);
9825 ret = btrfs_set_inode_index(new_dir, &index);
9829 BTRFS_I(old_inode)->dir_index = 0ULL;
9830 if (unlikely(old_ino == BTRFS_FIRST_FREE_OBJECTID)) {
9831 /* force full log commit if subvolume involved. */
9832 btrfs_set_log_full_commit(root->fs_info, trans);
9834 btrfs_pin_log_trans(root);
9836 ret = btrfs_insert_inode_ref(trans, dest,
9837 new_dentry->d_name.name,
9838 new_dentry->d_name.len,
9840 btrfs_ino(new_dir), index);
9845 inode_inc_iversion(old_dir);
9846 inode_inc_iversion(new_dir);
9847 inode_inc_iversion(old_inode);
9848 old_dir->i_ctime = old_dir->i_mtime =
9849 new_dir->i_ctime = new_dir->i_mtime =
9850 old_inode->i_ctime = current_fs_time(old_dir->i_sb);
9852 if (old_dentry->d_parent != new_dentry->d_parent)
9853 btrfs_record_unlink_dir(trans, old_dir, old_inode, 1);
9855 if (unlikely(old_ino == BTRFS_FIRST_FREE_OBJECTID)) {
9856 root_objectid = BTRFS_I(old_inode)->root->root_key.objectid;
9857 ret = btrfs_unlink_subvol(trans, root, old_dir, root_objectid,
9858 old_dentry->d_name.name,
9859 old_dentry->d_name.len);
9861 ret = __btrfs_unlink_inode(trans, root, old_dir,
9862 d_inode(old_dentry),
9863 old_dentry->d_name.name,
9864 old_dentry->d_name.len);
9866 ret = btrfs_update_inode(trans, root, old_inode);
9869 btrfs_abort_transaction(trans, ret);
9874 inode_inc_iversion(new_inode);
9875 new_inode->i_ctime = current_fs_time(new_inode->i_sb);
9876 if (unlikely(btrfs_ino(new_inode) ==
9877 BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)) {
9878 root_objectid = BTRFS_I(new_inode)->location.objectid;
9879 ret = btrfs_unlink_subvol(trans, dest, new_dir,
9881 new_dentry->d_name.name,
9882 new_dentry->d_name.len);
9883 BUG_ON(new_inode->i_nlink == 0);
9885 ret = btrfs_unlink_inode(trans, dest, new_dir,
9886 d_inode(new_dentry),
9887 new_dentry->d_name.name,
9888 new_dentry->d_name.len);
9890 if (!ret && new_inode->i_nlink == 0)
9891 ret = btrfs_orphan_add(trans, d_inode(new_dentry));
9893 btrfs_abort_transaction(trans, ret);
9898 ret = btrfs_add_link(trans, new_dir, old_inode,
9899 new_dentry->d_name.name,
9900 new_dentry->d_name.len, 0, index);
9902 btrfs_abort_transaction(trans, ret);
9906 if (old_inode->i_nlink == 1)
9907 BTRFS_I(old_inode)->dir_index = index;
9910 struct dentry *parent = new_dentry->d_parent;
9912 btrfs_log_new_name(trans, old_inode, old_dir, parent);
9913 btrfs_end_log_trans(root);
9917 if (flags & RENAME_WHITEOUT) {
9918 ret = btrfs_whiteout_for_rename(trans, root, old_dir,
9922 btrfs_abort_transaction(trans, ret);
9928 * If we have pinned the log and an error happened, we unpin tasks
9929 * trying to sync the log and force them to fallback to a transaction
9930 * commit if the log currently contains any of the inodes involved in
9931 * this rename operation (to ensure we do not persist a log with an
9932 * inconsistent state for any of these inodes or leading to any
9933 * inconsistencies when replayed). If the transaction was aborted, the
9934 * abortion reason is propagated to userspace when attempting to commit
9935 * the transaction. If the log does not contain any of these inodes, we
9936 * allow the tasks to sync it.
9938 if (ret && log_pinned) {
9939 if (btrfs_inode_in_log(old_dir, root->fs_info->generation) ||
9940 btrfs_inode_in_log(new_dir, root->fs_info->generation) ||
9941 btrfs_inode_in_log(old_inode, root->fs_info->generation) ||
9943 btrfs_inode_in_log(new_inode, root->fs_info->generation)))
9944 btrfs_set_log_full_commit(root->fs_info, trans);
9946 btrfs_end_log_trans(root);
9949 btrfs_end_transaction(trans, root);
9951 if (old_ino == BTRFS_FIRST_FREE_OBJECTID)
9952 up_read(&root->fs_info->subvol_sem);
9957 static int btrfs_rename2(struct inode *old_dir, struct dentry *old_dentry,
9958 struct inode *new_dir, struct dentry *new_dentry,
9961 if (flags & ~(RENAME_NOREPLACE | RENAME_EXCHANGE | RENAME_WHITEOUT))
9964 if (flags & RENAME_EXCHANGE)
9965 return btrfs_rename_exchange(old_dir, old_dentry, new_dir,
9968 return btrfs_rename(old_dir, old_dentry, new_dir, new_dentry, flags);
9971 static void btrfs_run_delalloc_work(struct btrfs_work *work)
9973 struct btrfs_delalloc_work *delalloc_work;
9974 struct inode *inode;
9976 delalloc_work = container_of(work, struct btrfs_delalloc_work,
9978 inode = delalloc_work->inode;
9979 filemap_flush(inode->i_mapping);
9980 if (test_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
9981 &BTRFS_I(inode)->runtime_flags))
9982 filemap_flush(inode->i_mapping);
9984 if (delalloc_work->delay_iput)
9985 btrfs_add_delayed_iput(inode);
9988 complete(&delalloc_work->completion);
9991 struct btrfs_delalloc_work *btrfs_alloc_delalloc_work(struct inode *inode,
9994 struct btrfs_delalloc_work *work;
9996 work = kmalloc(sizeof(*work), GFP_NOFS);
10000 init_completion(&work->completion);
10001 INIT_LIST_HEAD(&work->list);
10002 work->inode = inode;
10003 work->delay_iput = delay_iput;
10004 WARN_ON_ONCE(!inode);
10005 btrfs_init_work(&work->work, btrfs_flush_delalloc_helper,
10006 btrfs_run_delalloc_work, NULL, NULL);
10011 void btrfs_wait_and_free_delalloc_work(struct btrfs_delalloc_work *work)
10013 wait_for_completion(&work->completion);
10018 * some fairly slow code that needs optimization. This walks the list
10019 * of all the inodes with pending delalloc and forces them to disk.
10021 static int __start_delalloc_inodes(struct btrfs_root *root, int delay_iput,
10024 struct btrfs_inode *binode;
10025 struct inode *inode;
10026 struct btrfs_delalloc_work *work, *next;
10027 struct list_head works;
10028 struct list_head splice;
10031 INIT_LIST_HEAD(&works);
10032 INIT_LIST_HEAD(&splice);
10034 mutex_lock(&root->delalloc_mutex);
10035 spin_lock(&root->delalloc_lock);
10036 list_splice_init(&root->delalloc_inodes, &splice);
10037 while (!list_empty(&splice)) {
10038 binode = list_entry(splice.next, struct btrfs_inode,
10041 list_move_tail(&binode->delalloc_inodes,
10042 &root->delalloc_inodes);
10043 inode = igrab(&binode->vfs_inode);
10045 cond_resched_lock(&root->delalloc_lock);
10048 spin_unlock(&root->delalloc_lock);
10050 work = btrfs_alloc_delalloc_work(inode, delay_iput);
10053 btrfs_add_delayed_iput(inode);
10059 list_add_tail(&work->list, &works);
10060 btrfs_queue_work(root->fs_info->flush_workers,
10063 if (nr != -1 && ret >= nr)
10066 spin_lock(&root->delalloc_lock);
10068 spin_unlock(&root->delalloc_lock);
10071 list_for_each_entry_safe(work, next, &works, list) {
10072 list_del_init(&work->list);
10073 btrfs_wait_and_free_delalloc_work(work);
10076 if (!list_empty_careful(&splice)) {
10077 spin_lock(&root->delalloc_lock);
10078 list_splice_tail(&splice, &root->delalloc_inodes);
10079 spin_unlock(&root->delalloc_lock);
10081 mutex_unlock(&root->delalloc_mutex);
10085 int btrfs_start_delalloc_inodes(struct btrfs_root *root, int delay_iput)
10089 if (test_bit(BTRFS_FS_STATE_ERROR, &root->fs_info->fs_state))
10092 ret = __start_delalloc_inodes(root, delay_iput, -1);
10096 * the filemap_flush will queue IO into the worker threads, but
10097 * we have to make sure the IO is actually started and that
10098 * ordered extents get created before we return
10100 atomic_inc(&root->fs_info->async_submit_draining);
10101 while (atomic_read(&root->fs_info->nr_async_submits) ||
10102 atomic_read(&root->fs_info->async_delalloc_pages)) {
10103 wait_event(root->fs_info->async_submit_wait,
10104 (atomic_read(&root->fs_info->nr_async_submits) == 0 &&
10105 atomic_read(&root->fs_info->async_delalloc_pages) == 0));
10107 atomic_dec(&root->fs_info->async_submit_draining);
10111 int btrfs_start_delalloc_roots(struct btrfs_fs_info *fs_info, int delay_iput,
10114 struct btrfs_root *root;
10115 struct list_head splice;
10118 if (test_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state))
10121 INIT_LIST_HEAD(&splice);
10123 mutex_lock(&fs_info->delalloc_root_mutex);
10124 spin_lock(&fs_info->delalloc_root_lock);
10125 list_splice_init(&fs_info->delalloc_roots, &splice);
10126 while (!list_empty(&splice) && nr) {
10127 root = list_first_entry(&splice, struct btrfs_root,
10129 root = btrfs_grab_fs_root(root);
10131 list_move_tail(&root->delalloc_root,
10132 &fs_info->delalloc_roots);
10133 spin_unlock(&fs_info->delalloc_root_lock);
10135 ret = __start_delalloc_inodes(root, delay_iput, nr);
10136 btrfs_put_fs_root(root);
10144 spin_lock(&fs_info->delalloc_root_lock);
10146 spin_unlock(&fs_info->delalloc_root_lock);
10149 atomic_inc(&fs_info->async_submit_draining);
10150 while (atomic_read(&fs_info->nr_async_submits) ||
10151 atomic_read(&fs_info->async_delalloc_pages)) {
10152 wait_event(fs_info->async_submit_wait,
10153 (atomic_read(&fs_info->nr_async_submits) == 0 &&
10154 atomic_read(&fs_info->async_delalloc_pages) == 0));
10156 atomic_dec(&fs_info->async_submit_draining);
10158 if (!list_empty_careful(&splice)) {
10159 spin_lock(&fs_info->delalloc_root_lock);
10160 list_splice_tail(&splice, &fs_info->delalloc_roots);
10161 spin_unlock(&fs_info->delalloc_root_lock);
10163 mutex_unlock(&fs_info->delalloc_root_mutex);
10167 static int btrfs_symlink(struct inode *dir, struct dentry *dentry,
10168 const char *symname)
10170 struct btrfs_trans_handle *trans;
10171 struct btrfs_root *root = BTRFS_I(dir)->root;
10172 struct btrfs_path *path;
10173 struct btrfs_key key;
10174 struct inode *inode = NULL;
10176 int drop_inode = 0;
10182 struct btrfs_file_extent_item *ei;
10183 struct extent_buffer *leaf;
10185 name_len = strlen(symname);
10186 if (name_len > BTRFS_MAX_INLINE_DATA_SIZE(root))
10187 return -ENAMETOOLONG;
10190 * 2 items for inode item and ref
10191 * 2 items for dir items
10192 * 1 item for updating parent inode item
10193 * 1 item for the inline extent item
10194 * 1 item for xattr if selinux is on
10196 trans = btrfs_start_transaction(root, 7);
10198 return PTR_ERR(trans);
10200 err = btrfs_find_free_ino(root, &objectid);
10204 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
10205 dentry->d_name.len, btrfs_ino(dir), objectid,
10206 S_IFLNK|S_IRWXUGO, &index);
10207 if (IS_ERR(inode)) {
10208 err = PTR_ERR(inode);
10213 * If the active LSM wants to access the inode during
10214 * d_instantiate it needs these. Smack checks to see
10215 * if the filesystem supports xattrs by looking at the
10218 inode->i_fop = &btrfs_file_operations;
10219 inode->i_op = &btrfs_file_inode_operations;
10220 inode->i_mapping->a_ops = &btrfs_aops;
10221 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
10223 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
10225 goto out_unlock_inode;
10227 path = btrfs_alloc_path();
10230 goto out_unlock_inode;
10232 key.objectid = btrfs_ino(inode);
10234 key.type = BTRFS_EXTENT_DATA_KEY;
10235 datasize = btrfs_file_extent_calc_inline_size(name_len);
10236 err = btrfs_insert_empty_item(trans, root, path, &key,
10239 btrfs_free_path(path);
10240 goto out_unlock_inode;
10242 leaf = path->nodes[0];
10243 ei = btrfs_item_ptr(leaf, path->slots[0],
10244 struct btrfs_file_extent_item);
10245 btrfs_set_file_extent_generation(leaf, ei, trans->transid);
10246 btrfs_set_file_extent_type(leaf, ei,
10247 BTRFS_FILE_EXTENT_INLINE);
10248 btrfs_set_file_extent_encryption(leaf, ei, 0);
10249 btrfs_set_file_extent_compression(leaf, ei, 0);
10250 btrfs_set_file_extent_other_encoding(leaf, ei, 0);
10251 btrfs_set_file_extent_ram_bytes(leaf, ei, name_len);
10253 ptr = btrfs_file_extent_inline_start(ei);
10254 write_extent_buffer(leaf, symname, ptr, name_len);
10255 btrfs_mark_buffer_dirty(leaf);
10256 btrfs_free_path(path);
10258 inode->i_op = &btrfs_symlink_inode_operations;
10259 inode_nohighmem(inode);
10260 inode->i_mapping->a_ops = &btrfs_symlink_aops;
10261 inode_set_bytes(inode, name_len);
10262 btrfs_i_size_write(inode, name_len);
10263 err = btrfs_update_inode(trans, root, inode);
10265 * Last step, add directory indexes for our symlink inode. This is the
10266 * last step to avoid extra cleanup of these indexes if an error happens
10270 err = btrfs_add_nondir(trans, dir, dentry, inode, 0, index);
10273 goto out_unlock_inode;
10276 unlock_new_inode(inode);
10277 d_instantiate(dentry, inode);
10280 btrfs_end_transaction(trans, root);
10282 inode_dec_link_count(inode);
10285 btrfs_btree_balance_dirty(root);
10290 unlock_new_inode(inode);
10294 static int __btrfs_prealloc_file_range(struct inode *inode, int mode,
10295 u64 start, u64 num_bytes, u64 min_size,
10296 loff_t actual_len, u64 *alloc_hint,
10297 struct btrfs_trans_handle *trans)
10299 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
10300 struct extent_map *em;
10301 struct btrfs_root *root = BTRFS_I(inode)->root;
10302 struct btrfs_key ins;
10303 u64 cur_offset = start;
10306 u64 last_alloc = (u64)-1;
10308 bool own_trans = true;
10312 while (num_bytes > 0) {
10314 trans = btrfs_start_transaction(root, 3);
10315 if (IS_ERR(trans)) {
10316 ret = PTR_ERR(trans);
10321 cur_bytes = min_t(u64, num_bytes, SZ_256M);
10322 cur_bytes = max(cur_bytes, min_size);
10324 * If we are severely fragmented we could end up with really
10325 * small allocations, so if the allocator is returning small
10326 * chunks lets make its job easier by only searching for those
10329 cur_bytes = min(cur_bytes, last_alloc);
10330 ret = btrfs_reserve_extent(root, cur_bytes, min_size, 0,
10331 *alloc_hint, &ins, 1, 0);
10334 btrfs_end_transaction(trans, root);
10337 btrfs_dec_block_group_reservations(root->fs_info, ins.objectid);
10339 last_alloc = ins.offset;
10340 ret = insert_reserved_file_extent(trans, inode,
10341 cur_offset, ins.objectid,
10342 ins.offset, ins.offset,
10343 ins.offset, 0, 0, 0,
10344 BTRFS_FILE_EXTENT_PREALLOC);
10346 btrfs_free_reserved_extent(root, ins.objectid,
10348 btrfs_abort_transaction(trans, ret);
10350 btrfs_end_transaction(trans, root);
10354 btrfs_drop_extent_cache(inode, cur_offset,
10355 cur_offset + ins.offset -1, 0);
10357 em = alloc_extent_map();
10359 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
10360 &BTRFS_I(inode)->runtime_flags);
10364 em->start = cur_offset;
10365 em->orig_start = cur_offset;
10366 em->len = ins.offset;
10367 em->block_start = ins.objectid;
10368 em->block_len = ins.offset;
10369 em->orig_block_len = ins.offset;
10370 em->ram_bytes = ins.offset;
10371 em->bdev = root->fs_info->fs_devices->latest_bdev;
10372 set_bit(EXTENT_FLAG_PREALLOC, &em->flags);
10373 em->generation = trans->transid;
10376 write_lock(&em_tree->lock);
10377 ret = add_extent_mapping(em_tree, em, 1);
10378 write_unlock(&em_tree->lock);
10379 if (ret != -EEXIST)
10381 btrfs_drop_extent_cache(inode, cur_offset,
10382 cur_offset + ins.offset - 1,
10385 free_extent_map(em);
10387 num_bytes -= ins.offset;
10388 cur_offset += ins.offset;
10389 *alloc_hint = ins.objectid + ins.offset;
10391 inode_inc_iversion(inode);
10392 inode->i_ctime = current_fs_time(inode->i_sb);
10393 BTRFS_I(inode)->flags |= BTRFS_INODE_PREALLOC;
10394 if (!(mode & FALLOC_FL_KEEP_SIZE) &&
10395 (actual_len > inode->i_size) &&
10396 (cur_offset > inode->i_size)) {
10397 if (cur_offset > actual_len)
10398 i_size = actual_len;
10400 i_size = cur_offset;
10401 i_size_write(inode, i_size);
10402 btrfs_ordered_update_i_size(inode, i_size, NULL);
10405 ret = btrfs_update_inode(trans, root, inode);
10408 btrfs_abort_transaction(trans, ret);
10410 btrfs_end_transaction(trans, root);
10415 btrfs_end_transaction(trans, root);
10420 int btrfs_prealloc_file_range(struct inode *inode, int mode,
10421 u64 start, u64 num_bytes, u64 min_size,
10422 loff_t actual_len, u64 *alloc_hint)
10424 return __btrfs_prealloc_file_range(inode, mode, start, num_bytes,
10425 min_size, actual_len, alloc_hint,
10429 int btrfs_prealloc_file_range_trans(struct inode *inode,
10430 struct btrfs_trans_handle *trans, int mode,
10431 u64 start, u64 num_bytes, u64 min_size,
10432 loff_t actual_len, u64 *alloc_hint)
10434 return __btrfs_prealloc_file_range(inode, mode, start, num_bytes,
10435 min_size, actual_len, alloc_hint, trans);
10438 static int btrfs_set_page_dirty(struct page *page)
10440 return __set_page_dirty_nobuffers(page);
10443 static int btrfs_permission(struct inode *inode, int mask)
10445 struct btrfs_root *root = BTRFS_I(inode)->root;
10446 umode_t mode = inode->i_mode;
10448 if (mask & MAY_WRITE &&
10449 (S_ISREG(mode) || S_ISDIR(mode) || S_ISLNK(mode))) {
10450 if (btrfs_root_readonly(root))
10452 if (BTRFS_I(inode)->flags & BTRFS_INODE_READONLY)
10455 return generic_permission(inode, mask);
10458 static int btrfs_tmpfile(struct inode *dir, struct dentry *dentry, umode_t mode)
10460 struct btrfs_trans_handle *trans;
10461 struct btrfs_root *root = BTRFS_I(dir)->root;
10462 struct inode *inode = NULL;
10468 * 5 units required for adding orphan entry
10470 trans = btrfs_start_transaction(root, 5);
10472 return PTR_ERR(trans);
10474 ret = btrfs_find_free_ino(root, &objectid);
10478 inode = btrfs_new_inode(trans, root, dir, NULL, 0,
10479 btrfs_ino(dir), objectid, mode, &index);
10480 if (IS_ERR(inode)) {
10481 ret = PTR_ERR(inode);
10486 inode->i_fop = &btrfs_file_operations;
10487 inode->i_op = &btrfs_file_inode_operations;
10489 inode->i_mapping->a_ops = &btrfs_aops;
10490 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
10492 ret = btrfs_init_inode_security(trans, inode, dir, NULL);
10496 ret = btrfs_update_inode(trans, root, inode);
10499 ret = btrfs_orphan_add(trans, inode);
10504 * We set number of links to 0 in btrfs_new_inode(), and here we set
10505 * it to 1 because d_tmpfile() will issue a warning if the count is 0,
10508 * d_tmpfile() -> inode_dec_link_count() -> drop_nlink()
10510 set_nlink(inode, 1);
10511 unlock_new_inode(inode);
10512 d_tmpfile(dentry, inode);
10513 mark_inode_dirty(inode);
10516 btrfs_end_transaction(trans, root);
10519 btrfs_balance_delayed_items(root);
10520 btrfs_btree_balance_dirty(root);
10524 unlock_new_inode(inode);
10529 /* Inspired by filemap_check_errors() */
10530 int btrfs_inode_check_errors(struct inode *inode)
10534 if (test_bit(AS_ENOSPC, &inode->i_mapping->flags) &&
10535 test_and_clear_bit(AS_ENOSPC, &inode->i_mapping->flags))
10537 if (test_bit(AS_EIO, &inode->i_mapping->flags) &&
10538 test_and_clear_bit(AS_EIO, &inode->i_mapping->flags))
10544 static const struct inode_operations btrfs_dir_inode_operations = {
10545 .getattr = btrfs_getattr,
10546 .lookup = btrfs_lookup,
10547 .create = btrfs_create,
10548 .unlink = btrfs_unlink,
10549 .link = btrfs_link,
10550 .mkdir = btrfs_mkdir,
10551 .rmdir = btrfs_rmdir,
10552 .rename2 = btrfs_rename2,
10553 .symlink = btrfs_symlink,
10554 .setattr = btrfs_setattr,
10555 .mknod = btrfs_mknod,
10556 .setxattr = generic_setxattr,
10557 .getxattr = generic_getxattr,
10558 .listxattr = btrfs_listxattr,
10559 .removexattr = generic_removexattr,
10560 .permission = btrfs_permission,
10561 .get_acl = btrfs_get_acl,
10562 .set_acl = btrfs_set_acl,
10563 .update_time = btrfs_update_time,
10564 .tmpfile = btrfs_tmpfile,
10566 static const struct inode_operations btrfs_dir_ro_inode_operations = {
10567 .lookup = btrfs_lookup,
10568 .permission = btrfs_permission,
10569 .get_acl = btrfs_get_acl,
10570 .set_acl = btrfs_set_acl,
10571 .update_time = btrfs_update_time,
10574 static const struct file_operations btrfs_dir_file_operations = {
10575 .llseek = generic_file_llseek,
10576 .read = generic_read_dir,
10577 .iterate_shared = btrfs_real_readdir,
10578 .unlocked_ioctl = btrfs_ioctl,
10579 #ifdef CONFIG_COMPAT
10580 .compat_ioctl = btrfs_compat_ioctl,
10582 .release = btrfs_release_file,
10583 .fsync = btrfs_sync_file,
10586 static const struct extent_io_ops btrfs_extent_io_ops = {
10587 .fill_delalloc = run_delalloc_range,
10588 .submit_bio_hook = btrfs_submit_bio_hook,
10589 .merge_bio_hook = btrfs_merge_bio_hook,
10590 .readpage_end_io_hook = btrfs_readpage_end_io_hook,
10591 .writepage_end_io_hook = btrfs_writepage_end_io_hook,
10592 .writepage_start_hook = btrfs_writepage_start_hook,
10593 .set_bit_hook = btrfs_set_bit_hook,
10594 .clear_bit_hook = btrfs_clear_bit_hook,
10595 .merge_extent_hook = btrfs_merge_extent_hook,
10596 .split_extent_hook = btrfs_split_extent_hook,
10600 * btrfs doesn't support the bmap operation because swapfiles
10601 * use bmap to make a mapping of extents in the file. They assume
10602 * these extents won't change over the life of the file and they
10603 * use the bmap result to do IO directly to the drive.
10605 * the btrfs bmap call would return logical addresses that aren't
10606 * suitable for IO and they also will change frequently as COW
10607 * operations happen. So, swapfile + btrfs == corruption.
10609 * For now we're avoiding this by dropping bmap.
10611 static const struct address_space_operations btrfs_aops = {
10612 .readpage = btrfs_readpage,
10613 .writepage = btrfs_writepage,
10614 .writepages = btrfs_writepages,
10615 .readpages = btrfs_readpages,
10616 .direct_IO = btrfs_direct_IO,
10617 .invalidatepage = btrfs_invalidatepage,
10618 .releasepage = btrfs_releasepage,
10619 .set_page_dirty = btrfs_set_page_dirty,
10620 .error_remove_page = generic_error_remove_page,
10623 static const struct address_space_operations btrfs_symlink_aops = {
10624 .readpage = btrfs_readpage,
10625 .writepage = btrfs_writepage,
10626 .invalidatepage = btrfs_invalidatepage,
10627 .releasepage = btrfs_releasepage,
10630 static const struct inode_operations btrfs_file_inode_operations = {
10631 .getattr = btrfs_getattr,
10632 .setattr = btrfs_setattr,
10633 .setxattr = generic_setxattr,
10634 .getxattr = generic_getxattr,
10635 .listxattr = btrfs_listxattr,
10636 .removexattr = generic_removexattr,
10637 .permission = btrfs_permission,
10638 .fiemap = btrfs_fiemap,
10639 .get_acl = btrfs_get_acl,
10640 .set_acl = btrfs_set_acl,
10641 .update_time = btrfs_update_time,
10643 static const struct inode_operations btrfs_special_inode_operations = {
10644 .getattr = btrfs_getattr,
10645 .setattr = btrfs_setattr,
10646 .permission = btrfs_permission,
10647 .setxattr = generic_setxattr,
10648 .getxattr = generic_getxattr,
10649 .listxattr = btrfs_listxattr,
10650 .removexattr = generic_removexattr,
10651 .get_acl = btrfs_get_acl,
10652 .set_acl = btrfs_set_acl,
10653 .update_time = btrfs_update_time,
10655 static const struct inode_operations btrfs_symlink_inode_operations = {
10656 .readlink = generic_readlink,
10657 .get_link = page_get_link,
10658 .getattr = btrfs_getattr,
10659 .setattr = btrfs_setattr,
10660 .permission = btrfs_permission,
10661 .setxattr = generic_setxattr,
10662 .getxattr = generic_getxattr,
10663 .listxattr = btrfs_listxattr,
10664 .removexattr = generic_removexattr,
10665 .update_time = btrfs_update_time,
10668 const struct dentry_operations btrfs_dentry_operations = {
10669 .d_delete = btrfs_dentry_delete,
10670 .d_release = btrfs_dentry_release,