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"
64 struct btrfs_iget_args {
65 struct btrfs_key *location;
66 struct btrfs_root *root;
69 static const struct inode_operations btrfs_dir_inode_operations;
70 static const struct inode_operations btrfs_symlink_inode_operations;
71 static const struct inode_operations btrfs_dir_ro_inode_operations;
72 static const struct inode_operations btrfs_special_inode_operations;
73 static const struct inode_operations btrfs_file_inode_operations;
74 static const struct address_space_operations btrfs_aops;
75 static const struct address_space_operations btrfs_symlink_aops;
76 static const struct file_operations btrfs_dir_file_operations;
77 static struct extent_io_ops btrfs_extent_io_ops;
79 static struct kmem_cache *btrfs_inode_cachep;
80 static struct kmem_cache *btrfs_delalloc_work_cachep;
81 struct kmem_cache *btrfs_trans_handle_cachep;
82 struct kmem_cache *btrfs_transaction_cachep;
83 struct kmem_cache *btrfs_path_cachep;
84 struct kmem_cache *btrfs_free_space_cachep;
87 static unsigned char btrfs_type_by_mode[S_IFMT >> S_SHIFT] = {
88 [S_IFREG >> S_SHIFT] = BTRFS_FT_REG_FILE,
89 [S_IFDIR >> S_SHIFT] = BTRFS_FT_DIR,
90 [S_IFCHR >> S_SHIFT] = BTRFS_FT_CHRDEV,
91 [S_IFBLK >> S_SHIFT] = BTRFS_FT_BLKDEV,
92 [S_IFIFO >> S_SHIFT] = BTRFS_FT_FIFO,
93 [S_IFSOCK >> S_SHIFT] = BTRFS_FT_SOCK,
94 [S_IFLNK >> S_SHIFT] = BTRFS_FT_SYMLINK,
97 static int btrfs_setsize(struct inode *inode, struct iattr *attr);
98 static int btrfs_truncate(struct inode *inode);
99 static int btrfs_finish_ordered_io(struct btrfs_ordered_extent *ordered_extent);
100 static noinline int cow_file_range(struct inode *inode,
101 struct page *locked_page,
102 u64 start, u64 end, int *page_started,
103 unsigned long *nr_written, int unlock);
104 static struct extent_map *create_pinned_em(struct inode *inode, u64 start,
105 u64 len, u64 orig_start,
106 u64 block_start, u64 block_len,
107 u64 orig_block_len, u64 ram_bytes,
110 static int btrfs_dirty_inode(struct inode *inode);
112 #ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
113 void btrfs_test_inode_set_ops(struct inode *inode)
115 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
119 static int btrfs_init_inode_security(struct btrfs_trans_handle *trans,
120 struct inode *inode, struct inode *dir,
121 const struct qstr *qstr)
125 err = btrfs_init_acl(trans, inode, dir);
127 err = btrfs_xattr_security_init(trans, inode, dir, qstr);
132 * this does all the hard work for inserting an inline extent into
133 * the btree. The caller should have done a btrfs_drop_extents so that
134 * no overlapping inline items exist in the btree
136 static int insert_inline_extent(struct btrfs_trans_handle *trans,
137 struct btrfs_path *path, int extent_inserted,
138 struct btrfs_root *root, struct inode *inode,
139 u64 start, size_t size, size_t compressed_size,
141 struct page **compressed_pages)
143 struct extent_buffer *leaf;
144 struct page *page = NULL;
147 struct btrfs_file_extent_item *ei;
150 size_t cur_size = size;
151 unsigned long offset;
153 if (compressed_size && compressed_pages)
154 cur_size = compressed_size;
156 inode_add_bytes(inode, size);
158 if (!extent_inserted) {
159 struct btrfs_key key;
162 key.objectid = btrfs_ino(inode);
164 key.type = BTRFS_EXTENT_DATA_KEY;
166 datasize = btrfs_file_extent_calc_inline_size(cur_size);
167 path->leave_spinning = 1;
168 ret = btrfs_insert_empty_item(trans, root, path, &key,
175 leaf = path->nodes[0];
176 ei = btrfs_item_ptr(leaf, path->slots[0],
177 struct btrfs_file_extent_item);
178 btrfs_set_file_extent_generation(leaf, ei, trans->transid);
179 btrfs_set_file_extent_type(leaf, ei, BTRFS_FILE_EXTENT_INLINE);
180 btrfs_set_file_extent_encryption(leaf, ei, 0);
181 btrfs_set_file_extent_other_encoding(leaf, ei, 0);
182 btrfs_set_file_extent_ram_bytes(leaf, ei, size);
183 ptr = btrfs_file_extent_inline_start(ei);
185 if (compress_type != BTRFS_COMPRESS_NONE) {
188 while (compressed_size > 0) {
189 cpage = compressed_pages[i];
190 cur_size = min_t(unsigned long, compressed_size,
193 kaddr = kmap_atomic(cpage);
194 write_extent_buffer(leaf, kaddr, ptr, cur_size);
195 kunmap_atomic(kaddr);
199 compressed_size -= cur_size;
201 btrfs_set_file_extent_compression(leaf, ei,
204 page = find_get_page(inode->i_mapping,
205 start >> PAGE_CACHE_SHIFT);
206 btrfs_set_file_extent_compression(leaf, ei, 0);
207 kaddr = kmap_atomic(page);
208 offset = start & (PAGE_CACHE_SIZE - 1);
209 write_extent_buffer(leaf, kaddr + offset, ptr, size);
210 kunmap_atomic(kaddr);
211 page_cache_release(page);
213 btrfs_mark_buffer_dirty(leaf);
214 btrfs_release_path(path);
217 * we're an inline extent, so nobody can
218 * extend the file past i_size without locking
219 * a page we already have locked.
221 * We must do any isize and inode updates
222 * before we unlock the pages. Otherwise we
223 * could end up racing with unlink.
225 BTRFS_I(inode)->disk_i_size = inode->i_size;
226 ret = btrfs_update_inode(trans, root, inode);
235 * conditionally insert an inline extent into the file. This
236 * does the checks required to make sure the data is small enough
237 * to fit as an inline extent.
239 static noinline int cow_file_range_inline(struct btrfs_root *root,
240 struct inode *inode, u64 start,
241 u64 end, size_t compressed_size,
243 struct page **compressed_pages)
245 struct btrfs_trans_handle *trans;
246 u64 isize = i_size_read(inode);
247 u64 actual_end = min(end + 1, isize);
248 u64 inline_len = actual_end - start;
249 u64 aligned_end = ALIGN(end, root->sectorsize);
250 u64 data_len = inline_len;
252 struct btrfs_path *path;
253 int extent_inserted = 0;
254 u32 extent_item_size;
257 data_len = compressed_size;
260 actual_end > PAGE_CACHE_SIZE ||
261 data_len > BTRFS_MAX_INLINE_DATA_SIZE(root) ||
263 (actual_end & (root->sectorsize - 1)) == 0) ||
265 data_len > root->fs_info->max_inline) {
269 path = btrfs_alloc_path();
273 trans = btrfs_join_transaction(root);
275 btrfs_free_path(path);
276 return PTR_ERR(trans);
278 trans->block_rsv = &root->fs_info->delalloc_block_rsv;
280 if (compressed_size && compressed_pages)
281 extent_item_size = btrfs_file_extent_calc_inline_size(
284 extent_item_size = btrfs_file_extent_calc_inline_size(
287 ret = __btrfs_drop_extents(trans, root, inode, path,
288 start, aligned_end, NULL,
289 1, 1, extent_item_size, &extent_inserted);
291 btrfs_abort_transaction(trans, root, ret);
295 if (isize > actual_end)
296 inline_len = min_t(u64, isize, actual_end);
297 ret = insert_inline_extent(trans, path, extent_inserted,
299 inline_len, compressed_size,
300 compress_type, compressed_pages);
301 if (ret && ret != -ENOSPC) {
302 btrfs_abort_transaction(trans, root, ret);
304 } else if (ret == -ENOSPC) {
309 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &BTRFS_I(inode)->runtime_flags);
310 btrfs_delalloc_release_metadata(inode, end + 1 - start);
311 btrfs_drop_extent_cache(inode, start, aligned_end - 1, 0);
314 * Don't forget to free the reserved space, as for inlined extent
315 * it won't count as data extent, free them directly here.
316 * And at reserve time, it's always aligned to page size, so
317 * just free one page here.
319 btrfs_qgroup_free_data(inode, 0, PAGE_CACHE_SIZE);
320 btrfs_free_path(path);
321 btrfs_end_transaction(trans, root);
325 struct async_extent {
330 unsigned long nr_pages;
332 struct list_head list;
337 struct btrfs_root *root;
338 struct page *locked_page;
341 struct list_head extents;
342 struct btrfs_work work;
345 static noinline int add_async_extent(struct async_cow *cow,
346 u64 start, u64 ram_size,
349 unsigned long nr_pages,
352 struct async_extent *async_extent;
354 async_extent = kmalloc(sizeof(*async_extent), GFP_NOFS);
355 BUG_ON(!async_extent); /* -ENOMEM */
356 async_extent->start = start;
357 async_extent->ram_size = ram_size;
358 async_extent->compressed_size = compressed_size;
359 async_extent->pages = pages;
360 async_extent->nr_pages = nr_pages;
361 async_extent->compress_type = compress_type;
362 list_add_tail(&async_extent->list, &cow->extents);
366 static inline int inode_need_compress(struct inode *inode)
368 struct btrfs_root *root = BTRFS_I(inode)->root;
371 if (btrfs_test_opt(root, FORCE_COMPRESS))
373 /* bad compression ratios */
374 if (BTRFS_I(inode)->flags & BTRFS_INODE_NOCOMPRESS)
376 if (btrfs_test_opt(root, COMPRESS) ||
377 BTRFS_I(inode)->flags & BTRFS_INODE_COMPRESS ||
378 BTRFS_I(inode)->force_compress)
384 * we create compressed extents in two phases. The first
385 * phase compresses a range of pages that have already been
386 * locked (both pages and state bits are locked).
388 * This is done inside an ordered work queue, and the compression
389 * is spread across many cpus. The actual IO submission is step
390 * two, and the ordered work queue takes care of making sure that
391 * happens in the same order things were put onto the queue by
392 * writepages and friends.
394 * If this code finds it can't get good compression, it puts an
395 * entry onto the work queue to write the uncompressed bytes. This
396 * makes sure that both compressed inodes and uncompressed inodes
397 * are written in the same order that the flusher thread sent them
400 static noinline void compress_file_range(struct inode *inode,
401 struct page *locked_page,
403 struct async_cow *async_cow,
406 struct btrfs_root *root = BTRFS_I(inode)->root;
408 u64 blocksize = root->sectorsize;
410 u64 isize = i_size_read(inode);
412 struct page **pages = NULL;
413 unsigned long nr_pages;
414 unsigned long nr_pages_ret = 0;
415 unsigned long total_compressed = 0;
416 unsigned long total_in = 0;
417 unsigned long max_compressed = 128 * 1024;
418 unsigned long max_uncompressed = 128 * 1024;
421 int compress_type = root->fs_info->compress_type;
424 /* if this is a small write inside eof, kick off a defrag */
425 if ((end - start + 1) < 16 * 1024 &&
426 (start > 0 || end + 1 < BTRFS_I(inode)->disk_i_size))
427 btrfs_add_inode_defrag(NULL, inode);
429 actual_end = min_t(u64, isize, end + 1);
432 nr_pages = (end >> PAGE_CACHE_SHIFT) - (start >> PAGE_CACHE_SHIFT) + 1;
433 nr_pages = min(nr_pages, (128 * 1024UL) / PAGE_CACHE_SIZE);
436 * we don't want to send crud past the end of i_size through
437 * compression, that's just a waste of CPU time. So, if the
438 * end of the file is before the start of our current
439 * requested range of bytes, we bail out to the uncompressed
440 * cleanup code that can deal with all of this.
442 * It isn't really the fastest way to fix things, but this is a
443 * very uncommon corner.
445 if (actual_end <= start)
446 goto cleanup_and_bail_uncompressed;
448 total_compressed = actual_end - start;
451 * skip compression for a small file range(<=blocksize) that
452 * isn't an inline extent, since it dosen't save disk space at all.
454 if (total_compressed <= blocksize &&
455 (start > 0 || end + 1 < BTRFS_I(inode)->disk_i_size))
456 goto cleanup_and_bail_uncompressed;
458 /* we want to make sure that amount of ram required to uncompress
459 * an extent is reasonable, so we limit the total size in ram
460 * of a compressed extent to 128k. This is a crucial number
461 * because it also controls how easily we can spread reads across
462 * cpus for decompression.
464 * We also want to make sure the amount of IO required to do
465 * a random read is reasonably small, so we limit the size of
466 * a compressed extent to 128k.
468 total_compressed = min(total_compressed, max_uncompressed);
469 num_bytes = ALIGN(end - start + 1, blocksize);
470 num_bytes = max(blocksize, num_bytes);
475 * we do compression for mount -o compress and when the
476 * inode has not been flagged as nocompress. This flag can
477 * change at any time if we discover bad compression ratios.
479 if (inode_need_compress(inode)) {
481 pages = kcalloc(nr_pages, sizeof(struct page *), GFP_NOFS);
483 /* just bail out to the uncompressed code */
488 if (BTRFS_I(inode)->force_compress)
489 compress_type = BTRFS_I(inode)->force_compress;
492 * we need to call clear_page_dirty_for_io on each
493 * page in the range. Otherwise applications with the file
494 * mmap'd can wander in and change the page contents while
495 * we are compressing them.
497 * If the compression fails for any reason, we set the pages
498 * dirty again later on.
500 extent_range_clear_dirty_for_io(inode, start, end);
502 ret = btrfs_compress_pages(compress_type,
503 inode->i_mapping, start,
504 total_compressed, pages,
505 nr_pages, &nr_pages_ret,
511 unsigned long offset = total_compressed &
512 (PAGE_CACHE_SIZE - 1);
513 struct page *page = pages[nr_pages_ret - 1];
516 /* zero the tail end of the last page, we might be
517 * sending it down to disk
520 kaddr = kmap_atomic(page);
521 memset(kaddr + offset, 0,
522 PAGE_CACHE_SIZE - offset);
523 kunmap_atomic(kaddr);
530 /* lets try to make an inline extent */
531 if (ret || total_in < (actual_end - start)) {
532 /* we didn't compress the entire range, try
533 * to make an uncompressed inline extent.
535 ret = cow_file_range_inline(root, inode, start, end,
538 /* try making a compressed inline extent */
539 ret = cow_file_range_inline(root, inode, start, end,
541 compress_type, pages);
544 unsigned long clear_flags = EXTENT_DELALLOC |
546 unsigned long page_error_op;
548 clear_flags |= (ret < 0) ? EXTENT_DO_ACCOUNTING : 0;
549 page_error_op = ret < 0 ? PAGE_SET_ERROR : 0;
552 * inline extent creation worked or returned error,
553 * we don't need to create any more async work items.
554 * Unlock and free up our temp pages.
556 extent_clear_unlock_delalloc(inode, start, end, NULL,
557 clear_flags, PAGE_UNLOCK |
568 * we aren't doing an inline extent round the compressed size
569 * up to a block size boundary so the allocator does sane
572 total_compressed = ALIGN(total_compressed, blocksize);
575 * one last check to make sure the compression is really a
576 * win, compare the page count read with the blocks on disk
578 total_in = ALIGN(total_in, PAGE_CACHE_SIZE);
579 if (total_compressed >= total_in) {
582 num_bytes = total_in;
585 if (!will_compress && pages) {
587 * the compression code ran but failed to make things smaller,
588 * free any pages it allocated and our page pointer array
590 for (i = 0; i < nr_pages_ret; i++) {
591 WARN_ON(pages[i]->mapping);
592 page_cache_release(pages[i]);
596 total_compressed = 0;
599 /* flag the file so we don't compress in the future */
600 if (!btrfs_test_opt(root, FORCE_COMPRESS) &&
601 !(BTRFS_I(inode)->force_compress)) {
602 BTRFS_I(inode)->flags |= BTRFS_INODE_NOCOMPRESS;
608 /* the async work queues will take care of doing actual
609 * allocation on disk for these compressed pages,
610 * and will submit them to the elevator.
612 add_async_extent(async_cow, start, num_bytes,
613 total_compressed, pages, nr_pages_ret,
616 if (start + num_bytes < end) {
623 cleanup_and_bail_uncompressed:
625 * No compression, but we still need to write the pages in
626 * the file we've been given so far. redirty the locked
627 * page if it corresponds to our extent and set things up
628 * for the async work queue to run cow_file_range to do
629 * the normal delalloc dance
631 if (page_offset(locked_page) >= start &&
632 page_offset(locked_page) <= end) {
633 __set_page_dirty_nobuffers(locked_page);
634 /* unlocked later on in the async handlers */
637 extent_range_redirty_for_io(inode, start, end);
638 add_async_extent(async_cow, start, end - start + 1,
639 0, NULL, 0, BTRFS_COMPRESS_NONE);
646 for (i = 0; i < nr_pages_ret; i++) {
647 WARN_ON(pages[i]->mapping);
648 page_cache_release(pages[i]);
653 static void free_async_extent_pages(struct async_extent *async_extent)
657 if (!async_extent->pages)
660 for (i = 0; i < async_extent->nr_pages; i++) {
661 WARN_ON(async_extent->pages[i]->mapping);
662 page_cache_release(async_extent->pages[i]);
664 kfree(async_extent->pages);
665 async_extent->nr_pages = 0;
666 async_extent->pages = NULL;
670 * phase two of compressed writeback. This is the ordered portion
671 * of the code, which only gets called in the order the work was
672 * queued. We walk all the async extents created by compress_file_range
673 * and send them down to the disk.
675 static noinline void submit_compressed_extents(struct inode *inode,
676 struct async_cow *async_cow)
678 struct async_extent *async_extent;
680 struct btrfs_key ins;
681 struct extent_map *em;
682 struct btrfs_root *root = BTRFS_I(inode)->root;
683 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
684 struct extent_io_tree *io_tree;
688 while (!list_empty(&async_cow->extents)) {
689 async_extent = list_entry(async_cow->extents.next,
690 struct async_extent, list);
691 list_del(&async_extent->list);
693 io_tree = &BTRFS_I(inode)->io_tree;
696 /* did the compression code fall back to uncompressed IO? */
697 if (!async_extent->pages) {
698 int page_started = 0;
699 unsigned long nr_written = 0;
701 lock_extent(io_tree, async_extent->start,
702 async_extent->start +
703 async_extent->ram_size - 1);
705 /* allocate blocks */
706 ret = cow_file_range(inode, async_cow->locked_page,
708 async_extent->start +
709 async_extent->ram_size - 1,
710 &page_started, &nr_written, 0);
715 * if page_started, cow_file_range inserted an
716 * inline extent and took care of all the unlocking
717 * and IO for us. Otherwise, we need to submit
718 * all those pages down to the drive.
720 if (!page_started && !ret)
721 extent_write_locked_range(io_tree,
722 inode, async_extent->start,
723 async_extent->start +
724 async_extent->ram_size - 1,
728 unlock_page(async_cow->locked_page);
734 lock_extent(io_tree, async_extent->start,
735 async_extent->start + async_extent->ram_size - 1);
737 ret = btrfs_reserve_extent(root,
738 async_extent->compressed_size,
739 async_extent->compressed_size,
740 0, alloc_hint, &ins, 1, 1);
742 free_async_extent_pages(async_extent);
744 if (ret == -ENOSPC) {
745 unlock_extent(io_tree, async_extent->start,
746 async_extent->start +
747 async_extent->ram_size - 1);
750 * we need to redirty the pages if we decide to
751 * fallback to uncompressed IO, otherwise we
752 * will not submit these pages down to lower
755 extent_range_redirty_for_io(inode,
757 async_extent->start +
758 async_extent->ram_size - 1);
765 * here we're doing allocation and writeback of the
768 btrfs_drop_extent_cache(inode, async_extent->start,
769 async_extent->start +
770 async_extent->ram_size - 1, 0);
772 em = alloc_extent_map();
775 goto out_free_reserve;
777 em->start = async_extent->start;
778 em->len = async_extent->ram_size;
779 em->orig_start = em->start;
780 em->mod_start = em->start;
781 em->mod_len = em->len;
783 em->block_start = ins.objectid;
784 em->block_len = ins.offset;
785 em->orig_block_len = ins.offset;
786 em->ram_bytes = async_extent->ram_size;
787 em->bdev = root->fs_info->fs_devices->latest_bdev;
788 em->compress_type = async_extent->compress_type;
789 set_bit(EXTENT_FLAG_PINNED, &em->flags);
790 set_bit(EXTENT_FLAG_COMPRESSED, &em->flags);
794 write_lock(&em_tree->lock);
795 ret = add_extent_mapping(em_tree, em, 1);
796 write_unlock(&em_tree->lock);
797 if (ret != -EEXIST) {
801 btrfs_drop_extent_cache(inode, async_extent->start,
802 async_extent->start +
803 async_extent->ram_size - 1, 0);
807 goto out_free_reserve;
809 ret = btrfs_add_ordered_extent_compress(inode,
812 async_extent->ram_size,
814 BTRFS_ORDERED_COMPRESSED,
815 async_extent->compress_type);
817 btrfs_drop_extent_cache(inode, async_extent->start,
818 async_extent->start +
819 async_extent->ram_size - 1, 0);
820 goto out_free_reserve;
824 * clear dirty, set writeback and unlock the pages.
826 extent_clear_unlock_delalloc(inode, async_extent->start,
827 async_extent->start +
828 async_extent->ram_size - 1,
829 NULL, EXTENT_LOCKED | EXTENT_DELALLOC,
830 PAGE_UNLOCK | PAGE_CLEAR_DIRTY |
832 ret = btrfs_submit_compressed_write(inode,
834 async_extent->ram_size,
836 ins.offset, async_extent->pages,
837 async_extent->nr_pages);
839 struct extent_io_tree *tree = &BTRFS_I(inode)->io_tree;
840 struct page *p = async_extent->pages[0];
841 const u64 start = async_extent->start;
842 const u64 end = start + async_extent->ram_size - 1;
844 p->mapping = inode->i_mapping;
845 tree->ops->writepage_end_io_hook(p, start, end,
848 extent_clear_unlock_delalloc(inode, start, end, NULL, 0,
851 free_async_extent_pages(async_extent);
853 alloc_hint = ins.objectid + ins.offset;
859 btrfs_free_reserved_extent(root, ins.objectid, ins.offset, 1);
861 extent_clear_unlock_delalloc(inode, async_extent->start,
862 async_extent->start +
863 async_extent->ram_size - 1,
864 NULL, EXTENT_LOCKED | EXTENT_DELALLOC |
865 EXTENT_DEFRAG | EXTENT_DO_ACCOUNTING,
866 PAGE_UNLOCK | PAGE_CLEAR_DIRTY |
867 PAGE_SET_WRITEBACK | PAGE_END_WRITEBACK |
869 free_async_extent_pages(async_extent);
874 static u64 get_extent_allocation_hint(struct inode *inode, u64 start,
877 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
878 struct extent_map *em;
881 read_lock(&em_tree->lock);
882 em = search_extent_mapping(em_tree, start, num_bytes);
885 * if block start isn't an actual block number then find the
886 * first block in this inode and use that as a hint. If that
887 * block is also bogus then just don't worry about it.
889 if (em->block_start >= EXTENT_MAP_LAST_BYTE) {
891 em = search_extent_mapping(em_tree, 0, 0);
892 if (em && em->block_start < EXTENT_MAP_LAST_BYTE)
893 alloc_hint = em->block_start;
897 alloc_hint = em->block_start;
901 read_unlock(&em_tree->lock);
907 * when extent_io.c finds a delayed allocation range in the file,
908 * the call backs end up in this code. The basic idea is to
909 * allocate extents on disk for the range, and create ordered data structs
910 * in ram to track those extents.
912 * locked_page is the page that writepage had locked already. We use
913 * it to make sure we don't do extra locks or unlocks.
915 * *page_started is set to one if we unlock locked_page and do everything
916 * required to start IO on it. It may be clean and already done with
919 static noinline int cow_file_range(struct inode *inode,
920 struct page *locked_page,
921 u64 start, u64 end, int *page_started,
922 unsigned long *nr_written,
925 struct btrfs_root *root = BTRFS_I(inode)->root;
928 unsigned long ram_size;
931 u64 blocksize = root->sectorsize;
932 struct btrfs_key ins;
933 struct extent_map *em;
934 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
937 if (btrfs_is_free_space_inode(inode)) {
943 num_bytes = ALIGN(end - start + 1, blocksize);
944 num_bytes = max(blocksize, num_bytes);
946 /* if this is a small write inside eof, kick off defrag */
947 if (num_bytes < 64 * 1024 &&
948 (start > 0 || end + 1 < BTRFS_I(inode)->disk_i_size))
949 btrfs_add_inode_defrag(NULL, inode);
952 /* lets try to make an inline extent */
953 ret = cow_file_range_inline(root, inode, start, end, 0, 0,
956 extent_clear_unlock_delalloc(inode, start, end, NULL,
957 EXTENT_LOCKED | EXTENT_DELALLOC |
958 EXTENT_DEFRAG, PAGE_UNLOCK |
959 PAGE_CLEAR_DIRTY | PAGE_SET_WRITEBACK |
962 *nr_written = *nr_written +
963 (end - start + PAGE_CACHE_SIZE) / PAGE_CACHE_SIZE;
966 } else if (ret < 0) {
971 BUG_ON(num_bytes > btrfs_super_total_bytes(root->fs_info->super_copy));
973 alloc_hint = get_extent_allocation_hint(inode, start, num_bytes);
974 btrfs_drop_extent_cache(inode, start, start + num_bytes - 1, 0);
977 * Relocation relies on the relocated extents to have exactly the same
978 * size as the original extents. Normally writeback for relocation data
979 * extents follows a NOCOW path because relocation preallocates the
980 * extents. However, due to an operation such as scrub turning a block
981 * group to RO mode, it may fallback to COW mode, so we must make sure
982 * an extent allocated during COW has exactly the requested size and can
983 * not be split into smaller extents, otherwise relocation breaks and
984 * fails during the stage where it updates the bytenr of file extent
987 if (root->root_key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID)
988 min_alloc_size = num_bytes;
990 min_alloc_size = root->sectorsize;
992 while (num_bytes > 0) {
995 cur_alloc_size = num_bytes;
996 ret = btrfs_reserve_extent(root, cur_alloc_size,
997 min_alloc_size, 0, alloc_hint,
1002 em = alloc_extent_map();
1008 em->orig_start = em->start;
1009 ram_size = ins.offset;
1010 em->len = ins.offset;
1011 em->mod_start = em->start;
1012 em->mod_len = em->len;
1014 em->block_start = ins.objectid;
1015 em->block_len = ins.offset;
1016 em->orig_block_len = ins.offset;
1017 em->ram_bytes = ram_size;
1018 em->bdev = root->fs_info->fs_devices->latest_bdev;
1019 set_bit(EXTENT_FLAG_PINNED, &em->flags);
1020 em->generation = -1;
1023 write_lock(&em_tree->lock);
1024 ret = add_extent_mapping(em_tree, em, 1);
1025 write_unlock(&em_tree->lock);
1026 if (ret != -EEXIST) {
1027 free_extent_map(em);
1030 btrfs_drop_extent_cache(inode, start,
1031 start + ram_size - 1, 0);
1036 cur_alloc_size = ins.offset;
1037 ret = btrfs_add_ordered_extent(inode, start, ins.objectid,
1038 ram_size, cur_alloc_size, 0);
1040 goto out_drop_extent_cache;
1042 if (root->root_key.objectid ==
1043 BTRFS_DATA_RELOC_TREE_OBJECTID) {
1044 ret = btrfs_reloc_clone_csums(inode, start,
1047 goto out_drop_extent_cache;
1050 if (num_bytes < cur_alloc_size)
1053 /* we're not doing compressed IO, don't unlock the first
1054 * page (which the caller expects to stay locked), don't
1055 * clear any dirty bits and don't set any writeback bits
1057 * Do set the Private2 bit so we know this page was properly
1058 * setup for writepage
1060 op = unlock ? PAGE_UNLOCK : 0;
1061 op |= PAGE_SET_PRIVATE2;
1063 extent_clear_unlock_delalloc(inode, start,
1064 start + ram_size - 1, locked_page,
1065 EXTENT_LOCKED | EXTENT_DELALLOC,
1067 if (num_bytes < cur_alloc_size)
1070 num_bytes -= cur_alloc_size;
1071 alloc_hint = ins.objectid + ins.offset;
1072 start += cur_alloc_size;
1077 out_drop_extent_cache:
1078 btrfs_drop_extent_cache(inode, start, start + ram_size - 1, 0);
1080 btrfs_free_reserved_extent(root, ins.objectid, ins.offset, 1);
1082 extent_clear_unlock_delalloc(inode, start, end, locked_page,
1083 EXTENT_LOCKED | EXTENT_DO_ACCOUNTING |
1084 EXTENT_DELALLOC | EXTENT_DEFRAG,
1085 PAGE_UNLOCK | PAGE_CLEAR_DIRTY |
1086 PAGE_SET_WRITEBACK | PAGE_END_WRITEBACK);
1091 * work queue call back to started compression on a file and pages
1093 static noinline void async_cow_start(struct btrfs_work *work)
1095 struct async_cow *async_cow;
1097 async_cow = container_of(work, struct async_cow, work);
1099 compress_file_range(async_cow->inode, async_cow->locked_page,
1100 async_cow->start, async_cow->end, async_cow,
1102 if (num_added == 0) {
1103 btrfs_add_delayed_iput(async_cow->inode);
1104 async_cow->inode = NULL;
1109 * work queue call back to submit previously compressed pages
1111 static noinline void async_cow_submit(struct btrfs_work *work)
1113 struct async_cow *async_cow;
1114 struct btrfs_root *root;
1115 unsigned long nr_pages;
1117 async_cow = container_of(work, struct async_cow, work);
1119 root = async_cow->root;
1120 nr_pages = (async_cow->end - async_cow->start + PAGE_CACHE_SIZE) >>
1124 * atomic_sub_return implies a barrier for waitqueue_active
1126 if (atomic_sub_return(nr_pages, &root->fs_info->async_delalloc_pages) <
1128 waitqueue_active(&root->fs_info->async_submit_wait))
1129 wake_up(&root->fs_info->async_submit_wait);
1131 if (async_cow->inode)
1132 submit_compressed_extents(async_cow->inode, async_cow);
1135 static noinline void async_cow_free(struct btrfs_work *work)
1137 struct async_cow *async_cow;
1138 async_cow = container_of(work, struct async_cow, work);
1139 if (async_cow->inode)
1140 btrfs_add_delayed_iput(async_cow->inode);
1144 static int cow_file_range_async(struct inode *inode, struct page *locked_page,
1145 u64 start, u64 end, int *page_started,
1146 unsigned long *nr_written)
1148 struct async_cow *async_cow;
1149 struct btrfs_root *root = BTRFS_I(inode)->root;
1150 unsigned long nr_pages;
1152 int limit = 10 * 1024 * 1024;
1154 clear_extent_bit(&BTRFS_I(inode)->io_tree, start, end, EXTENT_LOCKED,
1155 1, 0, NULL, GFP_NOFS);
1156 while (start < end) {
1157 async_cow = kmalloc(sizeof(*async_cow), GFP_NOFS);
1158 BUG_ON(!async_cow); /* -ENOMEM */
1159 async_cow->inode = igrab(inode);
1160 async_cow->root = root;
1161 async_cow->locked_page = locked_page;
1162 async_cow->start = start;
1164 if (BTRFS_I(inode)->flags & BTRFS_INODE_NOCOMPRESS &&
1165 !btrfs_test_opt(root, FORCE_COMPRESS))
1168 cur_end = min(end, start + 512 * 1024 - 1);
1170 async_cow->end = cur_end;
1171 INIT_LIST_HEAD(&async_cow->extents);
1173 btrfs_init_work(&async_cow->work,
1174 btrfs_delalloc_helper,
1175 async_cow_start, async_cow_submit,
1178 nr_pages = (cur_end - start + PAGE_CACHE_SIZE) >>
1180 atomic_add(nr_pages, &root->fs_info->async_delalloc_pages);
1182 btrfs_queue_work(root->fs_info->delalloc_workers,
1185 if (atomic_read(&root->fs_info->async_delalloc_pages) > limit) {
1186 wait_event(root->fs_info->async_submit_wait,
1187 (atomic_read(&root->fs_info->async_delalloc_pages) <
1191 while (atomic_read(&root->fs_info->async_submit_draining) &&
1192 atomic_read(&root->fs_info->async_delalloc_pages)) {
1193 wait_event(root->fs_info->async_submit_wait,
1194 (atomic_read(&root->fs_info->async_delalloc_pages) ==
1198 *nr_written += nr_pages;
1199 start = cur_end + 1;
1205 static noinline int csum_exist_in_range(struct btrfs_root *root,
1206 u64 bytenr, u64 num_bytes)
1209 struct btrfs_ordered_sum *sums;
1212 ret = btrfs_lookup_csums_range(root->fs_info->csum_root, bytenr,
1213 bytenr + num_bytes - 1, &list, 0);
1214 if (ret == 0 && list_empty(&list))
1217 while (!list_empty(&list)) {
1218 sums = list_entry(list.next, struct btrfs_ordered_sum, list);
1219 list_del(&sums->list);
1228 * when nowcow writeback call back. This checks for snapshots or COW copies
1229 * of the extents that exist in the file, and COWs the file as required.
1231 * If no cow copies or snapshots exist, we write directly to the existing
1234 static noinline int run_delalloc_nocow(struct inode *inode,
1235 struct page *locked_page,
1236 u64 start, u64 end, int *page_started, int force,
1237 unsigned long *nr_written)
1239 struct btrfs_root *root = BTRFS_I(inode)->root;
1240 struct btrfs_trans_handle *trans;
1241 struct extent_buffer *leaf;
1242 struct btrfs_path *path;
1243 struct btrfs_file_extent_item *fi;
1244 struct btrfs_key found_key;
1259 u64 ino = btrfs_ino(inode);
1261 path = btrfs_alloc_path();
1263 extent_clear_unlock_delalloc(inode, start, end, locked_page,
1264 EXTENT_LOCKED | EXTENT_DELALLOC |
1265 EXTENT_DO_ACCOUNTING |
1266 EXTENT_DEFRAG, PAGE_UNLOCK |
1268 PAGE_SET_WRITEBACK |
1269 PAGE_END_WRITEBACK);
1273 nolock = btrfs_is_free_space_inode(inode);
1276 trans = btrfs_join_transaction_nolock(root);
1278 trans = btrfs_join_transaction(root);
1280 if (IS_ERR(trans)) {
1281 extent_clear_unlock_delalloc(inode, start, end, locked_page,
1282 EXTENT_LOCKED | EXTENT_DELALLOC |
1283 EXTENT_DO_ACCOUNTING |
1284 EXTENT_DEFRAG, PAGE_UNLOCK |
1286 PAGE_SET_WRITEBACK |
1287 PAGE_END_WRITEBACK);
1288 btrfs_free_path(path);
1289 return PTR_ERR(trans);
1292 trans->block_rsv = &root->fs_info->delalloc_block_rsv;
1294 cow_start = (u64)-1;
1297 ret = btrfs_lookup_file_extent(trans, root, path, ino,
1301 if (ret > 0 && path->slots[0] > 0 && check_prev) {
1302 leaf = path->nodes[0];
1303 btrfs_item_key_to_cpu(leaf, &found_key,
1304 path->slots[0] - 1);
1305 if (found_key.objectid == ino &&
1306 found_key.type == BTRFS_EXTENT_DATA_KEY)
1311 leaf = path->nodes[0];
1312 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
1313 ret = btrfs_next_leaf(root, path);
1315 if (cow_start != (u64)-1)
1316 cur_offset = cow_start;
1321 leaf = path->nodes[0];
1327 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
1329 if (found_key.objectid > ino)
1331 if (WARN_ON_ONCE(found_key.objectid < ino) ||
1332 found_key.type < BTRFS_EXTENT_DATA_KEY) {
1336 if (found_key.type > BTRFS_EXTENT_DATA_KEY ||
1337 found_key.offset > end)
1340 if (found_key.offset > cur_offset) {
1341 extent_end = found_key.offset;
1346 fi = btrfs_item_ptr(leaf, path->slots[0],
1347 struct btrfs_file_extent_item);
1348 extent_type = btrfs_file_extent_type(leaf, fi);
1350 ram_bytes = btrfs_file_extent_ram_bytes(leaf, fi);
1351 if (extent_type == BTRFS_FILE_EXTENT_REG ||
1352 extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
1353 disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
1354 extent_offset = btrfs_file_extent_offset(leaf, fi);
1355 extent_end = found_key.offset +
1356 btrfs_file_extent_num_bytes(leaf, fi);
1358 btrfs_file_extent_disk_num_bytes(leaf, fi);
1359 if (extent_end <= start) {
1363 if (disk_bytenr == 0)
1365 if (btrfs_file_extent_compression(leaf, fi) ||
1366 btrfs_file_extent_encryption(leaf, fi) ||
1367 btrfs_file_extent_other_encoding(leaf, fi))
1369 if (extent_type == BTRFS_FILE_EXTENT_REG && !force)
1371 if (btrfs_extent_readonly(root, disk_bytenr))
1373 ret = btrfs_cross_ref_exist(trans, root, ino,
1375 extent_offset, disk_bytenr);
1378 * ret could be -EIO if the above fails to read
1382 if (cow_start != (u64)-1)
1383 cur_offset = cow_start;
1387 WARN_ON_ONCE(nolock);
1390 disk_bytenr += extent_offset;
1391 disk_bytenr += cur_offset - found_key.offset;
1392 num_bytes = min(end + 1, extent_end) - cur_offset;
1394 * if there are pending snapshots for this root,
1395 * we fall into common COW way.
1398 err = btrfs_start_write_no_snapshoting(root);
1403 * force cow if csum exists in the range.
1404 * this ensure that csum for a given extent are
1405 * either valid or do not exist.
1407 ret = csum_exist_in_range(root, disk_bytenr, num_bytes);
1410 * ret could be -EIO if the above fails to read
1414 if (cow_start != (u64)-1)
1415 cur_offset = cow_start;
1418 WARN_ON_ONCE(nolock);
1422 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
1423 extent_end = found_key.offset +
1424 btrfs_file_extent_inline_len(leaf,
1425 path->slots[0], fi);
1426 extent_end = ALIGN(extent_end, root->sectorsize);
1431 if (extent_end <= start) {
1433 if (!nolock && nocow)
1434 btrfs_end_write_no_snapshoting(root);
1438 if (cow_start == (u64)-1)
1439 cow_start = cur_offset;
1440 cur_offset = extent_end;
1441 if (cur_offset > end)
1447 btrfs_release_path(path);
1448 if (cow_start != (u64)-1) {
1449 ret = cow_file_range(inode, locked_page,
1450 cow_start, found_key.offset - 1,
1451 page_started, nr_written, 1);
1453 if (!nolock && nocow)
1454 btrfs_end_write_no_snapshoting(root);
1457 cow_start = (u64)-1;
1460 if (extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
1461 struct extent_map *em;
1462 struct extent_map_tree *em_tree;
1463 em_tree = &BTRFS_I(inode)->extent_tree;
1464 em = alloc_extent_map();
1465 BUG_ON(!em); /* -ENOMEM */
1466 em->start = cur_offset;
1467 em->orig_start = found_key.offset - extent_offset;
1468 em->len = num_bytes;
1469 em->block_len = num_bytes;
1470 em->block_start = disk_bytenr;
1471 em->orig_block_len = disk_num_bytes;
1472 em->ram_bytes = ram_bytes;
1473 em->bdev = root->fs_info->fs_devices->latest_bdev;
1474 em->mod_start = em->start;
1475 em->mod_len = em->len;
1476 set_bit(EXTENT_FLAG_PINNED, &em->flags);
1477 set_bit(EXTENT_FLAG_FILLING, &em->flags);
1478 em->generation = -1;
1480 write_lock(&em_tree->lock);
1481 ret = add_extent_mapping(em_tree, em, 1);
1482 write_unlock(&em_tree->lock);
1483 if (ret != -EEXIST) {
1484 free_extent_map(em);
1487 btrfs_drop_extent_cache(inode, em->start,
1488 em->start + em->len - 1, 0);
1490 type = BTRFS_ORDERED_PREALLOC;
1492 type = BTRFS_ORDERED_NOCOW;
1495 ret = btrfs_add_ordered_extent(inode, cur_offset, disk_bytenr,
1496 num_bytes, num_bytes, type);
1497 BUG_ON(ret); /* -ENOMEM */
1499 if (root->root_key.objectid ==
1500 BTRFS_DATA_RELOC_TREE_OBJECTID) {
1501 ret = btrfs_reloc_clone_csums(inode, cur_offset,
1504 if (!nolock && nocow)
1505 btrfs_end_write_no_snapshoting(root);
1510 extent_clear_unlock_delalloc(inode, cur_offset,
1511 cur_offset + num_bytes - 1,
1512 locked_page, EXTENT_LOCKED |
1513 EXTENT_DELALLOC, PAGE_UNLOCK |
1515 if (!nolock && nocow)
1516 btrfs_end_write_no_snapshoting(root);
1517 cur_offset = extent_end;
1518 if (cur_offset > end)
1521 btrfs_release_path(path);
1523 if (cur_offset <= end && cow_start == (u64)-1) {
1524 cow_start = cur_offset;
1528 if (cow_start != (u64)-1) {
1529 ret = cow_file_range(inode, locked_page, cow_start, end,
1530 page_started, nr_written, 1);
1536 err = btrfs_end_transaction(trans, root);
1540 if (ret && cur_offset < end)
1541 extent_clear_unlock_delalloc(inode, cur_offset, end,
1542 locked_page, EXTENT_LOCKED |
1543 EXTENT_DELALLOC | EXTENT_DEFRAG |
1544 EXTENT_DO_ACCOUNTING, PAGE_UNLOCK |
1546 PAGE_SET_WRITEBACK |
1547 PAGE_END_WRITEBACK);
1548 btrfs_free_path(path);
1552 static inline int need_force_cow(struct inode *inode, u64 start, u64 end)
1555 if (!(BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW) &&
1556 !(BTRFS_I(inode)->flags & BTRFS_INODE_PREALLOC))
1560 * @defrag_bytes is a hint value, no spinlock held here,
1561 * if is not zero, it means the file is defragging.
1562 * Force cow if given extent needs to be defragged.
1564 if (BTRFS_I(inode)->defrag_bytes &&
1565 test_range_bit(&BTRFS_I(inode)->io_tree, start, end,
1566 EXTENT_DEFRAG, 0, NULL))
1573 * extent_io.c call back to do delayed allocation processing
1575 static int run_delalloc_range(struct inode *inode, struct page *locked_page,
1576 u64 start, u64 end, int *page_started,
1577 unsigned long *nr_written)
1580 int force_cow = need_force_cow(inode, start, end);
1582 if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW && !force_cow) {
1583 ret = run_delalloc_nocow(inode, locked_page, start, end,
1584 page_started, 1, nr_written);
1585 } else if (BTRFS_I(inode)->flags & BTRFS_INODE_PREALLOC && !force_cow) {
1586 ret = run_delalloc_nocow(inode, locked_page, start, end,
1587 page_started, 0, nr_written);
1588 } else if (!inode_need_compress(inode)) {
1589 ret = cow_file_range(inode, locked_page, start, end,
1590 page_started, nr_written, 1);
1592 set_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
1593 &BTRFS_I(inode)->runtime_flags);
1594 ret = cow_file_range_async(inode, locked_page, start, end,
1595 page_started, nr_written);
1600 static void btrfs_split_extent_hook(struct inode *inode,
1601 struct extent_state *orig, u64 split)
1605 /* not delalloc, ignore it */
1606 if (!(orig->state & EXTENT_DELALLOC))
1609 size = orig->end - orig->start + 1;
1610 if (size > BTRFS_MAX_EXTENT_SIZE) {
1615 * See the explanation in btrfs_merge_extent_hook, the same
1616 * applies here, just in reverse.
1618 new_size = orig->end - split + 1;
1619 num_extents = div64_u64(new_size + BTRFS_MAX_EXTENT_SIZE - 1,
1620 BTRFS_MAX_EXTENT_SIZE);
1621 new_size = split - orig->start;
1622 num_extents += div64_u64(new_size + BTRFS_MAX_EXTENT_SIZE - 1,
1623 BTRFS_MAX_EXTENT_SIZE);
1624 if (div64_u64(size + BTRFS_MAX_EXTENT_SIZE - 1,
1625 BTRFS_MAX_EXTENT_SIZE) >= num_extents)
1629 spin_lock(&BTRFS_I(inode)->lock);
1630 BTRFS_I(inode)->outstanding_extents++;
1631 spin_unlock(&BTRFS_I(inode)->lock);
1635 * extent_io.c merge_extent_hook, used to track merged delayed allocation
1636 * extents so we can keep track of new extents that are just merged onto old
1637 * extents, such as when we are doing sequential writes, so we can properly
1638 * account for the metadata space we'll need.
1640 static void btrfs_merge_extent_hook(struct inode *inode,
1641 struct extent_state *new,
1642 struct extent_state *other)
1644 u64 new_size, old_size;
1647 /* not delalloc, ignore it */
1648 if (!(other->state & EXTENT_DELALLOC))
1651 if (new->start > other->start)
1652 new_size = new->end - other->start + 1;
1654 new_size = other->end - new->start + 1;
1656 /* we're not bigger than the max, unreserve the space and go */
1657 if (new_size <= BTRFS_MAX_EXTENT_SIZE) {
1658 spin_lock(&BTRFS_I(inode)->lock);
1659 BTRFS_I(inode)->outstanding_extents--;
1660 spin_unlock(&BTRFS_I(inode)->lock);
1665 * We have to add up either side to figure out how many extents were
1666 * accounted for before we merged into one big extent. If the number of
1667 * extents we accounted for is <= the amount we need for the new range
1668 * then we can return, otherwise drop. Think of it like this
1672 * So we've grown the extent by a MAX_SIZE extent, this would mean we
1673 * need 2 outstanding extents, on one side we have 1 and the other side
1674 * we have 1 so they are == and we can return. But in this case
1676 * [MAX_SIZE+4k][MAX_SIZE+4k]
1678 * Each range on their own accounts for 2 extents, but merged together
1679 * they are only 3 extents worth of accounting, so we need to drop in
1682 old_size = other->end - other->start + 1;
1683 num_extents = div64_u64(old_size + BTRFS_MAX_EXTENT_SIZE - 1,
1684 BTRFS_MAX_EXTENT_SIZE);
1685 old_size = new->end - new->start + 1;
1686 num_extents += div64_u64(old_size + BTRFS_MAX_EXTENT_SIZE - 1,
1687 BTRFS_MAX_EXTENT_SIZE);
1689 if (div64_u64(new_size + BTRFS_MAX_EXTENT_SIZE - 1,
1690 BTRFS_MAX_EXTENT_SIZE) >= num_extents)
1693 spin_lock(&BTRFS_I(inode)->lock);
1694 BTRFS_I(inode)->outstanding_extents--;
1695 spin_unlock(&BTRFS_I(inode)->lock);
1698 static void btrfs_add_delalloc_inodes(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_add_tail(&BTRFS_I(inode)->delalloc_inodes,
1704 &root->delalloc_inodes);
1705 set_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1706 &BTRFS_I(inode)->runtime_flags);
1707 root->nr_delalloc_inodes++;
1708 if (root->nr_delalloc_inodes == 1) {
1709 spin_lock(&root->fs_info->delalloc_root_lock);
1710 BUG_ON(!list_empty(&root->delalloc_root));
1711 list_add_tail(&root->delalloc_root,
1712 &root->fs_info->delalloc_roots);
1713 spin_unlock(&root->fs_info->delalloc_root_lock);
1716 spin_unlock(&root->delalloc_lock);
1719 static void btrfs_del_delalloc_inode(struct btrfs_root *root,
1720 struct inode *inode)
1722 spin_lock(&root->delalloc_lock);
1723 if (!list_empty(&BTRFS_I(inode)->delalloc_inodes)) {
1724 list_del_init(&BTRFS_I(inode)->delalloc_inodes);
1725 clear_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1726 &BTRFS_I(inode)->runtime_flags);
1727 root->nr_delalloc_inodes--;
1728 if (!root->nr_delalloc_inodes) {
1729 spin_lock(&root->fs_info->delalloc_root_lock);
1730 BUG_ON(list_empty(&root->delalloc_root));
1731 list_del_init(&root->delalloc_root);
1732 spin_unlock(&root->fs_info->delalloc_root_lock);
1735 spin_unlock(&root->delalloc_lock);
1739 * extent_io.c set_bit_hook, used to track delayed allocation
1740 * bytes in this file, and to maintain the list of inodes that
1741 * have pending delalloc work to be done.
1743 static void btrfs_set_bit_hook(struct inode *inode,
1744 struct extent_state *state, unsigned *bits)
1747 if ((*bits & EXTENT_DEFRAG) && !(*bits & EXTENT_DELALLOC))
1750 * set_bit and clear bit hooks normally require _irqsave/restore
1751 * but in this case, we are only testing for the DELALLOC
1752 * bit, which is only set or cleared with irqs on
1754 if (!(state->state & EXTENT_DELALLOC) && (*bits & EXTENT_DELALLOC)) {
1755 struct btrfs_root *root = BTRFS_I(inode)->root;
1756 u64 len = state->end + 1 - state->start;
1757 bool do_list = !btrfs_is_free_space_inode(inode);
1759 if (*bits & EXTENT_FIRST_DELALLOC) {
1760 *bits &= ~EXTENT_FIRST_DELALLOC;
1762 spin_lock(&BTRFS_I(inode)->lock);
1763 BTRFS_I(inode)->outstanding_extents++;
1764 spin_unlock(&BTRFS_I(inode)->lock);
1767 /* For sanity tests */
1768 if (btrfs_test_is_dummy_root(root))
1771 __percpu_counter_add(&root->fs_info->delalloc_bytes, len,
1772 root->fs_info->delalloc_batch);
1773 spin_lock(&BTRFS_I(inode)->lock);
1774 BTRFS_I(inode)->delalloc_bytes += len;
1775 if (*bits & EXTENT_DEFRAG)
1776 BTRFS_I(inode)->defrag_bytes += len;
1777 if (do_list && !test_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1778 &BTRFS_I(inode)->runtime_flags))
1779 btrfs_add_delalloc_inodes(root, inode);
1780 spin_unlock(&BTRFS_I(inode)->lock);
1785 * extent_io.c clear_bit_hook, see set_bit_hook for why
1787 static void btrfs_clear_bit_hook(struct inode *inode,
1788 struct extent_state *state,
1791 u64 len = state->end + 1 - state->start;
1792 u64 num_extents = div64_u64(len + BTRFS_MAX_EXTENT_SIZE -1,
1793 BTRFS_MAX_EXTENT_SIZE);
1795 spin_lock(&BTRFS_I(inode)->lock);
1796 if ((state->state & EXTENT_DEFRAG) && (*bits & EXTENT_DEFRAG))
1797 BTRFS_I(inode)->defrag_bytes -= len;
1798 spin_unlock(&BTRFS_I(inode)->lock);
1801 * set_bit and clear bit hooks normally require _irqsave/restore
1802 * but in this case, we are only testing for the DELALLOC
1803 * bit, which is only set or cleared with irqs on
1805 if ((state->state & EXTENT_DELALLOC) && (*bits & EXTENT_DELALLOC)) {
1806 struct btrfs_root *root = BTRFS_I(inode)->root;
1807 bool do_list = !btrfs_is_free_space_inode(inode);
1809 if (*bits & EXTENT_FIRST_DELALLOC) {
1810 *bits &= ~EXTENT_FIRST_DELALLOC;
1811 } else if (!(*bits & EXTENT_DO_ACCOUNTING)) {
1812 spin_lock(&BTRFS_I(inode)->lock);
1813 BTRFS_I(inode)->outstanding_extents -= num_extents;
1814 spin_unlock(&BTRFS_I(inode)->lock);
1818 * We don't reserve metadata space for space cache inodes so we
1819 * don't need to call dellalloc_release_metadata if there is an
1822 if (*bits & EXTENT_DO_ACCOUNTING &&
1823 root != root->fs_info->tree_root)
1824 btrfs_delalloc_release_metadata(inode, len);
1826 /* For sanity tests. */
1827 if (btrfs_test_is_dummy_root(root))
1830 if (root->root_key.objectid != BTRFS_DATA_RELOC_TREE_OBJECTID
1831 && do_list && !(state->state & EXTENT_NORESERVE))
1832 btrfs_free_reserved_data_space_noquota(inode,
1835 __percpu_counter_add(&root->fs_info->delalloc_bytes, -len,
1836 root->fs_info->delalloc_batch);
1837 spin_lock(&BTRFS_I(inode)->lock);
1838 BTRFS_I(inode)->delalloc_bytes -= len;
1839 if (do_list && BTRFS_I(inode)->delalloc_bytes == 0 &&
1840 test_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1841 &BTRFS_I(inode)->runtime_flags))
1842 btrfs_del_delalloc_inode(root, inode);
1843 spin_unlock(&BTRFS_I(inode)->lock);
1848 * extent_io.c merge_bio_hook, this must check the chunk tree to make sure
1849 * we don't create bios that span stripes or chunks
1851 int btrfs_merge_bio_hook(int rw, struct page *page, unsigned long offset,
1852 size_t size, struct bio *bio,
1853 unsigned long bio_flags)
1855 struct btrfs_root *root = BTRFS_I(page->mapping->host)->root;
1856 u64 logical = (u64)bio->bi_iter.bi_sector << 9;
1861 if (bio_flags & EXTENT_BIO_COMPRESSED)
1864 length = bio->bi_iter.bi_size;
1865 map_length = length;
1866 ret = btrfs_map_block(root->fs_info, rw, logical,
1867 &map_length, NULL, 0);
1868 /* Will always return 0 with map_multi == NULL */
1870 if (map_length < length + size)
1876 * in order to insert checksums into the metadata in large chunks,
1877 * we wait until bio submission time. All the pages in the bio are
1878 * checksummed and sums are attached onto the ordered extent record.
1880 * At IO completion time the cums attached on the ordered extent record
1881 * are inserted into the btree
1883 static int __btrfs_submit_bio_start(struct inode *inode, int rw,
1884 struct bio *bio, int mirror_num,
1885 unsigned long bio_flags,
1888 struct btrfs_root *root = BTRFS_I(inode)->root;
1891 ret = btrfs_csum_one_bio(root, inode, bio, 0, 0);
1892 BUG_ON(ret); /* -ENOMEM */
1897 * in order to insert checksums into the metadata in large chunks,
1898 * we wait until bio submission time. All the pages in the bio are
1899 * checksummed and sums are attached onto the ordered extent record.
1901 * At IO completion time the cums attached on the ordered extent record
1902 * are inserted into the btree
1904 static int __btrfs_submit_bio_done(struct inode *inode, int rw, struct bio *bio,
1905 int mirror_num, unsigned long bio_flags,
1908 struct btrfs_root *root = BTRFS_I(inode)->root;
1911 ret = btrfs_map_bio(root, rw, bio, mirror_num, 1);
1913 bio->bi_error = ret;
1920 * extent_io.c submission hook. This does the right thing for csum calculation
1921 * on write, or reading the csums from the tree before a read
1923 static int btrfs_submit_bio_hook(struct inode *inode, int rw, struct bio *bio,
1924 int mirror_num, unsigned long bio_flags,
1927 struct btrfs_root *root = BTRFS_I(inode)->root;
1928 enum btrfs_wq_endio_type metadata = BTRFS_WQ_ENDIO_DATA;
1931 int async = !atomic_read(&BTRFS_I(inode)->sync_writers);
1933 skip_sum = BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM;
1935 if (btrfs_is_free_space_inode(inode))
1936 metadata = BTRFS_WQ_ENDIO_FREE_SPACE;
1938 if (!(rw & REQ_WRITE)) {
1939 ret = btrfs_bio_wq_end_io(root->fs_info, bio, metadata);
1943 if (bio_flags & EXTENT_BIO_COMPRESSED) {
1944 ret = btrfs_submit_compressed_read(inode, bio,
1948 } else if (!skip_sum) {
1949 ret = btrfs_lookup_bio_sums(root, inode, bio, NULL);
1954 } else if (async && !skip_sum) {
1955 /* csum items have already been cloned */
1956 if (root->root_key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID)
1958 /* we're doing a write, do the async checksumming */
1959 ret = btrfs_wq_submit_bio(BTRFS_I(inode)->root->fs_info,
1960 inode, rw, bio, mirror_num,
1961 bio_flags, bio_offset,
1962 __btrfs_submit_bio_start,
1963 __btrfs_submit_bio_done);
1965 } else if (!skip_sum) {
1966 ret = btrfs_csum_one_bio(root, inode, bio, 0, 0);
1972 ret = btrfs_map_bio(root, rw, bio, mirror_num, 0);
1976 bio->bi_error = ret;
1983 * given a list of ordered sums record them in the inode. This happens
1984 * at IO completion time based on sums calculated at bio submission time.
1986 static noinline int add_pending_csums(struct btrfs_trans_handle *trans,
1987 struct inode *inode, u64 file_offset,
1988 struct list_head *list)
1990 struct btrfs_ordered_sum *sum;
1992 list_for_each_entry(sum, list, list) {
1993 trans->adding_csums = 1;
1994 btrfs_csum_file_blocks(trans,
1995 BTRFS_I(inode)->root->fs_info->csum_root, sum);
1996 trans->adding_csums = 0;
2001 int btrfs_set_extent_delalloc(struct inode *inode, u64 start, u64 end,
2002 struct extent_state **cached_state)
2004 WARN_ON((end & (PAGE_CACHE_SIZE - 1)) == 0);
2005 return set_extent_delalloc(&BTRFS_I(inode)->io_tree, start, end,
2006 cached_state, GFP_NOFS);
2009 /* see btrfs_writepage_start_hook for details on why this is required */
2010 struct btrfs_writepage_fixup {
2012 struct btrfs_work work;
2015 static void btrfs_writepage_fixup_worker(struct btrfs_work *work)
2017 struct btrfs_writepage_fixup *fixup;
2018 struct btrfs_ordered_extent *ordered;
2019 struct extent_state *cached_state = NULL;
2021 struct inode *inode;
2026 fixup = container_of(work, struct btrfs_writepage_fixup, work);
2030 if (!page->mapping || !PageDirty(page) || !PageChecked(page)) {
2031 ClearPageChecked(page);
2035 inode = page->mapping->host;
2036 page_start = page_offset(page);
2037 page_end = page_offset(page) + PAGE_CACHE_SIZE - 1;
2039 lock_extent_bits(&BTRFS_I(inode)->io_tree, page_start, page_end, 0,
2042 /* already ordered? We're done */
2043 if (PagePrivate2(page))
2046 ordered = btrfs_lookup_ordered_extent(inode, page_start);
2048 unlock_extent_cached(&BTRFS_I(inode)->io_tree, page_start,
2049 page_end, &cached_state, GFP_NOFS);
2051 btrfs_start_ordered_extent(inode, ordered, 1);
2052 btrfs_put_ordered_extent(ordered);
2056 ret = btrfs_delalloc_reserve_space(inode, page_start,
2059 mapping_set_error(page->mapping, ret);
2060 end_extent_writepage(page, ret, page_start, page_end);
2061 ClearPageChecked(page);
2065 ret = btrfs_set_extent_delalloc(inode, page_start, page_end,
2068 mapping_set_error(page->mapping, ret);
2069 end_extent_writepage(page, ret, page_start, page_end);
2070 ClearPageChecked(page);
2074 ClearPageChecked(page);
2075 set_page_dirty(page);
2077 unlock_extent_cached(&BTRFS_I(inode)->io_tree, page_start, page_end,
2078 &cached_state, GFP_NOFS);
2081 page_cache_release(page);
2086 * There are a few paths in the higher layers of the kernel that directly
2087 * set the page dirty bit without asking the filesystem if it is a
2088 * good idea. This causes problems because we want to make sure COW
2089 * properly happens and the data=ordered rules are followed.
2091 * In our case any range that doesn't have the ORDERED bit set
2092 * hasn't been properly setup for IO. We kick off an async process
2093 * to fix it up. The async helper will wait for ordered extents, set
2094 * the delalloc bit and make it safe to write the page.
2096 static int btrfs_writepage_start_hook(struct page *page, u64 start, u64 end)
2098 struct inode *inode = page->mapping->host;
2099 struct btrfs_writepage_fixup *fixup;
2100 struct btrfs_root *root = BTRFS_I(inode)->root;
2102 /* this page is properly in the ordered list */
2103 if (TestClearPagePrivate2(page))
2106 if (PageChecked(page))
2109 fixup = kzalloc(sizeof(*fixup), GFP_NOFS);
2113 SetPageChecked(page);
2114 page_cache_get(page);
2115 btrfs_init_work(&fixup->work, btrfs_fixup_helper,
2116 btrfs_writepage_fixup_worker, NULL, NULL);
2118 btrfs_queue_work(root->fs_info->fixup_workers, &fixup->work);
2122 static int insert_reserved_file_extent(struct btrfs_trans_handle *trans,
2123 struct inode *inode, u64 file_pos,
2124 u64 disk_bytenr, u64 disk_num_bytes,
2125 u64 num_bytes, u64 ram_bytes,
2126 u8 compression, u8 encryption,
2127 u16 other_encoding, int extent_type)
2129 struct btrfs_root *root = BTRFS_I(inode)->root;
2130 struct btrfs_file_extent_item *fi;
2131 struct btrfs_path *path;
2132 struct extent_buffer *leaf;
2133 struct btrfs_key ins;
2134 int extent_inserted = 0;
2137 path = btrfs_alloc_path();
2142 * we may be replacing one extent in the tree with another.
2143 * The new extent is pinned in the extent map, and we don't want
2144 * to drop it from the cache until it is completely in the btree.
2146 * So, tell btrfs_drop_extents to leave this extent in the cache.
2147 * the caller is expected to unpin it and allow it to be merged
2150 ret = __btrfs_drop_extents(trans, root, inode, path, file_pos,
2151 file_pos + num_bytes, NULL, 0,
2152 1, sizeof(*fi), &extent_inserted);
2156 if (!extent_inserted) {
2157 ins.objectid = btrfs_ino(inode);
2158 ins.offset = file_pos;
2159 ins.type = BTRFS_EXTENT_DATA_KEY;
2161 path->leave_spinning = 1;
2162 ret = btrfs_insert_empty_item(trans, root, path, &ins,
2167 leaf = path->nodes[0];
2168 fi = btrfs_item_ptr(leaf, path->slots[0],
2169 struct btrfs_file_extent_item);
2170 btrfs_set_file_extent_generation(leaf, fi, trans->transid);
2171 btrfs_set_file_extent_type(leaf, fi, extent_type);
2172 btrfs_set_file_extent_disk_bytenr(leaf, fi, disk_bytenr);
2173 btrfs_set_file_extent_disk_num_bytes(leaf, fi, disk_num_bytes);
2174 btrfs_set_file_extent_offset(leaf, fi, 0);
2175 btrfs_set_file_extent_num_bytes(leaf, fi, num_bytes);
2176 btrfs_set_file_extent_ram_bytes(leaf, fi, ram_bytes);
2177 btrfs_set_file_extent_compression(leaf, fi, compression);
2178 btrfs_set_file_extent_encryption(leaf, fi, encryption);
2179 btrfs_set_file_extent_other_encoding(leaf, fi, other_encoding);
2181 btrfs_mark_buffer_dirty(leaf);
2182 btrfs_release_path(path);
2184 inode_add_bytes(inode, num_bytes);
2186 ins.objectid = disk_bytenr;
2187 ins.offset = disk_num_bytes;
2188 ins.type = BTRFS_EXTENT_ITEM_KEY;
2189 ret = btrfs_alloc_reserved_file_extent(trans, root,
2190 root->root_key.objectid,
2191 btrfs_ino(inode), file_pos,
2194 * Release the reserved range from inode dirty range map, as it is
2195 * already moved into delayed_ref_head
2197 btrfs_qgroup_release_data(inode, file_pos, ram_bytes);
2199 btrfs_free_path(path);
2204 /* snapshot-aware defrag */
2205 struct sa_defrag_extent_backref {
2206 struct rb_node node;
2207 struct old_sa_defrag_extent *old;
2216 struct old_sa_defrag_extent {
2217 struct list_head list;
2218 struct new_sa_defrag_extent *new;
2227 struct new_sa_defrag_extent {
2228 struct rb_root root;
2229 struct list_head head;
2230 struct btrfs_path *path;
2231 struct inode *inode;
2239 static int backref_comp(struct sa_defrag_extent_backref *b1,
2240 struct sa_defrag_extent_backref *b2)
2242 if (b1->root_id < b2->root_id)
2244 else if (b1->root_id > b2->root_id)
2247 if (b1->inum < b2->inum)
2249 else if (b1->inum > b2->inum)
2252 if (b1->file_pos < b2->file_pos)
2254 else if (b1->file_pos > b2->file_pos)
2258 * [------------------------------] ===> (a range of space)
2259 * |<--->| |<---->| =============> (fs/file tree A)
2260 * |<---------------------------->| ===> (fs/file tree B)
2262 * A range of space can refer to two file extents in one tree while
2263 * refer to only one file extent in another tree.
2265 * So we may process a disk offset more than one time(two extents in A)
2266 * and locate at the same extent(one extent in B), then insert two same
2267 * backrefs(both refer to the extent in B).
2272 static void backref_insert(struct rb_root *root,
2273 struct sa_defrag_extent_backref *backref)
2275 struct rb_node **p = &root->rb_node;
2276 struct rb_node *parent = NULL;
2277 struct sa_defrag_extent_backref *entry;
2282 entry = rb_entry(parent, struct sa_defrag_extent_backref, node);
2284 ret = backref_comp(backref, entry);
2288 p = &(*p)->rb_right;
2291 rb_link_node(&backref->node, parent, p);
2292 rb_insert_color(&backref->node, root);
2296 * Note the backref might has changed, and in this case we just return 0.
2298 static noinline int record_one_backref(u64 inum, u64 offset, u64 root_id,
2301 struct btrfs_file_extent_item *extent;
2302 struct btrfs_fs_info *fs_info;
2303 struct old_sa_defrag_extent *old = ctx;
2304 struct new_sa_defrag_extent *new = old->new;
2305 struct btrfs_path *path = new->path;
2306 struct btrfs_key key;
2307 struct btrfs_root *root;
2308 struct sa_defrag_extent_backref *backref;
2309 struct extent_buffer *leaf;
2310 struct inode *inode = new->inode;
2316 if (BTRFS_I(inode)->root->root_key.objectid == root_id &&
2317 inum == btrfs_ino(inode))
2320 key.objectid = root_id;
2321 key.type = BTRFS_ROOT_ITEM_KEY;
2322 key.offset = (u64)-1;
2324 fs_info = BTRFS_I(inode)->root->fs_info;
2325 root = btrfs_read_fs_root_no_name(fs_info, &key);
2327 if (PTR_ERR(root) == -ENOENT)
2330 pr_debug("inum=%llu, offset=%llu, root_id=%llu\n",
2331 inum, offset, root_id);
2332 return PTR_ERR(root);
2335 key.objectid = inum;
2336 key.type = BTRFS_EXTENT_DATA_KEY;
2337 if (offset > (u64)-1 << 32)
2340 key.offset = offset;
2342 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2343 if (WARN_ON(ret < 0))
2350 leaf = path->nodes[0];
2351 slot = path->slots[0];
2353 if (slot >= btrfs_header_nritems(leaf)) {
2354 ret = btrfs_next_leaf(root, path);
2357 } else if (ret > 0) {
2366 btrfs_item_key_to_cpu(leaf, &key, slot);
2368 if (key.objectid > inum)
2371 if (key.objectid < inum || key.type != BTRFS_EXTENT_DATA_KEY)
2374 extent = btrfs_item_ptr(leaf, slot,
2375 struct btrfs_file_extent_item);
2377 if (btrfs_file_extent_disk_bytenr(leaf, extent) != old->bytenr)
2381 * 'offset' refers to the exact key.offset,
2382 * NOT the 'offset' field in btrfs_extent_data_ref, ie.
2383 * (key.offset - extent_offset).
2385 if (key.offset != offset)
2388 extent_offset = btrfs_file_extent_offset(leaf, extent);
2389 num_bytes = btrfs_file_extent_num_bytes(leaf, extent);
2391 if (extent_offset >= old->extent_offset + old->offset +
2392 old->len || extent_offset + num_bytes <=
2393 old->extent_offset + old->offset)
2398 backref = kmalloc(sizeof(*backref), GFP_NOFS);
2404 backref->root_id = root_id;
2405 backref->inum = inum;
2406 backref->file_pos = offset;
2407 backref->num_bytes = num_bytes;
2408 backref->extent_offset = extent_offset;
2409 backref->generation = btrfs_file_extent_generation(leaf, extent);
2411 backref_insert(&new->root, backref);
2414 btrfs_release_path(path);
2419 static noinline bool record_extent_backrefs(struct btrfs_path *path,
2420 struct new_sa_defrag_extent *new)
2422 struct btrfs_fs_info *fs_info = BTRFS_I(new->inode)->root->fs_info;
2423 struct old_sa_defrag_extent *old, *tmp;
2428 list_for_each_entry_safe(old, tmp, &new->head, list) {
2429 ret = iterate_inodes_from_logical(old->bytenr +
2430 old->extent_offset, fs_info,
2431 path, record_one_backref,
2433 if (ret < 0 && ret != -ENOENT)
2436 /* no backref to be processed for this extent */
2438 list_del(&old->list);
2443 if (list_empty(&new->head))
2449 static int relink_is_mergable(struct extent_buffer *leaf,
2450 struct btrfs_file_extent_item *fi,
2451 struct new_sa_defrag_extent *new)
2453 if (btrfs_file_extent_disk_bytenr(leaf, fi) != new->bytenr)
2456 if (btrfs_file_extent_type(leaf, fi) != BTRFS_FILE_EXTENT_REG)
2459 if (btrfs_file_extent_compression(leaf, fi) != new->compress_type)
2462 if (btrfs_file_extent_encryption(leaf, fi) ||
2463 btrfs_file_extent_other_encoding(leaf, fi))
2470 * Note the backref might has changed, and in this case we just return 0.
2472 static noinline int relink_extent_backref(struct btrfs_path *path,
2473 struct sa_defrag_extent_backref *prev,
2474 struct sa_defrag_extent_backref *backref)
2476 struct btrfs_file_extent_item *extent;
2477 struct btrfs_file_extent_item *item;
2478 struct btrfs_ordered_extent *ordered;
2479 struct btrfs_trans_handle *trans;
2480 struct btrfs_fs_info *fs_info;
2481 struct btrfs_root *root;
2482 struct btrfs_key key;
2483 struct extent_buffer *leaf;
2484 struct old_sa_defrag_extent *old = backref->old;
2485 struct new_sa_defrag_extent *new = old->new;
2486 struct inode *src_inode = new->inode;
2487 struct inode *inode;
2488 struct extent_state *cached = NULL;
2497 if (prev && prev->root_id == backref->root_id &&
2498 prev->inum == backref->inum &&
2499 prev->file_pos + prev->num_bytes == backref->file_pos)
2502 /* step 1: get root */
2503 key.objectid = backref->root_id;
2504 key.type = BTRFS_ROOT_ITEM_KEY;
2505 key.offset = (u64)-1;
2507 fs_info = BTRFS_I(src_inode)->root->fs_info;
2508 index = srcu_read_lock(&fs_info->subvol_srcu);
2510 root = btrfs_read_fs_root_no_name(fs_info, &key);
2512 srcu_read_unlock(&fs_info->subvol_srcu, index);
2513 if (PTR_ERR(root) == -ENOENT)
2515 return PTR_ERR(root);
2518 if (btrfs_root_readonly(root)) {
2519 srcu_read_unlock(&fs_info->subvol_srcu, index);
2523 /* step 2: get inode */
2524 key.objectid = backref->inum;
2525 key.type = BTRFS_INODE_ITEM_KEY;
2528 inode = btrfs_iget(fs_info->sb, &key, root, NULL);
2529 if (IS_ERR(inode)) {
2530 srcu_read_unlock(&fs_info->subvol_srcu, index);
2534 srcu_read_unlock(&fs_info->subvol_srcu, index);
2536 /* step 3: relink backref */
2537 lock_start = backref->file_pos;
2538 lock_end = backref->file_pos + backref->num_bytes - 1;
2539 lock_extent_bits(&BTRFS_I(inode)->io_tree, lock_start, lock_end,
2542 ordered = btrfs_lookup_first_ordered_extent(inode, lock_end);
2544 btrfs_put_ordered_extent(ordered);
2548 trans = btrfs_join_transaction(root);
2549 if (IS_ERR(trans)) {
2550 ret = PTR_ERR(trans);
2554 key.objectid = backref->inum;
2555 key.type = BTRFS_EXTENT_DATA_KEY;
2556 key.offset = backref->file_pos;
2558 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2561 } else if (ret > 0) {
2566 extent = btrfs_item_ptr(path->nodes[0], path->slots[0],
2567 struct btrfs_file_extent_item);
2569 if (btrfs_file_extent_generation(path->nodes[0], extent) !=
2570 backref->generation)
2573 btrfs_release_path(path);
2575 start = backref->file_pos;
2576 if (backref->extent_offset < old->extent_offset + old->offset)
2577 start += old->extent_offset + old->offset -
2578 backref->extent_offset;
2580 len = min(backref->extent_offset + backref->num_bytes,
2581 old->extent_offset + old->offset + old->len);
2582 len -= max(backref->extent_offset, old->extent_offset + old->offset);
2584 ret = btrfs_drop_extents(trans, root, inode, start,
2589 key.objectid = btrfs_ino(inode);
2590 key.type = BTRFS_EXTENT_DATA_KEY;
2593 path->leave_spinning = 1;
2595 struct btrfs_file_extent_item *fi;
2597 struct btrfs_key found_key;
2599 ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
2604 leaf = path->nodes[0];
2605 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
2607 fi = btrfs_item_ptr(leaf, path->slots[0],
2608 struct btrfs_file_extent_item);
2609 extent_len = btrfs_file_extent_num_bytes(leaf, fi);
2611 if (extent_len + found_key.offset == start &&
2612 relink_is_mergable(leaf, fi, new)) {
2613 btrfs_set_file_extent_num_bytes(leaf, fi,
2615 btrfs_mark_buffer_dirty(leaf);
2616 inode_add_bytes(inode, len);
2622 btrfs_release_path(path);
2627 ret = btrfs_insert_empty_item(trans, root, path, &key,
2630 btrfs_abort_transaction(trans, root, ret);
2634 leaf = path->nodes[0];
2635 item = btrfs_item_ptr(leaf, path->slots[0],
2636 struct btrfs_file_extent_item);
2637 btrfs_set_file_extent_disk_bytenr(leaf, item, new->bytenr);
2638 btrfs_set_file_extent_disk_num_bytes(leaf, item, new->disk_len);
2639 btrfs_set_file_extent_offset(leaf, item, start - new->file_pos);
2640 btrfs_set_file_extent_num_bytes(leaf, item, len);
2641 btrfs_set_file_extent_ram_bytes(leaf, item, new->len);
2642 btrfs_set_file_extent_generation(leaf, item, trans->transid);
2643 btrfs_set_file_extent_type(leaf, item, BTRFS_FILE_EXTENT_REG);
2644 btrfs_set_file_extent_compression(leaf, item, new->compress_type);
2645 btrfs_set_file_extent_encryption(leaf, item, 0);
2646 btrfs_set_file_extent_other_encoding(leaf, item, 0);
2648 btrfs_mark_buffer_dirty(leaf);
2649 inode_add_bytes(inode, len);
2650 btrfs_release_path(path);
2652 ret = btrfs_inc_extent_ref(trans, root, new->bytenr,
2654 backref->root_id, backref->inum,
2655 new->file_pos); /* start - extent_offset */
2657 btrfs_abort_transaction(trans, root, ret);
2663 btrfs_release_path(path);
2664 path->leave_spinning = 0;
2665 btrfs_end_transaction(trans, root);
2667 unlock_extent_cached(&BTRFS_I(inode)->io_tree, lock_start, lock_end,
2673 static void free_sa_defrag_extent(struct new_sa_defrag_extent *new)
2675 struct old_sa_defrag_extent *old, *tmp;
2680 list_for_each_entry_safe(old, tmp, &new->head, list) {
2686 static void relink_file_extents(struct new_sa_defrag_extent *new)
2688 struct btrfs_path *path;
2689 struct sa_defrag_extent_backref *backref;
2690 struct sa_defrag_extent_backref *prev = NULL;
2691 struct inode *inode;
2692 struct btrfs_root *root;
2693 struct rb_node *node;
2697 root = BTRFS_I(inode)->root;
2699 path = btrfs_alloc_path();
2703 if (!record_extent_backrefs(path, new)) {
2704 btrfs_free_path(path);
2707 btrfs_release_path(path);
2710 node = rb_first(&new->root);
2713 rb_erase(node, &new->root);
2715 backref = rb_entry(node, struct sa_defrag_extent_backref, node);
2717 ret = relink_extent_backref(path, prev, backref);
2730 btrfs_free_path(path);
2732 free_sa_defrag_extent(new);
2734 atomic_dec(&root->fs_info->defrag_running);
2735 wake_up(&root->fs_info->transaction_wait);
2738 static struct new_sa_defrag_extent *
2739 record_old_file_extents(struct inode *inode,
2740 struct btrfs_ordered_extent *ordered)
2742 struct btrfs_root *root = BTRFS_I(inode)->root;
2743 struct btrfs_path *path;
2744 struct btrfs_key key;
2745 struct old_sa_defrag_extent *old;
2746 struct new_sa_defrag_extent *new;
2749 new = kmalloc(sizeof(*new), GFP_NOFS);
2754 new->file_pos = ordered->file_offset;
2755 new->len = ordered->len;
2756 new->bytenr = ordered->start;
2757 new->disk_len = ordered->disk_len;
2758 new->compress_type = ordered->compress_type;
2759 new->root = RB_ROOT;
2760 INIT_LIST_HEAD(&new->head);
2762 path = btrfs_alloc_path();
2766 key.objectid = btrfs_ino(inode);
2767 key.type = BTRFS_EXTENT_DATA_KEY;
2768 key.offset = new->file_pos;
2770 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2773 if (ret > 0 && path->slots[0] > 0)
2776 /* find out all the old extents for the file range */
2778 struct btrfs_file_extent_item *extent;
2779 struct extent_buffer *l;
2788 slot = path->slots[0];
2790 if (slot >= btrfs_header_nritems(l)) {
2791 ret = btrfs_next_leaf(root, path);
2799 btrfs_item_key_to_cpu(l, &key, slot);
2801 if (key.objectid != btrfs_ino(inode))
2803 if (key.type != BTRFS_EXTENT_DATA_KEY)
2805 if (key.offset >= new->file_pos + new->len)
2808 extent = btrfs_item_ptr(l, slot, struct btrfs_file_extent_item);
2810 num_bytes = btrfs_file_extent_num_bytes(l, extent);
2811 if (key.offset + num_bytes < new->file_pos)
2814 disk_bytenr = btrfs_file_extent_disk_bytenr(l, extent);
2818 extent_offset = btrfs_file_extent_offset(l, extent);
2820 old = kmalloc(sizeof(*old), GFP_NOFS);
2824 offset = max(new->file_pos, key.offset);
2825 end = min(new->file_pos + new->len, key.offset + num_bytes);
2827 old->bytenr = disk_bytenr;
2828 old->extent_offset = extent_offset;
2829 old->offset = offset - key.offset;
2830 old->len = end - offset;
2833 list_add_tail(&old->list, &new->head);
2839 btrfs_free_path(path);
2840 atomic_inc(&root->fs_info->defrag_running);
2845 btrfs_free_path(path);
2847 free_sa_defrag_extent(new);
2851 static void btrfs_release_delalloc_bytes(struct btrfs_root *root,
2854 struct btrfs_block_group_cache *cache;
2856 cache = btrfs_lookup_block_group(root->fs_info, start);
2859 spin_lock(&cache->lock);
2860 cache->delalloc_bytes -= len;
2861 spin_unlock(&cache->lock);
2863 btrfs_put_block_group(cache);
2866 /* as ordered data IO finishes, this gets called so we can finish
2867 * an ordered extent if the range of bytes in the file it covers are
2870 static int btrfs_finish_ordered_io(struct btrfs_ordered_extent *ordered_extent)
2872 struct inode *inode = ordered_extent->inode;
2873 struct btrfs_root *root = BTRFS_I(inode)->root;
2874 struct btrfs_trans_handle *trans = NULL;
2875 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
2876 struct extent_state *cached_state = NULL;
2877 struct new_sa_defrag_extent *new = NULL;
2878 int compress_type = 0;
2880 u64 logical_len = ordered_extent->len;
2882 bool truncated = false;
2884 nolock = btrfs_is_free_space_inode(inode);
2886 if (test_bit(BTRFS_ORDERED_IOERR, &ordered_extent->flags)) {
2891 btrfs_free_io_failure_record(inode, ordered_extent->file_offset,
2892 ordered_extent->file_offset +
2893 ordered_extent->len - 1);
2895 if (test_bit(BTRFS_ORDERED_TRUNCATED, &ordered_extent->flags)) {
2897 logical_len = ordered_extent->truncated_len;
2898 /* Truncated the entire extent, don't bother adding */
2903 if (test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags)) {
2904 BUG_ON(!list_empty(&ordered_extent->list)); /* Logic error */
2907 * For mwrite(mmap + memset to write) case, we still reserve
2908 * space for NOCOW range.
2909 * As NOCOW won't cause a new delayed ref, just free the space
2911 btrfs_qgroup_free_data(inode, ordered_extent->file_offset,
2912 ordered_extent->len);
2913 btrfs_ordered_update_i_size(inode, 0, ordered_extent);
2915 trans = btrfs_join_transaction_nolock(root);
2917 trans = btrfs_join_transaction(root);
2918 if (IS_ERR(trans)) {
2919 ret = PTR_ERR(trans);
2923 trans->block_rsv = &root->fs_info->delalloc_block_rsv;
2924 ret = btrfs_update_inode_fallback(trans, root, inode);
2925 if (ret) /* -ENOMEM or corruption */
2926 btrfs_abort_transaction(trans, root, ret);
2930 lock_extent_bits(io_tree, ordered_extent->file_offset,
2931 ordered_extent->file_offset + ordered_extent->len - 1,
2934 ret = test_range_bit(io_tree, ordered_extent->file_offset,
2935 ordered_extent->file_offset + ordered_extent->len - 1,
2936 EXTENT_DEFRAG, 1, cached_state);
2938 u64 last_snapshot = btrfs_root_last_snapshot(&root->root_item);
2939 if (0 && last_snapshot >= BTRFS_I(inode)->generation)
2940 /* the inode is shared */
2941 new = record_old_file_extents(inode, ordered_extent);
2943 clear_extent_bit(io_tree, ordered_extent->file_offset,
2944 ordered_extent->file_offset + ordered_extent->len - 1,
2945 EXTENT_DEFRAG, 0, 0, &cached_state, GFP_NOFS);
2949 trans = btrfs_join_transaction_nolock(root);
2951 trans = btrfs_join_transaction(root);
2952 if (IS_ERR(trans)) {
2953 ret = PTR_ERR(trans);
2958 trans->block_rsv = &root->fs_info->delalloc_block_rsv;
2960 if (test_bit(BTRFS_ORDERED_COMPRESSED, &ordered_extent->flags))
2961 compress_type = ordered_extent->compress_type;
2962 if (test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags)) {
2963 BUG_ON(compress_type);
2964 ret = btrfs_mark_extent_written(trans, inode,
2965 ordered_extent->file_offset,
2966 ordered_extent->file_offset +
2969 BUG_ON(root == root->fs_info->tree_root);
2970 ret = insert_reserved_file_extent(trans, inode,
2971 ordered_extent->file_offset,
2972 ordered_extent->start,
2973 ordered_extent->disk_len,
2974 logical_len, logical_len,
2975 compress_type, 0, 0,
2976 BTRFS_FILE_EXTENT_REG);
2978 btrfs_release_delalloc_bytes(root,
2979 ordered_extent->start,
2980 ordered_extent->disk_len);
2982 unpin_extent_cache(&BTRFS_I(inode)->extent_tree,
2983 ordered_extent->file_offset, ordered_extent->len,
2986 btrfs_abort_transaction(trans, root, ret);
2990 add_pending_csums(trans, inode, ordered_extent->file_offset,
2991 &ordered_extent->list);
2993 btrfs_ordered_update_i_size(inode, 0, ordered_extent);
2994 ret = btrfs_update_inode_fallback(trans, root, inode);
2995 if (ret) { /* -ENOMEM or corruption */
2996 btrfs_abort_transaction(trans, root, ret);
3001 unlock_extent_cached(io_tree, ordered_extent->file_offset,
3002 ordered_extent->file_offset +
3003 ordered_extent->len - 1, &cached_state, GFP_NOFS);
3005 if (root != root->fs_info->tree_root)
3006 btrfs_delalloc_release_metadata(inode, ordered_extent->len);
3008 btrfs_end_transaction(trans, root);
3010 if (ret || truncated) {
3014 start = ordered_extent->file_offset + logical_len;
3016 start = ordered_extent->file_offset;
3017 end = ordered_extent->file_offset + ordered_extent->len - 1;
3018 clear_extent_uptodate(io_tree, start, end, NULL, GFP_NOFS);
3020 /* Drop the cache for the part of the extent we didn't write. */
3021 btrfs_drop_extent_cache(inode, start, end, 0);
3024 * If the ordered extent had an IOERR or something else went
3025 * wrong we need to return the space for this ordered extent
3026 * back to the allocator. We only free the extent in the
3027 * truncated case if we didn't write out the extent at all.
3029 if ((ret || !logical_len) &&
3030 !test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags) &&
3031 !test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags))
3032 btrfs_free_reserved_extent(root, ordered_extent->start,
3033 ordered_extent->disk_len, 1);
3038 * This needs to be done to make sure anybody waiting knows we are done
3039 * updating everything for this ordered extent.
3041 btrfs_remove_ordered_extent(inode, ordered_extent);
3043 /* for snapshot-aware defrag */
3046 free_sa_defrag_extent(new);
3047 atomic_dec(&root->fs_info->defrag_running);
3049 relink_file_extents(new);
3054 btrfs_put_ordered_extent(ordered_extent);
3055 /* once for the tree */
3056 btrfs_put_ordered_extent(ordered_extent);
3061 static void finish_ordered_fn(struct btrfs_work *work)
3063 struct btrfs_ordered_extent *ordered_extent;
3064 ordered_extent = container_of(work, struct btrfs_ordered_extent, work);
3065 btrfs_finish_ordered_io(ordered_extent);
3068 static int btrfs_writepage_end_io_hook(struct page *page, u64 start, u64 end,
3069 struct extent_state *state, int uptodate)
3071 struct inode *inode = page->mapping->host;
3072 struct btrfs_root *root = BTRFS_I(inode)->root;
3073 struct btrfs_ordered_extent *ordered_extent = NULL;
3074 struct btrfs_workqueue *wq;
3075 btrfs_work_func_t func;
3077 trace_btrfs_writepage_end_io_hook(page, start, end, uptodate);
3079 ClearPagePrivate2(page);
3080 if (!btrfs_dec_test_ordered_pending(inode, &ordered_extent, start,
3081 end - start + 1, uptodate))
3084 if (btrfs_is_free_space_inode(inode)) {
3085 wq = root->fs_info->endio_freespace_worker;
3086 func = btrfs_freespace_write_helper;
3088 wq = root->fs_info->endio_write_workers;
3089 func = btrfs_endio_write_helper;
3092 btrfs_init_work(&ordered_extent->work, func, finish_ordered_fn, NULL,
3094 btrfs_queue_work(wq, &ordered_extent->work);
3099 static int __readpage_endio_check(struct inode *inode,
3100 struct btrfs_io_bio *io_bio,
3101 int icsum, struct page *page,
3102 int pgoff, u64 start, size_t len)
3108 csum_expected = *(((u32 *)io_bio->csum) + icsum);
3110 kaddr = kmap_atomic(page);
3111 csum = btrfs_csum_data(kaddr + pgoff, csum, len);
3112 btrfs_csum_final(csum, (char *)&csum);
3113 if (csum != csum_expected)
3116 kunmap_atomic(kaddr);
3119 btrfs_warn_rl(BTRFS_I(inode)->root->fs_info,
3120 "csum failed ino %llu off %llu csum %u expected csum %u",
3121 btrfs_ino(inode), start, csum, csum_expected);
3122 memset(kaddr + pgoff, 1, len);
3123 flush_dcache_page(page);
3124 kunmap_atomic(kaddr);
3125 if (csum_expected == 0)
3131 * when reads are done, we need to check csums to verify the data is correct
3132 * if there's a match, we allow the bio to finish. If not, the code in
3133 * extent_io.c will try to find good copies for us.
3135 static int btrfs_readpage_end_io_hook(struct btrfs_io_bio *io_bio,
3136 u64 phy_offset, struct page *page,
3137 u64 start, u64 end, int mirror)
3139 size_t offset = start - page_offset(page);
3140 struct inode *inode = page->mapping->host;
3141 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
3142 struct btrfs_root *root = BTRFS_I(inode)->root;
3144 if (PageChecked(page)) {
3145 ClearPageChecked(page);
3149 if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)
3152 if (root->root_key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID &&
3153 test_range_bit(io_tree, start, end, EXTENT_NODATASUM, 1, NULL)) {
3154 clear_extent_bits(io_tree, start, end, EXTENT_NODATASUM,
3159 phy_offset >>= inode->i_sb->s_blocksize_bits;
3160 return __readpage_endio_check(inode, io_bio, phy_offset, page, offset,
3161 start, (size_t)(end - start + 1));
3164 struct delayed_iput {
3165 struct list_head list;
3166 struct inode *inode;
3169 /* JDM: If this is fs-wide, why can't we add a pointer to
3170 * btrfs_inode instead and avoid the allocation? */
3171 void btrfs_add_delayed_iput(struct inode *inode)
3173 struct btrfs_fs_info *fs_info = BTRFS_I(inode)->root->fs_info;
3174 struct delayed_iput *delayed;
3176 if (atomic_add_unless(&inode->i_count, -1, 1))
3179 delayed = kmalloc(sizeof(*delayed), GFP_NOFS | __GFP_NOFAIL);
3180 delayed->inode = inode;
3182 spin_lock(&fs_info->delayed_iput_lock);
3183 list_add_tail(&delayed->list, &fs_info->delayed_iputs);
3184 spin_unlock(&fs_info->delayed_iput_lock);
3187 void btrfs_run_delayed_iputs(struct btrfs_root *root)
3190 struct btrfs_fs_info *fs_info = root->fs_info;
3191 struct delayed_iput *delayed;
3194 spin_lock(&fs_info->delayed_iput_lock);
3195 empty = list_empty(&fs_info->delayed_iputs);
3196 spin_unlock(&fs_info->delayed_iput_lock);
3200 spin_lock(&fs_info->delayed_iput_lock);
3201 list_splice_init(&fs_info->delayed_iputs, &list);
3202 spin_unlock(&fs_info->delayed_iput_lock);
3204 while (!list_empty(&list)) {
3205 delayed = list_entry(list.next, struct delayed_iput, list);
3206 list_del(&delayed->list);
3207 iput(delayed->inode);
3213 * This is called in transaction commit time. If there are no orphan
3214 * files in the subvolume, it removes orphan item and frees block_rsv
3217 void btrfs_orphan_commit_root(struct btrfs_trans_handle *trans,
3218 struct btrfs_root *root)
3220 struct btrfs_block_rsv *block_rsv;
3223 if (atomic_read(&root->orphan_inodes) ||
3224 root->orphan_cleanup_state != ORPHAN_CLEANUP_DONE)
3227 spin_lock(&root->orphan_lock);
3228 if (atomic_read(&root->orphan_inodes)) {
3229 spin_unlock(&root->orphan_lock);
3233 if (root->orphan_cleanup_state != ORPHAN_CLEANUP_DONE) {
3234 spin_unlock(&root->orphan_lock);
3238 block_rsv = root->orphan_block_rsv;
3239 root->orphan_block_rsv = NULL;
3240 spin_unlock(&root->orphan_lock);
3242 if (test_bit(BTRFS_ROOT_ORPHAN_ITEM_INSERTED, &root->state) &&
3243 btrfs_root_refs(&root->root_item) > 0) {
3244 ret = btrfs_del_orphan_item(trans, root->fs_info->tree_root,
3245 root->root_key.objectid);
3247 btrfs_abort_transaction(trans, root, ret);
3249 clear_bit(BTRFS_ROOT_ORPHAN_ITEM_INSERTED,
3254 WARN_ON(block_rsv->size > 0);
3255 btrfs_free_block_rsv(root, block_rsv);
3260 * This creates an orphan entry for the given inode in case something goes
3261 * wrong in the middle of an unlink/truncate.
3263 * NOTE: caller of this function should reserve 5 units of metadata for
3266 int btrfs_orphan_add(struct btrfs_trans_handle *trans, struct inode *inode)
3268 struct btrfs_root *root = BTRFS_I(inode)->root;
3269 struct btrfs_block_rsv *block_rsv = NULL;
3274 if (!root->orphan_block_rsv) {
3275 block_rsv = btrfs_alloc_block_rsv(root, BTRFS_BLOCK_RSV_TEMP);
3280 spin_lock(&root->orphan_lock);
3281 if (!root->orphan_block_rsv) {
3282 root->orphan_block_rsv = block_rsv;
3283 } else if (block_rsv) {
3284 btrfs_free_block_rsv(root, block_rsv);
3288 if (!test_and_set_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
3289 &BTRFS_I(inode)->runtime_flags)) {
3292 * For proper ENOSPC handling, we should do orphan
3293 * cleanup when mounting. But this introduces backward
3294 * compatibility issue.
3296 if (!xchg(&root->orphan_item_inserted, 1))
3302 atomic_inc(&root->orphan_inodes);
3305 if (!test_and_set_bit(BTRFS_INODE_ORPHAN_META_RESERVED,
3306 &BTRFS_I(inode)->runtime_flags))
3308 spin_unlock(&root->orphan_lock);
3310 /* grab metadata reservation from transaction handle */
3312 ret = btrfs_orphan_reserve_metadata(trans, inode);
3313 BUG_ON(ret); /* -ENOSPC in reservation; Logic error? JDM */
3316 /* insert an orphan item to track this unlinked/truncated file */
3318 ret = btrfs_insert_orphan_item(trans, root, btrfs_ino(inode));
3320 atomic_dec(&root->orphan_inodes);
3322 clear_bit(BTRFS_INODE_ORPHAN_META_RESERVED,
3323 &BTRFS_I(inode)->runtime_flags);
3324 btrfs_orphan_release_metadata(inode);
3326 if (ret != -EEXIST) {
3327 clear_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
3328 &BTRFS_I(inode)->runtime_flags);
3329 btrfs_abort_transaction(trans, root, ret);
3336 /* insert an orphan item to track subvolume contains orphan files */
3338 ret = btrfs_insert_orphan_item(trans, root->fs_info->tree_root,
3339 root->root_key.objectid);
3340 if (ret && ret != -EEXIST) {
3341 btrfs_abort_transaction(trans, root, ret);
3349 * We have done the truncate/delete so we can go ahead and remove the orphan
3350 * item for this particular inode.
3352 static int btrfs_orphan_del(struct btrfs_trans_handle *trans,
3353 struct inode *inode)
3355 struct btrfs_root *root = BTRFS_I(inode)->root;
3356 int delete_item = 0;
3357 int release_rsv = 0;
3360 spin_lock(&root->orphan_lock);
3361 if (test_and_clear_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
3362 &BTRFS_I(inode)->runtime_flags))
3365 if (test_and_clear_bit(BTRFS_INODE_ORPHAN_META_RESERVED,
3366 &BTRFS_I(inode)->runtime_flags))
3368 spin_unlock(&root->orphan_lock);
3371 atomic_dec(&root->orphan_inodes);
3373 ret = btrfs_del_orphan_item(trans, root,
3378 btrfs_orphan_release_metadata(inode);
3384 * this cleans up any orphans that may be left on the list from the last use
3387 int btrfs_orphan_cleanup(struct btrfs_root *root)
3389 struct btrfs_path *path;
3390 struct extent_buffer *leaf;
3391 struct btrfs_key key, found_key;
3392 struct btrfs_trans_handle *trans;
3393 struct inode *inode;
3394 u64 last_objectid = 0;
3395 int ret = 0, nr_unlink = 0, nr_truncate = 0;
3397 if (cmpxchg(&root->orphan_cleanup_state, 0, ORPHAN_CLEANUP_STARTED))
3400 path = btrfs_alloc_path();
3407 key.objectid = BTRFS_ORPHAN_OBJECTID;
3408 key.type = BTRFS_ORPHAN_ITEM_KEY;
3409 key.offset = (u64)-1;
3412 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
3417 * if ret == 0 means we found what we were searching for, which
3418 * is weird, but possible, so only screw with path if we didn't
3419 * find the key and see if we have stuff that matches
3423 if (path->slots[0] == 0)
3428 /* pull out the item */
3429 leaf = path->nodes[0];
3430 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
3432 /* make sure the item matches what we want */
3433 if (found_key.objectid != BTRFS_ORPHAN_OBJECTID)
3435 if (found_key.type != BTRFS_ORPHAN_ITEM_KEY)
3438 /* release the path since we're done with it */
3439 btrfs_release_path(path);
3442 * this is where we are basically btrfs_lookup, without the
3443 * crossing root thing. we store the inode number in the
3444 * offset of the orphan item.
3447 if (found_key.offset == last_objectid) {
3448 btrfs_err(root->fs_info,
3449 "Error removing orphan entry, stopping orphan cleanup");
3454 last_objectid = found_key.offset;
3456 found_key.objectid = found_key.offset;
3457 found_key.type = BTRFS_INODE_ITEM_KEY;
3458 found_key.offset = 0;
3459 inode = btrfs_iget(root->fs_info->sb, &found_key, root, NULL);
3460 ret = PTR_ERR_OR_ZERO(inode);
3461 if (ret && ret != -ESTALE)
3464 if (ret == -ESTALE && root == root->fs_info->tree_root) {
3465 struct btrfs_root *dead_root;
3466 struct btrfs_fs_info *fs_info = root->fs_info;
3467 int is_dead_root = 0;
3470 * this is an orphan in the tree root. Currently these
3471 * could come from 2 sources:
3472 * a) a snapshot deletion in progress
3473 * b) a free space cache inode
3474 * We need to distinguish those two, as the snapshot
3475 * orphan must not get deleted.
3476 * find_dead_roots already ran before us, so if this
3477 * is a snapshot deletion, we should find the root
3478 * in the dead_roots list
3480 spin_lock(&fs_info->trans_lock);
3481 list_for_each_entry(dead_root, &fs_info->dead_roots,
3483 if (dead_root->root_key.objectid ==
3484 found_key.objectid) {
3489 spin_unlock(&fs_info->trans_lock);
3491 /* prevent this orphan from being found again */
3492 key.offset = found_key.objectid - 1;
3497 * Inode is already gone but the orphan item is still there,
3498 * kill the orphan item.
3500 if (ret == -ESTALE) {
3501 trans = btrfs_start_transaction(root, 1);
3502 if (IS_ERR(trans)) {
3503 ret = PTR_ERR(trans);
3506 btrfs_debug(root->fs_info, "auto deleting %Lu",
3507 found_key.objectid);
3508 ret = btrfs_del_orphan_item(trans, root,
3509 found_key.objectid);
3510 btrfs_end_transaction(trans, root);
3517 * add this inode to the orphan list so btrfs_orphan_del does
3518 * the proper thing when we hit it
3520 set_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
3521 &BTRFS_I(inode)->runtime_flags);
3522 atomic_inc(&root->orphan_inodes);
3524 /* if we have links, this was a truncate, lets do that */
3525 if (inode->i_nlink) {
3526 if (WARN_ON(!S_ISREG(inode->i_mode))) {
3532 /* 1 for the orphan item deletion. */
3533 trans = btrfs_start_transaction(root, 1);
3534 if (IS_ERR(trans)) {
3536 ret = PTR_ERR(trans);
3539 ret = btrfs_orphan_add(trans, inode);
3540 btrfs_end_transaction(trans, root);
3546 ret = btrfs_truncate(inode);
3548 btrfs_orphan_del(NULL, inode);
3553 /* this will do delete_inode and everything for us */
3558 /* release the path since we're done with it */
3559 btrfs_release_path(path);
3561 root->orphan_cleanup_state = ORPHAN_CLEANUP_DONE;
3563 if (root->orphan_block_rsv)
3564 btrfs_block_rsv_release(root, root->orphan_block_rsv,
3567 if (root->orphan_block_rsv ||
3568 test_bit(BTRFS_ROOT_ORPHAN_ITEM_INSERTED, &root->state)) {
3569 trans = btrfs_join_transaction(root);
3571 btrfs_end_transaction(trans, root);
3575 btrfs_debug(root->fs_info, "unlinked %d orphans", nr_unlink);
3577 btrfs_debug(root->fs_info, "truncated %d orphans", nr_truncate);
3581 btrfs_err(root->fs_info,
3582 "could not do orphan cleanup %d", ret);
3583 btrfs_free_path(path);
3588 * very simple check to peek ahead in the leaf looking for xattrs. If we
3589 * don't find any xattrs, we know there can't be any acls.
3591 * slot is the slot the inode is in, objectid is the objectid of the inode
3593 static noinline int acls_after_inode_item(struct extent_buffer *leaf,
3594 int slot, u64 objectid,
3595 int *first_xattr_slot)
3597 u32 nritems = btrfs_header_nritems(leaf);
3598 struct btrfs_key found_key;
3599 static u64 xattr_access = 0;
3600 static u64 xattr_default = 0;
3603 if (!xattr_access) {
3604 xattr_access = btrfs_name_hash(POSIX_ACL_XATTR_ACCESS,
3605 strlen(POSIX_ACL_XATTR_ACCESS));
3606 xattr_default = btrfs_name_hash(POSIX_ACL_XATTR_DEFAULT,
3607 strlen(POSIX_ACL_XATTR_DEFAULT));
3611 *first_xattr_slot = -1;
3612 while (slot < nritems) {
3613 btrfs_item_key_to_cpu(leaf, &found_key, slot);
3615 /* we found a different objectid, there must not be acls */
3616 if (found_key.objectid != objectid)
3619 /* we found an xattr, assume we've got an acl */
3620 if (found_key.type == BTRFS_XATTR_ITEM_KEY) {
3621 if (*first_xattr_slot == -1)
3622 *first_xattr_slot = slot;
3623 if (found_key.offset == xattr_access ||
3624 found_key.offset == xattr_default)
3629 * we found a key greater than an xattr key, there can't
3630 * be any acls later on
3632 if (found_key.type > BTRFS_XATTR_ITEM_KEY)
3639 * it goes inode, inode backrefs, xattrs, extents,
3640 * so if there are a ton of hard links to an inode there can
3641 * be a lot of backrefs. Don't waste time searching too hard,
3642 * this is just an optimization
3647 /* we hit the end of the leaf before we found an xattr or
3648 * something larger than an xattr. We have to assume the inode
3651 if (*first_xattr_slot == -1)
3652 *first_xattr_slot = slot;
3657 * read an inode from the btree into the in-memory inode
3659 static void btrfs_read_locked_inode(struct inode *inode)
3661 struct btrfs_path *path;
3662 struct extent_buffer *leaf;
3663 struct btrfs_inode_item *inode_item;
3664 struct btrfs_root *root = BTRFS_I(inode)->root;
3665 struct btrfs_key location;
3670 bool filled = false;
3671 int first_xattr_slot;
3673 ret = btrfs_fill_inode(inode, &rdev);
3677 path = btrfs_alloc_path();
3681 memcpy(&location, &BTRFS_I(inode)->location, sizeof(location));
3683 ret = btrfs_lookup_inode(NULL, root, path, &location, 0);
3687 leaf = path->nodes[0];
3692 inode_item = btrfs_item_ptr(leaf, path->slots[0],
3693 struct btrfs_inode_item);
3694 inode->i_mode = btrfs_inode_mode(leaf, inode_item);
3695 set_nlink(inode, btrfs_inode_nlink(leaf, inode_item));
3696 i_uid_write(inode, btrfs_inode_uid(leaf, inode_item));
3697 i_gid_write(inode, btrfs_inode_gid(leaf, inode_item));
3698 btrfs_i_size_write(inode, btrfs_inode_size(leaf, inode_item));
3700 inode->i_atime.tv_sec = btrfs_timespec_sec(leaf, &inode_item->atime);
3701 inode->i_atime.tv_nsec = btrfs_timespec_nsec(leaf, &inode_item->atime);
3703 inode->i_mtime.tv_sec = btrfs_timespec_sec(leaf, &inode_item->mtime);
3704 inode->i_mtime.tv_nsec = btrfs_timespec_nsec(leaf, &inode_item->mtime);
3706 inode->i_ctime.tv_sec = btrfs_timespec_sec(leaf, &inode_item->ctime);
3707 inode->i_ctime.tv_nsec = btrfs_timespec_nsec(leaf, &inode_item->ctime);
3709 BTRFS_I(inode)->i_otime.tv_sec =
3710 btrfs_timespec_sec(leaf, &inode_item->otime);
3711 BTRFS_I(inode)->i_otime.tv_nsec =
3712 btrfs_timespec_nsec(leaf, &inode_item->otime);
3714 inode_set_bytes(inode, btrfs_inode_nbytes(leaf, inode_item));
3715 BTRFS_I(inode)->generation = btrfs_inode_generation(leaf, inode_item);
3716 BTRFS_I(inode)->last_trans = btrfs_inode_transid(leaf, inode_item);
3718 inode->i_version = btrfs_inode_sequence(leaf, inode_item);
3719 inode->i_generation = BTRFS_I(inode)->generation;
3721 rdev = btrfs_inode_rdev(leaf, inode_item);
3723 BTRFS_I(inode)->index_cnt = (u64)-1;
3724 BTRFS_I(inode)->flags = btrfs_inode_flags(leaf, inode_item);
3728 * If we were modified in the current generation and evicted from memory
3729 * and then re-read we need to do a full sync since we don't have any
3730 * idea about which extents were modified before we were evicted from
3733 * This is required for both inode re-read from disk and delayed inode
3734 * in delayed_nodes_tree.
3736 if (BTRFS_I(inode)->last_trans == root->fs_info->generation)
3737 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
3738 &BTRFS_I(inode)->runtime_flags);
3741 * We don't persist the id of the transaction where an unlink operation
3742 * against the inode was last made. So here we assume the inode might
3743 * have been evicted, and therefore the exact value of last_unlink_trans
3744 * lost, and set it to last_trans to avoid metadata inconsistencies
3745 * between the inode and its parent if the inode is fsync'ed and the log
3746 * replayed. For example, in the scenario:
3749 * ln mydir/foo mydir/bar
3752 * echo 2 > /proc/sys/vm/drop_caches # evicts inode
3753 * xfs_io -c fsync mydir/foo
3755 * mount fs, triggers fsync log replay
3757 * We must make sure that when we fsync our inode foo we also log its
3758 * parent inode, otherwise after log replay the parent still has the
3759 * dentry with the "bar" name but our inode foo has a link count of 1
3760 * and doesn't have an inode ref with the name "bar" anymore.
3762 * Setting last_unlink_trans to last_trans is a pessimistic approach,
3763 * but it guarantees correctness at the expense of ocassional full
3764 * transaction commits on fsync if our inode is a directory, or if our
3765 * inode is not a directory, logging its parent unnecessarily.
3767 BTRFS_I(inode)->last_unlink_trans = BTRFS_I(inode)->last_trans;
3770 if (inode->i_nlink != 1 ||
3771 path->slots[0] >= btrfs_header_nritems(leaf))
3774 btrfs_item_key_to_cpu(leaf, &location, path->slots[0]);
3775 if (location.objectid != btrfs_ino(inode))
3778 ptr = btrfs_item_ptr_offset(leaf, path->slots[0]);
3779 if (location.type == BTRFS_INODE_REF_KEY) {
3780 struct btrfs_inode_ref *ref;
3782 ref = (struct btrfs_inode_ref *)ptr;
3783 BTRFS_I(inode)->dir_index = btrfs_inode_ref_index(leaf, ref);
3784 } else if (location.type == BTRFS_INODE_EXTREF_KEY) {
3785 struct btrfs_inode_extref *extref;
3787 extref = (struct btrfs_inode_extref *)ptr;
3788 BTRFS_I(inode)->dir_index = btrfs_inode_extref_index(leaf,
3793 * try to precache a NULL acl entry for files that don't have
3794 * any xattrs or acls
3796 maybe_acls = acls_after_inode_item(leaf, path->slots[0],
3797 btrfs_ino(inode), &first_xattr_slot);
3798 if (first_xattr_slot != -1) {
3799 path->slots[0] = first_xattr_slot;
3800 ret = btrfs_load_inode_props(inode, path);
3802 btrfs_err(root->fs_info,
3803 "error loading props for ino %llu (root %llu): %d",
3805 root->root_key.objectid, ret);
3807 btrfs_free_path(path);
3810 cache_no_acl(inode);
3812 switch (inode->i_mode & S_IFMT) {
3814 inode->i_mapping->a_ops = &btrfs_aops;
3815 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
3816 inode->i_fop = &btrfs_file_operations;
3817 inode->i_op = &btrfs_file_inode_operations;
3820 inode->i_fop = &btrfs_dir_file_operations;
3821 if (root == root->fs_info->tree_root)
3822 inode->i_op = &btrfs_dir_ro_inode_operations;
3824 inode->i_op = &btrfs_dir_inode_operations;
3827 inode->i_op = &btrfs_symlink_inode_operations;
3828 inode->i_mapping->a_ops = &btrfs_symlink_aops;
3831 inode->i_op = &btrfs_special_inode_operations;
3832 init_special_inode(inode, inode->i_mode, rdev);
3836 btrfs_update_iflags(inode);
3840 btrfs_free_path(path);
3841 make_bad_inode(inode);
3845 * given a leaf and an inode, copy the inode fields into the leaf
3847 static void fill_inode_item(struct btrfs_trans_handle *trans,
3848 struct extent_buffer *leaf,
3849 struct btrfs_inode_item *item,
3850 struct inode *inode)
3852 struct btrfs_map_token token;
3854 btrfs_init_map_token(&token);
3856 btrfs_set_token_inode_uid(leaf, item, i_uid_read(inode), &token);
3857 btrfs_set_token_inode_gid(leaf, item, i_gid_read(inode), &token);
3858 btrfs_set_token_inode_size(leaf, item, BTRFS_I(inode)->disk_i_size,
3860 btrfs_set_token_inode_mode(leaf, item, inode->i_mode, &token);
3861 btrfs_set_token_inode_nlink(leaf, item, inode->i_nlink, &token);
3863 btrfs_set_token_timespec_sec(leaf, &item->atime,
3864 inode->i_atime.tv_sec, &token);
3865 btrfs_set_token_timespec_nsec(leaf, &item->atime,
3866 inode->i_atime.tv_nsec, &token);
3868 btrfs_set_token_timespec_sec(leaf, &item->mtime,
3869 inode->i_mtime.tv_sec, &token);
3870 btrfs_set_token_timespec_nsec(leaf, &item->mtime,
3871 inode->i_mtime.tv_nsec, &token);
3873 btrfs_set_token_timespec_sec(leaf, &item->ctime,
3874 inode->i_ctime.tv_sec, &token);
3875 btrfs_set_token_timespec_nsec(leaf, &item->ctime,
3876 inode->i_ctime.tv_nsec, &token);
3878 btrfs_set_token_timespec_sec(leaf, &item->otime,
3879 BTRFS_I(inode)->i_otime.tv_sec, &token);
3880 btrfs_set_token_timespec_nsec(leaf, &item->otime,
3881 BTRFS_I(inode)->i_otime.tv_nsec, &token);
3883 btrfs_set_token_inode_nbytes(leaf, item, inode_get_bytes(inode),
3885 btrfs_set_token_inode_generation(leaf, item, BTRFS_I(inode)->generation,
3887 btrfs_set_token_inode_sequence(leaf, item, inode->i_version, &token);
3888 btrfs_set_token_inode_transid(leaf, item, trans->transid, &token);
3889 btrfs_set_token_inode_rdev(leaf, item, inode->i_rdev, &token);
3890 btrfs_set_token_inode_flags(leaf, item, BTRFS_I(inode)->flags, &token);
3891 btrfs_set_token_inode_block_group(leaf, item, 0, &token);
3895 * copy everything in the in-memory inode into the btree.
3897 static noinline int btrfs_update_inode_item(struct btrfs_trans_handle *trans,
3898 struct btrfs_root *root, struct inode *inode)
3900 struct btrfs_inode_item *inode_item;
3901 struct btrfs_path *path;
3902 struct extent_buffer *leaf;
3905 path = btrfs_alloc_path();
3909 path->leave_spinning = 1;
3910 ret = btrfs_lookup_inode(trans, root, path, &BTRFS_I(inode)->location,
3918 leaf = path->nodes[0];
3919 inode_item = btrfs_item_ptr(leaf, path->slots[0],
3920 struct btrfs_inode_item);
3922 fill_inode_item(trans, leaf, inode_item, inode);
3923 btrfs_mark_buffer_dirty(leaf);
3924 btrfs_set_inode_last_trans(trans, inode);
3927 btrfs_free_path(path);
3932 * copy everything in the in-memory inode into the btree.
3934 noinline int btrfs_update_inode(struct btrfs_trans_handle *trans,
3935 struct btrfs_root *root, struct inode *inode)
3940 * If the inode is a free space inode, we can deadlock during commit
3941 * if we put it into the delayed code.
3943 * The data relocation inode should also be directly updated
3946 if (!btrfs_is_free_space_inode(inode)
3947 && root->root_key.objectid != BTRFS_DATA_RELOC_TREE_OBJECTID
3948 && !root->fs_info->log_root_recovering) {
3949 btrfs_update_root_times(trans, root);
3951 ret = btrfs_delayed_update_inode(trans, root, inode);
3953 btrfs_set_inode_last_trans(trans, inode);
3957 return btrfs_update_inode_item(trans, root, inode);
3960 noinline int btrfs_update_inode_fallback(struct btrfs_trans_handle *trans,
3961 struct btrfs_root *root,
3962 struct inode *inode)
3966 ret = btrfs_update_inode(trans, root, inode);
3968 return btrfs_update_inode_item(trans, root, inode);
3973 * unlink helper that gets used here in inode.c and in the tree logging
3974 * recovery code. It remove a link in a directory with a given name, and
3975 * also drops the back refs in the inode to the directory
3977 static int __btrfs_unlink_inode(struct btrfs_trans_handle *trans,
3978 struct btrfs_root *root,
3979 struct inode *dir, struct inode *inode,
3980 const char *name, int name_len)
3982 struct btrfs_path *path;
3984 struct extent_buffer *leaf;
3985 struct btrfs_dir_item *di;
3986 struct btrfs_key key;
3988 u64 ino = btrfs_ino(inode);
3989 u64 dir_ino = btrfs_ino(dir);
3991 path = btrfs_alloc_path();
3997 path->leave_spinning = 1;
3998 di = btrfs_lookup_dir_item(trans, root, path, dir_ino,
3999 name, name_len, -1);
4008 leaf = path->nodes[0];
4009 btrfs_dir_item_key_to_cpu(leaf, di, &key);
4010 ret = btrfs_delete_one_dir_name(trans, root, path, di);
4013 btrfs_release_path(path);
4016 * If we don't have dir index, we have to get it by looking up
4017 * the inode ref, since we get the inode ref, remove it directly,
4018 * it is unnecessary to do delayed deletion.
4020 * But if we have dir index, needn't search inode ref to get it.
4021 * Since the inode ref is close to the inode item, it is better
4022 * that we delay to delete it, and just do this deletion when
4023 * we update the inode item.
4025 if (BTRFS_I(inode)->dir_index) {
4026 ret = btrfs_delayed_delete_inode_ref(inode);
4028 index = BTRFS_I(inode)->dir_index;
4033 ret = btrfs_del_inode_ref(trans, root, name, name_len, ino,
4036 btrfs_info(root->fs_info,
4037 "failed to delete reference to %.*s, inode %llu parent %llu",
4038 name_len, name, ino, dir_ino);
4039 btrfs_abort_transaction(trans, root, ret);
4043 ret = btrfs_delete_delayed_dir_index(trans, root, dir, index);
4045 btrfs_abort_transaction(trans, root, ret);
4049 ret = btrfs_del_inode_ref_in_log(trans, root, name, name_len,
4051 if (ret != 0 && ret != -ENOENT) {
4052 btrfs_abort_transaction(trans, root, ret);
4056 ret = btrfs_del_dir_entries_in_log(trans, root, name, name_len,
4061 btrfs_abort_transaction(trans, root, ret);
4063 btrfs_free_path(path);
4067 btrfs_i_size_write(dir, dir->i_size - name_len * 2);
4068 inode_inc_iversion(inode);
4069 inode_inc_iversion(dir);
4070 inode->i_ctime = dir->i_mtime = dir->i_ctime = CURRENT_TIME;
4071 ret = btrfs_update_inode(trans, root, dir);
4076 int btrfs_unlink_inode(struct btrfs_trans_handle *trans,
4077 struct btrfs_root *root,
4078 struct inode *dir, struct inode *inode,
4079 const char *name, int name_len)
4082 ret = __btrfs_unlink_inode(trans, root, dir, inode, name, name_len);
4085 ret = btrfs_update_inode(trans, root, inode);
4091 * helper to start transaction for unlink and rmdir.
4093 * unlink and rmdir are special in btrfs, they do not always free space, so
4094 * if we cannot make our reservations the normal way try and see if there is
4095 * plenty of slack room in the global reserve to migrate, otherwise we cannot
4096 * allow the unlink to occur.
4098 static struct btrfs_trans_handle *__unlink_start_trans(struct inode *dir)
4100 struct btrfs_root *root = BTRFS_I(dir)->root;
4103 * 1 for the possible orphan item
4104 * 1 for the dir item
4105 * 1 for the dir index
4106 * 1 for the inode ref
4109 return btrfs_start_transaction_fallback_global_rsv(root, 5, 5);
4112 static int btrfs_unlink(struct inode *dir, struct dentry *dentry)
4114 struct btrfs_root *root = BTRFS_I(dir)->root;
4115 struct btrfs_trans_handle *trans;
4116 struct inode *inode = d_inode(dentry);
4119 trans = __unlink_start_trans(dir);
4121 return PTR_ERR(trans);
4123 btrfs_record_unlink_dir(trans, dir, d_inode(dentry), 0);
4125 ret = btrfs_unlink_inode(trans, root, dir, d_inode(dentry),
4126 dentry->d_name.name, dentry->d_name.len);
4130 if (inode->i_nlink == 0) {
4131 ret = btrfs_orphan_add(trans, inode);
4137 btrfs_end_transaction(trans, root);
4138 btrfs_btree_balance_dirty(root);
4142 int btrfs_unlink_subvol(struct btrfs_trans_handle *trans,
4143 struct btrfs_root *root,
4144 struct inode *dir, u64 objectid,
4145 const char *name, int name_len)
4147 struct btrfs_path *path;
4148 struct extent_buffer *leaf;
4149 struct btrfs_dir_item *di;
4150 struct btrfs_key key;
4153 u64 dir_ino = btrfs_ino(dir);
4155 path = btrfs_alloc_path();
4159 di = btrfs_lookup_dir_item(trans, root, path, dir_ino,
4160 name, name_len, -1);
4161 if (IS_ERR_OR_NULL(di)) {
4169 leaf = path->nodes[0];
4170 btrfs_dir_item_key_to_cpu(leaf, di, &key);
4171 WARN_ON(key.type != BTRFS_ROOT_ITEM_KEY || key.objectid != objectid);
4172 ret = btrfs_delete_one_dir_name(trans, root, path, di);
4174 btrfs_abort_transaction(trans, root, ret);
4177 btrfs_release_path(path);
4179 ret = btrfs_del_root_ref(trans, root->fs_info->tree_root,
4180 objectid, root->root_key.objectid,
4181 dir_ino, &index, name, name_len);
4183 if (ret != -ENOENT) {
4184 btrfs_abort_transaction(trans, root, ret);
4187 di = btrfs_search_dir_index_item(root, path, dir_ino,
4189 if (IS_ERR_OR_NULL(di)) {
4194 btrfs_abort_transaction(trans, root, ret);
4198 leaf = path->nodes[0];
4199 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
4200 btrfs_release_path(path);
4203 btrfs_release_path(path);
4205 ret = btrfs_delete_delayed_dir_index(trans, root, dir, index);
4207 btrfs_abort_transaction(trans, root, ret);
4211 btrfs_i_size_write(dir, dir->i_size - name_len * 2);
4212 inode_inc_iversion(dir);
4213 dir->i_mtime = dir->i_ctime = CURRENT_TIME;
4214 ret = btrfs_update_inode_fallback(trans, root, dir);
4216 btrfs_abort_transaction(trans, root, ret);
4218 btrfs_free_path(path);
4222 static int btrfs_rmdir(struct inode *dir, struct dentry *dentry)
4224 struct inode *inode = d_inode(dentry);
4226 struct btrfs_root *root = BTRFS_I(dir)->root;
4227 struct btrfs_trans_handle *trans;
4229 if (inode->i_size > BTRFS_EMPTY_DIR_SIZE)
4231 if (btrfs_ino(inode) == BTRFS_FIRST_FREE_OBJECTID)
4234 trans = __unlink_start_trans(dir);
4236 return PTR_ERR(trans);
4238 if (unlikely(btrfs_ino(inode) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)) {
4239 err = btrfs_unlink_subvol(trans, root, dir,
4240 BTRFS_I(inode)->location.objectid,
4241 dentry->d_name.name,
4242 dentry->d_name.len);
4246 err = btrfs_orphan_add(trans, inode);
4250 /* now the directory is empty */
4251 err = btrfs_unlink_inode(trans, root, dir, d_inode(dentry),
4252 dentry->d_name.name, dentry->d_name.len);
4254 btrfs_i_size_write(inode, 0);
4256 btrfs_end_transaction(trans, root);
4257 btrfs_btree_balance_dirty(root);
4262 static int truncate_space_check(struct btrfs_trans_handle *trans,
4263 struct btrfs_root *root,
4268 bytes_deleted = btrfs_csum_bytes_to_leaves(root, bytes_deleted);
4269 ret = btrfs_block_rsv_add(root, &root->fs_info->trans_block_rsv,
4270 bytes_deleted, BTRFS_RESERVE_NO_FLUSH);
4272 trans->bytes_reserved += bytes_deleted;
4277 static int truncate_inline_extent(struct inode *inode,
4278 struct btrfs_path *path,
4279 struct btrfs_key *found_key,
4283 struct extent_buffer *leaf = path->nodes[0];
4284 int slot = path->slots[0];
4285 struct btrfs_file_extent_item *fi;
4286 u32 size = (u32)(new_size - found_key->offset);
4287 struct btrfs_root *root = BTRFS_I(inode)->root;
4289 fi = btrfs_item_ptr(leaf, slot, struct btrfs_file_extent_item);
4291 if (btrfs_file_extent_compression(leaf, fi) != BTRFS_COMPRESS_NONE) {
4292 loff_t offset = new_size;
4293 loff_t page_end = ALIGN(offset, PAGE_CACHE_SIZE);
4296 * Zero out the remaining of the last page of our inline extent,
4297 * instead of directly truncating our inline extent here - that
4298 * would be much more complex (decompressing all the data, then
4299 * compressing the truncated data, which might be bigger than
4300 * the size of the inline extent, resize the extent, etc).
4301 * We release the path because to get the page we might need to
4302 * read the extent item from disk (data not in the page cache).
4304 btrfs_release_path(path);
4305 return btrfs_truncate_page(inode, offset, page_end - offset, 0);
4308 btrfs_set_file_extent_ram_bytes(leaf, fi, size);
4309 size = btrfs_file_extent_calc_inline_size(size);
4310 btrfs_truncate_item(root, path, size, 1);
4312 if (test_bit(BTRFS_ROOT_REF_COWS, &root->state))
4313 inode_sub_bytes(inode, item_end + 1 - new_size);
4319 * this can truncate away extent items, csum items and directory items.
4320 * It starts at a high offset and removes keys until it can't find
4321 * any higher than new_size
4323 * csum items that cross the new i_size are truncated to the new size
4326 * min_type is the minimum key type to truncate down to. If set to 0, this
4327 * will kill all the items on this inode, including the INODE_ITEM_KEY.
4329 int btrfs_truncate_inode_items(struct btrfs_trans_handle *trans,
4330 struct btrfs_root *root,
4331 struct inode *inode,
4332 u64 new_size, u32 min_type)
4334 struct btrfs_path *path;
4335 struct extent_buffer *leaf;
4336 struct btrfs_file_extent_item *fi;
4337 struct btrfs_key key;
4338 struct btrfs_key found_key;
4339 u64 extent_start = 0;
4340 u64 extent_num_bytes = 0;
4341 u64 extent_offset = 0;
4343 u64 last_size = new_size;
4344 u32 found_type = (u8)-1;
4347 int pending_del_nr = 0;
4348 int pending_del_slot = 0;
4349 int extent_type = -1;
4352 u64 ino = btrfs_ino(inode);
4353 u64 bytes_deleted = 0;
4355 bool should_throttle = 0;
4356 bool should_end = 0;
4358 BUG_ON(new_size > 0 && min_type != BTRFS_EXTENT_DATA_KEY);
4361 * for non-free space inodes and ref cows, we want to back off from
4364 if (!btrfs_is_free_space_inode(inode) &&
4365 test_bit(BTRFS_ROOT_REF_COWS, &root->state))
4368 path = btrfs_alloc_path();
4374 * We want to drop from the next block forward in case this new size is
4375 * not block aligned since we will be keeping the last block of the
4376 * extent just the way it is.
4378 if (test_bit(BTRFS_ROOT_REF_COWS, &root->state) ||
4379 root == root->fs_info->tree_root)
4380 btrfs_drop_extent_cache(inode, ALIGN(new_size,
4381 root->sectorsize), (u64)-1, 0);
4384 * This function is also used to drop the items in the log tree before
4385 * we relog the inode, so if root != BTRFS_I(inode)->root, it means
4386 * it is used to drop the loged items. So we shouldn't kill the delayed
4389 if (min_type == 0 && root == BTRFS_I(inode)->root)
4390 btrfs_kill_delayed_inode_items(inode);
4393 key.offset = (u64)-1;
4398 * with a 16K leaf size and 128MB extents, you can actually queue
4399 * up a huge file in a single leaf. Most of the time that
4400 * bytes_deleted is > 0, it will be huge by the time we get here
4402 if (be_nice && bytes_deleted > 32 * 1024 * 1024) {
4403 if (btrfs_should_end_transaction(trans, root)) {
4410 path->leave_spinning = 1;
4411 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
4418 /* there are no items in the tree for us to truncate, we're
4421 if (path->slots[0] == 0)
4428 leaf = path->nodes[0];
4429 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
4430 found_type = found_key.type;
4432 if (found_key.objectid != ino)
4435 if (found_type < min_type)
4438 item_end = found_key.offset;
4439 if (found_type == BTRFS_EXTENT_DATA_KEY) {
4440 fi = btrfs_item_ptr(leaf, path->slots[0],
4441 struct btrfs_file_extent_item);
4442 extent_type = btrfs_file_extent_type(leaf, fi);
4443 if (extent_type != BTRFS_FILE_EXTENT_INLINE) {
4445 btrfs_file_extent_num_bytes(leaf, fi);
4446 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
4447 item_end += btrfs_file_extent_inline_len(leaf,
4448 path->slots[0], fi);
4452 if (found_type > min_type) {
4455 if (item_end < new_size) {
4457 * With NO_HOLES mode, for the following mapping
4459 * [0-4k][hole][8k-12k]
4461 * if truncating isize down to 6k, it ends up
4464 if (btrfs_fs_incompat(root->fs_info, NO_HOLES))
4465 last_size = new_size;
4468 if (found_key.offset >= new_size)
4474 /* FIXME, shrink the extent if the ref count is only 1 */
4475 if (found_type != BTRFS_EXTENT_DATA_KEY)
4479 last_size = found_key.offset;
4481 last_size = new_size;
4483 if (extent_type != BTRFS_FILE_EXTENT_INLINE) {
4485 extent_start = btrfs_file_extent_disk_bytenr(leaf, fi);
4487 u64 orig_num_bytes =
4488 btrfs_file_extent_num_bytes(leaf, fi);
4489 extent_num_bytes = ALIGN(new_size -
4492 btrfs_set_file_extent_num_bytes(leaf, fi,
4494 num_dec = (orig_num_bytes -
4496 if (test_bit(BTRFS_ROOT_REF_COWS,
4499 inode_sub_bytes(inode, num_dec);
4500 btrfs_mark_buffer_dirty(leaf);
4503 btrfs_file_extent_disk_num_bytes(leaf,
4505 extent_offset = found_key.offset -
4506 btrfs_file_extent_offset(leaf, fi);
4508 /* FIXME blocksize != 4096 */
4509 num_dec = btrfs_file_extent_num_bytes(leaf, fi);
4510 if (extent_start != 0) {
4512 if (test_bit(BTRFS_ROOT_REF_COWS,
4514 inode_sub_bytes(inode, num_dec);
4517 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
4519 * we can't truncate inline items that have had
4523 btrfs_file_extent_encryption(leaf, fi) == 0 &&
4524 btrfs_file_extent_other_encoding(leaf, fi) == 0) {
4527 * Need to release path in order to truncate a
4528 * compressed extent. So delete any accumulated
4529 * extent items so far.
4531 if (btrfs_file_extent_compression(leaf, fi) !=
4532 BTRFS_COMPRESS_NONE && pending_del_nr) {
4533 err = btrfs_del_items(trans, root, path,
4537 btrfs_abort_transaction(trans,
4545 err = truncate_inline_extent(inode, path,
4550 btrfs_abort_transaction(trans,
4554 } else if (test_bit(BTRFS_ROOT_REF_COWS,
4556 inode_sub_bytes(inode, item_end + 1 - new_size);
4561 if (!pending_del_nr) {
4562 /* no pending yet, add ourselves */
4563 pending_del_slot = path->slots[0];
4565 } else if (pending_del_nr &&
4566 path->slots[0] + 1 == pending_del_slot) {
4567 /* hop on the pending chunk */
4569 pending_del_slot = path->slots[0];
4576 should_throttle = 0;
4579 (test_bit(BTRFS_ROOT_REF_COWS, &root->state) ||
4580 root == root->fs_info->tree_root)) {
4581 btrfs_set_path_blocking(path);
4582 bytes_deleted += extent_num_bytes;
4583 ret = btrfs_free_extent(trans, root, extent_start,
4584 extent_num_bytes, 0,
4585 btrfs_header_owner(leaf),
4586 ino, extent_offset);
4588 if (btrfs_should_throttle_delayed_refs(trans, root))
4589 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,
4620 btrfs_release_path(path);
4621 if (should_throttle) {
4622 unsigned long updates = trans->delayed_ref_updates;
4624 trans->delayed_ref_updates = 0;
4625 ret = btrfs_run_delayed_refs(trans, root, updates * 2);
4631 * if we failed to refill our space rsv, bail out
4632 * and let the transaction restart
4644 if (pending_del_nr) {
4645 ret = btrfs_del_items(trans, root, path, pending_del_slot,
4648 btrfs_abort_transaction(trans, root, ret);
4651 if (root->root_key.objectid != BTRFS_TREE_LOG_OBJECTID)
4652 btrfs_ordered_update_i_size(inode, last_size, NULL);
4654 btrfs_free_path(path);
4656 if (be_nice && bytes_deleted > 32 * 1024 * 1024) {
4657 unsigned long updates = trans->delayed_ref_updates;
4659 trans->delayed_ref_updates = 0;
4660 ret = btrfs_run_delayed_refs(trans, root, updates * 2);
4669 * btrfs_truncate_page - read, zero a chunk and write a page
4670 * @inode - inode that we're zeroing
4671 * @from - the offset to start zeroing
4672 * @len - the length to zero, 0 to zero the entire range respective to the
4674 * @front - zero up to the offset instead of from the offset on
4676 * This will find the page for the "from" offset and cow the page and zero the
4677 * part we want to zero. This is used with truncate and hole punching.
4679 int btrfs_truncate_page(struct inode *inode, loff_t from, loff_t len,
4682 struct address_space *mapping = inode->i_mapping;
4683 struct btrfs_root *root = BTRFS_I(inode)->root;
4684 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
4685 struct btrfs_ordered_extent *ordered;
4686 struct extent_state *cached_state = NULL;
4688 u32 blocksize = root->sectorsize;
4689 pgoff_t index = from >> PAGE_CACHE_SHIFT;
4690 unsigned offset = from & (PAGE_CACHE_SIZE-1);
4692 gfp_t mask = btrfs_alloc_write_mask(mapping);
4697 if ((offset & (blocksize - 1)) == 0 &&
4698 (!len || ((len & (blocksize - 1)) == 0)))
4700 ret = btrfs_delalloc_reserve_space(inode,
4701 round_down(from, PAGE_CACHE_SIZE), PAGE_CACHE_SIZE);
4706 page = find_or_create_page(mapping, index, mask);
4708 btrfs_delalloc_release_space(inode,
4709 round_down(from, PAGE_CACHE_SIZE),
4715 page_start = page_offset(page);
4716 page_end = page_start + PAGE_CACHE_SIZE - 1;
4718 if (!PageUptodate(page)) {
4719 ret = btrfs_readpage(NULL, page);
4721 if (page->mapping != mapping) {
4723 page_cache_release(page);
4726 if (!PageUptodate(page)) {
4731 wait_on_page_writeback(page);
4733 lock_extent_bits(io_tree, page_start, page_end, 0, &cached_state);
4734 set_page_extent_mapped(page);
4736 ordered = btrfs_lookup_ordered_extent(inode, page_start);
4738 unlock_extent_cached(io_tree, page_start, page_end,
4739 &cached_state, GFP_NOFS);
4741 page_cache_release(page);
4742 btrfs_start_ordered_extent(inode, ordered, 1);
4743 btrfs_put_ordered_extent(ordered);
4747 clear_extent_bit(&BTRFS_I(inode)->io_tree, page_start, page_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, page_start, page_end,
4755 unlock_extent_cached(io_tree, page_start, page_end,
4756 &cached_state, GFP_NOFS);
4760 if (offset != PAGE_CACHE_SIZE) {
4762 len = PAGE_CACHE_SIZE - offset;
4765 memset(kaddr, 0, offset);
4767 memset(kaddr + offset, 0, len);
4768 flush_dcache_page(page);
4771 ClearPageChecked(page);
4772 set_page_dirty(page);
4773 unlock_extent_cached(io_tree, page_start, page_end, &cached_state,
4778 btrfs_delalloc_release_space(inode, page_start,
4781 page_cache_release(page);
4786 static int maybe_insert_hole(struct btrfs_root *root, struct inode *inode,
4787 u64 offset, u64 len)
4789 struct btrfs_trans_handle *trans;
4793 * Still need to make sure the inode looks like it's been updated so
4794 * that any holes get logged if we fsync.
4796 if (btrfs_fs_incompat(root->fs_info, NO_HOLES)) {
4797 BTRFS_I(inode)->last_trans = root->fs_info->generation;
4798 BTRFS_I(inode)->last_sub_trans = root->log_transid;
4799 BTRFS_I(inode)->last_log_commit = root->last_log_commit;
4804 * 1 - for the one we're dropping
4805 * 1 - for the one we're adding
4806 * 1 - for updating the inode.
4808 trans = btrfs_start_transaction(root, 3);
4810 return PTR_ERR(trans);
4812 ret = btrfs_drop_extents(trans, root, inode, offset, offset + len, 1);
4814 btrfs_abort_transaction(trans, root, ret);
4815 btrfs_end_transaction(trans, root);
4819 ret = btrfs_insert_file_extent(trans, root, btrfs_ino(inode), offset,
4820 0, 0, len, 0, len, 0, 0, 0);
4822 btrfs_abort_transaction(trans, root, ret);
4824 btrfs_update_inode(trans, root, inode);
4825 btrfs_end_transaction(trans, root);
4830 * This function puts in dummy file extents for the area we're creating a hole
4831 * for. So if we are truncating this file to a larger size we need to insert
4832 * these file extents so that btrfs_get_extent will return a EXTENT_MAP_HOLE for
4833 * the range between oldsize and size
4835 int btrfs_cont_expand(struct inode *inode, loff_t oldsize, loff_t size)
4837 struct btrfs_root *root = BTRFS_I(inode)->root;
4838 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
4839 struct extent_map *em = NULL;
4840 struct extent_state *cached_state = NULL;
4841 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
4842 u64 hole_start = ALIGN(oldsize, root->sectorsize);
4843 u64 block_end = ALIGN(size, root->sectorsize);
4850 * If our size started in the middle of a page we need to zero out the
4851 * rest of the page before we expand the i_size, otherwise we could
4852 * expose stale data.
4854 err = btrfs_truncate_page(inode, oldsize, 0, 0);
4858 if (size <= hole_start)
4862 struct btrfs_ordered_extent *ordered;
4864 lock_extent_bits(io_tree, hole_start, block_end - 1, 0,
4866 ordered = btrfs_lookup_ordered_range(inode, hole_start,
4867 block_end - hole_start);
4870 unlock_extent_cached(io_tree, hole_start, block_end - 1,
4871 &cached_state, GFP_NOFS);
4872 btrfs_start_ordered_extent(inode, ordered, 1);
4873 btrfs_put_ordered_extent(ordered);
4876 cur_offset = hole_start;
4878 em = btrfs_get_extent(inode, NULL, 0, cur_offset,
4879 block_end - cur_offset, 0);
4885 last_byte = min(extent_map_end(em), block_end);
4886 last_byte = ALIGN(last_byte , root->sectorsize);
4887 if (!test_bit(EXTENT_FLAG_PREALLOC, &em->flags)) {
4888 struct extent_map *hole_em;
4889 hole_size = last_byte - cur_offset;
4891 err = maybe_insert_hole(root, inode, cur_offset,
4895 btrfs_drop_extent_cache(inode, cur_offset,
4896 cur_offset + hole_size - 1, 0);
4897 hole_em = alloc_extent_map();
4899 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
4900 &BTRFS_I(inode)->runtime_flags);
4903 hole_em->start = cur_offset;
4904 hole_em->len = hole_size;
4905 hole_em->orig_start = cur_offset;
4907 hole_em->block_start = EXTENT_MAP_HOLE;
4908 hole_em->block_len = 0;
4909 hole_em->orig_block_len = 0;
4910 hole_em->ram_bytes = hole_size;
4911 hole_em->bdev = root->fs_info->fs_devices->latest_bdev;
4912 hole_em->compress_type = BTRFS_COMPRESS_NONE;
4913 hole_em->generation = root->fs_info->generation;
4916 write_lock(&em_tree->lock);
4917 err = add_extent_mapping(em_tree, hole_em, 1);
4918 write_unlock(&em_tree->lock);
4921 btrfs_drop_extent_cache(inode, cur_offset,
4925 free_extent_map(hole_em);
4928 free_extent_map(em);
4930 cur_offset = last_byte;
4931 if (cur_offset >= block_end)
4934 free_extent_map(em);
4935 unlock_extent_cached(io_tree, hole_start, block_end - 1, &cached_state,
4940 static int wait_snapshoting_atomic_t(atomic_t *a)
4946 static void wait_for_snapshot_creation(struct btrfs_root *root)
4951 ret = btrfs_start_write_no_snapshoting(root);
4954 wait_on_atomic_t(&root->will_be_snapshoted,
4955 wait_snapshoting_atomic_t,
4956 TASK_UNINTERRUPTIBLE);
4960 static int btrfs_setsize(struct inode *inode, struct iattr *attr)
4962 struct btrfs_root *root = BTRFS_I(inode)->root;
4963 struct btrfs_trans_handle *trans;
4964 loff_t oldsize = i_size_read(inode);
4965 loff_t newsize = attr->ia_size;
4966 int mask = attr->ia_valid;
4970 * The regular truncate() case without ATTR_CTIME and ATTR_MTIME is a
4971 * special case where we need to update the times despite not having
4972 * these flags set. For all other operations the VFS set these flags
4973 * explicitly if it wants a timestamp update.
4975 if (newsize != oldsize) {
4976 inode_inc_iversion(inode);
4977 if (!(mask & (ATTR_CTIME | ATTR_MTIME)))
4978 inode->i_ctime = inode->i_mtime =
4979 current_fs_time(inode->i_sb);
4982 if (newsize > oldsize) {
4983 truncate_pagecache(inode, newsize);
4985 * Don't do an expanding truncate while snapshoting is ongoing.
4986 * This is to ensure the snapshot captures a fully consistent
4987 * state of this file - if the snapshot captures this expanding
4988 * truncation, it must capture all writes that happened before
4991 wait_for_snapshot_creation(root);
4992 ret = btrfs_cont_expand(inode, oldsize, newsize);
4994 btrfs_end_write_no_snapshoting(root);
4998 trans = btrfs_start_transaction(root, 1);
4999 if (IS_ERR(trans)) {
5000 btrfs_end_write_no_snapshoting(root);
5001 return PTR_ERR(trans);
5004 i_size_write(inode, newsize);
5005 btrfs_ordered_update_i_size(inode, i_size_read(inode), NULL);
5006 ret = btrfs_update_inode(trans, root, inode);
5007 btrfs_end_write_no_snapshoting(root);
5008 btrfs_end_transaction(trans, root);
5012 * We're truncating a file that used to have good data down to
5013 * zero. Make sure it gets into the ordered flush list so that
5014 * any new writes get down to disk quickly.
5017 set_bit(BTRFS_INODE_ORDERED_DATA_CLOSE,
5018 &BTRFS_I(inode)->runtime_flags);
5021 * 1 for the orphan item we're going to add
5022 * 1 for the orphan item deletion.
5024 trans = btrfs_start_transaction(root, 2);
5026 return PTR_ERR(trans);
5029 * We need to do this in case we fail at _any_ point during the
5030 * actual truncate. Once we do the truncate_setsize we could
5031 * invalidate pages which forces any outstanding ordered io to
5032 * be instantly completed which will give us extents that need
5033 * to be truncated. If we fail to get an orphan inode down we
5034 * could have left over extents that were never meant to live,
5035 * so we need to garuntee from this point on that everything
5036 * will be consistent.
5038 ret = btrfs_orphan_add(trans, inode);
5039 btrfs_end_transaction(trans, root);
5043 /* we don't support swapfiles, so vmtruncate shouldn't fail */
5044 truncate_setsize(inode, newsize);
5046 /* Disable nonlocked read DIO to avoid the end less truncate */
5047 btrfs_inode_block_unlocked_dio(inode);
5048 inode_dio_wait(inode);
5049 btrfs_inode_resume_unlocked_dio(inode);
5051 ret = btrfs_truncate(inode);
5052 if (ret && inode->i_nlink) {
5056 * failed to truncate, disk_i_size is only adjusted down
5057 * as we remove extents, so it should represent the true
5058 * size of the inode, so reset the in memory size and
5059 * delete our orphan entry.
5061 trans = btrfs_join_transaction(root);
5062 if (IS_ERR(trans)) {
5063 btrfs_orphan_del(NULL, inode);
5066 i_size_write(inode, BTRFS_I(inode)->disk_i_size);
5067 err = btrfs_orphan_del(trans, inode);
5069 btrfs_abort_transaction(trans, root, err);
5070 btrfs_end_transaction(trans, root);
5077 static int btrfs_setattr(struct dentry *dentry, struct iattr *attr)
5079 struct inode *inode = d_inode(dentry);
5080 struct btrfs_root *root = BTRFS_I(inode)->root;
5083 if (btrfs_root_readonly(root))
5086 err = inode_change_ok(inode, attr);
5090 if (S_ISREG(inode->i_mode) && (attr->ia_valid & ATTR_SIZE)) {
5091 err = btrfs_setsize(inode, attr);
5096 if (attr->ia_valid) {
5097 setattr_copy(inode, attr);
5098 inode_inc_iversion(inode);
5099 err = btrfs_dirty_inode(inode);
5101 if (!err && attr->ia_valid & ATTR_MODE)
5102 err = posix_acl_chmod(inode, inode->i_mode);
5109 * While truncating the inode pages during eviction, we get the VFS calling
5110 * btrfs_invalidatepage() against each page of the inode. This is slow because
5111 * the calls to btrfs_invalidatepage() result in a huge amount of calls to
5112 * lock_extent_bits() and clear_extent_bit(), which keep merging and splitting
5113 * extent_state structures over and over, wasting lots of time.
5115 * Therefore if the inode is being evicted, let btrfs_invalidatepage() skip all
5116 * those expensive operations on a per page basis and do only the ordered io
5117 * finishing, while we release here the extent_map and extent_state structures,
5118 * without the excessive merging and splitting.
5120 static void evict_inode_truncate_pages(struct inode *inode)
5122 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
5123 struct extent_map_tree *map_tree = &BTRFS_I(inode)->extent_tree;
5124 struct rb_node *node;
5126 ASSERT(inode->i_state & I_FREEING);
5127 truncate_inode_pages_final(&inode->i_data);
5129 write_lock(&map_tree->lock);
5130 while (!RB_EMPTY_ROOT(&map_tree->map)) {
5131 struct extent_map *em;
5133 node = rb_first(&map_tree->map);
5134 em = rb_entry(node, struct extent_map, rb_node);
5135 clear_bit(EXTENT_FLAG_PINNED, &em->flags);
5136 clear_bit(EXTENT_FLAG_LOGGING, &em->flags);
5137 remove_extent_mapping(map_tree, em);
5138 free_extent_map(em);
5139 if (need_resched()) {
5140 write_unlock(&map_tree->lock);
5142 write_lock(&map_tree->lock);
5145 write_unlock(&map_tree->lock);
5148 * Keep looping until we have no more ranges in the io tree.
5149 * We can have ongoing bios started by readpages (called from readahead)
5150 * that have their endio callback (extent_io.c:end_bio_extent_readpage)
5151 * still in progress (unlocked the pages in the bio but did not yet
5152 * unlocked the ranges in the io tree). Therefore this means some
5153 * ranges can still be locked and eviction started because before
5154 * submitting those bios, which are executed by a separate task (work
5155 * queue kthread), inode references (inode->i_count) were not taken
5156 * (which would be dropped in the end io callback of each bio).
5157 * Therefore here we effectively end up waiting for those bios and
5158 * anyone else holding locked ranges without having bumped the inode's
5159 * reference count - if we don't do it, when they access the inode's
5160 * io_tree to unlock a range it may be too late, leading to an
5161 * use-after-free issue.
5163 spin_lock(&io_tree->lock);
5164 while (!RB_EMPTY_ROOT(&io_tree->state)) {
5165 struct extent_state *state;
5166 struct extent_state *cached_state = NULL;
5170 node = rb_first(&io_tree->state);
5171 state = rb_entry(node, struct extent_state, rb_node);
5172 start = state->start;
5174 spin_unlock(&io_tree->lock);
5176 lock_extent_bits(io_tree, start, end, 0, &cached_state);
5179 * If still has DELALLOC flag, the extent didn't reach disk,
5180 * and its reserved space won't be freed by delayed_ref.
5181 * So we need to free its reserved space here.
5182 * (Refer to comment in btrfs_invalidatepage, case 2)
5184 * Note, end is the bytenr of last byte, so we need + 1 here.
5186 if (state->state & EXTENT_DELALLOC)
5187 btrfs_qgroup_free_data(inode, start, end - start + 1);
5189 clear_extent_bit(io_tree, start, end,
5190 EXTENT_LOCKED | EXTENT_DIRTY |
5191 EXTENT_DELALLOC | EXTENT_DO_ACCOUNTING |
5192 EXTENT_DEFRAG, 1, 1,
5193 &cached_state, GFP_NOFS);
5196 spin_lock(&io_tree->lock);
5198 spin_unlock(&io_tree->lock);
5201 void btrfs_evict_inode(struct inode *inode)
5203 struct btrfs_trans_handle *trans;
5204 struct btrfs_root *root = BTRFS_I(inode)->root;
5205 struct btrfs_block_rsv *rsv, *global_rsv;
5206 int steal_from_global = 0;
5207 u64 min_size = btrfs_calc_trunc_metadata_size(root, 1);
5210 trace_btrfs_inode_evict(inode);
5212 evict_inode_truncate_pages(inode);
5214 if (inode->i_nlink &&
5215 ((btrfs_root_refs(&root->root_item) != 0 &&
5216 root->root_key.objectid != BTRFS_ROOT_TREE_OBJECTID) ||
5217 btrfs_is_free_space_inode(inode)))
5220 if (is_bad_inode(inode)) {
5221 btrfs_orphan_del(NULL, inode);
5224 /* do we really want it for ->i_nlink > 0 and zero btrfs_root_refs? */
5225 if (!special_file(inode->i_mode))
5226 btrfs_wait_ordered_range(inode, 0, (u64)-1);
5228 btrfs_free_io_failure_record(inode, 0, (u64)-1);
5230 if (root->fs_info->log_root_recovering) {
5231 BUG_ON(test_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
5232 &BTRFS_I(inode)->runtime_flags));
5236 if (inode->i_nlink > 0) {
5237 BUG_ON(btrfs_root_refs(&root->root_item) != 0 &&
5238 root->root_key.objectid != BTRFS_ROOT_TREE_OBJECTID);
5242 ret = btrfs_commit_inode_delayed_inode(inode);
5244 btrfs_orphan_del(NULL, inode);
5248 rsv = btrfs_alloc_block_rsv(root, BTRFS_BLOCK_RSV_TEMP);
5250 btrfs_orphan_del(NULL, inode);
5253 rsv->size = min_size;
5255 global_rsv = &root->fs_info->global_block_rsv;
5257 btrfs_i_size_write(inode, 0);
5260 * This is a bit simpler than btrfs_truncate since we've already
5261 * reserved our space for our orphan item in the unlink, so we just
5262 * need to reserve some slack space in case we add bytes and update
5263 * inode item when doing the truncate.
5266 ret = btrfs_block_rsv_refill(root, rsv, min_size,
5267 BTRFS_RESERVE_FLUSH_LIMIT);
5270 * Try and steal from the global reserve since we will
5271 * likely not use this space anyway, we want to try as
5272 * hard as possible to get this to work.
5275 steal_from_global++;
5277 steal_from_global = 0;
5281 * steal_from_global == 0: we reserved stuff, hooray!
5282 * steal_from_global == 1: we didn't reserve stuff, boo!
5283 * steal_from_global == 2: we've committed, still not a lot of
5284 * room but maybe we'll have room in the global reserve this
5286 * steal_from_global == 3: abandon all hope!
5288 if (steal_from_global > 2) {
5289 btrfs_warn(root->fs_info,
5290 "Could not get space for a delete, will truncate on mount %d",
5292 btrfs_orphan_del(NULL, inode);
5293 btrfs_free_block_rsv(root, rsv);
5297 trans = btrfs_join_transaction(root);
5298 if (IS_ERR(trans)) {
5299 btrfs_orphan_del(NULL, inode);
5300 btrfs_free_block_rsv(root, rsv);
5305 * We can't just steal from the global reserve, we need tomake
5306 * sure there is room to do it, if not we need to commit and try
5309 if (steal_from_global) {
5310 if (!btrfs_check_space_for_delayed_refs(trans, root))
5311 ret = btrfs_block_rsv_migrate(global_rsv, rsv,
5318 * Couldn't steal from the global reserve, we have too much
5319 * pending stuff built up, commit the transaction and try it
5323 ret = btrfs_commit_transaction(trans, root);
5325 btrfs_orphan_del(NULL, inode);
5326 btrfs_free_block_rsv(root, rsv);
5331 steal_from_global = 0;
5334 trans->block_rsv = rsv;
5336 ret = btrfs_truncate_inode_items(trans, root, inode, 0, 0);
5337 if (ret != -ENOSPC && ret != -EAGAIN)
5340 trans->block_rsv = &root->fs_info->trans_block_rsv;
5341 btrfs_end_transaction(trans, root);
5343 btrfs_btree_balance_dirty(root);
5346 btrfs_free_block_rsv(root, rsv);
5349 * Errors here aren't a big deal, it just means we leave orphan items
5350 * in the tree. They will be cleaned up on the next mount.
5353 trans->block_rsv = root->orphan_block_rsv;
5354 btrfs_orphan_del(trans, inode);
5356 btrfs_orphan_del(NULL, inode);
5359 trans->block_rsv = &root->fs_info->trans_block_rsv;
5360 if (!(root == root->fs_info->tree_root ||
5361 root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID))
5362 btrfs_return_ino(root, btrfs_ino(inode));
5364 btrfs_end_transaction(trans, root);
5365 btrfs_btree_balance_dirty(root);
5367 btrfs_remove_delayed_node(inode);
5373 * Return the key found in the dir entry in the location pointer, fill @type
5374 * with BTRFS_FT_*, and return 0.
5376 * If no dir entries were found, location->objectid is 0.
5378 static int btrfs_inode_by_name(struct inode *dir, struct dentry *dentry,
5379 struct btrfs_key *location, u8 *type)
5381 const char *name = dentry->d_name.name;
5382 int namelen = dentry->d_name.len;
5383 struct btrfs_dir_item *di;
5384 struct btrfs_path *path;
5385 struct btrfs_root *root = BTRFS_I(dir)->root;
5388 path = btrfs_alloc_path();
5392 di = btrfs_lookup_dir_item(NULL, root, path, btrfs_ino(dir), name,
5397 if (IS_ERR_OR_NULL(di))
5400 btrfs_dir_item_key_to_cpu(path->nodes[0], di, location);
5402 *type = btrfs_dir_type(path->nodes[0], di);
5404 btrfs_free_path(path);
5407 location->objectid = 0;
5412 * when we hit a tree root in a directory, the btrfs part of the inode
5413 * needs to be changed to reflect the root directory of the tree root. This
5414 * is kind of like crossing a mount point.
5416 static int fixup_tree_root_location(struct btrfs_root *root,
5418 struct dentry *dentry,
5419 struct btrfs_key *location,
5420 struct btrfs_root **sub_root)
5422 struct btrfs_path *path;
5423 struct btrfs_root *new_root;
5424 struct btrfs_root_ref *ref;
5425 struct extent_buffer *leaf;
5426 struct btrfs_key key;
5430 path = btrfs_alloc_path();
5437 key.objectid = BTRFS_I(dir)->root->root_key.objectid;
5438 key.type = BTRFS_ROOT_REF_KEY;
5439 key.offset = location->objectid;
5441 ret = btrfs_search_slot(NULL, root->fs_info->tree_root, &key, path,
5449 leaf = path->nodes[0];
5450 ref = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_root_ref);
5451 if (btrfs_root_ref_dirid(leaf, ref) != btrfs_ino(dir) ||
5452 btrfs_root_ref_name_len(leaf, ref) != dentry->d_name.len)
5455 ret = memcmp_extent_buffer(leaf, dentry->d_name.name,
5456 (unsigned long)(ref + 1),
5457 dentry->d_name.len);
5461 btrfs_release_path(path);
5463 new_root = btrfs_read_fs_root_no_name(root->fs_info, location);
5464 if (IS_ERR(new_root)) {
5465 err = PTR_ERR(new_root);
5469 *sub_root = new_root;
5470 location->objectid = btrfs_root_dirid(&new_root->root_item);
5471 location->type = BTRFS_INODE_ITEM_KEY;
5472 location->offset = 0;
5475 btrfs_free_path(path);
5479 static void inode_tree_add(struct inode *inode)
5481 struct btrfs_root *root = BTRFS_I(inode)->root;
5482 struct btrfs_inode *entry;
5484 struct rb_node *parent;
5485 struct rb_node *new = &BTRFS_I(inode)->rb_node;
5486 u64 ino = btrfs_ino(inode);
5488 if (inode_unhashed(inode))
5491 spin_lock(&root->inode_lock);
5492 p = &root->inode_tree.rb_node;
5495 entry = rb_entry(parent, struct btrfs_inode, rb_node);
5497 if (ino < btrfs_ino(&entry->vfs_inode))
5498 p = &parent->rb_left;
5499 else if (ino > btrfs_ino(&entry->vfs_inode))
5500 p = &parent->rb_right;
5502 WARN_ON(!(entry->vfs_inode.i_state &
5503 (I_WILL_FREE | I_FREEING)));
5504 rb_replace_node(parent, new, &root->inode_tree);
5505 RB_CLEAR_NODE(parent);
5506 spin_unlock(&root->inode_lock);
5510 rb_link_node(new, parent, p);
5511 rb_insert_color(new, &root->inode_tree);
5512 spin_unlock(&root->inode_lock);
5515 static void inode_tree_del(struct inode *inode)
5517 struct btrfs_root *root = BTRFS_I(inode)->root;
5520 spin_lock(&root->inode_lock);
5521 if (!RB_EMPTY_NODE(&BTRFS_I(inode)->rb_node)) {
5522 rb_erase(&BTRFS_I(inode)->rb_node, &root->inode_tree);
5523 RB_CLEAR_NODE(&BTRFS_I(inode)->rb_node);
5524 empty = RB_EMPTY_ROOT(&root->inode_tree);
5526 spin_unlock(&root->inode_lock);
5528 if (empty && btrfs_root_refs(&root->root_item) == 0) {
5529 spin_lock(&root->inode_lock);
5530 empty = RB_EMPTY_ROOT(&root->inode_tree);
5531 spin_unlock(&root->inode_lock);
5533 btrfs_add_dead_root(root);
5537 void btrfs_invalidate_inodes(struct btrfs_root *root)
5539 struct rb_node *node;
5540 struct rb_node *prev;
5541 struct btrfs_inode *entry;
5542 struct inode *inode;
5545 if (!test_bit(BTRFS_FS_STATE_ERROR, &root->fs_info->fs_state))
5546 WARN_ON(btrfs_root_refs(&root->root_item) != 0);
5548 spin_lock(&root->inode_lock);
5550 node = root->inode_tree.rb_node;
5554 entry = rb_entry(node, struct btrfs_inode, rb_node);
5556 if (objectid < btrfs_ino(&entry->vfs_inode))
5557 node = node->rb_left;
5558 else if (objectid > btrfs_ino(&entry->vfs_inode))
5559 node = node->rb_right;
5565 entry = rb_entry(prev, struct btrfs_inode, rb_node);
5566 if (objectid <= btrfs_ino(&entry->vfs_inode)) {
5570 prev = rb_next(prev);
5574 entry = rb_entry(node, struct btrfs_inode, rb_node);
5575 objectid = btrfs_ino(&entry->vfs_inode) + 1;
5576 inode = igrab(&entry->vfs_inode);
5578 spin_unlock(&root->inode_lock);
5579 if (atomic_read(&inode->i_count) > 1)
5580 d_prune_aliases(inode);
5582 * btrfs_drop_inode will have it removed from
5583 * the inode cache when its usage count
5588 spin_lock(&root->inode_lock);
5592 if (cond_resched_lock(&root->inode_lock))
5595 node = rb_next(node);
5597 spin_unlock(&root->inode_lock);
5600 static int btrfs_init_locked_inode(struct inode *inode, void *p)
5602 struct btrfs_iget_args *args = p;
5603 inode->i_ino = args->location->objectid;
5604 memcpy(&BTRFS_I(inode)->location, args->location,
5605 sizeof(*args->location));
5606 BTRFS_I(inode)->root = args->root;
5610 static int btrfs_find_actor(struct inode *inode, void *opaque)
5612 struct btrfs_iget_args *args = opaque;
5613 return args->location->objectid == BTRFS_I(inode)->location.objectid &&
5614 args->root == BTRFS_I(inode)->root;
5617 static struct inode *btrfs_iget_locked(struct super_block *s,
5618 struct btrfs_key *location,
5619 struct btrfs_root *root)
5621 struct inode *inode;
5622 struct btrfs_iget_args args;
5623 unsigned long hashval = btrfs_inode_hash(location->objectid, root);
5625 args.location = location;
5628 inode = iget5_locked(s, hashval, btrfs_find_actor,
5629 btrfs_init_locked_inode,
5634 /* Get an inode object given its location and corresponding root.
5635 * Returns in *is_new if the inode was read from disk
5637 struct inode *btrfs_iget(struct super_block *s, struct btrfs_key *location,
5638 struct btrfs_root *root, int *new)
5640 struct inode *inode;
5642 inode = btrfs_iget_locked(s, location, root);
5644 return ERR_PTR(-ENOMEM);
5646 if (inode->i_state & I_NEW) {
5647 btrfs_read_locked_inode(inode);
5648 if (!is_bad_inode(inode)) {
5649 inode_tree_add(inode);
5650 unlock_new_inode(inode);
5654 unlock_new_inode(inode);
5656 inode = ERR_PTR(-ESTALE);
5663 static struct inode *new_simple_dir(struct super_block *s,
5664 struct btrfs_key *key,
5665 struct btrfs_root *root)
5667 struct inode *inode = new_inode(s);
5670 return ERR_PTR(-ENOMEM);
5672 BTRFS_I(inode)->root = root;
5673 memcpy(&BTRFS_I(inode)->location, key, sizeof(*key));
5674 set_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags);
5676 inode->i_ino = BTRFS_EMPTY_SUBVOL_DIR_OBJECTID;
5677 inode->i_op = &btrfs_dir_ro_inode_operations;
5678 inode->i_fop = &simple_dir_operations;
5679 inode->i_mode = S_IFDIR | S_IRUGO | S_IWUSR | S_IXUGO;
5680 inode->i_mtime = CURRENT_TIME;
5681 inode->i_atime = inode->i_mtime;
5682 inode->i_ctime = inode->i_mtime;
5683 BTRFS_I(inode)->i_otime = inode->i_mtime;
5688 static inline u8 btrfs_inode_type(struct inode *inode)
5690 return btrfs_type_by_mode[(inode->i_mode & S_IFMT) >> S_SHIFT];
5693 struct inode *btrfs_lookup_dentry(struct inode *dir, struct dentry *dentry)
5695 struct inode *inode;
5696 struct btrfs_root *root = BTRFS_I(dir)->root;
5697 struct btrfs_root *sub_root = root;
5698 struct btrfs_key location;
5703 if (dentry->d_name.len > BTRFS_NAME_LEN)
5704 return ERR_PTR(-ENAMETOOLONG);
5706 ret = btrfs_inode_by_name(dir, dentry, &location, &di_type);
5708 return ERR_PTR(ret);
5710 if (location.objectid == 0)
5711 return ERR_PTR(-ENOENT);
5713 if (location.type == BTRFS_INODE_ITEM_KEY) {
5714 inode = btrfs_iget(dir->i_sb, &location, root, NULL);
5718 /* Do extra check against inode mode with di_type */
5719 if (btrfs_inode_type(inode) != di_type) {
5720 btrfs_crit(root->fs_info,
5721 "inode mode mismatch with dir: inode mode=0%o btrfs type=%u dir type=%u",
5722 inode->i_mode, btrfs_inode_type(inode),
5725 return ERR_PTR(-EUCLEAN);
5730 BUG_ON(location.type != BTRFS_ROOT_ITEM_KEY);
5732 index = srcu_read_lock(&root->fs_info->subvol_srcu);
5733 ret = fixup_tree_root_location(root, dir, dentry,
5734 &location, &sub_root);
5737 inode = ERR_PTR(ret);
5739 inode = new_simple_dir(dir->i_sb, &location, sub_root);
5741 inode = btrfs_iget(dir->i_sb, &location, sub_root, NULL);
5743 srcu_read_unlock(&root->fs_info->subvol_srcu, index);
5745 if (!IS_ERR(inode) && root != sub_root) {
5746 down_read(&root->fs_info->cleanup_work_sem);
5747 if (!(inode->i_sb->s_flags & MS_RDONLY))
5748 ret = btrfs_orphan_cleanup(sub_root);
5749 up_read(&root->fs_info->cleanup_work_sem);
5752 inode = ERR_PTR(ret);
5759 static int btrfs_dentry_delete(const struct dentry *dentry)
5761 struct btrfs_root *root;
5762 struct inode *inode = d_inode(dentry);
5764 if (!inode && !IS_ROOT(dentry))
5765 inode = d_inode(dentry->d_parent);
5768 root = BTRFS_I(inode)->root;
5769 if (btrfs_root_refs(&root->root_item) == 0)
5772 if (btrfs_ino(inode) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)
5778 static void btrfs_dentry_release(struct dentry *dentry)
5780 kfree(dentry->d_fsdata);
5783 static struct dentry *btrfs_lookup(struct inode *dir, struct dentry *dentry,
5786 struct inode *inode;
5788 inode = btrfs_lookup_dentry(dir, dentry);
5789 if (IS_ERR(inode)) {
5790 if (PTR_ERR(inode) == -ENOENT)
5793 return ERR_CAST(inode);
5796 return d_splice_alias(inode, dentry);
5799 unsigned char btrfs_filetype_table[] = {
5800 DT_UNKNOWN, DT_REG, DT_DIR, DT_CHR, DT_BLK, DT_FIFO, DT_SOCK, DT_LNK
5803 static int btrfs_real_readdir(struct file *file, struct dir_context *ctx)
5805 struct inode *inode = file_inode(file);
5806 struct btrfs_root *root = BTRFS_I(inode)->root;
5807 struct btrfs_item *item;
5808 struct btrfs_dir_item *di;
5809 struct btrfs_key key;
5810 struct btrfs_key found_key;
5811 struct btrfs_path *path;
5812 struct list_head ins_list;
5813 struct list_head del_list;
5815 struct extent_buffer *leaf;
5817 unsigned char d_type;
5822 int key_type = BTRFS_DIR_INDEX_KEY;
5826 int is_curr = 0; /* ctx->pos points to the current index? */
5829 /* FIXME, use a real flag for deciding about the key type */
5830 if (root->fs_info->tree_root == root)
5831 key_type = BTRFS_DIR_ITEM_KEY;
5833 if (!dir_emit_dots(file, ctx))
5836 path = btrfs_alloc_path();
5842 if (key_type == BTRFS_DIR_INDEX_KEY) {
5843 INIT_LIST_HEAD(&ins_list);
5844 INIT_LIST_HEAD(&del_list);
5845 btrfs_get_delayed_items(inode, &ins_list, &del_list);
5848 key.type = key_type;
5849 key.offset = ctx->pos;
5850 key.objectid = btrfs_ino(inode);
5852 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
5858 leaf = path->nodes[0];
5859 slot = path->slots[0];
5860 if (slot >= btrfs_header_nritems(leaf)) {
5861 ret = btrfs_next_leaf(root, path);
5869 item = btrfs_item_nr(slot);
5870 btrfs_item_key_to_cpu(leaf, &found_key, slot);
5872 if (found_key.objectid != key.objectid)
5874 if (found_key.type != key_type)
5876 if (found_key.offset < ctx->pos)
5878 if (key_type == BTRFS_DIR_INDEX_KEY &&
5879 btrfs_should_delete_dir_index(&del_list,
5883 ctx->pos = found_key.offset;
5886 di = btrfs_item_ptr(leaf, slot, struct btrfs_dir_item);
5888 di_total = btrfs_item_size(leaf, item);
5890 while (di_cur < di_total) {
5891 struct btrfs_key location;
5893 if (verify_dir_item(root, leaf, di))
5896 name_len = btrfs_dir_name_len(leaf, di);
5897 if (name_len <= sizeof(tmp_name)) {
5898 name_ptr = tmp_name;
5900 name_ptr = kmalloc(name_len, GFP_NOFS);
5906 read_extent_buffer(leaf, name_ptr,
5907 (unsigned long)(di + 1), name_len);
5909 d_type = btrfs_filetype_table[btrfs_dir_type(leaf, di)];
5910 btrfs_dir_item_key_to_cpu(leaf, di, &location);
5913 /* is this a reference to our own snapshot? If so
5916 * In contrast to old kernels, we insert the snapshot's
5917 * dir item and dir index after it has been created, so
5918 * we won't find a reference to our own snapshot. We
5919 * still keep the following code for backward
5922 if (location.type == BTRFS_ROOT_ITEM_KEY &&
5923 location.objectid == root->root_key.objectid) {
5927 over = !dir_emit(ctx, name_ptr, name_len,
5928 location.objectid, d_type);
5931 if (name_ptr != tmp_name)
5937 di_len = btrfs_dir_name_len(leaf, di) +
5938 btrfs_dir_data_len(leaf, di) + sizeof(*di);
5940 di = (struct btrfs_dir_item *)((char *)di + di_len);
5946 if (key_type == BTRFS_DIR_INDEX_KEY) {
5949 ret = btrfs_readdir_delayed_dir_index(ctx, &ins_list, &emitted);
5955 * If we haven't emitted any dir entry, we must not touch ctx->pos as
5956 * it was was set to the termination value in previous call. We assume
5957 * that "." and ".." were emitted if we reach this point and set the
5958 * termination value as well for an empty directory.
5960 if (ctx->pos > 2 && !emitted)
5963 /* Reached end of directory/root. Bump pos past the last item. */
5967 * Stop new entries from being returned after we return the last
5970 * New directory entries are assigned a strictly increasing
5971 * offset. This means that new entries created during readdir
5972 * are *guaranteed* to be seen in the future by that readdir.
5973 * This has broken buggy programs which operate on names as
5974 * they're returned by readdir. Until we re-use freed offsets
5975 * we have this hack to stop new entries from being returned
5976 * under the assumption that they'll never reach this huge
5979 * This is being careful not to overflow 32bit loff_t unless the
5980 * last entry requires it because doing so has broken 32bit apps
5983 if (key_type == BTRFS_DIR_INDEX_KEY) {
5984 if (ctx->pos >= INT_MAX)
5985 ctx->pos = LLONG_MAX;
5992 if (key_type == BTRFS_DIR_INDEX_KEY)
5993 btrfs_put_delayed_items(&ins_list, &del_list);
5994 btrfs_free_path(path);
5998 int btrfs_write_inode(struct inode *inode, struct writeback_control *wbc)
6000 struct btrfs_root *root = BTRFS_I(inode)->root;
6001 struct btrfs_trans_handle *trans;
6003 bool nolock = false;
6005 if (test_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags))
6008 if (btrfs_fs_closing(root->fs_info) && btrfs_is_free_space_inode(inode))
6011 if (wbc->sync_mode == WB_SYNC_ALL) {
6013 trans = btrfs_join_transaction_nolock(root);
6015 trans = btrfs_join_transaction(root);
6017 return PTR_ERR(trans);
6018 ret = btrfs_commit_transaction(trans, root);
6024 * This is somewhat expensive, updating the tree every time the
6025 * inode changes. But, it is most likely to find the inode in cache.
6026 * FIXME, needs more benchmarking...there are no reasons other than performance
6027 * to keep or drop this code.
6029 static int btrfs_dirty_inode(struct inode *inode)
6031 struct btrfs_root *root = BTRFS_I(inode)->root;
6032 struct btrfs_trans_handle *trans;
6035 if (test_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags))
6038 trans = btrfs_join_transaction(root);
6040 return PTR_ERR(trans);
6042 ret = btrfs_update_inode(trans, root, inode);
6043 if (ret && ret == -ENOSPC) {
6044 /* whoops, lets try again with the full transaction */
6045 btrfs_end_transaction(trans, root);
6046 trans = btrfs_start_transaction(root, 1);
6048 return PTR_ERR(trans);
6050 ret = btrfs_update_inode(trans, root, inode);
6052 btrfs_end_transaction(trans, root);
6053 if (BTRFS_I(inode)->delayed_node)
6054 btrfs_balance_delayed_items(root);
6060 * This is a copy of file_update_time. We need this so we can return error on
6061 * ENOSPC for updating the inode in the case of file write and mmap writes.
6063 static int btrfs_update_time(struct inode *inode, struct timespec *now,
6066 struct btrfs_root *root = BTRFS_I(inode)->root;
6068 if (btrfs_root_readonly(root))
6071 if (flags & S_VERSION)
6072 inode_inc_iversion(inode);
6073 if (flags & S_CTIME)
6074 inode->i_ctime = *now;
6075 if (flags & S_MTIME)
6076 inode->i_mtime = *now;
6077 if (flags & S_ATIME)
6078 inode->i_atime = *now;
6079 return btrfs_dirty_inode(inode);
6083 * find the highest existing sequence number in a directory
6084 * and then set the in-memory index_cnt variable to reflect
6085 * free sequence numbers
6087 static int btrfs_set_inode_index_count(struct inode *inode)
6089 struct btrfs_root *root = BTRFS_I(inode)->root;
6090 struct btrfs_key key, found_key;
6091 struct btrfs_path *path;
6092 struct extent_buffer *leaf;
6095 key.objectid = btrfs_ino(inode);
6096 key.type = BTRFS_DIR_INDEX_KEY;
6097 key.offset = (u64)-1;
6099 path = btrfs_alloc_path();
6103 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
6106 /* FIXME: we should be able to handle this */
6112 * MAGIC NUMBER EXPLANATION:
6113 * since we search a directory based on f_pos we have to start at 2
6114 * since '.' and '..' have f_pos of 0 and 1 respectively, so everybody
6115 * else has to start at 2
6117 if (path->slots[0] == 0) {
6118 BTRFS_I(inode)->index_cnt = 2;
6124 leaf = path->nodes[0];
6125 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
6127 if (found_key.objectid != btrfs_ino(inode) ||
6128 found_key.type != BTRFS_DIR_INDEX_KEY) {
6129 BTRFS_I(inode)->index_cnt = 2;
6133 BTRFS_I(inode)->index_cnt = found_key.offset + 1;
6135 btrfs_free_path(path);
6140 * helper to find a free sequence number in a given directory. This current
6141 * code is very simple, later versions will do smarter things in the btree
6143 int btrfs_set_inode_index(struct inode *dir, u64 *index)
6147 if (BTRFS_I(dir)->index_cnt == (u64)-1) {
6148 ret = btrfs_inode_delayed_dir_index_count(dir);
6150 ret = btrfs_set_inode_index_count(dir);
6156 *index = BTRFS_I(dir)->index_cnt;
6157 BTRFS_I(dir)->index_cnt++;
6162 static int btrfs_insert_inode_locked(struct inode *inode)
6164 struct btrfs_iget_args args;
6165 args.location = &BTRFS_I(inode)->location;
6166 args.root = BTRFS_I(inode)->root;
6168 return insert_inode_locked4(inode,
6169 btrfs_inode_hash(inode->i_ino, BTRFS_I(inode)->root),
6170 btrfs_find_actor, &args);
6173 static struct inode *btrfs_new_inode(struct btrfs_trans_handle *trans,
6174 struct btrfs_root *root,
6176 const char *name, int name_len,
6177 u64 ref_objectid, u64 objectid,
6178 umode_t mode, u64 *index)
6180 struct inode *inode;
6181 struct btrfs_inode_item *inode_item;
6182 struct btrfs_key *location;
6183 struct btrfs_path *path;
6184 struct btrfs_inode_ref *ref;
6185 struct btrfs_key key[2];
6187 int nitems = name ? 2 : 1;
6191 path = btrfs_alloc_path();
6193 return ERR_PTR(-ENOMEM);
6195 inode = new_inode(root->fs_info->sb);
6197 btrfs_free_path(path);
6198 return ERR_PTR(-ENOMEM);
6202 * O_TMPFILE, set link count to 0, so that after this point,
6203 * we fill in an inode item with the correct link count.
6206 set_nlink(inode, 0);
6209 * we have to initialize this early, so we can reclaim the inode
6210 * number if we fail afterwards in this function.
6212 inode->i_ino = objectid;
6215 trace_btrfs_inode_request(dir);
6217 ret = btrfs_set_inode_index(dir, index);
6219 btrfs_free_path(path);
6221 return ERR_PTR(ret);
6227 * index_cnt is ignored for everything but a dir,
6228 * btrfs_get_inode_index_count has an explanation for the magic
6231 BTRFS_I(inode)->index_cnt = 2;
6232 BTRFS_I(inode)->dir_index = *index;
6233 BTRFS_I(inode)->root = root;
6234 BTRFS_I(inode)->generation = trans->transid;
6235 inode->i_generation = BTRFS_I(inode)->generation;
6238 * We could have gotten an inode number from somebody who was fsynced
6239 * and then removed in this same transaction, so let's just set full
6240 * sync since it will be a full sync anyway and this will blow away the
6241 * old info in the log.
6243 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &BTRFS_I(inode)->runtime_flags);
6245 key[0].objectid = objectid;
6246 key[0].type = BTRFS_INODE_ITEM_KEY;
6249 sizes[0] = sizeof(struct btrfs_inode_item);
6253 * Start new inodes with an inode_ref. This is slightly more
6254 * efficient for small numbers of hard links since they will
6255 * be packed into one item. Extended refs will kick in if we
6256 * add more hard links than can fit in the ref item.
6258 key[1].objectid = objectid;
6259 key[1].type = BTRFS_INODE_REF_KEY;
6260 key[1].offset = ref_objectid;
6262 sizes[1] = name_len + sizeof(*ref);
6265 location = &BTRFS_I(inode)->location;
6266 location->objectid = objectid;
6267 location->offset = 0;
6268 location->type = BTRFS_INODE_ITEM_KEY;
6270 ret = btrfs_insert_inode_locked(inode);
6274 path->leave_spinning = 1;
6275 ret = btrfs_insert_empty_items(trans, root, path, key, sizes, nitems);
6279 inode_init_owner(inode, dir, mode);
6280 inode_set_bytes(inode, 0);
6282 inode->i_mtime = CURRENT_TIME;
6283 inode->i_atime = inode->i_mtime;
6284 inode->i_ctime = inode->i_mtime;
6285 BTRFS_I(inode)->i_otime = inode->i_mtime;
6287 inode_item = btrfs_item_ptr(path->nodes[0], path->slots[0],
6288 struct btrfs_inode_item);
6289 memset_extent_buffer(path->nodes[0], 0, (unsigned long)inode_item,
6290 sizeof(*inode_item));
6291 fill_inode_item(trans, path->nodes[0], inode_item, inode);
6294 ref = btrfs_item_ptr(path->nodes[0], path->slots[0] + 1,
6295 struct btrfs_inode_ref);
6296 btrfs_set_inode_ref_name_len(path->nodes[0], ref, name_len);
6297 btrfs_set_inode_ref_index(path->nodes[0], ref, *index);
6298 ptr = (unsigned long)(ref + 1);
6299 write_extent_buffer(path->nodes[0], name, ptr, name_len);
6302 btrfs_mark_buffer_dirty(path->nodes[0]);
6303 btrfs_free_path(path);
6305 btrfs_inherit_iflags(inode, dir);
6307 if (S_ISREG(mode)) {
6308 if (btrfs_test_opt(root, NODATASUM))
6309 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATASUM;
6310 if (btrfs_test_opt(root, NODATACOW))
6311 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATACOW |
6312 BTRFS_INODE_NODATASUM;
6315 inode_tree_add(inode);
6317 trace_btrfs_inode_new(inode);
6318 btrfs_set_inode_last_trans(trans, inode);
6320 btrfs_update_root_times(trans, root);
6322 ret = btrfs_inode_inherit_props(trans, inode, dir);
6324 btrfs_err(root->fs_info,
6325 "error inheriting props for ino %llu (root %llu): %d",
6326 btrfs_ino(inode), root->root_key.objectid, ret);
6331 unlock_new_inode(inode);
6334 BTRFS_I(dir)->index_cnt--;
6335 btrfs_free_path(path);
6337 return ERR_PTR(ret);
6341 * utility function to add 'inode' into 'parent_inode' with
6342 * a give name and a given sequence number.
6343 * if 'add_backref' is true, also insert a backref from the
6344 * inode to the parent directory.
6346 int btrfs_add_link(struct btrfs_trans_handle *trans,
6347 struct inode *parent_inode, struct inode *inode,
6348 const char *name, int name_len, int add_backref, u64 index)
6351 struct btrfs_key key;
6352 struct btrfs_root *root = BTRFS_I(parent_inode)->root;
6353 u64 ino = btrfs_ino(inode);
6354 u64 parent_ino = btrfs_ino(parent_inode);
6356 if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
6357 memcpy(&key, &BTRFS_I(inode)->root->root_key, sizeof(key));
6360 key.type = BTRFS_INODE_ITEM_KEY;
6364 if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
6365 ret = btrfs_add_root_ref(trans, root->fs_info->tree_root,
6366 key.objectid, root->root_key.objectid,
6367 parent_ino, index, name, name_len);
6368 } else if (add_backref) {
6369 ret = btrfs_insert_inode_ref(trans, root, name, name_len, ino,
6373 /* Nothing to clean up yet */
6377 ret = btrfs_insert_dir_item(trans, root, name, name_len,
6379 btrfs_inode_type(inode), index);
6380 if (ret == -EEXIST || ret == -EOVERFLOW)
6383 btrfs_abort_transaction(trans, root, ret);
6387 btrfs_i_size_write(parent_inode, parent_inode->i_size +
6389 inode_inc_iversion(parent_inode);
6390 parent_inode->i_mtime = parent_inode->i_ctime = CURRENT_TIME;
6391 ret = btrfs_update_inode(trans, root, parent_inode);
6393 btrfs_abort_transaction(trans, root, ret);
6397 if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
6400 err = btrfs_del_root_ref(trans, root->fs_info->tree_root,
6401 key.objectid, root->root_key.objectid,
6402 parent_ino, &local_index, name, name_len);
6404 } else if (add_backref) {
6408 err = btrfs_del_inode_ref(trans, root, name, name_len,
6409 ino, parent_ino, &local_index);
6414 static int btrfs_add_nondir(struct btrfs_trans_handle *trans,
6415 struct inode *dir, struct dentry *dentry,
6416 struct inode *inode, int backref, u64 index)
6418 int err = btrfs_add_link(trans, dir, inode,
6419 dentry->d_name.name, dentry->d_name.len,
6426 static int btrfs_mknod(struct inode *dir, struct dentry *dentry,
6427 umode_t mode, dev_t rdev)
6429 struct btrfs_trans_handle *trans;
6430 struct btrfs_root *root = BTRFS_I(dir)->root;
6431 struct inode *inode = NULL;
6438 * 2 for inode item and ref
6440 * 1 for xattr if selinux is on
6442 trans = btrfs_start_transaction(root, 5);
6444 return PTR_ERR(trans);
6446 err = btrfs_find_free_ino(root, &objectid);
6450 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
6451 dentry->d_name.len, btrfs_ino(dir), objectid,
6453 if (IS_ERR(inode)) {
6454 err = PTR_ERR(inode);
6459 * If the active LSM wants to access the inode during
6460 * d_instantiate it needs these. Smack checks to see
6461 * if the filesystem supports xattrs by looking at the
6464 inode->i_op = &btrfs_special_inode_operations;
6465 init_special_inode(inode, inode->i_mode, rdev);
6467 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
6469 goto out_unlock_inode;
6471 err = btrfs_add_nondir(trans, dir, dentry, inode, 0, index);
6473 goto out_unlock_inode;
6475 btrfs_update_inode(trans, root, inode);
6476 d_instantiate_new(dentry, inode);
6480 btrfs_end_transaction(trans, root);
6481 btrfs_balance_delayed_items(root);
6482 btrfs_btree_balance_dirty(root);
6484 inode_dec_link_count(inode);
6491 unlock_new_inode(inode);
6496 static int btrfs_create(struct inode *dir, struct dentry *dentry,
6497 umode_t mode, bool excl)
6499 struct btrfs_trans_handle *trans;
6500 struct btrfs_root *root = BTRFS_I(dir)->root;
6501 struct inode *inode = NULL;
6502 int drop_inode_on_err = 0;
6508 * 2 for inode item and ref
6510 * 1 for xattr if selinux is on
6512 trans = btrfs_start_transaction(root, 5);
6514 return PTR_ERR(trans);
6516 err = btrfs_find_free_ino(root, &objectid);
6520 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
6521 dentry->d_name.len, btrfs_ino(dir), objectid,
6523 if (IS_ERR(inode)) {
6524 err = PTR_ERR(inode);
6527 drop_inode_on_err = 1;
6529 * If the active LSM wants to access the inode during
6530 * d_instantiate it needs these. Smack checks to see
6531 * if the filesystem supports xattrs by looking at the
6534 inode->i_fop = &btrfs_file_operations;
6535 inode->i_op = &btrfs_file_inode_operations;
6536 inode->i_mapping->a_ops = &btrfs_aops;
6538 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
6540 goto out_unlock_inode;
6542 err = btrfs_update_inode(trans, root, inode);
6544 goto out_unlock_inode;
6546 err = btrfs_add_nondir(trans, dir, dentry, inode, 0, index);
6548 goto out_unlock_inode;
6550 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
6551 d_instantiate_new(dentry, inode);
6554 btrfs_end_transaction(trans, root);
6555 if (err && drop_inode_on_err) {
6556 inode_dec_link_count(inode);
6559 btrfs_balance_delayed_items(root);
6560 btrfs_btree_balance_dirty(root);
6564 unlock_new_inode(inode);
6569 static int btrfs_link(struct dentry *old_dentry, struct inode *dir,
6570 struct dentry *dentry)
6572 struct btrfs_trans_handle *trans = NULL;
6573 struct btrfs_root *root = BTRFS_I(dir)->root;
6574 struct inode *inode = d_inode(old_dentry);
6579 /* do not allow sys_link's with other subvols of the same device */
6580 if (root->objectid != BTRFS_I(inode)->root->objectid)
6583 if (inode->i_nlink >= BTRFS_LINK_MAX)
6586 err = btrfs_set_inode_index(dir, &index);
6591 * 2 items for inode and inode ref
6592 * 2 items for dir items
6593 * 1 item for parent inode
6595 trans = btrfs_start_transaction(root, 5);
6596 if (IS_ERR(trans)) {
6597 err = PTR_ERR(trans);
6602 /* There are several dir indexes for this inode, clear the cache. */
6603 BTRFS_I(inode)->dir_index = 0ULL;
6605 inode_inc_iversion(inode);
6606 inode->i_ctime = CURRENT_TIME;
6608 set_bit(BTRFS_INODE_COPY_EVERYTHING, &BTRFS_I(inode)->runtime_flags);
6610 err = btrfs_add_nondir(trans, dir, dentry, inode, 1, index);
6615 struct dentry *parent = dentry->d_parent;
6616 err = btrfs_update_inode(trans, root, inode);
6619 if (inode->i_nlink == 1) {
6621 * If new hard link count is 1, it's a file created
6622 * with open(2) O_TMPFILE flag.
6624 err = btrfs_orphan_del(trans, inode);
6628 d_instantiate(dentry, inode);
6629 btrfs_log_new_name(trans, inode, NULL, parent);
6632 btrfs_balance_delayed_items(root);
6635 btrfs_end_transaction(trans, root);
6637 inode_dec_link_count(inode);
6640 btrfs_btree_balance_dirty(root);
6644 static int btrfs_mkdir(struct inode *dir, struct dentry *dentry, umode_t mode)
6646 struct inode *inode = NULL;
6647 struct btrfs_trans_handle *trans;
6648 struct btrfs_root *root = BTRFS_I(dir)->root;
6650 int drop_on_err = 0;
6655 * 2 items for inode and ref
6656 * 2 items for dir items
6657 * 1 for xattr if selinux is on
6659 trans = btrfs_start_transaction(root, 5);
6661 return PTR_ERR(trans);
6663 err = btrfs_find_free_ino(root, &objectid);
6667 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
6668 dentry->d_name.len, btrfs_ino(dir), objectid,
6669 S_IFDIR | mode, &index);
6670 if (IS_ERR(inode)) {
6671 err = PTR_ERR(inode);
6676 /* these must be set before we unlock the inode */
6677 inode->i_op = &btrfs_dir_inode_operations;
6678 inode->i_fop = &btrfs_dir_file_operations;
6680 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
6682 goto out_fail_inode;
6684 btrfs_i_size_write(inode, 0);
6685 err = btrfs_update_inode(trans, root, inode);
6687 goto out_fail_inode;
6689 err = btrfs_add_link(trans, dir, inode, dentry->d_name.name,
6690 dentry->d_name.len, 0, index);
6692 goto out_fail_inode;
6694 d_instantiate_new(dentry, inode);
6698 btrfs_end_transaction(trans, root);
6700 inode_dec_link_count(inode);
6703 btrfs_balance_delayed_items(root);
6704 btrfs_btree_balance_dirty(root);
6708 unlock_new_inode(inode);
6712 /* Find next extent map of a given extent map, caller needs to ensure locks */
6713 static struct extent_map *next_extent_map(struct extent_map *em)
6715 struct rb_node *next;
6717 next = rb_next(&em->rb_node);
6720 return container_of(next, struct extent_map, rb_node);
6723 static struct extent_map *prev_extent_map(struct extent_map *em)
6725 struct rb_node *prev;
6727 prev = rb_prev(&em->rb_node);
6730 return container_of(prev, struct extent_map, rb_node);
6733 /* helper for btfs_get_extent. Given an existing extent in the tree,
6734 * the existing extent is the nearest extent to map_start,
6735 * and an extent that you want to insert, deal with overlap and insert
6736 * the best fitted new extent into the tree.
6738 static int merge_extent_mapping(struct extent_map_tree *em_tree,
6739 struct extent_map *existing,
6740 struct extent_map *em,
6743 struct extent_map *prev;
6744 struct extent_map *next;
6749 BUG_ON(map_start < em->start || map_start >= extent_map_end(em));
6751 if (existing->start > map_start) {
6753 prev = prev_extent_map(next);
6756 next = next_extent_map(prev);
6759 start = prev ? extent_map_end(prev) : em->start;
6760 start = max_t(u64, start, em->start);
6761 end = next ? next->start : extent_map_end(em);
6762 end = min_t(u64, end, extent_map_end(em));
6763 start_diff = start - em->start;
6765 em->len = end - start;
6766 if (em->block_start < EXTENT_MAP_LAST_BYTE &&
6767 !test_bit(EXTENT_FLAG_COMPRESSED, &em->flags)) {
6768 em->block_start += start_diff;
6769 em->block_len -= start_diff;
6771 return add_extent_mapping(em_tree, em, 0);
6774 static noinline int uncompress_inline(struct btrfs_path *path,
6775 struct inode *inode, struct page *page,
6776 size_t pg_offset, u64 extent_offset,
6777 struct btrfs_file_extent_item *item)
6780 struct extent_buffer *leaf = path->nodes[0];
6783 unsigned long inline_size;
6787 WARN_ON(pg_offset != 0);
6788 compress_type = btrfs_file_extent_compression(leaf, item);
6789 max_size = btrfs_file_extent_ram_bytes(leaf, item);
6790 inline_size = btrfs_file_extent_inline_item_len(leaf,
6791 btrfs_item_nr(path->slots[0]));
6792 tmp = kmalloc(inline_size, GFP_NOFS);
6795 ptr = btrfs_file_extent_inline_start(item);
6797 read_extent_buffer(leaf, tmp, ptr, inline_size);
6799 max_size = min_t(unsigned long, PAGE_CACHE_SIZE, max_size);
6800 ret = btrfs_decompress(compress_type, tmp, page,
6801 extent_offset, inline_size, max_size);
6804 * decompression code contains a memset to fill in any space between the end
6805 * of the uncompressed data and the end of max_size in case the decompressed
6806 * data ends up shorter than ram_bytes. That doesn't cover the hole between
6807 * the end of an inline extent and the beginning of the next block, so we
6808 * cover that region here.
6811 if (max_size + pg_offset < PAGE_SIZE) {
6812 char *map = kmap(page);
6813 memset(map + pg_offset + max_size, 0, PAGE_SIZE - max_size - pg_offset);
6821 * a bit scary, this does extent mapping from logical file offset to the disk.
6822 * the ugly parts come from merging extents from the disk with the in-ram
6823 * representation. This gets more complex because of the data=ordered code,
6824 * where the in-ram extents might be locked pending data=ordered completion.
6826 * This also copies inline extents directly into the page.
6829 struct extent_map *btrfs_get_extent(struct inode *inode, struct page *page,
6830 size_t pg_offset, u64 start, u64 len,
6835 u64 extent_start = 0;
6837 u64 objectid = btrfs_ino(inode);
6839 struct btrfs_path *path = NULL;
6840 struct btrfs_root *root = BTRFS_I(inode)->root;
6841 struct btrfs_file_extent_item *item;
6842 struct extent_buffer *leaf;
6843 struct btrfs_key found_key;
6844 struct extent_map *em = NULL;
6845 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
6846 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
6847 struct btrfs_trans_handle *trans = NULL;
6848 const bool new_inline = !page || create;
6851 read_lock(&em_tree->lock);
6852 em = lookup_extent_mapping(em_tree, start, len);
6854 em->bdev = root->fs_info->fs_devices->latest_bdev;
6855 read_unlock(&em_tree->lock);
6858 if (em->start > start || em->start + em->len <= start)
6859 free_extent_map(em);
6860 else if (em->block_start == EXTENT_MAP_INLINE && page)
6861 free_extent_map(em);
6865 em = alloc_extent_map();
6870 em->bdev = root->fs_info->fs_devices->latest_bdev;
6871 em->start = EXTENT_MAP_HOLE;
6872 em->orig_start = EXTENT_MAP_HOLE;
6874 em->block_len = (u64)-1;
6877 path = btrfs_alloc_path();
6883 * Chances are we'll be called again, so go ahead and do
6889 ret = btrfs_lookup_file_extent(trans, root, path,
6890 objectid, start, trans != NULL);
6897 if (path->slots[0] == 0)
6902 leaf = path->nodes[0];
6903 item = btrfs_item_ptr(leaf, path->slots[0],
6904 struct btrfs_file_extent_item);
6905 /* are we inside the extent that was found? */
6906 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
6907 found_type = found_key.type;
6908 if (found_key.objectid != objectid ||
6909 found_type != BTRFS_EXTENT_DATA_KEY) {
6911 * If we backup past the first extent we want to move forward
6912 * and see if there is an extent in front of us, otherwise we'll
6913 * say there is a hole for our whole search range which can
6920 found_type = btrfs_file_extent_type(leaf, item);
6921 extent_start = found_key.offset;
6922 if (found_type == BTRFS_FILE_EXTENT_REG ||
6923 found_type == BTRFS_FILE_EXTENT_PREALLOC) {
6924 /* Only regular file could have regular/prealloc extent */
6925 if (!S_ISREG(inode->i_mode)) {
6927 btrfs_crit(root->fs_info,
6928 "regular/prealloc extent found for non-regular inode %llu",
6932 extent_end = extent_start +
6933 btrfs_file_extent_num_bytes(leaf, item);
6934 } else if (found_type == BTRFS_FILE_EXTENT_INLINE) {
6936 size = btrfs_file_extent_inline_len(leaf, path->slots[0], item);
6937 extent_end = ALIGN(extent_start + size, root->sectorsize);
6940 if (start >= extent_end) {
6942 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
6943 ret = btrfs_next_leaf(root, path);
6950 leaf = path->nodes[0];
6952 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
6953 if (found_key.objectid != objectid ||
6954 found_key.type != BTRFS_EXTENT_DATA_KEY)
6956 if (start + len <= found_key.offset)
6958 if (start > found_key.offset)
6961 em->orig_start = start;
6962 em->len = found_key.offset - start;
6966 btrfs_extent_item_to_extent_map(inode, path, item, new_inline, em);
6968 if (found_type == BTRFS_FILE_EXTENT_REG ||
6969 found_type == BTRFS_FILE_EXTENT_PREALLOC) {
6971 } else if (found_type == BTRFS_FILE_EXTENT_INLINE) {
6975 size_t extent_offset;
6981 size = btrfs_file_extent_inline_len(leaf, path->slots[0], item);
6982 extent_offset = page_offset(page) + pg_offset - extent_start;
6983 copy_size = min_t(u64, PAGE_CACHE_SIZE - pg_offset,
6984 size - extent_offset);
6985 em->start = extent_start + extent_offset;
6986 em->len = ALIGN(copy_size, root->sectorsize);
6987 em->orig_block_len = em->len;
6988 em->orig_start = em->start;
6989 ptr = btrfs_file_extent_inline_start(item) + extent_offset;
6990 if (create == 0 && !PageUptodate(page)) {
6991 if (btrfs_file_extent_compression(leaf, item) !=
6992 BTRFS_COMPRESS_NONE) {
6993 ret = uncompress_inline(path, inode, page,
6995 extent_offset, item);
7002 read_extent_buffer(leaf, map + pg_offset, ptr,
7004 if (pg_offset + copy_size < PAGE_CACHE_SIZE) {
7005 memset(map + pg_offset + copy_size, 0,
7006 PAGE_CACHE_SIZE - pg_offset -
7011 flush_dcache_page(page);
7012 } else if (create && PageUptodate(page)) {
7016 free_extent_map(em);
7019 btrfs_release_path(path);
7020 trans = btrfs_join_transaction(root);
7023 return ERR_CAST(trans);
7027 write_extent_buffer(leaf, map + pg_offset, ptr,
7030 btrfs_mark_buffer_dirty(leaf);
7032 set_extent_uptodate(io_tree, em->start,
7033 extent_map_end(em) - 1, NULL, GFP_NOFS);
7038 em->orig_start = start;
7041 em->block_start = EXTENT_MAP_HOLE;
7042 set_bit(EXTENT_FLAG_VACANCY, &em->flags);
7044 btrfs_release_path(path);
7045 if (em->start > start || extent_map_end(em) <= start) {
7046 btrfs_err(root->fs_info, "bad extent! em: [%llu %llu] passed [%llu %llu]",
7047 em->start, em->len, start, len);
7053 write_lock(&em_tree->lock);
7054 ret = add_extent_mapping(em_tree, em, 0);
7055 /* it is possible that someone inserted the extent into the tree
7056 * while we had the lock dropped. It is also possible that
7057 * an overlapping map exists in the tree
7059 if (ret == -EEXIST) {
7060 struct extent_map *existing;
7064 existing = search_extent_mapping(em_tree, start, len);
7066 * existing will always be non-NULL, since there must be
7067 * extent causing the -EEXIST.
7069 if (start >= extent_map_end(existing) ||
7070 start <= existing->start) {
7072 * The existing extent map is the one nearest to
7073 * the [start, start + len) range which overlaps
7075 err = merge_extent_mapping(em_tree, existing,
7077 free_extent_map(existing);
7079 free_extent_map(em);
7083 free_extent_map(em);
7088 write_unlock(&em_tree->lock);
7091 trace_btrfs_get_extent(root, em);
7093 btrfs_free_path(path);
7095 ret = btrfs_end_transaction(trans, root);
7100 free_extent_map(em);
7101 return ERR_PTR(err);
7103 BUG_ON(!em); /* Error is always set */
7107 struct extent_map *btrfs_get_extent_fiemap(struct inode *inode, struct page *page,
7108 size_t pg_offset, u64 start, u64 len,
7111 struct extent_map *em;
7112 struct extent_map *hole_em = NULL;
7113 u64 range_start = start;
7119 em = btrfs_get_extent(inode, page, pg_offset, start, len, create);
7126 * - a pre-alloc extent,
7127 * there might actually be delalloc bytes behind it.
7129 if (em->block_start != EXTENT_MAP_HOLE &&
7130 !test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
7136 /* check to see if we've wrapped (len == -1 or similar) */
7145 /* ok, we didn't find anything, lets look for delalloc */
7146 found = count_range_bits(&BTRFS_I(inode)->io_tree, &range_start,
7147 end, len, EXTENT_DELALLOC, 1);
7148 found_end = range_start + found;
7149 if (found_end < range_start)
7150 found_end = (u64)-1;
7153 * we didn't find anything useful, return
7154 * the original results from get_extent()
7156 if (range_start > end || found_end <= start) {
7162 /* adjust the range_start to make sure it doesn't
7163 * go backwards from the start they passed in
7165 range_start = max(start, range_start);
7166 found = found_end - range_start;
7169 u64 hole_start = start;
7172 em = alloc_extent_map();
7178 * when btrfs_get_extent can't find anything it
7179 * returns one huge hole
7181 * make sure what it found really fits our range, and
7182 * adjust to make sure it is based on the start from
7186 u64 calc_end = extent_map_end(hole_em);
7188 if (calc_end <= start || (hole_em->start > end)) {
7189 free_extent_map(hole_em);
7192 hole_start = max(hole_em->start, start);
7193 hole_len = calc_end - hole_start;
7197 if (hole_em && range_start > hole_start) {
7198 /* our hole starts before our delalloc, so we
7199 * have to return just the parts of the hole
7200 * that go until the delalloc starts
7202 em->len = min(hole_len,
7203 range_start - hole_start);
7204 em->start = hole_start;
7205 em->orig_start = hole_start;
7207 * don't adjust block start at all,
7208 * it is fixed at EXTENT_MAP_HOLE
7210 em->block_start = hole_em->block_start;
7211 em->block_len = hole_len;
7212 if (test_bit(EXTENT_FLAG_PREALLOC, &hole_em->flags))
7213 set_bit(EXTENT_FLAG_PREALLOC, &em->flags);
7215 em->start = range_start;
7217 em->orig_start = range_start;
7218 em->block_start = EXTENT_MAP_DELALLOC;
7219 em->block_len = found;
7221 } else if (hole_em) {
7226 free_extent_map(hole_em);
7228 free_extent_map(em);
7229 return ERR_PTR(err);
7234 static struct extent_map *btrfs_new_extent_direct(struct inode *inode,
7237 struct btrfs_root *root = BTRFS_I(inode)->root;
7238 struct extent_map *em;
7239 struct btrfs_key ins;
7243 alloc_hint = get_extent_allocation_hint(inode, start, len);
7244 ret = btrfs_reserve_extent(root, len, root->sectorsize, 0,
7245 alloc_hint, &ins, 1, 1);
7247 return ERR_PTR(ret);
7249 em = create_pinned_em(inode, start, ins.offset, start, ins.objectid,
7250 ins.offset, ins.offset, ins.offset, 0);
7252 btrfs_free_reserved_extent(root, ins.objectid, ins.offset, 1);
7256 ret = btrfs_add_ordered_extent_dio(inode, start, ins.objectid,
7257 ins.offset, ins.offset, 0);
7259 btrfs_free_reserved_extent(root, ins.objectid, ins.offset, 1);
7260 free_extent_map(em);
7261 return ERR_PTR(ret);
7268 * returns 1 when the nocow is safe, < 1 on error, 0 if the
7269 * block must be cow'd
7271 noinline int can_nocow_extent(struct inode *inode, u64 offset, u64 *len,
7272 u64 *orig_start, u64 *orig_block_len,
7275 struct btrfs_trans_handle *trans;
7276 struct btrfs_path *path;
7278 struct extent_buffer *leaf;
7279 struct btrfs_root *root = BTRFS_I(inode)->root;
7280 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
7281 struct btrfs_file_extent_item *fi;
7282 struct btrfs_key key;
7289 bool nocow = (BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW);
7291 path = btrfs_alloc_path();
7295 ret = btrfs_lookup_file_extent(NULL, root, path, btrfs_ino(inode),
7300 slot = path->slots[0];
7303 /* can't find the item, must cow */
7310 leaf = path->nodes[0];
7311 btrfs_item_key_to_cpu(leaf, &key, slot);
7312 if (key.objectid != btrfs_ino(inode) ||
7313 key.type != BTRFS_EXTENT_DATA_KEY) {
7314 /* not our file or wrong item type, must cow */
7318 if (key.offset > offset) {
7319 /* Wrong offset, must cow */
7323 fi = btrfs_item_ptr(leaf, slot, struct btrfs_file_extent_item);
7324 found_type = btrfs_file_extent_type(leaf, fi);
7325 if (found_type != BTRFS_FILE_EXTENT_REG &&
7326 found_type != BTRFS_FILE_EXTENT_PREALLOC) {
7327 /* not a regular extent, must cow */
7331 if (!nocow && found_type == BTRFS_FILE_EXTENT_REG)
7334 extent_end = key.offset + btrfs_file_extent_num_bytes(leaf, fi);
7335 if (extent_end <= offset)
7338 disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
7339 if (disk_bytenr == 0)
7342 if (btrfs_file_extent_compression(leaf, fi) ||
7343 btrfs_file_extent_encryption(leaf, fi) ||
7344 btrfs_file_extent_other_encoding(leaf, fi))
7347 backref_offset = btrfs_file_extent_offset(leaf, fi);
7350 *orig_start = key.offset - backref_offset;
7351 *orig_block_len = btrfs_file_extent_disk_num_bytes(leaf, fi);
7352 *ram_bytes = btrfs_file_extent_ram_bytes(leaf, fi);
7355 if (btrfs_extent_readonly(root, disk_bytenr))
7358 num_bytes = min(offset + *len, extent_end) - offset;
7359 if (!nocow && found_type == BTRFS_FILE_EXTENT_PREALLOC) {
7362 range_end = round_up(offset + num_bytes, root->sectorsize) - 1;
7363 ret = test_range_bit(io_tree, offset, range_end,
7364 EXTENT_DELALLOC, 0, NULL);
7371 btrfs_release_path(path);
7374 * look for other files referencing this extent, if we
7375 * find any we must cow
7377 trans = btrfs_join_transaction(root);
7378 if (IS_ERR(trans)) {
7383 ret = btrfs_cross_ref_exist(trans, root, btrfs_ino(inode),
7384 key.offset - backref_offset, disk_bytenr);
7385 btrfs_end_transaction(trans, root);
7392 * adjust disk_bytenr and num_bytes to cover just the bytes
7393 * in this extent we are about to write. If there
7394 * are any csums in that range we have to cow in order
7395 * to keep the csums correct
7397 disk_bytenr += backref_offset;
7398 disk_bytenr += offset - key.offset;
7399 if (csum_exist_in_range(root, disk_bytenr, num_bytes))
7402 * all of the above have passed, it is safe to overwrite this extent
7408 btrfs_free_path(path);
7412 bool btrfs_page_exists_in_range(struct inode *inode, loff_t start, loff_t end)
7414 struct radix_tree_root *root = &inode->i_mapping->page_tree;
7416 void **pagep = NULL;
7417 struct page *page = NULL;
7418 unsigned long start_idx;
7419 unsigned long end_idx;
7421 start_idx = start >> PAGE_CACHE_SHIFT;
7424 * end is the last byte in the last page. end == start is legal
7426 end_idx = end >> PAGE_CACHE_SHIFT;
7430 /* Most of the code in this while loop is lifted from
7431 * find_get_page. It's been modified to begin searching from a
7432 * page and return just the first page found in that range. If the
7433 * found idx is less than or equal to the end idx then we know that
7434 * a page exists. If no pages are found or if those pages are
7435 * outside of the range then we're fine (yay!) */
7436 while (page == NULL &&
7437 radix_tree_gang_lookup_slot(root, &pagep, NULL, start_idx, 1)) {
7438 page = radix_tree_deref_slot(pagep);
7439 if (unlikely(!page))
7442 if (radix_tree_exception(page)) {
7443 if (radix_tree_deref_retry(page)) {
7448 * Otherwise, shmem/tmpfs must be storing a swap entry
7449 * here as an exceptional entry: so return it without
7450 * attempting to raise page count.
7453 break; /* TODO: Is this relevant for this use case? */
7456 if (!page_cache_get_speculative(page)) {
7462 * Has the page moved?
7463 * This is part of the lockless pagecache protocol. See
7464 * include/linux/pagemap.h for details.
7466 if (unlikely(page != *pagep)) {
7467 page_cache_release(page);
7473 if (page->index <= end_idx)
7475 page_cache_release(page);
7482 static int lock_extent_direct(struct inode *inode, u64 lockstart, u64 lockend,
7483 struct extent_state **cached_state, int writing)
7485 struct btrfs_ordered_extent *ordered;
7489 lock_extent_bits(&BTRFS_I(inode)->io_tree, lockstart, lockend,
7492 * We're concerned with the entire range that we're going to be
7493 * doing DIO to, so we need to make sure theres no ordered
7494 * extents in this range.
7496 ordered = btrfs_lookup_ordered_range(inode, lockstart,
7497 lockend - lockstart + 1);
7500 * We need to make sure there are no buffered pages in this
7501 * range either, we could have raced between the invalidate in
7502 * generic_file_direct_write and locking the extent. The
7503 * invalidate needs to happen so that reads after a write do not
7508 !btrfs_page_exists_in_range(inode, lockstart, lockend)))
7511 unlock_extent_cached(&BTRFS_I(inode)->io_tree, lockstart, lockend,
7512 cached_state, GFP_NOFS);
7515 btrfs_start_ordered_extent(inode, ordered, 1);
7516 btrfs_put_ordered_extent(ordered);
7518 /* Screw you mmap */
7519 ret = btrfs_fdatawrite_range(inode, lockstart, lockend);
7522 ret = filemap_fdatawait_range(inode->i_mapping,
7529 * If we found a page that couldn't be invalidated just
7530 * fall back to buffered.
7532 ret = invalidate_inode_pages2_range(inode->i_mapping,
7533 lockstart >> PAGE_CACHE_SHIFT,
7534 lockend >> PAGE_CACHE_SHIFT);
7545 static struct extent_map *create_pinned_em(struct inode *inode, u64 start,
7546 u64 len, u64 orig_start,
7547 u64 block_start, u64 block_len,
7548 u64 orig_block_len, u64 ram_bytes,
7551 struct extent_map_tree *em_tree;
7552 struct extent_map *em;
7553 struct btrfs_root *root = BTRFS_I(inode)->root;
7556 em_tree = &BTRFS_I(inode)->extent_tree;
7557 em = alloc_extent_map();
7559 return ERR_PTR(-ENOMEM);
7562 em->orig_start = orig_start;
7563 em->mod_start = start;
7566 em->block_len = block_len;
7567 em->block_start = block_start;
7568 em->bdev = root->fs_info->fs_devices->latest_bdev;
7569 em->orig_block_len = orig_block_len;
7570 em->ram_bytes = ram_bytes;
7571 em->generation = -1;
7572 set_bit(EXTENT_FLAG_PINNED, &em->flags);
7573 if (type == BTRFS_ORDERED_PREALLOC)
7574 set_bit(EXTENT_FLAG_FILLING, &em->flags);
7577 btrfs_drop_extent_cache(inode, em->start,
7578 em->start + em->len - 1, 0);
7579 write_lock(&em_tree->lock);
7580 ret = add_extent_mapping(em_tree, em, 1);
7581 write_unlock(&em_tree->lock);
7582 } while (ret == -EEXIST);
7585 free_extent_map(em);
7586 return ERR_PTR(ret);
7592 struct btrfs_dio_data {
7593 u64 outstanding_extents;
7597 static void adjust_dio_outstanding_extents(struct inode *inode,
7598 struct btrfs_dio_data *dio_data,
7601 unsigned num_extents;
7603 num_extents = (unsigned) div64_u64(len + BTRFS_MAX_EXTENT_SIZE - 1,
7604 BTRFS_MAX_EXTENT_SIZE);
7606 * If we have an outstanding_extents count still set then we're
7607 * within our reservation, otherwise we need to adjust our inode
7608 * counter appropriately.
7610 if (dio_data->outstanding_extents >= num_extents) {
7611 dio_data->outstanding_extents -= num_extents;
7614 * If dio write length has been split due to no large enough
7615 * contiguous space, we need to compensate our inode counter
7618 u64 num_needed = num_extents - dio_data->outstanding_extents;
7620 spin_lock(&BTRFS_I(inode)->lock);
7621 BTRFS_I(inode)->outstanding_extents += num_needed;
7622 spin_unlock(&BTRFS_I(inode)->lock);
7626 static int btrfs_get_blocks_direct(struct inode *inode, sector_t iblock,
7627 struct buffer_head *bh_result, int create)
7629 struct extent_map *em;
7630 struct btrfs_root *root = BTRFS_I(inode)->root;
7631 struct extent_state *cached_state = NULL;
7632 struct btrfs_dio_data *dio_data = NULL;
7633 u64 start = iblock << inode->i_blkbits;
7634 u64 lockstart, lockend;
7635 u64 len = bh_result->b_size;
7636 int unlock_bits = EXTENT_LOCKED;
7640 unlock_bits |= EXTENT_DIRTY;
7642 len = min_t(u64, len, root->sectorsize);
7645 lockend = start + len - 1;
7647 if (current->journal_info) {
7649 * Need to pull our outstanding extents and set journal_info to NULL so
7650 * that anything that needs to check if there's a transction doesn't get
7653 dio_data = current->journal_info;
7654 current->journal_info = NULL;
7658 * If this errors out it's because we couldn't invalidate pagecache for
7659 * this range and we need to fallback to buffered.
7661 if (lock_extent_direct(inode, lockstart, lockend, &cached_state,
7667 em = btrfs_get_extent(inode, NULL, 0, start, len, 0);
7674 * Ok for INLINE and COMPRESSED extents we need to fallback on buffered
7675 * io. INLINE is special, and we could probably kludge it in here, but
7676 * it's still buffered so for safety lets just fall back to the generic
7679 * For COMPRESSED we _have_ to read the entire extent in so we can
7680 * decompress it, so there will be buffering required no matter what we
7681 * do, so go ahead and fallback to buffered.
7683 * We return -ENOTBLK because thats what makes DIO go ahead and go back
7684 * to buffered IO. Don't blame me, this is the price we pay for using
7687 if (test_bit(EXTENT_FLAG_COMPRESSED, &em->flags) ||
7688 em->block_start == EXTENT_MAP_INLINE) {
7689 free_extent_map(em);
7694 /* Just a good old fashioned hole, return */
7695 if (!create && (em->block_start == EXTENT_MAP_HOLE ||
7696 test_bit(EXTENT_FLAG_PREALLOC, &em->flags))) {
7697 free_extent_map(em);
7702 * We don't allocate a new extent in the following cases
7704 * 1) The inode is marked as NODATACOW. In this case we'll just use the
7706 * 2) The extent is marked as PREALLOC. We're good to go here and can
7707 * just use the extent.
7711 len = min(len, em->len - (start - em->start));
7712 lockstart = start + len;
7716 if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags) ||
7717 ((BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW) &&
7718 em->block_start != EXTENT_MAP_HOLE)) {
7720 u64 block_start, orig_start, orig_block_len, ram_bytes;
7722 if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
7723 type = BTRFS_ORDERED_PREALLOC;
7725 type = BTRFS_ORDERED_NOCOW;
7726 len = min(len, em->len - (start - em->start));
7727 block_start = em->block_start + (start - em->start);
7729 if (can_nocow_extent(inode, start, &len, &orig_start,
7730 &orig_block_len, &ram_bytes) == 1) {
7731 if (type == BTRFS_ORDERED_PREALLOC) {
7732 free_extent_map(em);
7733 em = create_pinned_em(inode, start, len,
7744 ret = btrfs_add_ordered_extent_dio(inode, start,
7745 block_start, len, len, type);
7747 free_extent_map(em);
7755 * this will cow the extent, reset the len in case we changed
7758 len = bh_result->b_size;
7759 free_extent_map(em);
7760 em = btrfs_new_extent_direct(inode, start, len);
7765 len = min(len, em->len - (start - em->start));
7767 bh_result->b_blocknr = (em->block_start + (start - em->start)) >>
7769 bh_result->b_size = len;
7770 bh_result->b_bdev = em->bdev;
7771 set_buffer_mapped(bh_result);
7773 if (!test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
7774 set_buffer_new(bh_result);
7777 * Need to update the i_size under the extent lock so buffered
7778 * readers will get the updated i_size when we unlock.
7780 if (start + len > i_size_read(inode))
7781 i_size_write(inode, start + len);
7783 adjust_dio_outstanding_extents(inode, dio_data, len);
7784 btrfs_free_reserved_data_space(inode, start, len);
7785 WARN_ON(dio_data->reserve < len);
7786 dio_data->reserve -= len;
7787 current->journal_info = dio_data;
7791 * In the case of write we need to clear and unlock the entire range,
7792 * in the case of read we need to unlock only the end area that we
7793 * aren't using if there is any left over space.
7795 if (lockstart < lockend) {
7796 clear_extent_bit(&BTRFS_I(inode)->io_tree, lockstart,
7797 lockend, unlock_bits, 1, 0,
7798 &cached_state, GFP_NOFS);
7800 free_extent_state(cached_state);
7803 free_extent_map(em);
7808 clear_extent_bit(&BTRFS_I(inode)->io_tree, lockstart, lockend,
7809 unlock_bits, 1, 0, &cached_state, GFP_NOFS);
7812 current->journal_info = dio_data;
7814 * Compensate the delalloc release we do in btrfs_direct_IO() when we
7815 * write less data then expected, so that we don't underflow our inode's
7816 * outstanding extents counter.
7818 if (create && dio_data)
7819 adjust_dio_outstanding_extents(inode, dio_data, len);
7824 static inline int submit_dio_repair_bio(struct inode *inode, struct bio *bio,
7825 int rw, int mirror_num)
7827 struct btrfs_root *root = BTRFS_I(inode)->root;
7830 BUG_ON(rw & REQ_WRITE);
7834 ret = btrfs_bio_wq_end_io(root->fs_info, bio,
7835 BTRFS_WQ_ENDIO_DIO_REPAIR);
7839 ret = btrfs_map_bio(root, rw, bio, mirror_num, 0);
7845 static int btrfs_check_dio_repairable(struct inode *inode,
7846 struct bio *failed_bio,
7847 struct io_failure_record *failrec,
7852 num_copies = btrfs_num_copies(BTRFS_I(inode)->root->fs_info,
7853 failrec->logical, failrec->len);
7854 if (num_copies == 1) {
7856 * we only have a single copy of the data, so don't bother with
7857 * all the retry and error correction code that follows. no
7858 * matter what the error is, it is very likely to persist.
7860 pr_debug("Check DIO Repairable: cannot repair, num_copies=%d, next_mirror %d, failed_mirror %d\n",
7861 num_copies, failrec->this_mirror, failed_mirror);
7865 failrec->failed_mirror = failed_mirror;
7866 failrec->this_mirror++;
7867 if (failrec->this_mirror == failed_mirror)
7868 failrec->this_mirror++;
7870 if (failrec->this_mirror > num_copies) {
7871 pr_debug("Check DIO Repairable: (fail) num_copies=%d, next_mirror %d, failed_mirror %d\n",
7872 num_copies, failrec->this_mirror, failed_mirror);
7879 static int dio_read_error(struct inode *inode, struct bio *failed_bio,
7880 struct page *page, u64 start, u64 end,
7881 int failed_mirror, bio_end_io_t *repair_endio,
7884 struct io_failure_record *failrec;
7890 BUG_ON(failed_bio->bi_rw & REQ_WRITE);
7892 ret = btrfs_get_io_failure_record(inode, start, end, &failrec);
7896 ret = btrfs_check_dio_repairable(inode, failed_bio, failrec,
7899 free_io_failure(inode, failrec);
7903 if (failed_bio->bi_vcnt > 1)
7904 read_mode = READ_SYNC | REQ_FAILFAST_DEV;
7906 read_mode = READ_SYNC;
7908 isector = start - btrfs_io_bio(failed_bio)->logical;
7909 isector >>= inode->i_sb->s_blocksize_bits;
7910 bio = btrfs_create_repair_bio(inode, failed_bio, failrec, page,
7911 0, isector, repair_endio, repair_arg);
7913 free_io_failure(inode, failrec);
7917 btrfs_debug(BTRFS_I(inode)->root->fs_info,
7918 "Repair DIO Read Error: submitting new dio read[%#x] to this_mirror=%d, in_validation=%d\n",
7919 read_mode, failrec->this_mirror, failrec->in_validation);
7921 ret = submit_dio_repair_bio(inode, bio, read_mode,
7922 failrec->this_mirror);
7924 free_io_failure(inode, failrec);
7931 struct btrfs_retry_complete {
7932 struct completion done;
7933 struct inode *inode;
7938 static void btrfs_retry_endio_nocsum(struct bio *bio)
7940 struct btrfs_retry_complete *done = bio->bi_private;
7941 struct bio_vec *bvec;
7948 bio_for_each_segment_all(bvec, bio, i)
7949 clean_io_failure(done->inode, done->start, bvec->bv_page, 0);
7951 complete(&done->done);
7955 static int __btrfs_correct_data_nocsum(struct inode *inode,
7956 struct btrfs_io_bio *io_bio)
7958 struct bio_vec *bvec;
7959 struct btrfs_retry_complete done;
7964 start = io_bio->logical;
7967 bio_for_each_segment_all(bvec, &io_bio->bio, i) {
7971 init_completion(&done.done);
7973 ret = dio_read_error(inode, &io_bio->bio, bvec->bv_page, start,
7974 start + bvec->bv_len - 1,
7976 btrfs_retry_endio_nocsum, &done);
7980 wait_for_completion(&done.done);
7982 if (!done.uptodate) {
7983 /* We might have another mirror, so try again */
7987 start += bvec->bv_len;
7993 static void btrfs_retry_endio(struct bio *bio)
7995 struct btrfs_retry_complete *done = bio->bi_private;
7996 struct btrfs_io_bio *io_bio = btrfs_io_bio(bio);
7997 struct bio_vec *bvec;
8006 bio_for_each_segment_all(bvec, bio, i) {
8007 ret = __readpage_endio_check(done->inode, io_bio, i,
8009 done->start, bvec->bv_len);
8011 clean_io_failure(done->inode, done->start,
8017 done->uptodate = uptodate;
8019 complete(&done->done);
8023 static int __btrfs_subio_endio_read(struct inode *inode,
8024 struct btrfs_io_bio *io_bio, int err)
8026 struct bio_vec *bvec;
8027 struct btrfs_retry_complete done;
8034 start = io_bio->logical;
8037 bio_for_each_segment_all(bvec, &io_bio->bio, i) {
8038 ret = __readpage_endio_check(inode, io_bio, i, bvec->bv_page,
8039 0, start, bvec->bv_len);
8045 init_completion(&done.done);
8047 ret = dio_read_error(inode, &io_bio->bio, bvec->bv_page, start,
8048 start + bvec->bv_len - 1,
8050 btrfs_retry_endio, &done);
8056 wait_for_completion(&done.done);
8058 if (!done.uptodate) {
8059 /* We might have another mirror, so try again */
8063 offset += bvec->bv_len;
8064 start += bvec->bv_len;
8070 static int btrfs_subio_endio_read(struct inode *inode,
8071 struct btrfs_io_bio *io_bio, int err)
8073 bool skip_csum = BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM;
8077 return __btrfs_correct_data_nocsum(inode, io_bio);
8081 return __btrfs_subio_endio_read(inode, io_bio, err);
8085 static void btrfs_endio_direct_read(struct bio *bio)
8087 struct btrfs_dio_private *dip = bio->bi_private;
8088 struct inode *inode = dip->inode;
8089 struct bio *dio_bio;
8090 struct btrfs_io_bio *io_bio = btrfs_io_bio(bio);
8091 int err = bio->bi_error;
8093 if (dip->flags & BTRFS_DIO_ORIG_BIO_SUBMITTED)
8094 err = btrfs_subio_endio_read(inode, io_bio, err);
8096 unlock_extent(&BTRFS_I(inode)->io_tree, dip->logical_offset,
8097 dip->logical_offset + dip->bytes - 1);
8098 dio_bio = dip->dio_bio;
8102 dio_bio->bi_error = bio->bi_error;
8103 dio_end_io(dio_bio, bio->bi_error);
8106 io_bio->end_io(io_bio, err);
8110 static void btrfs_endio_direct_write(struct bio *bio)
8112 struct btrfs_dio_private *dip = bio->bi_private;
8113 struct inode *inode = dip->inode;
8114 struct btrfs_root *root = BTRFS_I(inode)->root;
8115 struct btrfs_ordered_extent *ordered = NULL;
8116 u64 ordered_offset = dip->logical_offset;
8117 u64 ordered_bytes = dip->bytes;
8118 struct bio *dio_bio;
8122 ret = btrfs_dec_test_first_ordered_pending(inode, &ordered,
8129 btrfs_init_work(&ordered->work, btrfs_endio_write_helper,
8130 finish_ordered_fn, NULL, NULL);
8131 btrfs_queue_work(root->fs_info->endio_write_workers,
8135 * our bio might span multiple ordered extents. If we haven't
8136 * completed the accounting for the whole dio, go back and try again
8138 if (ordered_offset < dip->logical_offset + dip->bytes) {
8139 ordered_bytes = dip->logical_offset + dip->bytes -
8144 dio_bio = dip->dio_bio;
8148 dio_bio->bi_error = bio->bi_error;
8149 dio_end_io(dio_bio, bio->bi_error);
8153 static int __btrfs_submit_bio_start_direct_io(struct inode *inode, int rw,
8154 struct bio *bio, int mirror_num,
8155 unsigned long bio_flags, u64 offset)
8158 struct btrfs_root *root = BTRFS_I(inode)->root;
8159 ret = btrfs_csum_one_bio(root, inode, bio, offset, 1);
8160 BUG_ON(ret); /* -ENOMEM */
8164 static void btrfs_end_dio_bio(struct bio *bio)
8166 struct btrfs_dio_private *dip = bio->bi_private;
8167 int err = bio->bi_error;
8170 btrfs_warn(BTRFS_I(dip->inode)->root->fs_info,
8171 "direct IO failed ino %llu rw %lu sector %#Lx len %u err no %d",
8172 btrfs_ino(dip->inode), bio->bi_rw,
8173 (unsigned long long)bio->bi_iter.bi_sector,
8174 bio->bi_iter.bi_size, err);
8176 if (dip->subio_endio)
8177 err = dip->subio_endio(dip->inode, btrfs_io_bio(bio), err);
8183 * before atomic variable goto zero, we must make sure
8184 * dip->errors is perceived to be set.
8186 smp_mb__before_atomic();
8189 /* if there are more bios still pending for this dio, just exit */
8190 if (!atomic_dec_and_test(&dip->pending_bios))
8194 bio_io_error(dip->orig_bio);
8196 dip->dio_bio->bi_error = 0;
8197 bio_endio(dip->orig_bio);
8203 static struct bio *btrfs_dio_bio_alloc(struct block_device *bdev,
8204 u64 first_sector, gfp_t gfp_flags)
8207 bio = btrfs_bio_alloc(bdev, first_sector, BIO_MAX_PAGES, gfp_flags);
8209 bio_associate_current(bio);
8213 static inline int btrfs_lookup_and_bind_dio_csum(struct btrfs_root *root,
8214 struct inode *inode,
8215 struct btrfs_dio_private *dip,
8219 struct btrfs_io_bio *io_bio = btrfs_io_bio(bio);
8220 struct btrfs_io_bio *orig_io_bio = btrfs_io_bio(dip->orig_bio);
8224 * We load all the csum data we need when we submit
8225 * the first bio to reduce the csum tree search and
8228 if (dip->logical_offset == file_offset) {
8229 ret = btrfs_lookup_bio_sums_dio(root, inode, dip->orig_bio,
8235 if (bio == dip->orig_bio)
8238 file_offset -= dip->logical_offset;
8239 file_offset >>= inode->i_sb->s_blocksize_bits;
8240 io_bio->csum = (u8 *)(((u32 *)orig_io_bio->csum) + file_offset);
8245 static inline int __btrfs_submit_dio_bio(struct bio *bio, struct inode *inode,
8246 int rw, u64 file_offset, int skip_sum,
8249 struct btrfs_dio_private *dip = bio->bi_private;
8250 int write = rw & REQ_WRITE;
8251 struct btrfs_root *root = BTRFS_I(inode)->root;
8255 async_submit = !atomic_read(&BTRFS_I(inode)->sync_writers);
8260 ret = btrfs_bio_wq_end_io(root->fs_info, bio,
8261 BTRFS_WQ_ENDIO_DATA);
8269 if (write && async_submit) {
8270 ret = btrfs_wq_submit_bio(root->fs_info,
8271 inode, rw, bio, 0, 0,
8273 __btrfs_submit_bio_start_direct_io,
8274 __btrfs_submit_bio_done);
8278 * If we aren't doing async submit, calculate the csum of the
8281 ret = btrfs_csum_one_bio(root, inode, bio, file_offset, 1);
8285 ret = btrfs_lookup_and_bind_dio_csum(root, inode, dip, bio,
8291 ret = btrfs_map_bio(root, rw, bio, 0, async_submit);
8297 static int btrfs_submit_direct_hook(int rw, struct btrfs_dio_private *dip,
8300 struct inode *inode = dip->inode;
8301 struct btrfs_root *root = BTRFS_I(inode)->root;
8303 struct bio *orig_bio = dip->orig_bio;
8304 struct bio_vec *bvec = orig_bio->bi_io_vec;
8305 u64 start_sector = orig_bio->bi_iter.bi_sector;
8306 u64 file_offset = dip->logical_offset;
8311 int async_submit = 0;
8313 map_length = orig_bio->bi_iter.bi_size;
8314 ret = btrfs_map_block(root->fs_info, rw, start_sector << 9,
8315 &map_length, NULL, 0);
8319 if (map_length >= orig_bio->bi_iter.bi_size) {
8321 dip->flags |= BTRFS_DIO_ORIG_BIO_SUBMITTED;
8325 /* async crcs make it difficult to collect full stripe writes. */
8326 if (btrfs_get_alloc_profile(root, 1) & BTRFS_BLOCK_GROUP_RAID56_MASK)
8331 bio = btrfs_dio_bio_alloc(orig_bio->bi_bdev, start_sector, GFP_NOFS);
8335 bio->bi_private = dip;
8336 bio->bi_end_io = btrfs_end_dio_bio;
8337 btrfs_io_bio(bio)->logical = file_offset;
8339 while (bvec <= (orig_bio->bi_io_vec + orig_bio->bi_vcnt - 1)) {
8340 if (map_length < submit_len + bvec->bv_len ||
8341 bio_add_page(bio, bvec->bv_page, bvec->bv_len,
8342 bvec->bv_offset) < bvec->bv_len) {
8344 * inc the count before we submit the bio so
8345 * we know the end IO handler won't happen before
8346 * we inc the count. Otherwise, the dip might get freed
8347 * before we're done setting it up
8349 atomic_inc(&dip->pending_bios);
8350 ret = __btrfs_submit_dio_bio(bio, inode, rw,
8351 file_offset, skip_sum,
8355 atomic_dec(&dip->pending_bios);
8359 start_sector += submit_len >> 9;
8360 file_offset += submit_len;
8365 bio = btrfs_dio_bio_alloc(orig_bio->bi_bdev,
8366 start_sector, GFP_NOFS);
8369 bio->bi_private = dip;
8370 bio->bi_end_io = btrfs_end_dio_bio;
8371 btrfs_io_bio(bio)->logical = file_offset;
8373 map_length = orig_bio->bi_iter.bi_size;
8374 ret = btrfs_map_block(root->fs_info, rw,
8376 &map_length, NULL, 0);
8382 submit_len += bvec->bv_len;
8389 ret = __btrfs_submit_dio_bio(bio, inode, rw, file_offset, skip_sum,
8394 if (bio != orig_bio)
8399 * before atomic variable goto zero, we must
8400 * make sure dip->errors is perceived to be set.
8402 smp_mb__before_atomic();
8403 if (atomic_dec_and_test(&dip->pending_bios))
8404 bio_io_error(dip->orig_bio);
8406 /* bio_end_io() will handle error, so we needn't return it */
8410 static void btrfs_submit_direct(int rw, struct bio *dio_bio,
8411 struct inode *inode, loff_t file_offset)
8413 struct btrfs_dio_private *dip = NULL;
8414 struct bio *io_bio = NULL;
8415 struct btrfs_io_bio *btrfs_bio;
8417 int write = rw & REQ_WRITE;
8420 skip_sum = BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM;
8422 io_bio = btrfs_bio_clone(dio_bio, GFP_NOFS);
8428 dip = kzalloc(sizeof(*dip), GFP_NOFS);
8434 dip->private = dio_bio->bi_private;
8436 dip->logical_offset = file_offset;
8437 dip->bytes = dio_bio->bi_iter.bi_size;
8438 dip->disk_bytenr = (u64)dio_bio->bi_iter.bi_sector << 9;
8439 io_bio->bi_private = dip;
8440 dip->orig_bio = io_bio;
8441 dip->dio_bio = dio_bio;
8442 atomic_set(&dip->pending_bios, 1);
8443 btrfs_bio = btrfs_io_bio(io_bio);
8444 btrfs_bio->logical = file_offset;
8447 io_bio->bi_end_io = btrfs_endio_direct_write;
8449 io_bio->bi_end_io = btrfs_endio_direct_read;
8450 dip->subio_endio = btrfs_subio_endio_read;
8453 ret = btrfs_submit_direct_hook(rw, dip, skip_sum);
8457 if (btrfs_bio->end_io)
8458 btrfs_bio->end_io(btrfs_bio, ret);
8462 * If we arrived here it means either we failed to submit the dip
8463 * or we either failed to clone the dio_bio or failed to allocate the
8464 * dip. If we cloned the dio_bio and allocated the dip, we can just
8465 * call bio_endio against our io_bio so that we get proper resource
8466 * cleanup if we fail to submit the dip, otherwise, we must do the
8467 * same as btrfs_endio_direct_[write|read] because we can't call these
8468 * callbacks - they require an allocated dip and a clone of dio_bio.
8470 if (io_bio && dip) {
8471 io_bio->bi_error = -EIO;
8474 * The end io callbacks free our dip, do the final put on io_bio
8475 * and all the cleanup and final put for dio_bio (through
8482 struct btrfs_ordered_extent *ordered;
8484 ordered = btrfs_lookup_ordered_extent(inode,
8486 set_bit(BTRFS_ORDERED_IOERR, &ordered->flags);
8488 * Decrements our ref on the ordered extent and removes
8489 * the ordered extent from the inode's ordered tree,
8490 * doing all the proper resource cleanup such as for the
8491 * reserved space and waking up any waiters for this
8492 * ordered extent (through btrfs_remove_ordered_extent).
8494 btrfs_finish_ordered_io(ordered);
8496 unlock_extent(&BTRFS_I(inode)->io_tree, file_offset,
8497 file_offset + dio_bio->bi_iter.bi_size - 1);
8499 dio_bio->bi_error = -EIO;
8501 * Releases and cleans up our dio_bio, no need to bio_put()
8502 * nor bio_endio()/bio_io_error() against dio_bio.
8504 dio_end_io(dio_bio, ret);
8511 static ssize_t check_direct_IO(struct btrfs_root *root, struct kiocb *iocb,
8512 const struct iov_iter *iter, loff_t offset)
8516 unsigned blocksize_mask = root->sectorsize - 1;
8517 ssize_t retval = -EINVAL;
8519 if (offset & blocksize_mask)
8522 if (iov_iter_alignment(iter) & blocksize_mask)
8525 /* If this is a write we don't need to check anymore */
8526 if (iov_iter_rw(iter) == WRITE)
8529 * Check to make sure we don't have duplicate iov_base's in this
8530 * iovec, if so return EINVAL, otherwise we'll get csum errors
8531 * when reading back.
8533 for (seg = 0; seg < iter->nr_segs; seg++) {
8534 for (i = seg + 1; i < iter->nr_segs; i++) {
8535 if (iter->iov[seg].iov_base == iter->iov[i].iov_base)
8544 static ssize_t btrfs_direct_IO(struct kiocb *iocb, struct iov_iter *iter,
8547 struct file *file = iocb->ki_filp;
8548 struct inode *inode = file->f_mapping->host;
8549 struct btrfs_root *root = BTRFS_I(inode)->root;
8550 struct btrfs_dio_data dio_data = { 0 };
8554 bool relock = false;
8557 if (check_direct_IO(BTRFS_I(inode)->root, iocb, iter, offset))
8560 inode_dio_begin(inode);
8561 smp_mb__after_atomic();
8564 * The generic stuff only does filemap_write_and_wait_range, which
8565 * isn't enough if we've written compressed pages to this area, so
8566 * we need to flush the dirty pages again to make absolutely sure
8567 * that any outstanding dirty pages are on disk.
8569 count = iov_iter_count(iter);
8570 if (test_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
8571 &BTRFS_I(inode)->runtime_flags))
8572 filemap_fdatawrite_range(inode->i_mapping, offset,
8573 offset + count - 1);
8575 if (iov_iter_rw(iter) == WRITE) {
8577 * If the write DIO is beyond the EOF, we need update
8578 * the isize, but it is protected by i_mutex. So we can
8579 * not unlock the i_mutex at this case.
8581 if (offset + count <= inode->i_size) {
8582 mutex_unlock(&inode->i_mutex);
8585 ret = btrfs_delalloc_reserve_space(inode, offset, count);
8588 dio_data.outstanding_extents = div64_u64(count +
8589 BTRFS_MAX_EXTENT_SIZE - 1,
8590 BTRFS_MAX_EXTENT_SIZE);
8593 * We need to know how many extents we reserved so that we can
8594 * do the accounting properly if we go over the number we
8595 * originally calculated. Abuse current->journal_info for this.
8597 dio_data.reserve = round_up(count, root->sectorsize);
8598 current->journal_info = &dio_data;
8599 } else if (test_bit(BTRFS_INODE_READDIO_NEED_LOCK,
8600 &BTRFS_I(inode)->runtime_flags)) {
8601 inode_dio_end(inode);
8602 flags = DIO_LOCKING | DIO_SKIP_HOLES;
8606 ret = __blockdev_direct_IO(iocb, inode,
8607 BTRFS_I(inode)->root->fs_info->fs_devices->latest_bdev,
8608 iter, offset, btrfs_get_blocks_direct, NULL,
8609 btrfs_submit_direct, flags);
8610 if (iov_iter_rw(iter) == WRITE) {
8611 current->journal_info = NULL;
8612 if (ret < 0 && ret != -EIOCBQUEUED) {
8613 if (dio_data.reserve)
8614 btrfs_delalloc_release_space(inode, offset,
8616 } else if (ret >= 0 && (size_t)ret < count)
8617 btrfs_delalloc_release_space(inode, offset,
8618 count - (size_t)ret);
8622 inode_dio_end(inode);
8624 mutex_lock(&inode->i_mutex);
8629 #define BTRFS_FIEMAP_FLAGS (FIEMAP_FLAG_SYNC)
8631 static int btrfs_fiemap(struct inode *inode, struct fiemap_extent_info *fieinfo,
8632 __u64 start, __u64 len)
8636 ret = fiemap_check_flags(fieinfo, BTRFS_FIEMAP_FLAGS);
8640 return extent_fiemap(inode, fieinfo, start, len, btrfs_get_extent_fiemap);
8643 int btrfs_readpage(struct file *file, struct page *page)
8645 struct extent_io_tree *tree;
8646 tree = &BTRFS_I(page->mapping->host)->io_tree;
8647 return extent_read_full_page(tree, page, btrfs_get_extent, 0);
8650 static int btrfs_writepage(struct page *page, struct writeback_control *wbc)
8652 struct extent_io_tree *tree;
8653 struct inode *inode = page->mapping->host;
8656 if (current->flags & PF_MEMALLOC) {
8657 redirty_page_for_writepage(wbc, page);
8663 * If we are under memory pressure we will call this directly from the
8664 * VM, we need to make sure we have the inode referenced for the ordered
8665 * extent. If not just return like we didn't do anything.
8667 if (!igrab(inode)) {
8668 redirty_page_for_writepage(wbc, page);
8669 return AOP_WRITEPAGE_ACTIVATE;
8671 tree = &BTRFS_I(page->mapping->host)->io_tree;
8672 ret = extent_write_full_page(tree, page, btrfs_get_extent, wbc);
8673 btrfs_add_delayed_iput(inode);
8677 static int btrfs_writepages(struct address_space *mapping,
8678 struct writeback_control *wbc)
8680 struct extent_io_tree *tree;
8682 tree = &BTRFS_I(mapping->host)->io_tree;
8683 return extent_writepages(tree, mapping, btrfs_get_extent, wbc);
8687 btrfs_readpages(struct file *file, struct address_space *mapping,
8688 struct list_head *pages, unsigned nr_pages)
8690 struct extent_io_tree *tree;
8691 tree = &BTRFS_I(mapping->host)->io_tree;
8692 return extent_readpages(tree, mapping, pages, nr_pages,
8695 static int __btrfs_releasepage(struct page *page, gfp_t gfp_flags)
8697 struct extent_io_tree *tree;
8698 struct extent_map_tree *map;
8701 tree = &BTRFS_I(page->mapping->host)->io_tree;
8702 map = &BTRFS_I(page->mapping->host)->extent_tree;
8703 ret = try_release_extent_mapping(map, tree, page, gfp_flags);
8705 ClearPagePrivate(page);
8706 set_page_private(page, 0);
8707 page_cache_release(page);
8712 static int btrfs_releasepage(struct page *page, gfp_t gfp_flags)
8714 if (PageWriteback(page) || PageDirty(page))
8716 return __btrfs_releasepage(page, gfp_flags & GFP_NOFS);
8719 static void btrfs_invalidatepage(struct page *page, unsigned int offset,
8720 unsigned int length)
8722 struct inode *inode = page->mapping->host;
8723 struct extent_io_tree *tree;
8724 struct btrfs_ordered_extent *ordered;
8725 struct extent_state *cached_state = NULL;
8726 u64 page_start = page_offset(page);
8727 u64 page_end = page_start + PAGE_CACHE_SIZE - 1;
8728 int inode_evicting = inode->i_state & I_FREEING;
8731 * we have the page locked, so new writeback can't start,
8732 * and the dirty bit won't be cleared while we are here.
8734 * Wait for IO on this page so that we can safely clear
8735 * the PagePrivate2 bit and do ordered accounting
8737 wait_on_page_writeback(page);
8739 tree = &BTRFS_I(inode)->io_tree;
8741 btrfs_releasepage(page, GFP_NOFS);
8745 if (!inode_evicting)
8746 lock_extent_bits(tree, page_start, page_end, 0, &cached_state);
8747 ordered = btrfs_lookup_ordered_extent(inode, page_start);
8750 * IO on this page will never be started, so we need
8751 * to account for any ordered extents now
8753 if (!inode_evicting)
8754 clear_extent_bit(tree, page_start, page_end,
8755 EXTENT_DIRTY | EXTENT_DELALLOC |
8756 EXTENT_LOCKED | EXTENT_DO_ACCOUNTING |
8757 EXTENT_DEFRAG, 1, 0, &cached_state,
8760 * whoever cleared the private bit is responsible
8761 * for the finish_ordered_io
8763 if (TestClearPagePrivate2(page)) {
8764 struct btrfs_ordered_inode_tree *tree;
8767 tree = &BTRFS_I(inode)->ordered_tree;
8769 spin_lock_irq(&tree->lock);
8770 set_bit(BTRFS_ORDERED_TRUNCATED, &ordered->flags);
8771 new_len = page_start - ordered->file_offset;
8772 if (new_len < ordered->truncated_len)
8773 ordered->truncated_len = new_len;
8774 spin_unlock_irq(&tree->lock);
8776 if (btrfs_dec_test_ordered_pending(inode, &ordered,
8778 PAGE_CACHE_SIZE, 1))
8779 btrfs_finish_ordered_io(ordered);
8781 btrfs_put_ordered_extent(ordered);
8782 if (!inode_evicting) {
8783 cached_state = NULL;
8784 lock_extent_bits(tree, page_start, page_end, 0,
8790 * Qgroup reserved space handler
8791 * Page here will be either
8792 * 1) Already written to disk
8793 * In this case, its reserved space is released from data rsv map
8794 * and will be freed by delayed_ref handler finally.
8795 * So even we call qgroup_free_data(), it won't decrease reserved
8797 * 2) Not written to disk
8798 * This means the reserved space should be freed here. However,
8799 * if a truncate invalidates the page (by clearing PageDirty)
8800 * and the page is accounted for while allocating extent
8801 * in btrfs_check_data_free_space() we let delayed_ref to
8802 * free the entire extent.
8804 if (PageDirty(page))
8805 btrfs_qgroup_free_data(inode, page_start, PAGE_SIZE);
8806 if (!inode_evicting) {
8807 clear_extent_bit(tree, page_start, page_end,
8808 EXTENT_LOCKED | EXTENT_DIRTY |
8809 EXTENT_DELALLOC | EXTENT_DO_ACCOUNTING |
8810 EXTENT_DEFRAG, 1, 1,
8811 &cached_state, GFP_NOFS);
8813 __btrfs_releasepage(page, GFP_NOFS);
8816 ClearPageChecked(page);
8817 if (PagePrivate(page)) {
8818 ClearPagePrivate(page);
8819 set_page_private(page, 0);
8820 page_cache_release(page);
8825 * btrfs_page_mkwrite() is not allowed to change the file size as it gets
8826 * called from a page fault handler when a page is first dirtied. Hence we must
8827 * be careful to check for EOF conditions here. We set the page up correctly
8828 * for a written page which means we get ENOSPC checking when writing into
8829 * holes and correct delalloc and unwritten extent mapping on filesystems that
8830 * support these features.
8832 * We are not allowed to take the i_mutex here so we have to play games to
8833 * protect against truncate races as the page could now be beyond EOF. Because
8834 * vmtruncate() writes the inode size before removing pages, once we have the
8835 * page lock we can determine safely if the page is beyond EOF. If it is not
8836 * beyond EOF, then the page is guaranteed safe against truncation until we
8839 int btrfs_page_mkwrite(struct vm_area_struct *vma, struct vm_fault *vmf)
8841 struct page *page = vmf->page;
8842 struct inode *inode = file_inode(vma->vm_file);
8843 struct btrfs_root *root = BTRFS_I(inode)->root;
8844 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
8845 struct btrfs_ordered_extent *ordered;
8846 struct extent_state *cached_state = NULL;
8848 unsigned long zero_start;
8855 sb_start_pagefault(inode->i_sb);
8856 page_start = page_offset(page);
8857 page_end = page_start + PAGE_CACHE_SIZE - 1;
8859 ret = btrfs_delalloc_reserve_space(inode, page_start,
8862 ret = file_update_time(vma->vm_file);
8868 else /* -ENOSPC, -EIO, etc */
8869 ret = VM_FAULT_SIGBUS;
8875 ret = VM_FAULT_NOPAGE; /* make the VM retry the fault */
8878 size = i_size_read(inode);
8880 if ((page->mapping != inode->i_mapping) ||
8881 (page_start >= size)) {
8882 /* page got truncated out from underneath us */
8885 wait_on_page_writeback(page);
8887 lock_extent_bits(io_tree, page_start, page_end, 0, &cached_state);
8888 set_page_extent_mapped(page);
8891 * we can't set the delalloc bits if there are pending ordered
8892 * extents. Drop our locks and wait for them to finish
8894 ordered = btrfs_lookup_ordered_extent(inode, page_start);
8896 unlock_extent_cached(io_tree, page_start, page_end,
8897 &cached_state, GFP_NOFS);
8899 btrfs_start_ordered_extent(inode, ordered, 1);
8900 btrfs_put_ordered_extent(ordered);
8905 * XXX - page_mkwrite gets called every time the page is dirtied, even
8906 * if it was already dirty, so for space accounting reasons we need to
8907 * clear any delalloc bits for the range we are fixing to save. There
8908 * is probably a better way to do this, but for now keep consistent with
8909 * prepare_pages in the normal write path.
8911 clear_extent_bit(&BTRFS_I(inode)->io_tree, page_start, page_end,
8912 EXTENT_DIRTY | EXTENT_DELALLOC |
8913 EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG,
8914 0, 0, &cached_state, GFP_NOFS);
8916 ret = btrfs_set_extent_delalloc(inode, page_start, page_end,
8919 unlock_extent_cached(io_tree, page_start, page_end,
8920 &cached_state, GFP_NOFS);
8921 ret = VM_FAULT_SIGBUS;
8926 /* page is wholly or partially inside EOF */
8927 if (page_start + PAGE_CACHE_SIZE > size)
8928 zero_start = size & ~PAGE_CACHE_MASK;
8930 zero_start = PAGE_CACHE_SIZE;
8932 if (zero_start != PAGE_CACHE_SIZE) {
8934 memset(kaddr + zero_start, 0, PAGE_CACHE_SIZE - zero_start);
8935 flush_dcache_page(page);
8938 ClearPageChecked(page);
8939 set_page_dirty(page);
8940 SetPageUptodate(page);
8942 BTRFS_I(inode)->last_trans = root->fs_info->generation;
8943 BTRFS_I(inode)->last_sub_trans = BTRFS_I(inode)->root->log_transid;
8944 BTRFS_I(inode)->last_log_commit = BTRFS_I(inode)->root->last_log_commit;
8946 unlock_extent_cached(io_tree, page_start, page_end, &cached_state, GFP_NOFS);
8950 sb_end_pagefault(inode->i_sb);
8951 return VM_FAULT_LOCKED;
8955 btrfs_delalloc_release_space(inode, page_start, PAGE_CACHE_SIZE);
8957 sb_end_pagefault(inode->i_sb);
8961 static int btrfs_truncate(struct inode *inode)
8963 struct btrfs_root *root = BTRFS_I(inode)->root;
8964 struct btrfs_block_rsv *rsv;
8967 struct btrfs_trans_handle *trans;
8968 u64 mask = root->sectorsize - 1;
8969 u64 min_size = btrfs_calc_trunc_metadata_size(root, 1);
8971 ret = btrfs_wait_ordered_range(inode, inode->i_size & (~mask),
8977 * Yes ladies and gentelment, this is indeed ugly. The fact is we have
8978 * 3 things going on here
8980 * 1) We need to reserve space for our orphan item and the space to
8981 * delete our orphan item. Lord knows we don't want to have a dangling
8982 * orphan item because we didn't reserve space to remove it.
8984 * 2) We need to reserve space to update our inode.
8986 * 3) We need to have something to cache all the space that is going to
8987 * be free'd up by the truncate operation, but also have some slack
8988 * space reserved in case it uses space during the truncate (thank you
8989 * very much snapshotting).
8991 * And we need these to all be seperate. The fact is we can use alot of
8992 * space doing the truncate, and we have no earthly idea how much space
8993 * we will use, so we need the truncate reservation to be seperate so it
8994 * doesn't end up using space reserved for updating the inode or
8995 * removing the orphan item. We also need to be able to stop the
8996 * transaction and start a new one, which means we need to be able to
8997 * update the inode several times, and we have no idea of knowing how
8998 * many times that will be, so we can't just reserve 1 item for the
8999 * entirety of the opration, so that has to be done seperately as well.
9000 * Then there is the orphan item, which does indeed need to be held on
9001 * to for the whole operation, and we need nobody to touch this reserved
9002 * space except the orphan code.
9004 * So that leaves us with
9006 * 1) root->orphan_block_rsv - for the orphan deletion.
9007 * 2) rsv - for the truncate reservation, which we will steal from the
9008 * transaction reservation.
9009 * 3) fs_info->trans_block_rsv - this will have 1 items worth left for
9010 * updating the inode.
9012 rsv = btrfs_alloc_block_rsv(root, BTRFS_BLOCK_RSV_TEMP);
9015 rsv->size = min_size;
9019 * 1 for the truncate slack space
9020 * 1 for updating the inode.
9022 trans = btrfs_start_transaction(root, 2);
9023 if (IS_ERR(trans)) {
9024 err = PTR_ERR(trans);
9028 /* Migrate the slack space for the truncate to our reserve */
9029 ret = btrfs_block_rsv_migrate(&root->fs_info->trans_block_rsv, rsv,
9034 * So if we truncate and then write and fsync we normally would just
9035 * write the extents that changed, which is a problem if we need to
9036 * first truncate that entire inode. So set this flag so we write out
9037 * all of the extents in the inode to the sync log so we're completely
9040 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &BTRFS_I(inode)->runtime_flags);
9041 trans->block_rsv = rsv;
9044 ret = btrfs_truncate_inode_items(trans, root, inode,
9046 BTRFS_EXTENT_DATA_KEY);
9047 if (ret != -ENOSPC && ret != -EAGAIN) {
9052 trans->block_rsv = &root->fs_info->trans_block_rsv;
9053 ret = btrfs_update_inode(trans, root, inode);
9059 btrfs_end_transaction(trans, root);
9060 btrfs_btree_balance_dirty(root);
9062 trans = btrfs_start_transaction(root, 2);
9063 if (IS_ERR(trans)) {
9064 ret = err = PTR_ERR(trans);
9069 ret = btrfs_block_rsv_migrate(&root->fs_info->trans_block_rsv,
9071 BUG_ON(ret); /* shouldn't happen */
9072 trans->block_rsv = rsv;
9075 if (ret == 0 && inode->i_nlink > 0) {
9076 trans->block_rsv = root->orphan_block_rsv;
9077 ret = btrfs_orphan_del(trans, inode);
9083 trans->block_rsv = &root->fs_info->trans_block_rsv;
9084 ret = btrfs_update_inode(trans, root, inode);
9088 ret = btrfs_end_transaction(trans, root);
9089 btrfs_btree_balance_dirty(root);
9093 btrfs_free_block_rsv(root, rsv);
9102 * create a new subvolume directory/inode (helper for the ioctl).
9104 int btrfs_create_subvol_root(struct btrfs_trans_handle *trans,
9105 struct btrfs_root *new_root,
9106 struct btrfs_root *parent_root,
9109 struct inode *inode;
9113 inode = btrfs_new_inode(trans, new_root, NULL, "..", 2,
9114 new_dirid, new_dirid,
9115 S_IFDIR | (~current_umask() & S_IRWXUGO),
9118 return PTR_ERR(inode);
9119 inode->i_op = &btrfs_dir_inode_operations;
9120 inode->i_fop = &btrfs_dir_file_operations;
9122 set_nlink(inode, 1);
9123 btrfs_i_size_write(inode, 0);
9124 unlock_new_inode(inode);
9126 err = btrfs_subvol_inherit_props(trans, new_root, parent_root);
9128 btrfs_err(new_root->fs_info,
9129 "error inheriting subvolume %llu properties: %d",
9130 new_root->root_key.objectid, err);
9132 err = btrfs_update_inode(trans, new_root, inode);
9138 struct inode *btrfs_alloc_inode(struct super_block *sb)
9140 struct btrfs_inode *ei;
9141 struct inode *inode;
9143 ei = kmem_cache_alloc(btrfs_inode_cachep, GFP_NOFS);
9150 ei->last_sub_trans = 0;
9151 ei->logged_trans = 0;
9152 ei->delalloc_bytes = 0;
9153 ei->defrag_bytes = 0;
9154 ei->disk_i_size = 0;
9157 ei->index_cnt = (u64)-1;
9159 ei->last_unlink_trans = 0;
9160 ei->last_log_commit = 0;
9162 spin_lock_init(&ei->lock);
9163 ei->outstanding_extents = 0;
9164 ei->reserved_extents = 0;
9166 ei->runtime_flags = 0;
9167 ei->force_compress = BTRFS_COMPRESS_NONE;
9169 ei->delayed_node = NULL;
9171 ei->i_otime.tv_sec = 0;
9172 ei->i_otime.tv_nsec = 0;
9174 inode = &ei->vfs_inode;
9175 extent_map_tree_init(&ei->extent_tree);
9176 extent_io_tree_init(&ei->io_tree, &inode->i_data);
9177 extent_io_tree_init(&ei->io_failure_tree, &inode->i_data);
9178 ei->io_tree.track_uptodate = 1;
9179 ei->io_failure_tree.track_uptodate = 1;
9180 atomic_set(&ei->sync_writers, 0);
9181 mutex_init(&ei->log_mutex);
9182 mutex_init(&ei->delalloc_mutex);
9183 btrfs_ordered_inode_tree_init(&ei->ordered_tree);
9184 INIT_LIST_HEAD(&ei->delalloc_inodes);
9185 RB_CLEAR_NODE(&ei->rb_node);
9190 #ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
9191 void btrfs_test_destroy_inode(struct inode *inode)
9193 btrfs_drop_extent_cache(inode, 0, (u64)-1, 0);
9194 kmem_cache_free(btrfs_inode_cachep, BTRFS_I(inode));
9198 static void btrfs_i_callback(struct rcu_head *head)
9200 struct inode *inode = container_of(head, struct inode, i_rcu);
9201 kmem_cache_free(btrfs_inode_cachep, BTRFS_I(inode));
9204 void btrfs_destroy_inode(struct inode *inode)
9206 struct btrfs_ordered_extent *ordered;
9207 struct btrfs_root *root = BTRFS_I(inode)->root;
9209 WARN_ON(!hlist_empty(&inode->i_dentry));
9210 WARN_ON(inode->i_data.nrpages);
9211 WARN_ON(BTRFS_I(inode)->outstanding_extents);
9212 WARN_ON(BTRFS_I(inode)->reserved_extents);
9213 WARN_ON(BTRFS_I(inode)->delalloc_bytes);
9214 WARN_ON(BTRFS_I(inode)->csum_bytes);
9215 WARN_ON(BTRFS_I(inode)->defrag_bytes);
9218 * This can happen where we create an inode, but somebody else also
9219 * created the same inode and we need to destroy the one we already
9225 if (test_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
9226 &BTRFS_I(inode)->runtime_flags)) {
9227 btrfs_info(root->fs_info, "inode %llu still on the orphan list",
9229 atomic_dec(&root->orphan_inodes);
9233 ordered = btrfs_lookup_first_ordered_extent(inode, (u64)-1);
9237 btrfs_err(root->fs_info, "found ordered extent %llu %llu on inode cleanup",
9238 ordered->file_offset, ordered->len);
9239 btrfs_remove_ordered_extent(inode, ordered);
9240 btrfs_put_ordered_extent(ordered);
9241 btrfs_put_ordered_extent(ordered);
9244 btrfs_qgroup_check_reserved_leak(inode);
9245 inode_tree_del(inode);
9246 btrfs_drop_extent_cache(inode, 0, (u64)-1, 0);
9248 call_rcu(&inode->i_rcu, btrfs_i_callback);
9251 int btrfs_drop_inode(struct inode *inode)
9253 struct btrfs_root *root = BTRFS_I(inode)->root;
9258 /* the snap/subvol tree is on deleting */
9259 if (btrfs_root_refs(&root->root_item) == 0)
9262 return generic_drop_inode(inode);
9265 static void init_once(void *foo)
9267 struct btrfs_inode *ei = (struct btrfs_inode *) foo;
9269 inode_init_once(&ei->vfs_inode);
9272 void btrfs_destroy_cachep(void)
9275 * Make sure all delayed rcu free inodes are flushed before we
9279 if (btrfs_inode_cachep)
9280 kmem_cache_destroy(btrfs_inode_cachep);
9281 if (btrfs_trans_handle_cachep)
9282 kmem_cache_destroy(btrfs_trans_handle_cachep);
9283 if (btrfs_transaction_cachep)
9284 kmem_cache_destroy(btrfs_transaction_cachep);
9285 if (btrfs_path_cachep)
9286 kmem_cache_destroy(btrfs_path_cachep);
9287 if (btrfs_free_space_cachep)
9288 kmem_cache_destroy(btrfs_free_space_cachep);
9289 if (btrfs_delalloc_work_cachep)
9290 kmem_cache_destroy(btrfs_delalloc_work_cachep);
9293 int btrfs_init_cachep(void)
9295 btrfs_inode_cachep = kmem_cache_create("btrfs_inode",
9296 sizeof(struct btrfs_inode), 0,
9297 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD, init_once);
9298 if (!btrfs_inode_cachep)
9301 btrfs_trans_handle_cachep = kmem_cache_create("btrfs_trans_handle",
9302 sizeof(struct btrfs_trans_handle), 0,
9303 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD, NULL);
9304 if (!btrfs_trans_handle_cachep)
9307 btrfs_transaction_cachep = kmem_cache_create("btrfs_transaction",
9308 sizeof(struct btrfs_transaction), 0,
9309 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD, NULL);
9310 if (!btrfs_transaction_cachep)
9313 btrfs_path_cachep = kmem_cache_create("btrfs_path",
9314 sizeof(struct btrfs_path), 0,
9315 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD, NULL);
9316 if (!btrfs_path_cachep)
9319 btrfs_free_space_cachep = kmem_cache_create("btrfs_free_space",
9320 sizeof(struct btrfs_free_space), 0,
9321 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD, NULL);
9322 if (!btrfs_free_space_cachep)
9325 btrfs_delalloc_work_cachep = kmem_cache_create("btrfs_delalloc_work",
9326 sizeof(struct btrfs_delalloc_work), 0,
9327 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD,
9329 if (!btrfs_delalloc_work_cachep)
9334 btrfs_destroy_cachep();
9338 static int btrfs_getattr(struct vfsmount *mnt,
9339 struct dentry *dentry, struct kstat *stat)
9342 struct inode *inode = d_inode(dentry);
9343 u32 blocksize = inode->i_sb->s_blocksize;
9345 generic_fillattr(inode, stat);
9346 stat->dev = BTRFS_I(inode)->root->anon_dev;
9347 stat->blksize = PAGE_CACHE_SIZE;
9349 spin_lock(&BTRFS_I(inode)->lock);
9350 delalloc_bytes = BTRFS_I(inode)->delalloc_bytes;
9351 spin_unlock(&BTRFS_I(inode)->lock);
9352 stat->blocks = (ALIGN(inode_get_bytes(inode), blocksize) +
9353 ALIGN(delalloc_bytes, blocksize)) >> 9;
9357 static int btrfs_rename(struct inode *old_dir, struct dentry *old_dentry,
9358 struct inode *new_dir, struct dentry *new_dentry)
9360 struct btrfs_trans_handle *trans;
9361 struct btrfs_root *root = BTRFS_I(old_dir)->root;
9362 struct btrfs_root *dest = BTRFS_I(new_dir)->root;
9363 struct inode *new_inode = d_inode(new_dentry);
9364 struct inode *old_inode = d_inode(old_dentry);
9365 struct timespec ctime = CURRENT_TIME;
9369 u64 old_ino = btrfs_ino(old_inode);
9371 if (btrfs_ino(new_dir) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)
9374 /* we only allow rename subvolume link between subvolumes */
9375 if (old_ino != BTRFS_FIRST_FREE_OBJECTID && root != dest)
9378 if (old_ino == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID ||
9379 (new_inode && btrfs_ino(new_inode) == BTRFS_FIRST_FREE_OBJECTID))
9382 if (S_ISDIR(old_inode->i_mode) && new_inode &&
9383 new_inode->i_size > BTRFS_EMPTY_DIR_SIZE)
9387 /* check for collisions, even if the name isn't there */
9388 ret = btrfs_check_dir_item_collision(dest, new_dir->i_ino,
9389 new_dentry->d_name.name,
9390 new_dentry->d_name.len);
9393 if (ret == -EEXIST) {
9395 * eexist without a new_inode */
9396 if (WARN_ON(!new_inode)) {
9400 /* maybe -EOVERFLOW */
9407 * we're using rename to replace one file with another. Start IO on it
9408 * now so we don't add too much work to the end of the transaction
9410 if (new_inode && S_ISREG(old_inode->i_mode) && new_inode->i_size)
9411 filemap_flush(old_inode->i_mapping);
9413 /* close the racy window with snapshot create/destroy ioctl */
9414 if (old_ino == BTRFS_FIRST_FREE_OBJECTID)
9415 down_read(&root->fs_info->subvol_sem);
9417 * We want to reserve the absolute worst case amount of items. So if
9418 * both inodes are subvols and we need to unlink them then that would
9419 * require 4 item modifications, but if they are both normal inodes it
9420 * would require 5 item modifications, so we'll assume their normal
9421 * inodes. So 5 * 2 is 10, plus 1 for the new link, so 11 total items
9422 * should cover the worst case number of items we'll modify.
9424 trans = btrfs_start_transaction(root, 11);
9425 if (IS_ERR(trans)) {
9426 ret = PTR_ERR(trans);
9431 btrfs_record_root_in_trans(trans, dest);
9433 ret = btrfs_set_inode_index(new_dir, &index);
9437 BTRFS_I(old_inode)->dir_index = 0ULL;
9438 if (unlikely(old_ino == BTRFS_FIRST_FREE_OBJECTID)) {
9439 /* force full log commit if subvolume involved. */
9440 btrfs_set_log_full_commit(root->fs_info, trans);
9442 ret = btrfs_insert_inode_ref(trans, dest,
9443 new_dentry->d_name.name,
9444 new_dentry->d_name.len,
9446 btrfs_ino(new_dir), index);
9450 * this is an ugly little race, but the rename is required
9451 * to make sure that if we crash, the inode is either at the
9452 * old name or the new one. pinning the log transaction lets
9453 * us make sure we don't allow a log commit to come in after
9454 * we unlink the name but before we add the new name back in.
9456 btrfs_pin_log_trans(root);
9459 inode_inc_iversion(old_dir);
9460 inode_inc_iversion(new_dir);
9461 inode_inc_iversion(old_inode);
9462 old_dir->i_ctime = old_dir->i_mtime = ctime;
9463 new_dir->i_ctime = new_dir->i_mtime = ctime;
9464 old_inode->i_ctime = ctime;
9466 if (old_dentry->d_parent != new_dentry->d_parent)
9467 btrfs_record_unlink_dir(trans, old_dir, old_inode, 1);
9469 if (unlikely(old_ino == BTRFS_FIRST_FREE_OBJECTID)) {
9470 root_objectid = BTRFS_I(old_inode)->root->root_key.objectid;
9471 ret = btrfs_unlink_subvol(trans, root, old_dir, root_objectid,
9472 old_dentry->d_name.name,
9473 old_dentry->d_name.len);
9475 ret = __btrfs_unlink_inode(trans, root, old_dir,
9476 d_inode(old_dentry),
9477 old_dentry->d_name.name,
9478 old_dentry->d_name.len);
9480 ret = btrfs_update_inode(trans, root, old_inode);
9483 btrfs_abort_transaction(trans, root, ret);
9488 inode_inc_iversion(new_inode);
9489 new_inode->i_ctime = CURRENT_TIME;
9490 if (unlikely(btrfs_ino(new_inode) ==
9491 BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)) {
9492 root_objectid = BTRFS_I(new_inode)->location.objectid;
9493 ret = btrfs_unlink_subvol(trans, dest, new_dir,
9495 new_dentry->d_name.name,
9496 new_dentry->d_name.len);
9497 BUG_ON(new_inode->i_nlink == 0);
9499 ret = btrfs_unlink_inode(trans, dest, new_dir,
9500 d_inode(new_dentry),
9501 new_dentry->d_name.name,
9502 new_dentry->d_name.len);
9504 if (!ret && new_inode->i_nlink == 0)
9505 ret = btrfs_orphan_add(trans, d_inode(new_dentry));
9507 btrfs_abort_transaction(trans, root, ret);
9512 ret = btrfs_add_link(trans, new_dir, old_inode,
9513 new_dentry->d_name.name,
9514 new_dentry->d_name.len, 0, index);
9516 btrfs_abort_transaction(trans, root, ret);
9520 if (old_inode->i_nlink == 1)
9521 BTRFS_I(old_inode)->dir_index = index;
9523 if (old_ino != BTRFS_FIRST_FREE_OBJECTID) {
9524 struct dentry *parent = new_dentry->d_parent;
9525 btrfs_log_new_name(trans, old_inode, old_dir, parent);
9526 btrfs_end_log_trans(root);
9529 btrfs_end_transaction(trans, root);
9531 if (old_ino == BTRFS_FIRST_FREE_OBJECTID)
9532 up_read(&root->fs_info->subvol_sem);
9537 static int btrfs_rename2(struct inode *old_dir, struct dentry *old_dentry,
9538 struct inode *new_dir, struct dentry *new_dentry,
9541 if (flags & ~RENAME_NOREPLACE)
9544 return btrfs_rename(old_dir, old_dentry, new_dir, new_dentry);
9547 static void btrfs_run_delalloc_work(struct btrfs_work *work)
9549 struct btrfs_delalloc_work *delalloc_work;
9550 struct inode *inode;
9552 delalloc_work = container_of(work, struct btrfs_delalloc_work,
9554 inode = delalloc_work->inode;
9555 if (delalloc_work->wait) {
9556 btrfs_wait_ordered_range(inode, 0, (u64)-1);
9558 filemap_flush(inode->i_mapping);
9559 if (test_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
9560 &BTRFS_I(inode)->runtime_flags))
9561 filemap_flush(inode->i_mapping);
9564 if (delalloc_work->delay_iput)
9565 btrfs_add_delayed_iput(inode);
9568 complete(&delalloc_work->completion);
9571 struct btrfs_delalloc_work *btrfs_alloc_delalloc_work(struct inode *inode,
9572 int wait, int delay_iput)
9574 struct btrfs_delalloc_work *work;
9576 work = kmem_cache_zalloc(btrfs_delalloc_work_cachep, GFP_NOFS);
9580 init_completion(&work->completion);
9581 INIT_LIST_HEAD(&work->list);
9582 work->inode = inode;
9584 work->delay_iput = delay_iput;
9585 WARN_ON_ONCE(!inode);
9586 btrfs_init_work(&work->work, btrfs_flush_delalloc_helper,
9587 btrfs_run_delalloc_work, NULL, NULL);
9592 void btrfs_wait_and_free_delalloc_work(struct btrfs_delalloc_work *work)
9594 wait_for_completion(&work->completion);
9595 kmem_cache_free(btrfs_delalloc_work_cachep, work);
9599 * some fairly slow code that needs optimization. This walks the list
9600 * of all the inodes with pending delalloc and forces them to disk.
9602 static int __start_delalloc_inodes(struct btrfs_root *root, int delay_iput,
9605 struct btrfs_inode *binode;
9606 struct inode *inode;
9607 struct btrfs_delalloc_work *work, *next;
9608 struct list_head works;
9609 struct list_head splice;
9612 INIT_LIST_HEAD(&works);
9613 INIT_LIST_HEAD(&splice);
9615 mutex_lock(&root->delalloc_mutex);
9616 spin_lock(&root->delalloc_lock);
9617 list_splice_init(&root->delalloc_inodes, &splice);
9618 while (!list_empty(&splice)) {
9619 binode = list_entry(splice.next, struct btrfs_inode,
9622 list_move_tail(&binode->delalloc_inodes,
9623 &root->delalloc_inodes);
9624 inode = igrab(&binode->vfs_inode);
9626 cond_resched_lock(&root->delalloc_lock);
9629 spin_unlock(&root->delalloc_lock);
9631 work = btrfs_alloc_delalloc_work(inode, 0, delay_iput);
9634 btrfs_add_delayed_iput(inode);
9640 list_add_tail(&work->list, &works);
9641 btrfs_queue_work(root->fs_info->flush_workers,
9644 if (nr != -1 && ret >= nr)
9647 spin_lock(&root->delalloc_lock);
9649 spin_unlock(&root->delalloc_lock);
9652 list_for_each_entry_safe(work, next, &works, list) {
9653 list_del_init(&work->list);
9654 btrfs_wait_and_free_delalloc_work(work);
9657 if (!list_empty_careful(&splice)) {
9658 spin_lock(&root->delalloc_lock);
9659 list_splice_tail(&splice, &root->delalloc_inodes);
9660 spin_unlock(&root->delalloc_lock);
9662 mutex_unlock(&root->delalloc_mutex);
9666 int btrfs_start_delalloc_inodes(struct btrfs_root *root, int delay_iput)
9670 if (test_bit(BTRFS_FS_STATE_ERROR, &root->fs_info->fs_state))
9673 ret = __start_delalloc_inodes(root, delay_iput, -1);
9677 * the filemap_flush will queue IO into the worker threads, but
9678 * we have to make sure the IO is actually started and that
9679 * ordered extents get created before we return
9681 atomic_inc(&root->fs_info->async_submit_draining);
9682 while (atomic_read(&root->fs_info->nr_async_submits) ||
9683 atomic_read(&root->fs_info->async_delalloc_pages)) {
9684 wait_event(root->fs_info->async_submit_wait,
9685 (atomic_read(&root->fs_info->nr_async_submits) == 0 &&
9686 atomic_read(&root->fs_info->async_delalloc_pages) == 0));
9688 atomic_dec(&root->fs_info->async_submit_draining);
9692 int btrfs_start_delalloc_roots(struct btrfs_fs_info *fs_info, int delay_iput,
9695 struct btrfs_root *root;
9696 struct list_head splice;
9699 if (test_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state))
9702 INIT_LIST_HEAD(&splice);
9704 mutex_lock(&fs_info->delalloc_root_mutex);
9705 spin_lock(&fs_info->delalloc_root_lock);
9706 list_splice_init(&fs_info->delalloc_roots, &splice);
9707 while (!list_empty(&splice) && nr) {
9708 root = list_first_entry(&splice, struct btrfs_root,
9710 root = btrfs_grab_fs_root(root);
9712 list_move_tail(&root->delalloc_root,
9713 &fs_info->delalloc_roots);
9714 spin_unlock(&fs_info->delalloc_root_lock);
9716 ret = __start_delalloc_inodes(root, delay_iput, nr);
9717 btrfs_put_fs_root(root);
9725 spin_lock(&fs_info->delalloc_root_lock);
9727 spin_unlock(&fs_info->delalloc_root_lock);
9730 atomic_inc(&fs_info->async_submit_draining);
9731 while (atomic_read(&fs_info->nr_async_submits) ||
9732 atomic_read(&fs_info->async_delalloc_pages)) {
9733 wait_event(fs_info->async_submit_wait,
9734 (atomic_read(&fs_info->nr_async_submits) == 0 &&
9735 atomic_read(&fs_info->async_delalloc_pages) == 0));
9737 atomic_dec(&fs_info->async_submit_draining);
9739 if (!list_empty_careful(&splice)) {
9740 spin_lock(&fs_info->delalloc_root_lock);
9741 list_splice_tail(&splice, &fs_info->delalloc_roots);
9742 spin_unlock(&fs_info->delalloc_root_lock);
9744 mutex_unlock(&fs_info->delalloc_root_mutex);
9748 static int btrfs_symlink(struct inode *dir, struct dentry *dentry,
9749 const char *symname)
9751 struct btrfs_trans_handle *trans;
9752 struct btrfs_root *root = BTRFS_I(dir)->root;
9753 struct btrfs_path *path;
9754 struct btrfs_key key;
9755 struct inode *inode = NULL;
9763 struct btrfs_file_extent_item *ei;
9764 struct extent_buffer *leaf;
9766 name_len = strlen(symname);
9767 if (name_len > BTRFS_MAX_INLINE_DATA_SIZE(root))
9768 return -ENAMETOOLONG;
9771 * 2 items for inode item and ref
9772 * 2 items for dir items
9773 * 1 item for updating parent inode item
9774 * 1 item for the inline extent item
9775 * 1 item for xattr if selinux is on
9777 trans = btrfs_start_transaction(root, 7);
9779 return PTR_ERR(trans);
9781 err = btrfs_find_free_ino(root, &objectid);
9785 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
9786 dentry->d_name.len, btrfs_ino(dir), objectid,
9787 S_IFLNK|S_IRWXUGO, &index);
9788 if (IS_ERR(inode)) {
9789 err = PTR_ERR(inode);
9794 * If the active LSM wants to access the inode during
9795 * d_instantiate it needs these. Smack checks to see
9796 * if the filesystem supports xattrs by looking at the
9799 inode->i_fop = &btrfs_file_operations;
9800 inode->i_op = &btrfs_file_inode_operations;
9801 inode->i_mapping->a_ops = &btrfs_aops;
9802 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
9804 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
9806 goto out_unlock_inode;
9808 err = btrfs_add_nondir(trans, dir, dentry, inode, 0, index);
9810 goto out_unlock_inode;
9812 path = btrfs_alloc_path();
9815 goto out_unlock_inode;
9817 key.objectid = btrfs_ino(inode);
9819 key.type = BTRFS_EXTENT_DATA_KEY;
9820 datasize = btrfs_file_extent_calc_inline_size(name_len);
9821 err = btrfs_insert_empty_item(trans, root, path, &key,
9824 btrfs_free_path(path);
9825 goto out_unlock_inode;
9827 leaf = path->nodes[0];
9828 ei = btrfs_item_ptr(leaf, path->slots[0],
9829 struct btrfs_file_extent_item);
9830 btrfs_set_file_extent_generation(leaf, ei, trans->transid);
9831 btrfs_set_file_extent_type(leaf, ei,
9832 BTRFS_FILE_EXTENT_INLINE);
9833 btrfs_set_file_extent_encryption(leaf, ei, 0);
9834 btrfs_set_file_extent_compression(leaf, ei, 0);
9835 btrfs_set_file_extent_other_encoding(leaf, ei, 0);
9836 btrfs_set_file_extent_ram_bytes(leaf, ei, name_len);
9838 ptr = btrfs_file_extent_inline_start(ei);
9839 write_extent_buffer(leaf, symname, ptr, name_len);
9840 btrfs_mark_buffer_dirty(leaf);
9841 btrfs_free_path(path);
9843 inode->i_op = &btrfs_symlink_inode_operations;
9844 inode->i_mapping->a_ops = &btrfs_symlink_aops;
9845 inode_set_bytes(inode, name_len);
9846 btrfs_i_size_write(inode, name_len);
9847 err = btrfs_update_inode(trans, root, inode);
9850 goto out_unlock_inode;
9853 d_instantiate_new(dentry, inode);
9856 btrfs_end_transaction(trans, root);
9858 inode_dec_link_count(inode);
9861 btrfs_btree_balance_dirty(root);
9866 unlock_new_inode(inode);
9870 static int __btrfs_prealloc_file_range(struct inode *inode, int mode,
9871 u64 start, u64 num_bytes, u64 min_size,
9872 loff_t actual_len, u64 *alloc_hint,
9873 struct btrfs_trans_handle *trans)
9875 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
9876 struct extent_map *em;
9877 struct btrfs_root *root = BTRFS_I(inode)->root;
9878 struct btrfs_key ins;
9879 u64 cur_offset = start;
9882 u64 last_alloc = (u64)-1;
9884 bool own_trans = true;
9888 while (num_bytes > 0) {
9890 trans = btrfs_start_transaction(root, 3);
9891 if (IS_ERR(trans)) {
9892 ret = PTR_ERR(trans);
9897 cur_bytes = min(num_bytes, 256ULL * 1024 * 1024);
9898 cur_bytes = max(cur_bytes, min_size);
9900 * If we are severely fragmented we could end up with really
9901 * small allocations, so if the allocator is returning small
9902 * chunks lets make its job easier by only searching for those
9905 cur_bytes = min(cur_bytes, last_alloc);
9906 ret = btrfs_reserve_extent(root, cur_bytes, min_size, 0,
9907 *alloc_hint, &ins, 1, 0);
9910 btrfs_end_transaction(trans, root);
9914 last_alloc = ins.offset;
9915 ret = insert_reserved_file_extent(trans, inode,
9916 cur_offset, ins.objectid,
9917 ins.offset, ins.offset,
9918 ins.offset, 0, 0, 0,
9919 BTRFS_FILE_EXTENT_PREALLOC);
9921 btrfs_free_reserved_extent(root, ins.objectid,
9923 btrfs_abort_transaction(trans, root, ret);
9925 btrfs_end_transaction(trans, root);
9929 btrfs_drop_extent_cache(inode, cur_offset,
9930 cur_offset + ins.offset -1, 0);
9932 em = alloc_extent_map();
9934 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
9935 &BTRFS_I(inode)->runtime_flags);
9939 em->start = cur_offset;
9940 em->orig_start = cur_offset;
9941 em->len = ins.offset;
9942 em->block_start = ins.objectid;
9943 em->block_len = ins.offset;
9944 em->orig_block_len = ins.offset;
9945 em->ram_bytes = ins.offset;
9946 em->bdev = root->fs_info->fs_devices->latest_bdev;
9947 set_bit(EXTENT_FLAG_PREALLOC, &em->flags);
9948 em->generation = trans->transid;
9951 write_lock(&em_tree->lock);
9952 ret = add_extent_mapping(em_tree, em, 1);
9953 write_unlock(&em_tree->lock);
9956 btrfs_drop_extent_cache(inode, cur_offset,
9957 cur_offset + ins.offset - 1,
9960 free_extent_map(em);
9962 num_bytes -= ins.offset;
9963 cur_offset += ins.offset;
9964 *alloc_hint = ins.objectid + ins.offset;
9966 inode_inc_iversion(inode);
9967 inode->i_ctime = CURRENT_TIME;
9968 BTRFS_I(inode)->flags |= BTRFS_INODE_PREALLOC;
9969 if (!(mode & FALLOC_FL_KEEP_SIZE) &&
9970 (actual_len > inode->i_size) &&
9971 (cur_offset > inode->i_size)) {
9972 if (cur_offset > actual_len)
9973 i_size = actual_len;
9975 i_size = cur_offset;
9976 i_size_write(inode, i_size);
9977 btrfs_ordered_update_i_size(inode, i_size, NULL);
9980 ret = btrfs_update_inode(trans, root, inode);
9983 btrfs_abort_transaction(trans, root, ret);
9985 btrfs_end_transaction(trans, root);
9990 btrfs_end_transaction(trans, root);
9995 int btrfs_prealloc_file_range(struct inode *inode, int mode,
9996 u64 start, u64 num_bytes, u64 min_size,
9997 loff_t actual_len, u64 *alloc_hint)
9999 return __btrfs_prealloc_file_range(inode, mode, start, num_bytes,
10000 min_size, actual_len, alloc_hint,
10004 int btrfs_prealloc_file_range_trans(struct inode *inode,
10005 struct btrfs_trans_handle *trans, int mode,
10006 u64 start, u64 num_bytes, u64 min_size,
10007 loff_t actual_len, u64 *alloc_hint)
10009 return __btrfs_prealloc_file_range(inode, mode, start, num_bytes,
10010 min_size, actual_len, alloc_hint, trans);
10013 static int btrfs_set_page_dirty(struct page *page)
10015 return __set_page_dirty_nobuffers(page);
10018 static int btrfs_permission(struct inode *inode, int mask)
10020 struct btrfs_root *root = BTRFS_I(inode)->root;
10021 umode_t mode = inode->i_mode;
10023 if (mask & MAY_WRITE &&
10024 (S_ISREG(mode) || S_ISDIR(mode) || S_ISLNK(mode))) {
10025 if (btrfs_root_readonly(root))
10027 if (BTRFS_I(inode)->flags & BTRFS_INODE_READONLY)
10030 return generic_permission(inode, mask);
10033 static int btrfs_tmpfile(struct inode *dir, struct dentry *dentry, umode_t mode)
10035 struct btrfs_trans_handle *trans;
10036 struct btrfs_root *root = BTRFS_I(dir)->root;
10037 struct inode *inode = NULL;
10043 * 5 units required for adding orphan entry
10045 trans = btrfs_start_transaction(root, 5);
10047 return PTR_ERR(trans);
10049 ret = btrfs_find_free_ino(root, &objectid);
10053 inode = btrfs_new_inode(trans, root, dir, NULL, 0,
10054 btrfs_ino(dir), objectid, mode, &index);
10055 if (IS_ERR(inode)) {
10056 ret = PTR_ERR(inode);
10061 inode->i_fop = &btrfs_file_operations;
10062 inode->i_op = &btrfs_file_inode_operations;
10064 inode->i_mapping->a_ops = &btrfs_aops;
10065 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
10067 ret = btrfs_init_inode_security(trans, inode, dir, NULL);
10071 ret = btrfs_update_inode(trans, root, inode);
10074 ret = btrfs_orphan_add(trans, inode);
10079 * We set number of links to 0 in btrfs_new_inode(), and here we set
10080 * it to 1 because d_tmpfile() will issue a warning if the count is 0,
10083 * d_tmpfile() -> inode_dec_link_count() -> drop_nlink()
10085 set_nlink(inode, 1);
10086 unlock_new_inode(inode);
10087 d_tmpfile(dentry, inode);
10088 mark_inode_dirty(inode);
10091 btrfs_end_transaction(trans, root);
10094 btrfs_balance_delayed_items(root);
10095 btrfs_btree_balance_dirty(root);
10099 unlock_new_inode(inode);
10104 /* Inspired by filemap_check_errors() */
10105 int btrfs_inode_check_errors(struct inode *inode)
10109 if (test_bit(AS_ENOSPC, &inode->i_mapping->flags) &&
10110 test_and_clear_bit(AS_ENOSPC, &inode->i_mapping->flags))
10112 if (test_bit(AS_EIO, &inode->i_mapping->flags) &&
10113 test_and_clear_bit(AS_EIO, &inode->i_mapping->flags))
10119 static const struct inode_operations btrfs_dir_inode_operations = {
10120 .getattr = btrfs_getattr,
10121 .lookup = btrfs_lookup,
10122 .create = btrfs_create,
10123 .unlink = btrfs_unlink,
10124 .link = btrfs_link,
10125 .mkdir = btrfs_mkdir,
10126 .rmdir = btrfs_rmdir,
10127 .rename2 = btrfs_rename2,
10128 .symlink = btrfs_symlink,
10129 .setattr = btrfs_setattr,
10130 .mknod = btrfs_mknod,
10131 .setxattr = btrfs_setxattr,
10132 .getxattr = btrfs_getxattr,
10133 .listxattr = btrfs_listxattr,
10134 .removexattr = btrfs_removexattr,
10135 .permission = btrfs_permission,
10136 .get_acl = btrfs_get_acl,
10137 .set_acl = btrfs_set_acl,
10138 .update_time = btrfs_update_time,
10139 .tmpfile = btrfs_tmpfile,
10141 static const struct inode_operations btrfs_dir_ro_inode_operations = {
10142 .lookup = btrfs_lookup,
10143 .permission = btrfs_permission,
10144 .get_acl = btrfs_get_acl,
10145 .set_acl = btrfs_set_acl,
10146 .update_time = btrfs_update_time,
10149 static const struct file_operations btrfs_dir_file_operations = {
10150 .llseek = generic_file_llseek,
10151 .read = generic_read_dir,
10152 .iterate = btrfs_real_readdir,
10153 .unlocked_ioctl = btrfs_ioctl,
10154 #ifdef CONFIG_COMPAT
10155 .compat_ioctl = btrfs_ioctl,
10157 .release = btrfs_release_file,
10158 .fsync = btrfs_sync_file,
10161 static struct extent_io_ops btrfs_extent_io_ops = {
10162 .fill_delalloc = run_delalloc_range,
10163 .submit_bio_hook = btrfs_submit_bio_hook,
10164 .merge_bio_hook = btrfs_merge_bio_hook,
10165 .readpage_end_io_hook = btrfs_readpage_end_io_hook,
10166 .writepage_end_io_hook = btrfs_writepage_end_io_hook,
10167 .writepage_start_hook = btrfs_writepage_start_hook,
10168 .set_bit_hook = btrfs_set_bit_hook,
10169 .clear_bit_hook = btrfs_clear_bit_hook,
10170 .merge_extent_hook = btrfs_merge_extent_hook,
10171 .split_extent_hook = btrfs_split_extent_hook,
10175 * btrfs doesn't support the bmap operation because swapfiles
10176 * use bmap to make a mapping of extents in the file. They assume
10177 * these extents won't change over the life of the file and they
10178 * use the bmap result to do IO directly to the drive.
10180 * the btrfs bmap call would return logical addresses that aren't
10181 * suitable for IO and they also will change frequently as COW
10182 * operations happen. So, swapfile + btrfs == corruption.
10184 * For now we're avoiding this by dropping bmap.
10186 static const struct address_space_operations btrfs_aops = {
10187 .readpage = btrfs_readpage,
10188 .writepage = btrfs_writepage,
10189 .writepages = btrfs_writepages,
10190 .readpages = btrfs_readpages,
10191 .direct_IO = btrfs_direct_IO,
10192 .invalidatepage = btrfs_invalidatepage,
10193 .releasepage = btrfs_releasepage,
10194 .set_page_dirty = btrfs_set_page_dirty,
10195 .error_remove_page = generic_error_remove_page,
10198 static const struct address_space_operations btrfs_symlink_aops = {
10199 .readpage = btrfs_readpage,
10200 .writepage = btrfs_writepage,
10201 .invalidatepage = btrfs_invalidatepage,
10202 .releasepage = btrfs_releasepage,
10205 static const struct inode_operations btrfs_file_inode_operations = {
10206 .getattr = btrfs_getattr,
10207 .setattr = btrfs_setattr,
10208 .setxattr = btrfs_setxattr,
10209 .getxattr = btrfs_getxattr,
10210 .listxattr = btrfs_listxattr,
10211 .removexattr = btrfs_removexattr,
10212 .permission = btrfs_permission,
10213 .fiemap = btrfs_fiemap,
10214 .get_acl = btrfs_get_acl,
10215 .set_acl = btrfs_set_acl,
10216 .update_time = btrfs_update_time,
10218 static const struct inode_operations btrfs_special_inode_operations = {
10219 .getattr = btrfs_getattr,
10220 .setattr = btrfs_setattr,
10221 .permission = btrfs_permission,
10222 .setxattr = btrfs_setxattr,
10223 .getxattr = btrfs_getxattr,
10224 .listxattr = btrfs_listxattr,
10225 .removexattr = btrfs_removexattr,
10226 .get_acl = btrfs_get_acl,
10227 .set_acl = btrfs_set_acl,
10228 .update_time = btrfs_update_time,
10230 static const struct inode_operations btrfs_symlink_inode_operations = {
10231 .readlink = generic_readlink,
10232 .follow_link = page_follow_link_light,
10233 .put_link = page_put_link,
10234 .getattr = btrfs_getattr,
10235 .setattr = btrfs_setattr,
10236 .permission = btrfs_permission,
10237 .setxattr = btrfs_setxattr,
10238 .getxattr = btrfs_getxattr,
10239 .listxattr = btrfs_listxattr,
10240 .removexattr = btrfs_removexattr,
10241 .update_time = btrfs_update_time,
10244 const struct dentry_operations btrfs_dentry_operations = {
10245 .d_delete = btrfs_dentry_delete,
10246 .d_release = btrfs_dentry_release,